From c5dac1da7518002ec206c75f84ce05c541c19114 Mon Sep 17 00:00:00 2001 From: Rahul Sethuram Date: Mon, 20 Jan 2025 14:04:50 +0400 Subject: [PATCH 1/9] feat: 4626 --- .../contracts/ionic/strategies/IonicERC4626.sol | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol b/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol index 04cae86d35..5ca37592dc 100644 --- a/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol +++ b/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol @@ -10,6 +10,10 @@ import { SafeERC20Upgradeable } from "openzeppelin-contracts-upgradeable/contrac import { SafeOwnableUpgradeable } from "../../ionic/SafeOwnableUpgradeable.sol"; +interface IonicFlywheelLensRouter_4626 { + function claimAllRewardTokens(address user) external returns (address[] memory, uint256[] memory); +} + abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, ERC4626Upgradeable { using FixedPointMathLib for uint256; using SafeERC20Upgradeable for ERC20Upgradeable; @@ -19,6 +23,7 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E uint256 public vaultShareHWM; uint256 public performanceFee; address public feeRecipient; + IonicFlywheelLensRouter_4626 public flywheelLensRouter; /* ========== EVENTS ========== */ @@ -31,18 +36,19 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E /* ========== INITIALIZER ========== */ - function __IonicER4626_init(ERC20Upgradeable asset_) internal onlyInitializing { + function __IonicER4626_init(ERC20Upgradeable asset_, address flywheelLensRouter_) internal onlyInitializing { __SafeOwnable_init(msg.sender); __Pausable_init(); __Context_init(); __ERC20_init( string(abi.encodePacked("Ionic ", asset_.name(), " Vault")), - string(abi.encodePacked("mv", asset_.symbol())) + string(abi.encodePacked("iv", asset_.symbol())) ); __ERC4626_init(asset_); vaultShareHWM = 10**asset_.decimals(); feeRecipient = msg.sender; + flywheelLensRouter = IonicFlywheelLensRouter_4626(flywheelLensRouter_); } function _asset() internal view returns (ERC20Upgradeable) { From b7b6ff34d8588440a7fe15b989512e47185bbc8c Mon Sep 17 00:00:00 2001 From: Rahul Sethuram Date: Mon, 20 Jan 2025 14:34:10 +0400 Subject: [PATCH 2/9] feat: 4626 --- .../ionic/strategies/IonicERC4626.sol | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol b/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol index 5ca37592dc..a5a8ec057d 100644 --- a/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol +++ b/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol @@ -23,6 +23,7 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E uint256 public vaultShareHWM; uint256 public performanceFee; address public feeRecipient; + address public rewardsRecipient; IonicFlywheelLensRouter_4626 public flywheelLensRouter; /* ========== EVENTS ========== */ @@ -34,6 +35,8 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E address newFeeRecipient ); + event UpdatedRewardsRecipient(address oldRewardsRecipient, address newRewardsRecipient); + /* ========== INITIALIZER ========== */ function __IonicER4626_init(ERC20Upgradeable asset_, address flywheelLensRouter_) internal onlyInitializing { @@ -48,6 +51,7 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E vaultShareHWM = 10**asset_.decimals(); feeRecipient = msg.sender; + rewardsRecipient = msg.sender; flywheelLensRouter = IonicFlywheelLensRouter_4626(flywheelLensRouter_); } @@ -141,6 +145,20 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E _asset().safeTransfer(receiver, assets); } + /* ========== REWARDS FUNCTIONS ========== */ + + function updateRewardsRecipient(address newRewardsRecipient) external onlyOwner { + emit UpdatedRewardsRecipient(rewardsRecipient, newRewardsRecipient); + rewardsRecipient = newRewardsRecipient; + } + + function claimRewards() external { + (address[] memory tokens, uint256[] memory amounts) = flywheelLensRouter.claimAllRewardTokens(address(this)); + for (uint256 i = 0; i < tokens.length; i++) { + _asset().safeTransfer(rewardsRecipient, amounts[i]); + } + } + /* ========== FEE FUNCTIONS ========== */ /** From 7a8151fab1254439eac90fef7ddc96cc8a0cb3ba Mon Sep 17 00:00:00 2001 From: Rahul Sethuram Date: Tue, 21 Jan 2025 15:24:44 +0400 Subject: [PATCH 3/9] feat: 4626 --- .../ionic/strategies/IonicERC4626.sol | 24 +-- .../ionic/strategies/IonicMarketERC4626.sol | 158 ++++++++++++++++++ 2 files changed, 159 insertions(+), 23 deletions(-) create mode 100644 packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol diff --git a/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol b/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol index a5a8ec057d..7b728e72de 100644 --- a/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol +++ b/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol @@ -10,10 +10,6 @@ import { SafeERC20Upgradeable } from "openzeppelin-contracts-upgradeable/contrac import { SafeOwnableUpgradeable } from "../../ionic/SafeOwnableUpgradeable.sol"; -interface IonicFlywheelLensRouter_4626 { - function claimAllRewardTokens(address user) external returns (address[] memory, uint256[] memory); -} - abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, ERC4626Upgradeable { using FixedPointMathLib for uint256; using SafeERC20Upgradeable for ERC20Upgradeable; @@ -23,8 +19,6 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E uint256 public vaultShareHWM; uint256 public performanceFee; address public feeRecipient; - address public rewardsRecipient; - IonicFlywheelLensRouter_4626 public flywheelLensRouter; /* ========== EVENTS ========== */ @@ -39,7 +33,7 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E /* ========== INITIALIZER ========== */ - function __IonicER4626_init(ERC20Upgradeable asset_, address flywheelLensRouter_) internal onlyInitializing { + function __IonicER4626_init(ERC20Upgradeable asset_) internal onlyInitializing { __SafeOwnable_init(msg.sender); __Pausable_init(); __Context_init(); @@ -51,8 +45,6 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E vaultShareHWM = 10**asset_.decimals(); feeRecipient = msg.sender; - rewardsRecipient = msg.sender; - flywheelLensRouter = IonicFlywheelLensRouter_4626(flywheelLensRouter_); } function _asset() internal view returns (ERC20Upgradeable) { @@ -145,20 +137,6 @@ abstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, E _asset().safeTransfer(receiver, assets); } - /* ========== REWARDS FUNCTIONS ========== */ - - function updateRewardsRecipient(address newRewardsRecipient) external onlyOwner { - emit UpdatedRewardsRecipient(rewardsRecipient, newRewardsRecipient); - rewardsRecipient = newRewardsRecipient; - } - - function claimRewards() external { - (address[] memory tokens, uint256[] memory amounts) = flywheelLensRouter.claimAllRewardTokens(address(this)); - for (uint256 i = 0; i < tokens.length; i++) { - _asset().safeTransfer(rewardsRecipient, amounts[i]); - } - } - /* ========== FEE FUNCTIONS ========== */ /** diff --git a/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol b/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol new file mode 100644 index 0000000000..ac5d55b5f1 --- /dev/null +++ b/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: Unlicense +pragma solidity ^0.8.22; +import { IonicERC4626, ERC20Upgradeable } from "./IonicERC4626.sol"; +import { SafeERC20Upgradeable } from "openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol"; +import { ICErc20 } from "../../compound/CTokenInterfaces.sol"; +import { ComptrollerErrorReporter } from "../../compound/ErrorReporter.sol"; + +interface IonicFlywheelLensRouter_4626 { + function claimAllRewardTokens(address user) external returns (address[] memory, uint256[] memory); +} + +contract IonicMarketERC4626 is IonicERC4626 { + using SafeERC20Upgradeable for ERC20Upgradeable; + + error IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error); + + // STATE VARIABLES + address public rewardsRecipient; + IonicFlywheelLensRouter_4626 public flywheelLensRouter; + ICErc20 public cToken; + + function initialize( + ERC20Upgradeable asset_, + ICErc20 cToken_, + address flywheelLensRouter_, + address rewardsRecipient_ + ) public initializer { + __IonicER4626_init(asset_); + cToken = cToken_; + rewardsRecipient = rewardsRecipient_; + flywheelLensRouter = IonicFlywheelLensRouter_4626(flywheelLensRouter_); + } + + /* ========== VIEW FUNCTIONS ========== */ + /// @notice maximum amount of underlying tokens that can be deposited into the underlying protocol + function maxDeposit(address) public view override returns (uint256) { + if (cToken.comptroller().mintGuardianPaused(address(cToken))) { + return 0; + } + + uint256 supplyCap = cToken.comptroller().supplyCaps(address(cToken)); + if (supplyCap != 0) { + uint256 currentExchangeRate = cToken.exchangeRateCurrent(); + uint256 _totalSupply = cToken.totalSupply(); + uint256 totalSupplies = (_totalSupply * currentExchangeRate) / 1e18; /// exchange rate is scaled up by 1e18, so needs to be divided off to get accurate total supply + + // uint256 totalCash = MToken(address(mToken)).getCash(); + // uint256 totalBorrows = MToken(address(mToken)).totalBorrows(); + // uint256 totalReserves = MToken(address(mToken)).totalReserves(); + + // // (Pseudocode) totalSupplies = totalCash + totalBorrows - totalReserves + // uint256 totalSupplies = (totalCash + totalBorrows) - totalReserves; + + // supply cap is 3 + // total supplies is 1 + /// no room for additional supplies + + // supply cap is 3 + // total supplies is 0 + /// room for 1 additional supplies + + // supply cap is 4 + // total supplies is 1 + /// room for 1 additional supplies + + /// total supplies could exceed supply cap as interest accrues, need to handle this edge case + /// going to subtract 2 from supply cap to account for rounding errors + if (totalSupplies + 2 >= supplyCap) { + return 0; + } + + return supplyCap - totalSupplies - 2; + } + + return type(uint256).max; + } + + /// @notice Returns the maximum amount of tokens that can be supplied + /// no way for this function to ever revert unless comptroller or mToken is broken + /// @dev accrue interest must be called before this function is called, otherwise + /// an outdated value will be fetched, and the returned value will be incorrect + /// (greater than actual amount available to be minted will be returned) + function maxMint(address) public view override returns (uint256) { + uint256 mintAmount = maxDeposit(address(0)); + + return mintAmount == type(uint256).max ? mintAmount : convertToShares(mintAmount); + } + + /// @notice maximum amount of underlying tokens that can be withdrawn + /// @param owner The address that owns the shares + function maxWithdraw(address owner) public view override returns (uint256) { + uint256 cash = cToken.getCash(); + uint256 assetsBalance = convertToAssets(balanceOf(owner)); + return cash < assetsBalance ? cash : assetsBalance; + } + + /// @notice maximum amount of shares that can be withdrawn + /// @param owner The address that owns the shares + function maxRedeem(address owner) public view override returns (uint256) { + uint256 cash = cToken.getCash(); + uint256 cashInShares = convertToShares(cash); + uint256 shareBalance = balanceOf(owner); + return cashInShares < shareBalance ? cashInShares : shareBalance; + } + + /* ========== REWARDS FUNCTIONS ========== */ + + function updateRewardsRecipient(address newRewardsRecipient) external onlyOwner { + emit UpdatedRewardsRecipient(rewardsRecipient, newRewardsRecipient); + rewardsRecipient = newRewardsRecipient; + } + + function claimRewards() external { + (address[] memory tokens, uint256[] memory amounts) = flywheelLensRouter.claimAllRewardTokens(address(this)); + for (uint256 i = 0; i < tokens.length; i++) { + _asset().safeTransfer(rewardsRecipient, amounts[i]); + } + } + + /* ========== EMERGENCY FUNCTIONS ========== */ + + // Should withdraw all funds from the strategy and pause the contract + function emergencyWithdrawAndPause() external override onlyOwner { + _pause(); + } + + function unpause() external override onlyOwner { + _unpause(); + } + + /* ========== INTERNAL HOOKS LOGIC ========== */ + + function beforeWithdraw(uint256 assets, uint256 /*shares*/) internal override { + /// ----------------------------------------------------------------------- + /// Withdraw assets from Ionic + /// ----------------------------------------------------------------------- + + uint256 errorCode = cToken.redeemUnderlying(assets); + if (errorCode != uint256(ComptrollerErrorReporter.Error.NO_ERROR)) { + revert IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error(errorCode)); + } + } + + function afterDeposit(uint256 assets, uint256 /*shares*/) internal override { + /// ----------------------------------------------------------------------- + /// Deposit assets into Ionic + /// ----------------------------------------------------------------------- + + // approve to cToken + _asset().safeApprove(address(cToken), assets); + + // deposit into cToken + uint256 errorCode = cToken.mint(assets); + if (errorCode != uint256(ComptrollerErrorReporter.Error.NO_ERROR)) { + revert IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error(errorCode)); + } + } +} From 2466ad9c1a092b1bca1e7804da5f9d22fc5f137d Mon Sep 17 00:00:00 2001 From: Rahul Sethuram Date: Tue, 21 Jan 2025 15:44:57 +0400 Subject: [PATCH 4/9] fix: total assets override --- .../contracts/ionic/strategies/IonicMarketERC4626.sol | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol b/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol index ac5d55b5f1..bcd3d5b137 100644 --- a/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol +++ b/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol @@ -32,6 +32,10 @@ contract IonicMarketERC4626 is IonicERC4626 { } /* ========== VIEW FUNCTIONS ========== */ + function totalAssets() public view virtual override returns (uint256) { + return cToken.balanceOfUnderlying(address(this)); + } + /// @notice maximum amount of underlying tokens that can be deposited into the underlying protocol function maxDeposit(address) public view override returns (uint256) { if (cToken.comptroller().mintGuardianPaused(address(cToken))) { From d8f93ee7c83210024cb764358de3162db9751956 Mon Sep 17 00:00:00 2001 From: Rahul Sethuram Date: Fri, 24 Jan 2025 13:54:30 +0400 Subject: [PATCH 5/9] fix: import --- .../contracts/contracts/ionic/strategies/IonicMarketERC4626.sol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol b/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol index bcd3d5b137..5ae87eb93c 100644 --- a/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol +++ b/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol @@ -1,7 +1,7 @@ // SPDX-License-Identifier: Unlicense pragma solidity ^0.8.22; import { IonicERC4626, ERC20Upgradeable } from "./IonicERC4626.sol"; -import { SafeERC20Upgradeable } from "openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol"; +import { SafeERC20Upgradeable } from "@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol"; import { ICErc20 } from "../../compound/CTokenInterfaces.sol"; import { ComptrollerErrorReporter } from "../../compound/ErrorReporter.sol"; From e51d49a2cfa4b8dbc751c6b028bad0a11c3b6b19 Mon Sep 17 00:00:00 2001 From: Rahul Sethuram Date: Fri, 24 Jan 2025 15:35:00 +0400 Subject: [PATCH 6/9] feat: deploy --- ...20311B518f3d0c94e897592014de53831cfA3.json | 1366 +++++++++++++++ ...4e897592014de53831cfA3_Implementation.json | 1547 +++++++++++++++++ ...518f3d0c94e897592014de53831cfA3_Proxy.json | 275 +++ ...0A17a49Bc4D442bA7F72c39FA2108865671f0.json | 1366 +++++++++++++++ ...A7F72c39FA2108865671f0_Implementation.json | 1547 +++++++++++++++++ ...9Bc4D442bA7F72c39FA2108865671f0_Proxy.json | 275 +++ .../34a0d1556aea7d4f3124b66dedee8846.json | 957 ++++++++++ packages/contracts/foundry.toml | 2 +- packages/contracts/hardhat.config.ts | 2 +- .../tasks/chain-specific/base/erc4626.ts | 26 + .../tasks/chain-specific/base/index.ts | 1 + packages/contracts/tasks/erc4626/deploy.ts | 44 + packages/contracts/tasks/erc4626/index.ts | 1 + packages/contracts/tasks/index.ts | 1 + 14 files changed, 7408 insertions(+), 2 deletions(-) create mode 100644 packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3.json create mode 100644 packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3_Implementation.json create mode 100644 packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3_Proxy.json create mode 100644 packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0.json create mode 100644 packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0_Implementation.json create mode 100644 packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0_Proxy.json create mode 100644 packages/contracts/deployments/base/solcInputs/34a0d1556aea7d4f3124b66dedee8846.json create mode 100644 packages/contracts/tasks/chain-specific/base/erc4626.ts create mode 100644 packages/contracts/tasks/erc4626/deploy.ts create mode 100644 packages/contracts/tasks/erc4626/index.ts diff --git a/packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3.json b/packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3.json new file mode 100644 index 0000000000..3c1c10c702 --- /dev/null +++ b/packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3.json @@ -0,0 +1,1366 @@ +{ + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "abi": [ + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "previousAdmin", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newAdmin", + "type": "address" + } + ], + "name": "AdminChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "beacon", + "type": "address" + } + ], + "name": "BeaconUpgraded", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "implementation", + "type": "address" + } + ], + "name": "Upgraded", + "type": "event" + }, + { + "stateMutability": "payable", + "type": "fallback" + }, + { + "inputs": [], + "name": "admin", + "outputs": [ + { + "internalType": "address", + "name": "admin_", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newAdmin", + "type": "address" + } + ], + "name": "changeAdmin", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "implementation", + "outputs": [ + { + "internalType": "address", + "name": "implementation_", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newImplementation", + "type": "address" + } + ], + "name": "upgradeTo", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newImplementation", + "type": "address" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "upgradeToAndCall", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "stateMutability": "payable", + "type": "receive" + }, + { + "inputs": [ + { + "internalType": "enum ComptrollerErrorReporter.Error", + "name": "", + "type": "uint8" + } + ], + "name": "IonicMarketERC4626__CompoundError", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Deposit", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint8", + "name": "version", + "type": "uint8" + } + ], + "name": "Initialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldOwner", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "NewOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldPendingOwner", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newPendingOwner", + "type": "address" + } + ], + "name": "NewPendingOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Paused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Unpaused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "oldPerformanceFee", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "newPerformanceFee", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "oldFeeRecipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newFeeRecipient", + "type": "address" + } + ], + "name": "UpdatedFeeSettings", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldRewardsRecipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newRewardsRecipient", + "type": "address" + } + ], + "name": "UpdatedRewardsRecipient", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Withdraw", + "type": "event" + }, + { + "inputs": [], + "name": "_acceptOwner", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newPendingOwner", + "type": "address" + } + ], + "name": "_setPendingOwner", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "asset", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "cToken", + "outputs": [ + { + "internalType": "contract ICErc20", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "claimRewards", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "convertToAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "convertToShares", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "decimals", + "outputs": [ + { + "internalType": "uint8", + "name": "", + "type": "uint8" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "subtractedValue", + "type": "uint256" + } + ], + "name": "decreaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "deposit", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "emergencyWithdrawAndPause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "feeRecipient", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "flywheelLensRouter", + "outputs": [ + { + "internalType": "contract IonicFlywheelLensRouter_4626", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "addedValue", + "type": "uint256" + } + ], + "name": "increaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "contract ICErc20", + "name": "cToken_", + "type": "address" + }, + { + "internalType": "address", + "name": "flywheelLensRouter_", + "type": "address" + }, + { + "internalType": "address", + "name": "rewardsRecipient_", + "type": "address" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "mint", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "name", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "paused", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pendingOwner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "performanceFee", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "redeem", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "rewardsRecipient", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "market", + "type": "address" + } + ], + "name": "shutdown", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "symbol", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "takePerformanceFee", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "totalAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "unpause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "newPerformanceFee", + "type": "uint256" + }, + { + "internalType": "address", + "name": "newFeeRecipient", + "type": "address" + } + ], + "name": "updateFeeSettings", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newRewardsRecipient", + "type": "address" + } + ], + "name": "updateRewardsRecipient", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "vaultShareHWM", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "withdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "withdrawAccruedFees", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_logic", + "type": "address" + }, + { + "internalType": "address", + "name": "admin_", + "type": "address" + }, + { + "internalType": "bytes", + "name": "_data", + "type": "bytes" + } + ], + "stateMutability": "payable", + "type": "constructor" + } + ], + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "receipt": { + "to": null, + "from": "0x1155b614971f16758C92c4890eD338C9e3ede6b7", + "contractAddress": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "transactionIndex": 102, + "gasUsed": "975823", + "logsBloom": "0x00000000000000000000000000000000400000040000000000800000000200000000000000000000000000000000000000000000100000000000000000000000000000000000000000000800000002000001000000000000000000000000000000000000020000000000000000000800000000800000000000000000000000400000000000000200000000000000000000000000000080000000000000c00000000020000000000000000000002400000000000000000000000000000000000000000020000000000000000000040000000000000400000000000000000020000000000000000000000000000080000000000000000000000000000000000000", + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932", + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "logs": [ + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b", + "0x000000000000000000000000986f1289b2e803b0bf7ac29b777bbacbdb3de872" + ], + "data": "0x", + "logIndex": 1313, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + }, + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "data": "0x", + "logIndex": 1314, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + }, + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "data": "0x", + "logIndex": 1315, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + }, + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498" + ], + "data": "0x0000000000000000000000000000000000000000000000000000000000000001", + "logIndex": 1316, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + }, + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0x7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f" + ], + "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000028df5636456049b891bf9d40fa46ef5ad20822c5", + "logIndex": 1317, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + } + ], + "blockNumber": 25464415, + "cumulativeGasUsed": "55424046", + "status": 1, + "byzantium": true + }, + "args": [ + "0x986F1289B2E803B0bf7ac29b777bbAcBDb3dE872", + "0x28DF5636456049B891bF9D40fa46eF5ad20822C5", + "0xc0c53b8b00000000000000000000000049420311b518f3d0c94e897592014de53831cfa3000000000000000000000000b1402333b12fc066c3d7f55d37944d5e281a3e8b0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "numDeployments": 1, + "solcInputHash": "0e89febeebc7444140de8e67c9067d2c", + "metadata": "{\"compiler\":{\"version\":\"0.8.10+commit.fc410830\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_logic\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"admin_\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previousAdmin\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"AdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"beacon\",\"type\":\"address\"}],\"name\":\"BeaconUpgraded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"implementation\",\"type\":\"address\"}],\"name\":\"Upgraded\",\"type\":\"event\"},{\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"inputs\":[],\"name\":\"admin\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"admin_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"changeAdmin\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"implementation\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"implementation_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newImplementation\",\"type\":\"address\"}],\"name\":\"upgradeTo\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newImplementation\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"upgradeToAndCall\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}],\"devdoc\":{\"details\":\"This contract implements a proxy that is upgradeable by an admin. To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector clashing], which can potentially be used in an attack, this contract uses the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two things that go hand in hand: 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches one of the admin functions exposed by the proxy itself. 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error that says \\\"admin cannot fallback to proxy target\\\". These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to call a function from the proxy implementation. Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\",\"kind\":\"dev\",\"methods\":{\"admin()\":{\"details\":\"Returns the current admin. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\"},\"changeAdmin(address)\":{\"details\":\"Changes the admin of the proxy. Emits an {AdminChanged} event. NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\"},\"constructor\":{\"details\":\"Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\"},\"implementation()\":{\"details\":\"Returns the current implementation. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\"},\"upgradeTo(address)\":{\"details\":\"Upgrade the implementation of the proxy. NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\"},\"upgradeToAndCall(address,bytes)\":{\"details\":\"Upgrade the implementation of the proxy, and then call a function from the new implementation as specified by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the proxied contract. NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\"}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"solc_0.8/openzeppelin/proxy/transparent/TransparentUpgradeableProxy.sol\":\"TransparentUpgradeableProxy\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":999999},\"remappings\":[]},\"sources\":{\"solc_0.8/openzeppelin/interfaces/draft-IERC1822.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (interfaces/draft-IERC1822.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\\n * proxy whose upgrades are fully controlled by the current implementation.\\n */\\ninterface IERC1822Proxiable {\\n /**\\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\\n * address.\\n *\\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\\n * function revert if invoked through a proxy.\\n */\\n function proxiableUUID() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x93b4e21c931252739a1ec13ea31d3d35a5c068be3163ccab83e4d70c40355f03\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../Proxy.sol\\\";\\nimport \\\"./ERC1967Upgrade.sol\\\";\\n\\n/**\\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\\n * implementation address that can be changed. This address is stored in storage in the location specified by\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\\n * implementation behind the proxy.\\n */\\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\\n /**\\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\\n *\\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\\n * function call, and allows initializating the storage of the proxy like a Solidity constructor.\\n */\\n constructor(address _logic, bytes memory _data) payable {\\n assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256(\\\"eip1967.proxy.implementation\\\")) - 1));\\n _upgradeToAndCall(_logic, _data, false);\\n }\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _implementation() internal view virtual override returns (address impl) {\\n return ERC1967Upgrade._getImplementation();\\n }\\n}\\n\",\"keccak256\":\"0x6309f9f39dc6f4f45a24f296543867aa358e32946cd6b2874627a996d606b3a0\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Upgrade.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/ERC1967/ERC1967Upgrade.sol)\\n\\npragma solidity ^0.8.2;\\n\\nimport \\\"../beacon/IBeacon.sol\\\";\\nimport \\\"../../interfaces/draft-IERC1822.sol\\\";\\nimport \\\"../../utils/Address.sol\\\";\\nimport \\\"../../utils/StorageSlot.sol\\\";\\n\\n/**\\n * @dev This abstract contract provides getters and event emitting update functions for\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\\n *\\n * _Available since v4.1._\\n *\\n * @custom:oz-upgrades-unsafe-allow delegatecall\\n */\\nabstract contract ERC1967Upgrade {\\n // This is the keccak-256 hash of \\\"eip1967.proxy.rollback\\\" subtracted by 1\\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\\n\\n /**\\n * @dev Storage slot with the address of the current implementation.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.implementation\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n\\n /**\\n * @dev Emitted when the implementation is upgraded.\\n */\\n event Upgraded(address indexed implementation);\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _getImplementation() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 implementation slot.\\n */\\n function _setImplementation(address newImplementation) private {\\n require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n }\\n\\n /**\\n * @dev Perform implementation upgrade\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeTo(address newImplementation) internal {\\n _setImplementation(newImplementation);\\n emit Upgraded(newImplementation);\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCall(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _upgradeTo(newImplementation);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(newImplementation, data);\\n }\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCallUUPS(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n // Upgrades from old implementations will perform a rollback test. This test requires the new\\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\\n // this special case will break upgrade paths from old UUPS implementation to new ones.\\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\\n _setImplementation(newImplementation);\\n } else {\\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\\n require(slot == _IMPLEMENTATION_SLOT, \\\"ERC1967Upgrade: unsupported proxiableUUID\\\");\\n } catch {\\n revert(\\\"ERC1967Upgrade: new implementation is not UUPS\\\");\\n }\\n _upgradeToAndCall(newImplementation, data, forceCall);\\n }\\n }\\n\\n /**\\n * @dev Storage slot with the admin of the contract.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.admin\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\\n\\n /**\\n * @dev Emitted when the admin account has changed.\\n */\\n event AdminChanged(address previousAdmin, address newAdmin);\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _getAdmin() internal view virtual returns (address) {\\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 admin slot.\\n */\\n function _setAdmin(address newAdmin) private {\\n require(newAdmin != address(0), \\\"ERC1967: new admin is the zero address\\\");\\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n */\\n function _changeAdmin(address newAdmin) internal {\\n emit AdminChanged(_getAdmin(), newAdmin);\\n _setAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\\n */\\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\\n\\n /**\\n * @dev Emitted when the beacon is upgraded.\\n */\\n event BeaconUpgraded(address indexed beacon);\\n\\n /**\\n * @dev Returns the current beacon.\\n */\\n function _getBeacon() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new beacon in the EIP1967 beacon slot.\\n */\\n function _setBeacon(address newBeacon) private {\\n require(Address.isContract(newBeacon), \\\"ERC1967: new beacon is not a contract\\\");\\n require(Address.isContract(IBeacon(newBeacon).implementation()), \\\"ERC1967: beacon implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\\n }\\n\\n /**\\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\\n *\\n * Emits a {BeaconUpgraded} event.\\n */\\n function _upgradeBeaconToAndCall(\\n address newBeacon,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _setBeacon(newBeacon);\\n emit BeaconUpgraded(newBeacon);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x17668652127feebed0ce8d9431ef95ccc8c4292f03e3b8cf06c6ca16af396633\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\\n * be specified by overriding the virtual {_implementation} function.\\n *\\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\\n * different contract through the {_delegate} function.\\n *\\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\\n */\\nabstract contract Proxy {\\n /**\\n * @dev Delegates the current call to `implementation`.\\n *\\n * This function does not return to its internal call site, it will return directly to the external caller.\\n */\\n function _delegate(address implementation) internal virtual {\\n assembly {\\n // Copy msg.data. We take full control of memory in this inline assembly\\n // block because it will not return to Solidity code. We overwrite the\\n // Solidity scratch pad at memory position 0.\\n calldatacopy(0, 0, calldatasize())\\n\\n // Call the implementation.\\n // out and outsize are 0 because we don't know the size yet.\\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\\n\\n // Copy the returned data.\\n returndatacopy(0, 0, returndatasize())\\n\\n switch result\\n // delegatecall returns 0 on error.\\n case 0 {\\n revert(0, returndatasize())\\n }\\n default {\\n return(0, returndatasize())\\n }\\n }\\n }\\n\\n /**\\n * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function\\n * and {_fallback} should delegate.\\n */\\n function _implementation() internal view virtual returns (address);\\n\\n /**\\n * @dev Delegates the current call to the address returned by `_implementation()`.\\n *\\n * This function does not return to its internall call site, it will return directly to the external caller.\\n */\\n function _fallback() internal virtual {\\n _beforeFallback();\\n _delegate(_implementation());\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\\n * function in the contract matches the call data.\\n */\\n fallback() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\\n * is empty.\\n */\\n receive() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\\n * call, or as part of the Solidity `fallback` or `receive` functions.\\n *\\n * If overriden should call `super._beforeFallback()`.\\n */\\n function _beforeFallback() internal virtual {}\\n}\\n\",\"keccak256\":\"0xd5d1fd16e9faff7fcb3a52e02a8d49156f42a38a03f07b5f1810c21c2149a8ab\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/beacon/IBeacon.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\\n */\\ninterface IBeacon {\\n /**\\n * @dev Must return an address that can be used as a delegate call target.\\n *\\n * {BeaconProxy} will check that this address is a contract.\\n */\\n function implementation() external view returns (address);\\n}\\n\",\"keccak256\":\"0xd50a3421ac379ccb1be435fa646d66a65c986b4924f0849839f08692f39dde61\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/transparent/TransparentUpgradeableProxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../ERC1967/ERC1967Proxy.sol\\\";\\n\\n/**\\n * @dev This contract implements a proxy that is upgradeable by an admin.\\n *\\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\\n * clashing], which can potentially be used in an attack, this contract uses the\\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\\n * things that go hand in hand:\\n *\\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\\n * that call matches one of the admin functions exposed by the proxy itself.\\n * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the\\n * implementation. If the admin tries to call a function on the implementation it will fail with an error that says\\n * \\\"admin cannot fallback to proxy target\\\".\\n *\\n * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing\\n * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due\\n * to sudden errors when trying to call a function from the proxy implementation.\\n *\\n * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,\\n * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\\n */\\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\\n /**\\n * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and\\n * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\\n */\\n constructor(\\n address _logic,\\n address admin_,\\n bytes memory _data\\n ) payable ERC1967Proxy(_logic, _data) {\\n assert(_ADMIN_SLOT == bytes32(uint256(keccak256(\\\"eip1967.proxy.admin\\\")) - 1));\\n _changeAdmin(admin_);\\n }\\n\\n /**\\n * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.\\n */\\n modifier ifAdmin() {\\n if (msg.sender == _getAdmin()) {\\n _;\\n } else {\\n _fallback();\\n }\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\\n */\\n function admin() external ifAdmin returns (address admin_) {\\n admin_ = _getAdmin();\\n }\\n\\n /**\\n * @dev Returns the current implementation.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\\n */\\n function implementation() external ifAdmin returns (address implementation_) {\\n implementation_ = _implementation();\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\\n */\\n function changeAdmin(address newAdmin) external virtual ifAdmin {\\n _changeAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\\n */\\n function upgradeTo(address newImplementation) external ifAdmin {\\n _upgradeToAndCall(newImplementation, bytes(\\\"\\\"), false);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified\\n * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the\\n * proxied contract.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\\n */\\n function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {\\n _upgradeToAndCall(newImplementation, data, true);\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _admin() internal view virtual returns (address) {\\n return _getAdmin();\\n }\\n\\n /**\\n * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.\\n */\\n function _beforeFallback() internal virtual override {\\n require(msg.sender != _getAdmin(), \\\"TransparentUpgradeableProxy: admin cannot fallback to proxy target\\\");\\n super._beforeFallback();\\n }\\n}\\n\",\"keccak256\":\"0x140055a64cf579d622e04f5a198595832bf2cb193cd0005f4f2d4d61ca906253\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.1;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev Returns true if `account` is a contract.\\n *\\n * [IMPORTANT]\\n * ====\\n * It is unsafe to assume that an address for which this function returns\\n * false is an externally-owned account (EOA) and not a contract.\\n *\\n * Among others, `isContract` will return false for the following\\n * types of addresses:\\n *\\n * - an externally-owned account\\n * - a contract in construction\\n * - an address where a contract will be created\\n * - an address where a contract lived, but was destroyed\\n * ====\\n *\\n * [IMPORTANT]\\n * ====\\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\\n *\\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\\n * constructor.\\n * ====\\n */\\n function isContract(address account) internal view returns (bool) {\\n // This method relies on extcodesize/address.code.length, which returns 0\\n // for contracts in construction, since the code is only stored at the end\\n // of the constructor execution.\\n\\n return account.code.length > 0;\\n }\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n require(address(this).balance >= amount, \\\"Address: insufficient balance\\\");\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(success, \\\"Address: unable to send value, recipient may have reverted\\\");\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason, it is bubbled up by this\\n * function (like regular Solidity function calls).\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCall(target, data, \\\"Address: low-level call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\\n * `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, value, \\\"Address: low-level call with value failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\\n * with `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(address(this).balance >= value, \\\"Address: insufficient balance for call\\\");\\n require(isContract(target), \\\"Address: call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n return functionStaticCall(target, data, \\\"Address: low-level static call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n require(isContract(target), \\\"Address: static call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionDelegateCall(target, data, \\\"Address: low-level delegate call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(isContract(target), \\\"Address: delegate call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\\n * revert reason using the provided one.\\n *\\n * _Available since v4.3._\\n */\\n function verifyCallResult(\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal pure returns (bytes memory) {\\n if (success) {\\n return returndata;\\n } else {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n }\\n}\\n\",\"keccak256\":\"0x3777e696b62134e6177440dbe6e6601c0c156a443f57167194b67e75527439de\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/utils/StorageSlot.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Library for reading and writing primitive types to specific storage slots.\\n *\\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\\n * This library helps with reading and writing to such slots without the need for inline assembly.\\n *\\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\\n *\\n * Example usage to set ERC1967 implementation slot:\\n * ```\\n * contract ERC1967 {\\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n *\\n * function _getImplementation() internal view returns (address) {\\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n * }\\n *\\n * function _setImplementation(address newImplementation) internal {\\n * require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n * }\\n * }\\n * ```\\n *\\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\\n */\\nlibrary StorageSlot {\\n struct AddressSlot {\\n address value;\\n }\\n\\n struct BooleanSlot {\\n bool value;\\n }\\n\\n struct Bytes32Slot {\\n bytes32 value;\\n }\\n\\n struct Uint256Slot {\\n uint256 value;\\n }\\n\\n /**\\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\\n */\\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\\n */\\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\\n */\\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\\n */\\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n}\\n\",\"keccak256\":\"0xfe1b7a9aa2a530a9e705b220e26cd584e2fbdc9602a3a1066032b12816b46aca\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x6080604052604051620011b2380380620011b2833981016040819052620000269162000519565b82816200005560017f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbd620005f9565b6000805160206200116b833981519152146200007557620000756200061f565b6200008382826000620000e7565b50620000b3905060017fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6104620005f9565b6000805160206200114b83398151915214620000d357620000d36200061f565b620000de8262000124565b50505062000688565b620000f2836200017f565b600082511180620001005750805b156200011f576200011d8383620001c160201b620002ff1760201c565b505b505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6200014f620001f0565b604080516001600160a01b03928316815291841660208301520160405180910390a16200017c8162000229565b50565b6200018a81620002de565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b6060620001e983836040518060600160405280602781526020016200118b6027913962000381565b9392505050565b60006200021a6000805160206200114b83398151915260001b6200046760201b620002731760201c565b546001600160a01b0316919050565b6001600160a01b038116620002945760405162461bcd60e51b815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201526564647265737360d01b60648201526084015b60405180910390fd5b80620002bd6000805160206200114b83398151915260001b6200046760201b620002731760201c565b80546001600160a01b0319166001600160a01b039290921691909117905550565b620002f4816200046a60201b6200032b1760201c565b620003585760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084016200028b565b80620002bd6000805160206200116b83398151915260001b6200046760201b620002731760201c565b60606001600160a01b0384163b620003eb5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f6044820152651b9d1c9858dd60d21b60648201526084016200028b565b600080856001600160a01b03168560405162000408919062000635565b600060405180830381855af49150503d806000811462000445576040519150601f19603f3d011682016040523d82523d6000602084013e6200044a565b606091505b5090925090506200045d82828662000479565b9695505050505050565b90565b6001600160a01b03163b151590565b606083156200048a575081620001e9565b8251156200049b5782518084602001fd5b8160405162461bcd60e51b81526004016200028b919062000653565b80516001600160a01b0381168114620004cf57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101562000507578181015183820152602001620004ed565b838111156200011d5750506000910152565b6000806000606084860312156200052f57600080fd5b6200053a84620004b7565b92506200054a60208501620004b7565b60408501519092506001600160401b03808211156200056857600080fd5b818601915086601f8301126200057d57600080fd5b815181811115620005925762000592620004d4565b604051601f8201601f19908116603f01168101908382118183101715620005bd57620005bd620004d4565b81604052828152896020848701011115620005d757600080fd5b620005ea836020830160208801620004ea565b80955050505050509250925092565b6000828210156200061a57634e487b7160e01b600052601160045260246000fd5b500390565b634e487b7160e01b600052600160045260246000fd5b6000825162000649818460208701620004ea565b9190910192915050565b602081526000825180602084015262000674816040850160208701620004ea565b601f01601f19169190910160400192915050565b610ab380620006986000396000f3fe60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100a85780638f283970146100e6578063f851a440146101065761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61011b565b005b61006b61011b565b34801561008157600080fd5b5061006b61009036600461091f565b610135565b61006b6100a336600461093a565b610196565b3480156100b457600080fd5b506100bd610221565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b3480156100f257600080fd5b5061006b61010136600461091f565b610276565b34801561011257600080fd5b506100bd6102ba565b610123610347565b61013361012e610435565b61043f565b565b61013d610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816040518060200160405280600081525060006104a3565b50565b61018b61011b565b61019e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610219576102148383838080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250600192506104a3915050565b505050565b61021461011b565b600061022b610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610435565b905090565b61027361011b565b90565b61027e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816104ce565b60006102c4610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610463565b60606103248383604051806060016040528060278152602001610a576027913961052f565b9392505050565b73ffffffffffffffffffffffffffffffffffffffff163b151590565b61034f610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152604260248201527f5472616e73706172656e745570677261646561626c6550726f78793a2061646d60448201527f696e2063616e6e6f742066616c6c6261636b20746f2070726f7879207461726760648201527f6574000000000000000000000000000000000000000000000000000000000000608482015260a4015b60405180910390fd5b6000610266610657565b3660008037600080366000845af43d6000803e80801561045e573d6000f35b3d6000fd5b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b5473ffffffffffffffffffffffffffffffffffffffff16919050565b6104ac8361067f565b6000825111806104b95750805b15610214576104c883836102ff565b50505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6104f7610463565b6040805173ffffffffffffffffffffffffffffffffffffffff928316815291841660208301520160405180910390a161018b816106cc565b606073ffffffffffffffffffffffffffffffffffffffff84163b6105d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f60448201527f6e74726163740000000000000000000000000000000000000000000000000000606482015260840161042c565b6000808573ffffffffffffffffffffffffffffffffffffffff16856040516105fd91906109e9565b600060405180830381855af49150503d8060008114610638576040519150601f19603f3d011682016040523d82523d6000602084013e61063d565b606091505b509150915061064d8282866107d8565b9695505050505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610487565b6106888161082b565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b73ffffffffffffffffffffffffffffffffffffffff811661076f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201527f6464726573730000000000000000000000000000000000000000000000000000606482015260840161042c565b807fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff9290921691909117905550565b606083156107e7575081610324565b8251156107f75782518084602001fd5b816040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042c9190610a05565b73ffffffffffffffffffffffffffffffffffffffff81163b6108cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e747261637400000000000000000000000000000000000000606482015260840161042c565b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610792565b803573ffffffffffffffffffffffffffffffffffffffff8116811461091a57600080fd5b919050565b60006020828403121561093157600080fd5b610324826108f6565b60008060006040848603121561094f57600080fd5b610958846108f6565b9250602084013567ffffffffffffffff8082111561097557600080fd5b818601915086601f83011261098957600080fd5b81358181111561099857600080fd5b8760208285010111156109aa57600080fd5b6020830194508093505050509250925092565b60005b838110156109d85781810151838201526020016109c0565b838111156104c85750506000910152565b600082516109fb8184602087016109bd565b9190910192915050565b6020815260008251806020840152610a248160408501602087016109bd565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016919091016040019291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220b29caa54336b3ee836679675e9732ec5e526fb3f803cca2fe336cc3555aba62264736f6c634300080a0033b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564", + "deployedBytecode": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100a85780638f283970146100e6578063f851a440146101065761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61011b565b005b61006b61011b565b34801561008157600080fd5b5061006b61009036600461091f565b610135565b61006b6100a336600461093a565b610196565b3480156100b457600080fd5b506100bd610221565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b3480156100f257600080fd5b5061006b61010136600461091f565b610276565b34801561011257600080fd5b506100bd6102ba565b610123610347565b61013361012e610435565b61043f565b565b61013d610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816040518060200160405280600081525060006104a3565b50565b61018b61011b565b61019e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610219576102148383838080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250600192506104a3915050565b505050565b61021461011b565b600061022b610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610435565b905090565b61027361011b565b90565b61027e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816104ce565b60006102c4610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610463565b60606103248383604051806060016040528060278152602001610a576027913961052f565b9392505050565b73ffffffffffffffffffffffffffffffffffffffff163b151590565b61034f610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152604260248201527f5472616e73706172656e745570677261646561626c6550726f78793a2061646d60448201527f696e2063616e6e6f742066616c6c6261636b20746f2070726f7879207461726760648201527f6574000000000000000000000000000000000000000000000000000000000000608482015260a4015b60405180910390fd5b6000610266610657565b3660008037600080366000845af43d6000803e80801561045e573d6000f35b3d6000fd5b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b5473ffffffffffffffffffffffffffffffffffffffff16919050565b6104ac8361067f565b6000825111806104b95750805b15610214576104c883836102ff565b50505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6104f7610463565b6040805173ffffffffffffffffffffffffffffffffffffffff928316815291841660208301520160405180910390a161018b816106cc565b606073ffffffffffffffffffffffffffffffffffffffff84163b6105d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f60448201527f6e74726163740000000000000000000000000000000000000000000000000000606482015260840161042c565b6000808573ffffffffffffffffffffffffffffffffffffffff16856040516105fd91906109e9565b600060405180830381855af49150503d8060008114610638576040519150601f19603f3d011682016040523d82523d6000602084013e61063d565b606091505b509150915061064d8282866107d8565b9695505050505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610487565b6106888161082b565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b73ffffffffffffffffffffffffffffffffffffffff811661076f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201527f6464726573730000000000000000000000000000000000000000000000000000606482015260840161042c565b807fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff9290921691909117905550565b606083156107e7575081610324565b8251156107f75782518084602001fd5b816040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042c9190610a05565b73ffffffffffffffffffffffffffffffffffffffff81163b6108cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e747261637400000000000000000000000000000000000000606482015260840161042c565b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610792565b803573ffffffffffffffffffffffffffffffffffffffff8116811461091a57600080fd5b919050565b60006020828403121561093157600080fd5b610324826108f6565b60008060006040848603121561094f57600080fd5b610958846108f6565b9250602084013567ffffffffffffffff8082111561097557600080fd5b818601915086601f83011261098957600080fd5b81358181111561099857600080fd5b8760208285010111156109aa57600080fd5b6020830194508093505050509250925092565b60005b838110156109d85781810151838201526020016109c0565b838111156104c85750506000910152565b600082516109fb8184602087016109bd565b9190910192915050565b6020815260008251806020840152610a248160408501602087016109bd565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016919091016040019291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220b29caa54336b3ee836679675e9732ec5e526fb3f803cca2fe336cc3555aba62264736f6c634300080a0033", + "execute": { + "methodName": "initialize", + "args": [ + "0x49420311B518f3d0c94e897592014de53831cfA3", + "0xB1402333b12fc066C3D7F55d37944D5e281a3e8B", + "0x1155b614971f16758C92c4890eD338C9e3ede6b7" + ] + }, + "implementation": "0x986F1289B2E803B0bf7ac29b777bbAcBDb3dE872", + "devdoc": { + "details": "This contract implements a proxy that is upgradeable by an admin. To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector clashing], which can potentially be used in an attack, this contract uses the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two things that go hand in hand: 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches one of the admin functions exposed by the proxy itself. 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error that says \"admin cannot fallback to proxy target\". These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to call a function from the proxy implementation. Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.", + "kind": "dev", + "methods": { + "admin()": { + "details": "Returns the current admin. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`" + }, + "changeAdmin(address)": { + "details": "Changes the admin of the proxy. Emits an {AdminChanged} event. NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}." + }, + "constructor": { + "details": "Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}." + }, + "implementation()": { + "details": "Returns the current implementation. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`" + }, + "upgradeTo(address)": { + "details": "Upgrade the implementation of the proxy. NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}." + }, + "upgradeToAndCall(address,bytes)": { + "details": "Upgrade the implementation of the proxy, and then call a function from the new implementation as specified by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the proxied contract. NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}." + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3_Implementation.json b/packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3_Implementation.json new file mode 100644 index 0000000000..ed6ba6995c --- /dev/null +++ b/packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3_Implementation.json @@ -0,0 +1,1547 @@ +{ + "address": "0x986F1289B2E803B0bf7ac29b777bbAcBDb3dE872", + "abi": [ + { + "inputs": [ + { + "internalType": "enum ComptrollerErrorReporter.Error", + "name": "", + "type": "uint8" + } + ], + "name": "IonicMarketERC4626__CompoundError", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Deposit", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint8", + "name": "version", + "type": "uint8" + } + ], + "name": "Initialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldOwner", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "NewOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldPendingOwner", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newPendingOwner", + "type": "address" + } + ], + "name": "NewPendingOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Paused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Unpaused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "oldPerformanceFee", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "newPerformanceFee", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "oldFeeRecipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newFeeRecipient", + "type": "address" + } + ], + "name": "UpdatedFeeSettings", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldRewardsRecipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newRewardsRecipient", + "type": "address" + } + ], + "name": "UpdatedRewardsRecipient", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Withdraw", + "type": "event" + }, + { + "inputs": [], + "name": "_acceptOwner", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newPendingOwner", + "type": "address" + } + ], + "name": "_setPendingOwner", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "asset", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "cToken", + "outputs": [ + { + "internalType": "contract ICErc20", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "claimRewards", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "convertToAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "convertToShares", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "decimals", + "outputs": [ + { + "internalType": "uint8", + "name": "", + "type": "uint8" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "subtractedValue", + "type": "uint256" + } + ], + "name": "decreaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "deposit", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "emergencyWithdrawAndPause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "feeRecipient", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "flywheelLensRouter", + "outputs": [ + { + "internalType": "contract IonicFlywheelLensRouter_4626", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "addedValue", + "type": "uint256" + } + ], + "name": "increaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "contract ICErc20", + "name": "cToken_", + "type": "address" + }, + { + "internalType": "address", + "name": "flywheelLensRouter_", + "type": "address" + }, + { + "internalType": "address", + "name": "rewardsRecipient_", + "type": "address" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "mint", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "name", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "paused", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pendingOwner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "performanceFee", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "redeem", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "rewardsRecipient", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "market", + "type": "address" + } + ], + "name": "shutdown", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "symbol", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "takePerformanceFee", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "totalAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "unpause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "newPerformanceFee", + "type": "uint256" + }, + { + "internalType": "address", + "name": "newFeeRecipient", + "type": "address" + } + ], + "name": "updateFeeSettings", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newRewardsRecipient", + "type": "address" + } + ], + "name": "updateRewardsRecipient", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "vaultShareHWM", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "withdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "withdrawAccruedFees", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0xa59bc0e2c556a3072297b0499e95248ab0a32c23ab036042abde6b8542ffda2f", + "receipt": { + "to": null, + "from": "0x1155b614971f16758C92c4890eD338C9e3ede6b7", + "contractAddress": "0x986F1289B2E803B0bf7ac29b777bbAcBDb3dE872", + "transactionIndex": 162, + "gasUsed": "3107222", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xf66040764cd1a6d9f523602d98b10357da1ffd1b94b6ad35e4bfeed82fb8bb88", + "transactionHash": "0xa59bc0e2c556a3072297b0499e95248ab0a32c23ab036042abde6b8542ffda2f", + "logs": [], + "blockNumber": 25464411, + "cumulativeGasUsed": "33902401", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "34a0d1556aea7d4f3124b66dedee8846", + "metadata": "{\"compiler\":{\"version\":\"0.8.22+commit.4fc1097e\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"enum ComptrollerErrorReporter.Error\",\"name\":\"\",\"type\":\"uint8\"}],\"name\":\"IonicMarketERC4626__CompoundError\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"Deposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint8\",\"name\":\"version\",\"type\":\"uint8\"}],\"name\":\"Initialized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldOwner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"NewOwner\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldPendingOwner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newPendingOwner\",\"type\":\"address\"}],\"name\":\"NewPendingOwner\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"oldPerformanceFee\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"newPerformanceFee\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldFeeRecipient\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newFeeRecipient\",\"type\":\"address\"}],\"name\":\"UpdatedFeeSettings\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldRewardsRecipient\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newRewardsRecipient\",\"type\":\"address\"}],\"name\":\"UpdatedRewardsRecipient\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"Withdraw\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"_acceptOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newPendingOwner\",\"type\":\"address\"}],\"name\":\"_setPendingOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"asset\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"cToken\",\"outputs\":[{\"internalType\":\"contract ICErc20\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"claimRewards\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"convertToAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"convertToShares\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"emergencyWithdrawAndPause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"feeRecipient\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"flywheelLensRouter\",\"outputs\":[{\"internalType\":\"contract IonicFlywheelLensRouter_4626\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contract ICErc20\",\"name\":\"cToken_\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"flywheelLensRouter_\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"rewardsRecipient_\",\"type\":\"address\"}],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"maxDeposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"maxMint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"maxRedeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"maxWithdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"mint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pendingOwner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"performanceFee\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"previewDeposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"previewMint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"previewRedeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"previewWithdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"redeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"rewardsRecipient\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"market\",\"type\":\"address\"}],\"name\":\"shutdown\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"takePerformanceFee\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"newPerformanceFee\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"newFeeRecipient\",\"type\":\"address\"}],\"name\":\"updateFeeSettings\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newRewardsRecipient\",\"type\":\"address\"}],\"name\":\"updateRewardsRecipient\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"vaultShareHWM\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdrawAccruedFees\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"events\":{\"Approval(address,address,uint256)\":{\"details\":\"Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance.\"},\"Initialized(uint8)\":{\"details\":\"Triggered when the contract has been initialized or reinitialized.\"},\"Paused(address)\":{\"details\":\"Emitted when the pause is triggered by `account`.\"},\"Transfer(address,address,uint256)\":{\"details\":\"Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero.\"},\"Unpaused(address)\":{\"details\":\"Emitted when the pause is lifted by `account`.\"}},\"kind\":\"dev\",\"methods\":{\"_acceptOwner()\":{\"details\":\"Owner function for pending owner to accept role and update owner\"},\"_setPendingOwner(address)\":{\"details\":\"Owner function to begin change of owner. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\",\"params\":{\"newPendingOwner\":\"New pending owner.\"}},\"allowance(address,address)\":{\"details\":\"See {IERC20-allowance}.\"},\"approve(address,uint256)\":{\"details\":\"See {IERC20-approve}. NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address.\"},\"asset()\":{\"details\":\"See {IERC4626-asset}. \"},\"balanceOf(address)\":{\"details\":\"See {IERC20-balanceOf}.\"},\"convertToAssets(uint256)\":{\"details\":\"See {IERC4626-convertToAssets}. \"},\"convertToShares(uint256)\":{\"details\":\"See {IERC4626-convertToShares}. \"},\"decimals()\":{\"details\":\"Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value. See {IERC20Metadata-decimals}.\"},\"decreaseAllowance(address,uint256)\":{\"details\":\"Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`.\"},\"deposit(uint256,address)\":{\"details\":\"See {IERC4626-deposit}. \"},\"increaseAllowance(address,uint256)\":{\"details\":\"Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.\"},\"maxMint(address)\":{\"details\":\"accrue interest must be called before this function is called, otherwise an outdated value will be fetched, and the returned value will be incorrect (greater than actual amount available to be minted will be returned)\"},\"maxRedeem(address)\":{\"params\":{\"owner\":\"The address that owns the shares\"}},\"maxWithdraw(address)\":{\"params\":{\"owner\":\"The address that owns the shares\"}},\"mint(uint256,address)\":{\"details\":\"See {IERC4626-mint}. \"},\"name()\":{\"details\":\"Returns the name of the token.\"},\"owner()\":{\"details\":\"Returns the address of the current owner.\"},\"paused()\":{\"details\":\"Returns true if the contract is paused, and false otherwise.\"},\"previewDeposit(uint256)\":{\"details\":\"See {IERC4626-previewDeposit}. \"},\"previewMint(uint256)\":{\"details\":\"See {IERC4626-previewMint}. \"},\"previewRedeem(uint256)\":{\"details\":\"See {IERC4626-previewRedeem}. \"},\"previewWithdraw(uint256)\":{\"details\":\"See {IERC4626-previewWithdraw}. \"},\"redeem(uint256,address,address)\":{\"details\":\"See {IERC4626-redeem}. \"},\"renounceOwnership()\":{\"details\":\"Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner.\"},\"symbol()\":{\"details\":\"Returns the symbol of the token, usually a shorter version of the name.\"},\"takePerformanceFee()\":{\"details\":\"Performance fee is based on a vault share high water mark value. If vault share value has increased above the HWM in a fee period, issue fee shares to the vault equal to the performance fee.\"},\"totalAssets()\":{\"details\":\"See {IERC4626-totalAssets}. \"},\"totalSupply()\":{\"details\":\"See {IERC20-totalSupply}.\"},\"transfer(address,uint256)\":{\"details\":\"See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `amount`.\"},\"transferFrom(address,address,uint256)\":{\"details\":\"See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `amount`. - the caller must have allowance for ``from``'s tokens of at least `amount`.\"},\"transferOwnership(address)\":{\"details\":\"Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.\"},\"withdraw(uint256,address,address)\":{\"details\":\"See {IERC4626-withdraw}. \"},\"withdrawAccruedFees()\":{\"details\":\"We must make sure that feeRecipient is not address(0) before withdrawing fees\"}},\"version\":1},\"userdoc\":{\"events\":{\"NewOwner(address,address)\":{\"notice\":\"Emitted when pendingOwner is accepted, which means owner is updated\"},\"NewPendingOwner(address,address)\":{\"notice\":\"Emitted when pendingOwner is changed\"}},\"kind\":\"user\",\"methods\":{\"_acceptOwner()\":{\"notice\":\"Accepts transfer of owner rights. msg.sender must be pendingOwner\"},\"_setPendingOwner(address)\":{\"notice\":\"Begins transfer of owner rights. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\"},\"maxDeposit(address)\":{\"notice\":\"maximum amount of underlying tokens that can be deposited into the underlying protocol\"},\"maxMint(address)\":{\"notice\":\"Returns the maximum amount of tokens that can be supplied no way for this function to ever revert unless comptroller or mToken is broken\"},\"maxRedeem(address)\":{\"notice\":\"maximum amount of shares that can be withdrawn\"},\"maxWithdraw(address)\":{\"notice\":\"maximum amount of underlying tokens that can be withdrawn\"},\"pendingOwner()\":{\"notice\":\"Pending owner of this contract\"},\"takePerformanceFee()\":{\"notice\":\"Take the performance fee that has accrued since last fee harvest.\"},\"updateFeeSettings(uint256,address)\":{\"notice\":\"Update performanceFee and/or feeRecipient\"},\"withdrawAccruedFees()\":{\"notice\":\"Transfer accrued fees to rewards manager contract. Caller must be a registered keeper.\"}},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/src/ionic/strategies/IonicMarketERC4626.sol\":\"IonicMarketERC4626\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../utils/ContextUpgradeable.sol\\\";\\nimport \\\"../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Contract module which provides a basic access control mechanism, where\\n * there is an account (an owner) that can be granted exclusive access to\\n * specific functions.\\n *\\n * By default, the owner account will be the one that deploys the contract. This\\n * can later be changed with {transferOwnership}.\\n *\\n * This module is used through inheritance. It will make available the modifier\\n * `onlyOwner`, which can be applied to your functions to restrict their use to\\n * the owner.\\n */\\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\\n address private _owner;\\n\\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\\n\\n /**\\n * @dev Initializes the contract setting the deployer as the initial owner.\\n */\\n function __Ownable_init() internal onlyInitializing {\\n __Ownable_init_unchained();\\n }\\n\\n function __Ownable_init_unchained() internal onlyInitializing {\\n _transferOwnership(_msgSender());\\n }\\n\\n /**\\n * @dev Throws if called by any account other than the owner.\\n */\\n modifier onlyOwner() {\\n _checkOwner();\\n _;\\n }\\n\\n /**\\n * @dev Returns the address of the current owner.\\n */\\n function owner() public view virtual returns (address) {\\n return _owner;\\n }\\n\\n /**\\n * @dev Throws if the sender is not the owner.\\n */\\n function _checkOwner() internal view virtual {\\n require(owner() == _msgSender(), \\\"Ownable: caller is not the owner\\\");\\n }\\n\\n /**\\n * @dev Leaves the contract without owner. It will not be possible to call\\n * `onlyOwner` functions anymore. Can only be called by the current owner.\\n *\\n * NOTE: Renouncing ownership will leave the contract without an owner,\\n * thereby removing any functionality that is only available to the owner.\\n */\\n function renounceOwnership() public virtual onlyOwner {\\n _transferOwnership(address(0));\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Can only be called by the current owner.\\n */\\n function transferOwnership(address newOwner) public virtual onlyOwner {\\n require(newOwner != address(0), \\\"Ownable: new owner is the zero address\\\");\\n _transferOwnership(newOwner);\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Internal function without access restriction.\\n */\\n function _transferOwnership(address newOwner) internal virtual {\\n address oldOwner = _owner;\\n _owner = newOwner;\\n emit OwnershipTransferred(oldOwner, newOwner);\\n }\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[49] private __gap;\\n}\\n\",\"keccak256\":\"0x247c62047745915c0af6b955470a72d1696ebad4352d7d3011aef1a2463cd888\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/interfaces/IERC4626Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC4626.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../token/ERC20/IERC20Upgradeable.sol\\\";\\nimport \\\"../token/ERC20/extensions/IERC20MetadataUpgradeable.sol\\\";\\n\\n/**\\n * @dev Interface of the ERC4626 \\\"Tokenized Vault Standard\\\", as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\\n *\\n * _Available since v4.7._\\n */\\ninterface IERC4626Upgradeable is IERC20Upgradeable, IERC20MetadataUpgradeable {\\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\\n\\n event Withdraw(\\n address indexed sender,\\n address indexed receiver,\\n address indexed owner,\\n uint256 assets,\\n uint256 shares\\n );\\n\\n /**\\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\\n *\\n * - MUST be an ERC-20 token contract.\\n * - MUST NOT revert.\\n */\\n function asset() external view returns (address assetTokenAddress);\\n\\n /**\\n * @dev Returns the total amount of the underlying asset that is \\u201cmanaged\\u201d by Vault.\\n *\\n * - SHOULD include any compounding that occurs from yield.\\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT revert.\\n */\\n function totalAssets() external view returns (uint256 totalManagedAssets);\\n\\n /**\\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToShares(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\\n * through a deposit call.\\n *\\n * - MUST return a limited value if receiver is subject to some deposit limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\\n * - MUST NOT revert.\\n */\\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\\n * in the same transaction.\\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * deposit execution, and are accounted for during deposit.\\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\\n * - MUST return a limited value if receiver is subject to some mint limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\\n * - MUST NOT revert.\\n */\\n function maxMint(address receiver) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\\n * same transaction.\\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\\n * would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\\n */\\n function previewMint(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\\n * execution, and are accounted for during mint.\\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\\n * Vault, through a withdraw call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\\n * called\\n * in the same transaction.\\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * withdraw execution, and are accounted for during withdraw.\\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function withdraw(\\n uint256 assets,\\n address receiver,\\n address owner\\n ) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\\n * through a redeem call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxRedeem(address owner) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\\n * same transaction.\\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\\n * redemption would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\\n */\\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * redeem execution, and are accounted for during redeem.\\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function redeem(\\n uint256 shares,\\n address receiver,\\n address owner\\n ) external returns (uint256 assets);\\n}\\n\",\"keccak256\":\"0xe3d54e1a1a10fbc86fdfaf9100ba99c9c808588fd20d0c919457b903b5cae61a\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\\n\\npragma solidity ^0.8.2;\\n\\nimport \\\"../../utils/AddressUpgradeable.sol\\\";\\n\\n/**\\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\\n *\\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\\n * reused. This mechanism prevents re-execution of each \\\"step\\\" but allows the creation of new initialization steps in\\n * case an upgrade adds a module that needs to be initialized.\\n *\\n * For example:\\n *\\n * [.hljs-theme-light.nopadding]\\n * ```\\n * contract MyToken is ERC20Upgradeable {\\n * function initialize() initializer public {\\n * __ERC20_init(\\\"MyToken\\\", \\\"MTK\\\");\\n * }\\n * }\\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\\n * function initializeV2() reinitializer(2) public {\\n * __ERC20Permit_init(\\\"MyToken\\\");\\n * }\\n * }\\n * ```\\n *\\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\\n *\\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\\n *\\n * [CAUTION]\\n * ====\\n * Avoid leaving a contract uninitialized.\\n *\\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\\n *\\n * [.hljs-theme-light.nopadding]\\n * ```\\n * /// @custom:oz-upgrades-unsafe-allow constructor\\n * constructor() {\\n * _disableInitializers();\\n * }\\n * ```\\n * ====\\n */\\nabstract contract Initializable {\\n /**\\n * @dev Indicates that the contract has been initialized.\\n * @custom:oz-retyped-from bool\\n */\\n uint8 private _initialized;\\n\\n /**\\n * @dev Indicates that the contract is in the process of being initialized.\\n */\\n bool private _initializing;\\n\\n /**\\n * @dev Triggered when the contract has been initialized or reinitialized.\\n */\\n event Initialized(uint8 version);\\n\\n /**\\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\\n * `onlyInitializing` functions can be used to initialize parent contracts.\\n *\\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\\n * constructor.\\n *\\n * Emits an {Initialized} event.\\n */\\n modifier initializer() {\\n bool isTopLevelCall = !_initializing;\\n require(\\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\\n \\\"Initializable: contract is already initialized\\\"\\n );\\n _initialized = 1;\\n if (isTopLevelCall) {\\n _initializing = true;\\n }\\n _;\\n if (isTopLevelCall) {\\n _initializing = false;\\n emit Initialized(1);\\n }\\n }\\n\\n /**\\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\\n * used to initialize parent contracts.\\n *\\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\\n * are added through upgrades and that require initialization.\\n *\\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\\n * cannot be nested. If one is invoked in the context of another, execution will revert.\\n *\\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\\n * a contract, executing them in the right order is up to the developer or operator.\\n *\\n * WARNING: setting the version to 255 will prevent any future reinitialization.\\n *\\n * Emits an {Initialized} event.\\n */\\n modifier reinitializer(uint8 version) {\\n require(!_initializing && _initialized < version, \\\"Initializable: contract is already initialized\\\");\\n _initialized = version;\\n _initializing = true;\\n _;\\n _initializing = false;\\n emit Initialized(version);\\n }\\n\\n /**\\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\\n */\\n modifier onlyInitializing() {\\n require(_initializing, \\\"Initializable: contract is not initializing\\\");\\n _;\\n }\\n\\n /**\\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\\n * through proxies.\\n *\\n * Emits an {Initialized} event the first time it is successfully executed.\\n */\\n function _disableInitializers() internal virtual {\\n require(!_initializing, \\\"Initializable: contract is initializing\\\");\\n if (_initialized < type(uint8).max) {\\n _initialized = type(uint8).max;\\n emit Initialized(type(uint8).max);\\n }\\n }\\n\\n /**\\n * @dev Internal function that returns the initialized version. Returns `_initialized`\\n */\\n function _getInitializedVersion() internal view returns (uint8) {\\n return _initialized;\\n }\\n\\n /**\\n * @dev Internal function that returns the initialized version. Returns `_initializing`\\n */\\n function _isInitializing() internal view returns (bool) {\\n return _initializing;\\n }\\n}\\n\",\"keccak256\":\"0x6c2b54ec184943843041ab77f61988b5060f6f03acbfe92cdc125f95f00891da\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/security/PausableUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../utils/ContextUpgradeable.sol\\\";\\nimport \\\"../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Contract module which allows children to implement an emergency stop\\n * mechanism that can be triggered by an authorized account.\\n *\\n * This module is used through inheritance. It will make available the\\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\\n * the functions of your contract. Note that they will not be pausable by\\n * simply including this module, only once the modifiers are put in place.\\n */\\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\\n /**\\n * @dev Emitted when the pause is triggered by `account`.\\n */\\n event Paused(address account);\\n\\n /**\\n * @dev Emitted when the pause is lifted by `account`.\\n */\\n event Unpaused(address account);\\n\\n bool private _paused;\\n\\n /**\\n * @dev Initializes the contract in unpaused state.\\n */\\n function __Pausable_init() internal onlyInitializing {\\n __Pausable_init_unchained();\\n }\\n\\n function __Pausable_init_unchained() internal onlyInitializing {\\n _paused = false;\\n }\\n\\n /**\\n * @dev Modifier to make a function callable only when the contract is not paused.\\n *\\n * Requirements:\\n *\\n * - The contract must not be paused.\\n */\\n modifier whenNotPaused() {\\n _requireNotPaused();\\n _;\\n }\\n\\n /**\\n * @dev Modifier to make a function callable only when the contract is paused.\\n *\\n * Requirements:\\n *\\n * - The contract must be paused.\\n */\\n modifier whenPaused() {\\n _requirePaused();\\n _;\\n }\\n\\n /**\\n * @dev Returns true if the contract is paused, and false otherwise.\\n */\\n function paused() public view virtual returns (bool) {\\n return _paused;\\n }\\n\\n /**\\n * @dev Throws if the contract is paused.\\n */\\n function _requireNotPaused() internal view virtual {\\n require(!paused(), \\\"Pausable: paused\\\");\\n }\\n\\n /**\\n * @dev Throws if the contract is not paused.\\n */\\n function _requirePaused() internal view virtual {\\n require(paused(), \\\"Pausable: not paused\\\");\\n }\\n\\n /**\\n * @dev Triggers stopped state.\\n *\\n * Requirements:\\n *\\n * - The contract must not be paused.\\n */\\n function _pause() internal virtual whenNotPaused {\\n _paused = true;\\n emit Paused(_msgSender());\\n }\\n\\n /**\\n * @dev Returns to normal state.\\n *\\n * Requirements:\\n *\\n * - The contract must be paused.\\n */\\n function _unpause() internal virtual whenPaused {\\n _paused = false;\\n emit Unpaused(_msgSender());\\n }\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[49] private __gap;\\n}\\n\",\"keccak256\":\"0x40c636b4572ff5f1dc50cf22097e93c0723ee14eff87e99ac2b02636eeca1250\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"./IERC20Upgradeable.sol\\\";\\nimport \\\"./extensions/IERC20MetadataUpgradeable.sol\\\";\\nimport \\\"../../utils/ContextUpgradeable.sol\\\";\\nimport \\\"../../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Implementation of the {IERC20} interface.\\n *\\n * This implementation is agnostic to the way tokens are created. This means\\n * that a supply mechanism has to be added in a derived contract using {_mint}.\\n * For a generic mechanism see {ERC20PresetMinterPauser}.\\n *\\n * TIP: For a detailed writeup see our guide\\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\\n * to implement supply mechanisms].\\n *\\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\\n * instead returning `false` on failure. This behavior is nonetheless\\n * conventional and does not conflict with the expectations of ERC20\\n * applications.\\n *\\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\\n * This allows applications to reconstruct the allowance for all accounts just\\n * by listening to said events. Other implementations of the EIP may not emit\\n * these events, as it isn't required by the specification.\\n *\\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\\n * functions have been added to mitigate the well-known issues around setting\\n * allowances. See {IERC20-approve}.\\n */\\ncontract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\\n mapping(address => uint256) private _balances;\\n\\n mapping(address => mapping(address => uint256)) private _allowances;\\n\\n uint256 private _totalSupply;\\n\\n string private _name;\\n string private _symbol;\\n\\n /**\\n * @dev Sets the values for {name} and {symbol}.\\n *\\n * The default value of {decimals} is 18. To select a different value for\\n * {decimals} you should overload it.\\n *\\n * All two of these values are immutable: they can only be set once during\\n * construction.\\n */\\n function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\\n __ERC20_init_unchained(name_, symbol_);\\n }\\n\\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\\n _name = name_;\\n _symbol = symbol_;\\n }\\n\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() public view virtual override returns (string memory) {\\n return _name;\\n }\\n\\n /**\\n * @dev Returns the symbol of the token, usually a shorter version of the\\n * name.\\n */\\n function symbol() public view virtual override returns (string memory) {\\n return _symbol;\\n }\\n\\n /**\\n * @dev Returns the number of decimals used to get its user representation.\\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\\n *\\n * Tokens usually opt for a value of 18, imitating the relationship between\\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\\n * overridden;\\n *\\n * NOTE: This information is only used for _display_ purposes: it in\\n * no way affects any of the arithmetic of the contract, including\\n * {IERC20-balanceOf} and {IERC20-transfer}.\\n */\\n function decimals() public view virtual override returns (uint8) {\\n return 18;\\n }\\n\\n /**\\n * @dev See {IERC20-totalSupply}.\\n */\\n function totalSupply() public view virtual override returns (uint256) {\\n return _totalSupply;\\n }\\n\\n /**\\n * @dev See {IERC20-balanceOf}.\\n */\\n function balanceOf(address account) public view virtual override returns (uint256) {\\n return _balances[account];\\n }\\n\\n /**\\n * @dev See {IERC20-transfer}.\\n *\\n * Requirements:\\n *\\n * - `to` cannot be the zero address.\\n * - the caller must have a balance of at least `amount`.\\n */\\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\\n address owner = _msgSender();\\n _transfer(owner, to, amount);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-allowance}.\\n */\\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\\n return _allowances[owner][spender];\\n }\\n\\n /**\\n * @dev See {IERC20-approve}.\\n *\\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\\n * `transferFrom`. This is semantically equivalent to an infinite approval.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n */\\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\\n address owner = _msgSender();\\n _approve(owner, spender, amount);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-transferFrom}.\\n *\\n * Emits an {Approval} event indicating the updated allowance. This is not\\n * required by the EIP. See the note at the beginning of {ERC20}.\\n *\\n * NOTE: Does not update the allowance if the current allowance\\n * is the maximum `uint256`.\\n *\\n * Requirements:\\n *\\n * - `from` and `to` cannot be the zero address.\\n * - `from` must have a balance of at least `amount`.\\n * - the caller must have allowance for ``from``'s tokens of at least\\n * `amount`.\\n */\\n function transferFrom(\\n address from,\\n address to,\\n uint256 amount\\n ) public virtual override returns (bool) {\\n address spender = _msgSender();\\n _spendAllowance(from, spender, amount);\\n _transfer(from, to, amount);\\n return true;\\n }\\n\\n /**\\n * @dev Atomically increases the allowance granted to `spender` by the caller.\\n *\\n * This is an alternative to {approve} that can be used as a mitigation for\\n * problems described in {IERC20-approve}.\\n *\\n * Emits an {Approval} event indicating the updated allowance.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n */\\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\\n address owner = _msgSender();\\n _approve(owner, spender, allowance(owner, spender) + addedValue);\\n return true;\\n }\\n\\n /**\\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\\n *\\n * This is an alternative to {approve} that can be used as a mitigation for\\n * problems described in {IERC20-approve}.\\n *\\n * Emits an {Approval} event indicating the updated allowance.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n * - `spender` must have allowance for the caller of at least\\n * `subtractedValue`.\\n */\\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\\n address owner = _msgSender();\\n uint256 currentAllowance = allowance(owner, spender);\\n require(currentAllowance >= subtractedValue, \\\"ERC20: decreased allowance below zero\\\");\\n unchecked {\\n _approve(owner, spender, currentAllowance - subtractedValue);\\n }\\n\\n return true;\\n }\\n\\n /**\\n * @dev Moves `amount` of tokens from `from` to `to`.\\n *\\n * This internal function is equivalent to {transfer}, and can be used to\\n * e.g. implement automatic token fees, slashing mechanisms, etc.\\n *\\n * Emits a {Transfer} event.\\n *\\n * Requirements:\\n *\\n * - `from` cannot be the zero address.\\n * - `to` cannot be the zero address.\\n * - `from` must have a balance of at least `amount`.\\n */\\n function _transfer(\\n address from,\\n address to,\\n uint256 amount\\n ) internal virtual {\\n require(from != address(0), \\\"ERC20: transfer from the zero address\\\");\\n require(to != address(0), \\\"ERC20: transfer to the zero address\\\");\\n\\n _beforeTokenTransfer(from, to, amount);\\n\\n uint256 fromBalance = _balances[from];\\n require(fromBalance >= amount, \\\"ERC20: transfer amount exceeds balance\\\");\\n unchecked {\\n _balances[from] = fromBalance - amount;\\n // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\\n // decrementing then incrementing.\\n _balances[to] += amount;\\n }\\n\\n emit Transfer(from, to, amount);\\n\\n _afterTokenTransfer(from, to, amount);\\n }\\n\\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\\n * the total supply.\\n *\\n * Emits a {Transfer} event with `from` set to the zero address.\\n *\\n * Requirements:\\n *\\n * - `account` cannot be the zero address.\\n */\\n function _mint(address account, uint256 amount) internal virtual {\\n require(account != address(0), \\\"ERC20: mint to the zero address\\\");\\n\\n _beforeTokenTransfer(address(0), account, amount);\\n\\n _totalSupply += amount;\\n unchecked {\\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\\n _balances[account] += amount;\\n }\\n emit Transfer(address(0), account, amount);\\n\\n _afterTokenTransfer(address(0), account, amount);\\n }\\n\\n /**\\n * @dev Destroys `amount` tokens from `account`, reducing the\\n * total supply.\\n *\\n * Emits a {Transfer} event with `to` set to the zero address.\\n *\\n * Requirements:\\n *\\n * - `account` cannot be the zero address.\\n * - `account` must have at least `amount` tokens.\\n */\\n function _burn(address account, uint256 amount) internal virtual {\\n require(account != address(0), \\\"ERC20: burn from the zero address\\\");\\n\\n _beforeTokenTransfer(account, address(0), amount);\\n\\n uint256 accountBalance = _balances[account];\\n require(accountBalance >= amount, \\\"ERC20: burn amount exceeds balance\\\");\\n unchecked {\\n _balances[account] = accountBalance - amount;\\n // Overflow not possible: amount <= accountBalance <= totalSupply.\\n _totalSupply -= amount;\\n }\\n\\n emit Transfer(account, address(0), amount);\\n\\n _afterTokenTransfer(account, address(0), amount);\\n }\\n\\n /**\\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\\n *\\n * This internal function is equivalent to `approve`, and can be used to\\n * e.g. set automatic allowances for certain subsystems, etc.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `owner` cannot be the zero address.\\n * - `spender` cannot be the zero address.\\n */\\n function _approve(\\n address owner,\\n address spender,\\n uint256 amount\\n ) internal virtual {\\n require(owner != address(0), \\\"ERC20: approve from the zero address\\\");\\n require(spender != address(0), \\\"ERC20: approve to the zero address\\\");\\n\\n _allowances[owner][spender] = amount;\\n emit Approval(owner, spender, amount);\\n }\\n\\n /**\\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\\n *\\n * Does not update the allowance amount in case of infinite allowance.\\n * Revert if not enough allowance is available.\\n *\\n * Might emit an {Approval} event.\\n */\\n function _spendAllowance(\\n address owner,\\n address spender,\\n uint256 amount\\n ) internal virtual {\\n uint256 currentAllowance = allowance(owner, spender);\\n if (currentAllowance != type(uint256).max) {\\n require(currentAllowance >= amount, \\\"ERC20: insufficient allowance\\\");\\n unchecked {\\n _approve(owner, spender, currentAllowance - amount);\\n }\\n }\\n }\\n\\n /**\\n * @dev Hook that is called before any transfer of tokens. This includes\\n * minting and burning.\\n *\\n * Calling conditions:\\n *\\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\\n * will be transferred to `to`.\\n * - when `from` is zero, `amount` tokens will be minted for `to`.\\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\\n * - `from` and `to` are never both zero.\\n *\\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\\n */\\n function _beforeTokenTransfer(\\n address from,\\n address to,\\n uint256 amount\\n ) internal virtual {}\\n\\n /**\\n * @dev Hook that is called after any transfer of tokens. This includes\\n * minting and burning.\\n *\\n * Calling conditions:\\n *\\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\\n * has been transferred to `to`.\\n * - when `from` is zero, `amount` tokens have been minted for `to`.\\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\\n * - `from` and `to` are never both zero.\\n *\\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\\n */\\n function _afterTokenTransfer(\\n address from,\\n address to,\\n uint256 amount\\n ) internal virtual {}\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[45] private __gap;\\n}\\n\",\"keccak256\":\"0x17aff86be546601617585e91fd98aad74cf39f1be65d8eb6f93b7f3c30181275\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Interface of the ERC20 standard as defined in the EIP.\\n */\\ninterface IERC20Upgradeable {\\n /**\\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\\n * another (`to`).\\n *\\n * Note that `value` may be zero.\\n */\\n event Transfer(address indexed from, address indexed to, uint256 value);\\n\\n /**\\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\\n * a call to {approve}. `value` is the new allowance.\\n */\\n event Approval(address indexed owner, address indexed spender, uint256 value);\\n\\n /**\\n * @dev Returns the amount of tokens in existence.\\n */\\n function totalSupply() external view returns (uint256);\\n\\n /**\\n * @dev Returns the amount of tokens owned by `account`.\\n */\\n function balanceOf(address account) external view returns (uint256);\\n\\n /**\\n * @dev Moves `amount` tokens from the caller's account to `to`.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transfer(address to, uint256 amount) external returns (bool);\\n\\n /**\\n * @dev Returns the remaining number of tokens that `spender` will be\\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\\n * zero by default.\\n *\\n * This value changes when {approve} or {transferFrom} are called.\\n */\\n function allowance(address owner, address spender) external view returns (uint256);\\n\\n /**\\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\\n * that someone may use both the old and the new allowance by unfortunate\\n * transaction ordering. One possible solution to mitigate this race\\n * condition is to first reduce the spender's allowance to 0 and set the\\n * desired value afterwards:\\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\\n *\\n * Emits an {Approval} event.\\n */\\n function approve(address spender, uint256 amount) external returns (bool);\\n\\n /**\\n * @dev Moves `amount` tokens from `from` to `to` using the\\n * allowance mechanism. `amount` is then deducted from the caller's\\n * allowance.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transferFrom(\\n address from,\\n address to,\\n uint256 amount\\n ) external returns (bool);\\n}\\n\",\"keccak256\":\"0x4e733d3164f73f461eaf9d8087a7ad1ea180bdc8ba0d3d61b0e1ae16d8e63dff\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/extensions/ERC4626.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../ERC20Upgradeable.sol\\\";\\nimport \\\"../utils/SafeERC20Upgradeable.sol\\\";\\nimport \\\"../../../interfaces/IERC4626Upgradeable.sol\\\";\\nimport \\\"../../../utils/math/MathUpgradeable.sol\\\";\\nimport \\\"../../../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Implementation of the ERC4626 \\\"Tokenized Vault Standard\\\" as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\\n *\\n * This extension allows the minting and burning of \\\"shares\\\" (represented using the ERC20 inheritance) in exchange for\\n * underlying \\\"assets\\\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\\n * the ERC20 standard. Any additional extensions included along it would affect the \\\"shares\\\" token represented by this\\n * contract and not the \\\"assets\\\" token which is an independent contract.\\n *\\n * CAUTION: Deposits and withdrawals may incur unexpected slippage. Users should verify that the amount received of\\n * shares or assets is as expected. EOAs should operate through a wrapper that performs these checks such as\\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\\n *\\n * _Available since v4.7._\\n */\\nabstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626Upgradeable {\\n using MathUpgradeable for uint256;\\n\\n IERC20Upgradeable private _asset;\\n uint8 private _decimals;\\n\\n /**\\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\\n */\\n function __ERC4626_init(IERC20Upgradeable asset_) internal onlyInitializing {\\n __ERC4626_init_unchained(asset_);\\n }\\n\\n function __ERC4626_init_unchained(IERC20Upgradeable asset_) internal onlyInitializing {\\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\\n _decimals = success ? assetDecimals : super.decimals();\\n _asset = asset_;\\n }\\n\\n /**\\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\\n */\\n function _tryGetAssetDecimals(IERC20Upgradeable asset_) private returns (bool, uint8) {\\n (bool success, bytes memory encodedDecimals) = address(asset_).call(\\n abi.encodeWithSelector(IERC20MetadataUpgradeable.decimals.selector)\\n );\\n if (success && encodedDecimals.length >= 32) {\\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\\n if (returnedDecimals <= type(uint8).max) {\\n return (true, uint8(returnedDecimals));\\n }\\n }\\n return (false, 0);\\n }\\n\\n /**\\n * @dev Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset\\n * has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on\\n * inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value.\\n * See {IERC20Metadata-decimals}.\\n */\\n function decimals() public view virtual override(IERC20MetadataUpgradeable, ERC20Upgradeable) returns (uint8) {\\n return _decimals;\\n }\\n\\n /** @dev See {IERC4626-asset}. */\\n function asset() public view virtual override returns (address) {\\n return address(_asset);\\n }\\n\\n /** @dev See {IERC4626-totalAssets}. */\\n function totalAssets() public view virtual override returns (uint256) {\\n return _asset.balanceOf(address(this));\\n }\\n\\n /** @dev See {IERC4626-convertToShares}. */\\n function convertToShares(uint256 assets) public view virtual override returns (uint256 shares) {\\n return _convertToShares(assets, MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-convertToAssets}. */\\n function convertToAssets(uint256 shares) public view virtual override returns (uint256 assets) {\\n return _convertToAssets(shares, MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-maxDeposit}. */\\n function maxDeposit(address) public view virtual override returns (uint256) {\\n return _isVaultCollateralized() ? type(uint256).max : 0;\\n }\\n\\n /** @dev See {IERC4626-maxMint}. */\\n function maxMint(address) public view virtual override returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxWithdraw}. */\\n function maxWithdraw(address owner) public view virtual override returns (uint256) {\\n return _convertToAssets(balanceOf(owner), MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-maxRedeem}. */\\n function maxRedeem(address owner) public view virtual override returns (uint256) {\\n return balanceOf(owner);\\n }\\n\\n /** @dev See {IERC4626-previewDeposit}. */\\n function previewDeposit(uint256 assets) public view virtual override returns (uint256) {\\n return _convertToShares(assets, MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-previewMint}. */\\n function previewMint(uint256 shares) public view virtual override returns (uint256) {\\n return _convertToAssets(shares, MathUpgradeable.Rounding.Up);\\n }\\n\\n /** @dev See {IERC4626-previewWithdraw}. */\\n function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {\\n return _convertToShares(assets, MathUpgradeable.Rounding.Up);\\n }\\n\\n /** @dev See {IERC4626-previewRedeem}. */\\n function previewRedeem(uint256 shares) public view virtual override returns (uint256) {\\n return _convertToAssets(shares, MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-deposit}. */\\n function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {\\n require(assets <= maxDeposit(receiver), \\\"ERC4626: deposit more than max\\\");\\n\\n uint256 shares = previewDeposit(assets);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-mint}. */\\n function mint(uint256 shares, address receiver) public virtual override returns (uint256) {\\n require(shares <= maxMint(receiver), \\\"ERC4626: mint more than max\\\");\\n\\n uint256 assets = previewMint(shares);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return assets;\\n }\\n\\n /** @dev See {IERC4626-withdraw}. */\\n function withdraw(\\n uint256 assets,\\n address receiver,\\n address owner\\n ) public virtual override returns (uint256) {\\n require(assets <= maxWithdraw(owner), \\\"ERC4626: withdraw more than max\\\");\\n\\n uint256 shares = previewWithdraw(assets);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-redeem}. */\\n function redeem(\\n uint256 shares,\\n address receiver,\\n address owner\\n ) public virtual override returns (uint256) {\\n require(shares <= maxRedeem(owner), \\\"ERC4626: redeem more than max\\\");\\n\\n uint256 assets = previewRedeem(shares);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return assets;\\n }\\n\\n /**\\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\\n *\\n * Will revert if assets > 0, totalSupply > 0 and totalAssets = 0. That corresponds to a case where any asset\\n * would represent an infinite amount of shares.\\n */\\n function _convertToShares(uint256 assets, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256 shares) {\\n uint256 supply = totalSupply();\\n return\\n (assets == 0 || supply == 0)\\n ? _initialConvertToShares(assets, rounding)\\n : assets.mulDiv(supply, totalAssets(), rounding);\\n }\\n\\n /**\\n * @dev Internal conversion function (from assets to shares) to apply when the vault is empty.\\n *\\n * NOTE: Make sure to keep this function consistent with {_initialConvertToAssets} when overriding it.\\n */\\n function _initialConvertToShares(\\n uint256 assets,\\n MathUpgradeable.Rounding /*rounding*/\\n ) internal view virtual returns (uint256 shares) {\\n return assets;\\n }\\n\\n /**\\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\\n */\\n function _convertToAssets(uint256 shares, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256 assets) {\\n uint256 supply = totalSupply();\\n return\\n (supply == 0) ? _initialConvertToAssets(shares, rounding) : shares.mulDiv(totalAssets(), supply, rounding);\\n }\\n\\n /**\\n * @dev Internal conversion function (from shares to assets) to apply when the vault is empty.\\n *\\n * NOTE: Make sure to keep this function consistent with {_initialConvertToShares} when overriding it.\\n */\\n function _initialConvertToAssets(\\n uint256 shares,\\n MathUpgradeable.Rounding /*rounding*/\\n ) internal view virtual returns (uint256 assets) {\\n return shares;\\n }\\n\\n /**\\n * @dev Deposit/mint common workflow.\\n */\\n function _deposit(\\n address caller,\\n address receiver,\\n uint256 assets,\\n uint256 shares\\n ) internal virtual {\\n // If _asset is ERC777, `transferFrom` can trigger a reenterancy BEFORE the transfer happens through the\\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\\n // assets are transferred and before the shares are minted, which is a valid state.\\n // slither-disable-next-line reentrancy-no-eth\\n SafeERC20Upgradeable.safeTransferFrom(_asset, caller, address(this), assets);\\n _mint(receiver, shares);\\n\\n emit Deposit(caller, receiver, assets, shares);\\n }\\n\\n /**\\n * @dev Withdraw/redeem common workflow.\\n */\\n function _withdraw(\\n address caller,\\n address receiver,\\n address owner,\\n uint256 assets,\\n uint256 shares\\n ) internal virtual {\\n if (caller != owner) {\\n _spendAllowance(owner, caller, shares);\\n }\\n\\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\\n // shares are burned and after the assets are transferred, which is a valid state.\\n _burn(owner, shares);\\n SafeERC20Upgradeable.safeTransfer(_asset, receiver, assets);\\n\\n emit Withdraw(caller, receiver, owner, assets, shares);\\n }\\n\\n function _isVaultCollateralized() private view returns (bool) {\\n return totalAssets() > 0 || totalSupply() == 0;\\n }\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[49] private __gap;\\n}\\n\",\"keccak256\":\"0x82dd1556d6774b8bdaec0fb70d09c9d9cb0d75e9f2ffc183bb09a16b86d7c598\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../IERC20Upgradeable.sol\\\";\\n\\n/**\\n * @dev Interface for the optional metadata functions from the ERC20 standard.\\n *\\n * _Available since v4.1._\\n */\\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() external view returns (string memory);\\n\\n /**\\n * @dev Returns the symbol of the token.\\n */\\n function symbol() external view returns (string memory);\\n\\n /**\\n * @dev Returns the decimals places of the token.\\n */\\n function decimals() external view returns (uint8);\\n}\\n\",\"keccak256\":\"0x605434219ebbe4653f703640f06969faa5a1d78f0bfef878e5ddbb1ca369ceeb\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\\n *\\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\\n * need to send a transaction, and thus is not required to hold Ether at all.\\n */\\ninterface IERC20PermitUpgradeable {\\n /**\\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\\n * given ``owner``'s signed approval.\\n *\\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\\n * ordering also apply here.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n * - `deadline` must be a timestamp in the future.\\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\\n * over the EIP712-formatted function arguments.\\n * - the signature must use ``owner``'s current nonce (see {nonces}).\\n *\\n * For more information on the signature format, see the\\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\\n * section].\\n */\\n function permit(\\n address owner,\\n address spender,\\n uint256 value,\\n uint256 deadline,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) external;\\n\\n /**\\n * @dev Returns the current nonce for `owner`. This value must be\\n * included whenever a signature is generated for {permit}.\\n *\\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\\n * prevents a signature from being used multiple times.\\n */\\n function nonces(address owner) external view returns (uint256);\\n\\n /**\\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\\n */\\n // solhint-disable-next-line func-name-mixedcase\\n function DOMAIN_SEPARATOR() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0xcc70d8e2281fb3ff69e8ab242500f10142cd0a7fa8dd9e45882be270d4d09024\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../IERC20Upgradeable.sol\\\";\\nimport \\\"../extensions/draft-IERC20PermitUpgradeable.sol\\\";\\nimport \\\"../../../utils/AddressUpgradeable.sol\\\";\\n\\n/**\\n * @title SafeERC20\\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\\n * contract returns false). Tokens that return no value (and instead revert or\\n * throw on failure) are also supported, non-reverting calls are assumed to be\\n * successful.\\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\\n */\\nlibrary SafeERC20Upgradeable {\\n using AddressUpgradeable for address;\\n\\n function safeTransfer(\\n IERC20Upgradeable token,\\n address to,\\n uint256 value\\n ) internal {\\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\\n }\\n\\n function safeTransferFrom(\\n IERC20Upgradeable token,\\n address from,\\n address to,\\n uint256 value\\n ) internal {\\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\\n }\\n\\n /**\\n * @dev Deprecated. This function has issues similar to the ones found in\\n * {IERC20-approve}, and its usage is discouraged.\\n *\\n * Whenever possible, use {safeIncreaseAllowance} and\\n * {safeDecreaseAllowance} instead.\\n */\\n function safeApprove(\\n IERC20Upgradeable token,\\n address spender,\\n uint256 value\\n ) internal {\\n // safeApprove should only be called when setting an initial allowance,\\n // or when resetting it to zero. To increase and decrease it, use\\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\\n require(\\n (value == 0) || (token.allowance(address(this), spender) == 0),\\n \\\"SafeERC20: approve from non-zero to non-zero allowance\\\"\\n );\\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\\n }\\n\\n function safeIncreaseAllowance(\\n IERC20Upgradeable token,\\n address spender,\\n uint256 value\\n ) internal {\\n uint256 newAllowance = token.allowance(address(this), spender) + value;\\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\\n }\\n\\n function safeDecreaseAllowance(\\n IERC20Upgradeable token,\\n address spender,\\n uint256 value\\n ) internal {\\n unchecked {\\n uint256 oldAllowance = token.allowance(address(this), spender);\\n require(oldAllowance >= value, \\\"SafeERC20: decreased allowance below zero\\\");\\n uint256 newAllowance = oldAllowance - value;\\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\\n }\\n }\\n\\n function safePermit(\\n IERC20PermitUpgradeable token,\\n address owner,\\n address spender,\\n uint256 value,\\n uint256 deadline,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) internal {\\n uint256 nonceBefore = token.nonces(owner);\\n token.permit(owner, spender, value, deadline, v, r, s);\\n uint256 nonceAfter = token.nonces(owner);\\n require(nonceAfter == nonceBefore + 1, \\\"SafeERC20: permit did not succeed\\\");\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n */\\n function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\\n // the target address contains contract code and also asserts for success in the low-level call.\\n\\n bytes memory returndata = address(token).functionCall(data, \\\"SafeERC20: low-level call failed\\\");\\n if (returndata.length > 0) {\\n // Return data is optional\\n require(abi.decode(returndata, (bool)), \\\"SafeERC20: ERC20 operation did not succeed\\\");\\n }\\n }\\n}\\n\",\"keccak256\":\"0x4586689c55edb37fc3cac296d75d3851b3aee3f378aaa54d8a9258a384fbf541\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.1;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary AddressUpgradeable {\\n /**\\n * @dev Returns true if `account` is a contract.\\n *\\n * [IMPORTANT]\\n * ====\\n * It is unsafe to assume that an address for which this function returns\\n * false is an externally-owned account (EOA) and not a contract.\\n *\\n * Among others, `isContract` will return false for the following\\n * types of addresses:\\n *\\n * - an externally-owned account\\n * - a contract in construction\\n * - an address where a contract will be created\\n * - an address where a contract lived, but was destroyed\\n * ====\\n *\\n * [IMPORTANT]\\n * ====\\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\\n *\\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\\n * constructor.\\n * ====\\n */\\n function isContract(address account) internal view returns (bool) {\\n // This method relies on extcodesize/address.code.length, which returns 0\\n // for contracts in construction, since the code is only stored at the end\\n // of the constructor execution.\\n\\n return account.code.length > 0;\\n }\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n require(address(this).balance >= amount, \\\"Address: insufficient balance\\\");\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(success, \\\"Address: unable to send value, recipient may have reverted\\\");\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason, it is bubbled up by this\\n * function (like regular Solidity function calls).\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, \\\"Address: low-level call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\\n * `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, value, \\\"Address: low-level call with value failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\\n * with `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(address(this).balance >= value, \\\"Address: insufficient balance for call\\\");\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n return functionStaticCall(target, data, \\\"Address: low-level static call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\\n *\\n * _Available since v4.8._\\n */\\n function verifyCallResultFromTarget(\\n address target,\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n if (success) {\\n if (returndata.length == 0) {\\n // only check isContract if the call was successful and the return data is empty\\n // otherwise we already know that it was a contract\\n require(isContract(target), \\\"Address: call to non-contract\\\");\\n }\\n return returndata;\\n } else {\\n _revert(returndata, errorMessage);\\n }\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\\n * revert reason or using the provided one.\\n *\\n * _Available since v4.3._\\n */\\n function verifyCallResult(\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal pure returns (bytes memory) {\\n if (success) {\\n return returndata;\\n } else {\\n _revert(returndata, errorMessage);\\n }\\n }\\n\\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x0a3b4afc301241e2629ad192fa02e0f8626e3cf38ab6f45342bfd7afbde16ee0\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\\n\\npragma solidity ^0.8.0;\\nimport \\\"../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Provides information about the current execution context, including the\\n * sender of the transaction and its data. While these are generally available\\n * via msg.sender and msg.data, they should not be accessed in such a direct\\n * manner, since when dealing with meta-transactions the account sending and\\n * paying for execution may not be the actual sender (as far as an application\\n * is concerned).\\n *\\n * This contract is only required for intermediate, library-like contracts.\\n */\\nabstract contract ContextUpgradeable is Initializable {\\n function __Context_init() internal onlyInitializing {\\n }\\n\\n function __Context_init_unchained() internal onlyInitializing {\\n }\\n function _msgSender() internal view virtual returns (address) {\\n return msg.sender;\\n }\\n\\n function _msgData() internal view virtual returns (bytes calldata) {\\n return msg.data;\\n }\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[50] private __gap;\\n}\\n\",\"keccak256\":\"0x963ea7f0b48b032eef72fe3a7582edf78408d6f834115b9feadd673a4d5bd149\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Standard math utilities missing in the Solidity language.\\n */\\nlibrary MathUpgradeable {\\n enum Rounding {\\n Down, // Toward negative infinity\\n Up, // Toward infinity\\n Zero // Toward zero\\n }\\n\\n /**\\n * @dev Returns the largest of two numbers.\\n */\\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a > b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the smallest of two numbers.\\n */\\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a < b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the average of two numbers. The result is rounded towards\\n * zero.\\n */\\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\\n // (a + b) / 2 can overflow.\\n return (a & b) + (a ^ b) / 2;\\n }\\n\\n /**\\n * @dev Returns the ceiling of the division of two numbers.\\n *\\n * This differs from standard division with `/` in that it rounds up instead\\n * of rounding down.\\n */\\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\\n // (a + b - 1) / b can overflow on addition, so we distribute.\\n return a == 0 ? 0 : (a - 1) / b + 1;\\n }\\n\\n /**\\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\\n * with further edits by Uniswap Labs also under MIT license.\\n */\\n function mulDiv(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 result) {\\n unchecked {\\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\\n // variables such that product = prod1 * 2^256 + prod0.\\n uint256 prod0; // Least significant 256 bits of the product\\n uint256 prod1; // Most significant 256 bits of the product\\n assembly {\\n let mm := mulmod(x, y, not(0))\\n prod0 := mul(x, y)\\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\\n }\\n\\n // Handle non-overflow cases, 256 by 256 division.\\n if (prod1 == 0) {\\n return prod0 / denominator;\\n }\\n\\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\\n require(denominator > prod1);\\n\\n ///////////////////////////////////////////////\\n // 512 by 256 division.\\n ///////////////////////////////////////////////\\n\\n // Make division exact by subtracting the remainder from [prod1 prod0].\\n uint256 remainder;\\n assembly {\\n // Compute remainder using mulmod.\\n remainder := mulmod(x, y, denominator)\\n\\n // Subtract 256 bit number from 512 bit number.\\n prod1 := sub(prod1, gt(remainder, prod0))\\n prod0 := sub(prod0, remainder)\\n }\\n\\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\\n // See https://cs.stackexchange.com/q/138556/92363.\\n\\n // Does not overflow because the denominator cannot be zero at this stage in the function.\\n uint256 twos = denominator & (~denominator + 1);\\n assembly {\\n // Divide denominator by twos.\\n denominator := div(denominator, twos)\\n\\n // Divide [prod1 prod0] by twos.\\n prod0 := div(prod0, twos)\\n\\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\\n twos := add(div(sub(0, twos), twos), 1)\\n }\\n\\n // Shift in bits from prod1 into prod0.\\n prod0 |= prod1 * twos;\\n\\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\\n // four bits. That is, denominator * inv = 1 mod 2^4.\\n uint256 inverse = (3 * denominator) ^ 2;\\n\\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\\n // in modular arithmetic, doubling the correct bits in each step.\\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\\n\\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\\n // is no longer required.\\n result = prod0 * inverse;\\n return result;\\n }\\n }\\n\\n /**\\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\\n */\\n function mulDiv(\\n uint256 x,\\n uint256 y,\\n uint256 denominator,\\n Rounding rounding\\n ) internal pure returns (uint256) {\\n uint256 result = mulDiv(x, y, denominator);\\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\\n result += 1;\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\\n *\\n * Inspired by Henry S. Warren, Jr.'s \\\"Hacker's Delight\\\" (Chapter 11).\\n */\\n function sqrt(uint256 a) internal pure returns (uint256) {\\n if (a == 0) {\\n return 0;\\n }\\n\\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\\n //\\n // We know that the \\\"msb\\\" (most significant bit) of our target number `a` is a power of 2 such that we have\\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\\n //\\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\\n // \\u2192 `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\\n // \\u2192 `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\\n //\\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\\n uint256 result = 1 << (log2(a) >> 1);\\n\\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\\n // into the expected uint128 result.\\n unchecked {\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n return min(result, a / result);\\n }\\n }\\n\\n /**\\n * @notice Calculates sqrt(a), following the selected rounding direction.\\n */\\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = sqrt(a);\\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 2, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 128;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 64;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 32;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 16;\\n }\\n if (value >> 8 > 0) {\\n value >>= 8;\\n result += 8;\\n }\\n if (value >> 4 > 0) {\\n value >>= 4;\\n result += 4;\\n }\\n if (value >> 2 > 0) {\\n value >>= 2;\\n result += 2;\\n }\\n if (value >> 1 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log2(value);\\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 10, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >= 10**64) {\\n value /= 10**64;\\n result += 64;\\n }\\n if (value >= 10**32) {\\n value /= 10**32;\\n result += 32;\\n }\\n if (value >= 10**16) {\\n value /= 10**16;\\n result += 16;\\n }\\n if (value >= 10**8) {\\n value /= 10**8;\\n result += 8;\\n }\\n if (value >= 10**4) {\\n value /= 10**4;\\n result += 4;\\n }\\n if (value >= 10**2) {\\n value /= 10**2;\\n result += 2;\\n }\\n if (value >= 10**1) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log10(value);\\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 256, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n *\\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\\n */\\n function log256(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 16;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 8;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 4;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 2;\\n }\\n if (value >> 8 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log256(value);\\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\\n }\\n }\\n}\\n\",\"keccak256\":\"0xb49137b771712774960cca0acf428499e2aa85f179fe03712e5c06c5a6ab6316\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/draft-IERC1822.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\\n * proxy whose upgrades are fully controlled by the current implementation.\\n */\\ninterface IERC1822Proxiable {\\n /**\\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\\n * address.\\n *\\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\\n * function revert if invoked through a proxy.\\n */\\n function proxiableUUID() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x1d4afe6cb24200cc4545eed814ecf5847277dfe5d613a1707aad5fceecebcfff\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../Proxy.sol\\\";\\nimport \\\"./ERC1967Upgrade.sol\\\";\\n\\n/**\\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\\n * implementation address that can be changed. This address is stored in storage in the location specified by\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\\n * implementation behind the proxy.\\n */\\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\\n /**\\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\\n *\\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\\n * function call, and allows initializing the storage of the proxy like a Solidity constructor.\\n */\\n constructor(address _logic, bytes memory _data) payable {\\n _upgradeToAndCall(_logic, _data, false);\\n }\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _implementation() internal view virtual override returns (address impl) {\\n return ERC1967Upgrade._getImplementation();\\n }\\n}\\n\",\"keccak256\":\"0xa2b22da3032e50b55f95ec1d13336102d675f341167aa76db571ef7f8bb7975d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\\n\\npragma solidity ^0.8.2;\\n\\nimport \\\"../beacon/IBeacon.sol\\\";\\nimport \\\"../../interfaces/draft-IERC1822.sol\\\";\\nimport \\\"../../utils/Address.sol\\\";\\nimport \\\"../../utils/StorageSlot.sol\\\";\\n\\n/**\\n * @dev This abstract contract provides getters and event emitting update functions for\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\\n *\\n * _Available since v4.1._\\n *\\n * @custom:oz-upgrades-unsafe-allow delegatecall\\n */\\nabstract contract ERC1967Upgrade {\\n // This is the keccak-256 hash of \\\"eip1967.proxy.rollback\\\" subtracted by 1\\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\\n\\n /**\\n * @dev Storage slot with the address of the current implementation.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.implementation\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n\\n /**\\n * @dev Emitted when the implementation is upgraded.\\n */\\n event Upgraded(address indexed implementation);\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _getImplementation() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 implementation slot.\\n */\\n function _setImplementation(address newImplementation) private {\\n require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n }\\n\\n /**\\n * @dev Perform implementation upgrade\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeTo(address newImplementation) internal {\\n _setImplementation(newImplementation);\\n emit Upgraded(newImplementation);\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCall(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _upgradeTo(newImplementation);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(newImplementation, data);\\n }\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCallUUPS(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n // Upgrades from old implementations will perform a rollback test. This test requires the new\\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\\n // this special case will break upgrade paths from old UUPS implementation to new ones.\\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\\n _setImplementation(newImplementation);\\n } else {\\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\\n require(slot == _IMPLEMENTATION_SLOT, \\\"ERC1967Upgrade: unsupported proxiableUUID\\\");\\n } catch {\\n revert(\\\"ERC1967Upgrade: new implementation is not UUPS\\\");\\n }\\n _upgradeToAndCall(newImplementation, data, forceCall);\\n }\\n }\\n\\n /**\\n * @dev Storage slot with the admin of the contract.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.admin\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\\n\\n /**\\n * @dev Emitted when the admin account has changed.\\n */\\n event AdminChanged(address previousAdmin, address newAdmin);\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _getAdmin() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 admin slot.\\n */\\n function _setAdmin(address newAdmin) private {\\n require(newAdmin != address(0), \\\"ERC1967: new admin is the zero address\\\");\\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n */\\n function _changeAdmin(address newAdmin) internal {\\n emit AdminChanged(_getAdmin(), newAdmin);\\n _setAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\\n */\\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\\n\\n /**\\n * @dev Emitted when the beacon is upgraded.\\n */\\n event BeaconUpgraded(address indexed beacon);\\n\\n /**\\n * @dev Returns the current beacon.\\n */\\n function _getBeacon() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new beacon in the EIP1967 beacon slot.\\n */\\n function _setBeacon(address newBeacon) private {\\n require(Address.isContract(newBeacon), \\\"ERC1967: new beacon is not a contract\\\");\\n require(\\n Address.isContract(IBeacon(newBeacon).implementation()),\\n \\\"ERC1967: beacon implementation is not a contract\\\"\\n );\\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\\n }\\n\\n /**\\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\\n *\\n * Emits a {BeaconUpgraded} event.\\n */\\n function _upgradeBeaconToAndCall(\\n address newBeacon,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _setBeacon(newBeacon);\\n emit BeaconUpgraded(newBeacon);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\\n }\\n }\\n}\\n\",\"keccak256\":\"0xabf3f59bc0e5423eae45e459dbe92e7052c6983628d39008590edc852a62f94a\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\\n * be specified by overriding the virtual {_implementation} function.\\n *\\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\\n * different contract through the {_delegate} function.\\n *\\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\\n */\\nabstract contract Proxy {\\n /**\\n * @dev Delegates the current call to `implementation`.\\n *\\n * This function does not return to its internal call site, it will return directly to the external caller.\\n */\\n function _delegate(address implementation) internal virtual {\\n assembly {\\n // Copy msg.data. We take full control of memory in this inline assembly\\n // block because it will not return to Solidity code. We overwrite the\\n // Solidity scratch pad at memory position 0.\\n calldatacopy(0, 0, calldatasize())\\n\\n // Call the implementation.\\n // out and outsize are 0 because we don't know the size yet.\\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\\n\\n // Copy the returned data.\\n returndatacopy(0, 0, returndatasize())\\n\\n switch result\\n // delegatecall returns 0 on error.\\n case 0 {\\n revert(0, returndatasize())\\n }\\n default {\\n return(0, returndatasize())\\n }\\n }\\n }\\n\\n /**\\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\\n * and {_fallback} should delegate.\\n */\\n function _implementation() internal view virtual returns (address);\\n\\n /**\\n * @dev Delegates the current call to the address returned by `_implementation()`.\\n *\\n * This function does not return to its internal call site, it will return directly to the external caller.\\n */\\n function _fallback() internal virtual {\\n _beforeFallback();\\n _delegate(_implementation());\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\\n * function in the contract matches the call data.\\n */\\n fallback() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\\n * is empty.\\n */\\n receive() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\\n * call, or as part of the Solidity `fallback` or `receive` functions.\\n *\\n * If overridden should call `super._beforeFallback()`.\\n */\\n function _beforeFallback() internal virtual {}\\n}\\n\",\"keccak256\":\"0xc130fe33f1b2132158531a87734153293f6d07bc263ff4ac90e85da9c82c0e27\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/beacon/IBeacon.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\\n */\\ninterface IBeacon {\\n /**\\n * @dev Must return an address that can be used as a delegate call target.\\n *\\n * {BeaconProxy} will check that this address is a contract.\\n */\\n function implementation() external view returns (address);\\n}\\n\",\"keccak256\":\"0xd50a3421ac379ccb1be435fa646d66a65c986b4924f0849839f08692f39dde61\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../ERC1967/ERC1967Proxy.sol\\\";\\n\\n/**\\n * @dev This contract implements a proxy that is upgradeable by an admin.\\n *\\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\\n * clashing], which can potentially be used in an attack, this contract uses the\\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\\n * things that go hand in hand:\\n *\\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\\n * that call matches one of the admin functions exposed by the proxy itself.\\n * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the\\n * implementation. If the admin tries to call a function on the implementation it will fail with an error that says\\n * \\\"admin cannot fallback to proxy target\\\".\\n *\\n * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing\\n * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due\\n * to sudden errors when trying to call a function from the proxy implementation.\\n *\\n * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,\\n * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\\n */\\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\\n /**\\n * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and\\n * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\\n */\\n constructor(\\n address _logic,\\n address admin_,\\n bytes memory _data\\n ) payable ERC1967Proxy(_logic, _data) {\\n _changeAdmin(admin_);\\n }\\n\\n /**\\n * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.\\n */\\n modifier ifAdmin() {\\n if (msg.sender == _getAdmin()) {\\n _;\\n } else {\\n _fallback();\\n }\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\\n */\\n function admin() external ifAdmin returns (address admin_) {\\n admin_ = _getAdmin();\\n }\\n\\n /**\\n * @dev Returns the current implementation.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\\n */\\n function implementation() external ifAdmin returns (address implementation_) {\\n implementation_ = _implementation();\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\\n */\\n function changeAdmin(address newAdmin) external virtual ifAdmin {\\n _changeAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\\n */\\n function upgradeTo(address newImplementation) external ifAdmin {\\n _upgradeToAndCall(newImplementation, bytes(\\\"\\\"), false);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified\\n * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the\\n * proxied contract.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\\n */\\n function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {\\n _upgradeToAndCall(newImplementation, data, true);\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _admin() internal view virtual returns (address) {\\n return _getAdmin();\\n }\\n\\n /**\\n * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.\\n */\\n function _beforeFallback() internal virtual override {\\n require(msg.sender != _getAdmin(), \\\"TransparentUpgradeableProxy: admin cannot fallback to proxy target\\\");\\n super._beforeFallback();\\n }\\n}\\n\",\"keccak256\":\"0xa6a787e7a901af6511e19aa53e1a00352db215a011d2c7a438d0582dd5da76f9\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.1;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev Returns true if `account` is a contract.\\n *\\n * [IMPORTANT]\\n * ====\\n * It is unsafe to assume that an address for which this function returns\\n * false is an externally-owned account (EOA) and not a contract.\\n *\\n * Among others, `isContract` will return false for the following\\n * types of addresses:\\n *\\n * - an externally-owned account\\n * - a contract in construction\\n * - an address where a contract will be created\\n * - an address where a contract lived, but was destroyed\\n * ====\\n *\\n * [IMPORTANT]\\n * ====\\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\\n *\\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\\n * constructor.\\n * ====\\n */\\n function isContract(address account) internal view returns (bool) {\\n // This method relies on extcodesize/address.code.length, which returns 0\\n // for contracts in construction, since the code is only stored at the end\\n // of the constructor execution.\\n\\n return account.code.length > 0;\\n }\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n require(address(this).balance >= amount, \\\"Address: insufficient balance\\\");\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(success, \\\"Address: unable to send value, recipient may have reverted\\\");\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason, it is bubbled up by this\\n * function (like regular Solidity function calls).\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, \\\"Address: low-level call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\\n * `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, value, \\\"Address: low-level call with value failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\\n * with `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(address(this).balance >= value, \\\"Address: insufficient balance for call\\\");\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n return functionStaticCall(target, data, \\\"Address: low-level static call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionDelegateCall(target, data, \\\"Address: low-level delegate call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\\n *\\n * _Available since v4.8._\\n */\\n function verifyCallResultFromTarget(\\n address target,\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n if (success) {\\n if (returndata.length == 0) {\\n // only check isContract if the call was successful and the return data is empty\\n // otherwise we already know that it was a contract\\n require(isContract(target), \\\"Address: call to non-contract\\\");\\n }\\n return returndata;\\n } else {\\n _revert(returndata, errorMessage);\\n }\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\\n * revert reason or using the provided one.\\n *\\n * _Available since v4.3._\\n */\\n function verifyCallResult(\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal pure returns (bytes memory) {\\n if (success) {\\n return returndata;\\n } else {\\n _revert(returndata, errorMessage);\\n }\\n }\\n\\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n}\\n\",\"keccak256\":\"0xb94eac067c85cd79a4195c0a1f4a878e9827329045c12475a0199f1ae17b9700\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/StorageSlot.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Library for reading and writing primitive types to specific storage slots.\\n *\\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\\n * This library helps with reading and writing to such slots without the need for inline assembly.\\n *\\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\\n *\\n * Example usage to set ERC1967 implementation slot:\\n * ```\\n * contract ERC1967 {\\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n *\\n * function _getImplementation() internal view returns (address) {\\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n * }\\n *\\n * function _setImplementation(address newImplementation) internal {\\n * require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n * }\\n * }\\n * ```\\n *\\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\\n */\\nlibrary StorageSlot {\\n struct AddressSlot {\\n address value;\\n }\\n\\n struct BooleanSlot {\\n bool value;\\n }\\n\\n struct Bytes32Slot {\\n bytes32 value;\\n }\\n\\n struct Uint256Slot {\\n uint256 value;\\n }\\n\\n /**\\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\\n */\\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\\n */\\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\\n */\\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\\n */\\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n r.slot := slot\\n }\\n }\\n}\\n\",\"keccak256\":\"0xd5c50c54bf02740ebd122ff06832546cb5fa84486d52695a9ccfd11666e0c81d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)\\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Library for managing\\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\\n * types.\\n *\\n * Sets have the following properties:\\n *\\n * - Elements are added, removed, and checked for existence in constant time\\n * (O(1)).\\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\\n *\\n * ```\\n * contract Example {\\n * // Add the library methods\\n * using EnumerableSet for EnumerableSet.AddressSet;\\n *\\n * // Declare a set state variable\\n * EnumerableSet.AddressSet private mySet;\\n * }\\n * ```\\n *\\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\\n * and `uint256` (`UintSet`) are supported.\\n *\\n * [WARNING]\\n * ====\\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\\n * unusable.\\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\\n *\\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\\n * array of EnumerableSet.\\n * ====\\n */\\nlibrary EnumerableSet {\\n // To implement this library for multiple types with as little code\\n // repetition as possible, we write it in terms of a generic Set type with\\n // bytes32 values.\\n // The Set implementation uses private functions, and user-facing\\n // implementations (such as AddressSet) are just wrappers around the\\n // underlying Set.\\n // This means that we can only create new EnumerableSets for types that fit\\n // in bytes32.\\n\\n struct Set {\\n // Storage of set values\\n bytes32[] _values;\\n // Position of the value in the `values` array, plus 1 because index 0\\n // means a value is not in the set.\\n mapping(bytes32 => uint256) _indexes;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function _add(Set storage set, bytes32 value) private returns (bool) {\\n if (!_contains(set, value)) {\\n set._values.push(value);\\n // The value is stored at length-1, but we add 1 to all indexes\\n // and use 0 as a sentinel value\\n set._indexes[value] = set._values.length;\\n return true;\\n } else {\\n return false;\\n }\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function _remove(Set storage set, bytes32 value) private returns (bool) {\\n // We read and store the value's index to prevent multiple reads from the same storage slot\\n uint256 valueIndex = set._indexes[value];\\n\\n if (valueIndex != 0) {\\n // Equivalent to contains(set, value)\\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\\n // the array, and then remove the last element (sometimes called as 'swap and pop').\\n // This modifies the order of the array, as noted in {at}.\\n\\n uint256 toDeleteIndex = valueIndex - 1;\\n uint256 lastIndex = set._values.length - 1;\\n\\n if (lastIndex != toDeleteIndex) {\\n bytes32 lastValue = set._values[lastIndex];\\n\\n // Move the last value to the index where the value to delete is\\n set._values[toDeleteIndex] = lastValue;\\n // Update the index for the moved value\\n set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\\n }\\n\\n // Delete the slot where the moved value was stored\\n set._values.pop();\\n\\n // Delete the index for the deleted slot\\n delete set._indexes[value];\\n\\n return true;\\n } else {\\n return false;\\n }\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\\n return set._indexes[value] != 0;\\n }\\n\\n /**\\n * @dev Returns the number of values on the set. O(1).\\n */\\n function _length(Set storage set) private view returns (uint256) {\\n return set._values.length;\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\\n return set._values[index];\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function _values(Set storage set) private view returns (bytes32[] memory) {\\n return set._values;\\n }\\n\\n // Bytes32Set\\n\\n struct Bytes32Set {\\n Set _inner;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\\n return _add(set._inner, value);\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\\n return _remove(set._inner, value);\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\\n return _contains(set._inner, value);\\n }\\n\\n /**\\n * @dev Returns the number of values in the set. O(1).\\n */\\n function length(Bytes32Set storage set) internal view returns (uint256) {\\n return _length(set._inner);\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\\n return _at(set._inner, index);\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\\n bytes32[] memory store = _values(set._inner);\\n bytes32[] memory result;\\n\\n /// @solidity memory-safe-assembly\\n assembly {\\n result := store\\n }\\n\\n return result;\\n }\\n\\n // AddressSet\\n\\n struct AddressSet {\\n Set _inner;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function add(AddressSet storage set, address value) internal returns (bool) {\\n return _add(set._inner, bytes32(uint256(uint160(value))));\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function remove(AddressSet storage set, address value) internal returns (bool) {\\n return _remove(set._inner, bytes32(uint256(uint160(value))));\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function contains(AddressSet storage set, address value) internal view returns (bool) {\\n return _contains(set._inner, bytes32(uint256(uint160(value))));\\n }\\n\\n /**\\n * @dev Returns the number of values in the set. O(1).\\n */\\n function length(AddressSet storage set) internal view returns (uint256) {\\n return _length(set._inner);\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\\n return address(uint160(uint256(_at(set._inner, index))));\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function values(AddressSet storage set) internal view returns (address[] memory) {\\n bytes32[] memory store = _values(set._inner);\\n address[] memory result;\\n\\n /// @solidity memory-safe-assembly\\n assembly {\\n result := store\\n }\\n\\n return result;\\n }\\n\\n // UintSet\\n\\n struct UintSet {\\n Set _inner;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function add(UintSet storage set, uint256 value) internal returns (bool) {\\n return _add(set._inner, bytes32(value));\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\\n return _remove(set._inner, bytes32(value));\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\\n return _contains(set._inner, bytes32(value));\\n }\\n\\n /**\\n * @dev Returns the number of values in the set. O(1).\\n */\\n function length(UintSet storage set) internal view returns (uint256) {\\n return _length(set._inner);\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\\n return uint256(_at(set._inner, index));\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function values(UintSet storage set) internal view returns (uint256[] memory) {\\n bytes32[] memory store = _values(set._inner);\\n uint256[] memory result;\\n\\n /// @solidity memory-safe-assembly\\n assembly {\\n result := store\\n }\\n\\n return result;\\n }\\n}\\n\",\"keccak256\":\"0x636eab608b4563c01e88042aba9330e6fe69af2c567fe1adf4d85731974ac81d\",\"license\":\"MIT\"},\"adrastia-periphery/rates/IHistoricalRates.sol\":{\"content\":\"//SPDX-License-Identifier: MIT\\npragma solidity >=0.5.0 <0.9.0;\\n\\nimport \\\"./RateLibrary.sol\\\";\\n\\n/**\\n * @title IHistoricalRates\\n * @notice An interface that defines a contract that stores historical rates.\\n */\\ninterface IHistoricalRates {\\n /// @notice Gets an rate for a token at a specific index.\\n /// @param token The address of the token to get the rates for.\\n /// @param index The index of the rate to get, where index 0 contains the latest rate, and the last\\n /// index contains the oldest rate (uses reverse chronological ordering).\\n /// @return rate The rate for the token at the specified index.\\n function getRateAt(address token, uint256 index) external view returns (RateLibrary.Rate memory);\\n\\n /// @notice Gets the latest rates for a token.\\n /// @param token The address of the token to get the rates for.\\n /// @param amount The number of rates to get.\\n /// @return rates The latest rates for the token, in reverse chronological order, from newest to oldest.\\n function getRates(address token, uint256 amount) external view returns (RateLibrary.Rate[] memory);\\n\\n /// @notice Gets the latest rates for a token.\\n /// @param token The address of the token to get the rates for.\\n /// @param amount The number of rates to get.\\n /// @param offset The index of the first rate to get (default: 0).\\n /// @param increment The increment between rates to get (default: 1).\\n /// @return rates The latest rates for the token, in reverse chronological order, from newest to oldest.\\n function getRates(\\n address token,\\n uint256 amount,\\n uint256 offset,\\n uint256 increment\\n ) external view returns (RateLibrary.Rate[] memory);\\n\\n /// @notice Gets the number of rates for a token.\\n /// @param token The address of the token to get the number of rates for.\\n /// @return count The number of rates for the token.\\n function getRatesCount(address token) external view returns (uint256);\\n\\n /// @notice Gets the capacity of rates for a token.\\n /// @param token The address of the token to get the capacity of rates for.\\n /// @return capacity The capacity of rates for the token.\\n function getRatesCapacity(address token) external view returns (uint256);\\n\\n /// @notice Sets the capacity of rates for a token.\\n /// @param token The address of the token to set the capacity of rates for.\\n /// @param amount The new capacity of rates for the token.\\n function setRatesCapacity(address token, uint256 amount) external;\\n}\\n\",\"keccak256\":\"0x2754968c368df628f1ed00c2016b1a73f0f9b44f29e48d405887ad108723b3af\",\"license\":\"MIT\"},\"adrastia-periphery/rates/RateLibrary.sol\":{\"content\":\"//SPDX-License-Identifier: MIT\\npragma solidity >=0.5.0 <0.9.0;\\n\\npragma experimental ABIEncoderV2;\\n\\nlibrary RateLibrary {\\n struct Rate {\\n uint64 target;\\n uint64 current;\\n uint32 timestamp;\\n }\\n}\\n\",\"keccak256\":\"0x397b79cf9f183afa76db3c8d10cffb408e31ba154900f671a7e93c071bacbff4\",\"license\":\"MIT\"},\"contracts/src/adrastia/PrudentiaLib.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nlibrary PrudentiaLib {\\n struct PrudentiaConfig {\\n address controller; // Adrastia Prudentia controller address\\n uint8 offset; // Offset for delayed rate activation\\n int8 decimalShift; // Positive values scale the rate up (in powers of 10), negative values scale the rate down\\n }\\n}\\n\",\"keccak256\":\"0x8cc50f1a5dab30e0c205b0bba5f58c18eda9ebf01c661895c8f40678b86bf31f\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/CTokenInterfaces.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport { IonicComptroller } from \\\"./ComptrollerInterface.sol\\\";\\nimport { InterestRateModel } from \\\"./InterestRateModel.sol\\\";\\nimport { ComptrollerV3Storage } from \\\"./ComptrollerStorage.sol\\\";\\nimport { AddressesProvider } from \\\"../ionic/AddressesProvider.sol\\\";\\n\\nabstract contract CTokenAdminStorage {\\n /*\\n * Administrator for Ionic\\n */\\n address payable public ionicAdmin;\\n}\\n\\nabstract contract CErc20Storage is CTokenAdminStorage {\\n /**\\n * @dev Guard variable for re-entrancy checks\\n */\\n bool internal _notEntered;\\n\\n /**\\n * @notice EIP-20 token name for this token\\n */\\n string public name;\\n\\n /**\\n * @notice EIP-20 token symbol for this token\\n */\\n string public symbol;\\n\\n /**\\n * @notice EIP-20 token decimals for this token\\n */\\n uint8 public decimals;\\n\\n /*\\n * Maximum borrow rate that can ever be applied (.0005% / block)\\n */\\n uint256 internal constant borrowRateMaxMantissa = 0.0005e16;\\n\\n /*\\n * Maximum fraction of interest that can be set aside for reserves + fees\\n */\\n uint256 internal constant reserveFactorPlusFeesMaxMantissa = 1e18;\\n\\n /**\\n * @notice Contract which oversees inter-cToken operations\\n */\\n IonicComptroller public comptroller;\\n\\n /**\\n * @notice Model which tells what the current interest rate should be\\n */\\n InterestRateModel public interestRateModel;\\n\\n /*\\n * Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)\\n */\\n uint256 internal initialExchangeRateMantissa;\\n\\n /**\\n * @notice Fraction of interest currently set aside for admin fees\\n */\\n uint256 public adminFeeMantissa;\\n\\n /**\\n * @notice Fraction of interest currently set aside for Ionic fees\\n */\\n uint256 public ionicFeeMantissa;\\n\\n /**\\n * @notice Fraction of interest currently set aside for reserves\\n */\\n uint256 public reserveFactorMantissa;\\n\\n /**\\n * @notice Block number that interest was last accrued at\\n */\\n uint256 public accrualBlockNumber;\\n\\n /**\\n * @notice Accumulator of the total earned interest rate since the opening of the market\\n */\\n uint256 public borrowIndex;\\n\\n /**\\n * @notice Total amount of outstanding borrows of the underlying in this market\\n */\\n uint256 public totalBorrows;\\n\\n /**\\n * @notice Total amount of reserves of the underlying held in this market\\n */\\n uint256 public totalReserves;\\n\\n /**\\n * @notice Total amount of admin fees of the underlying held in this market\\n */\\n uint256 public totalAdminFees;\\n\\n /**\\n * @notice Total amount of Ionic fees of the underlying held in this market\\n */\\n uint256 public totalIonicFees;\\n\\n /**\\n * @notice Total number of tokens in circulation\\n */\\n uint256 public totalSupply;\\n\\n /*\\n * Official record of token balances for each account\\n */\\n mapping(address => uint256) internal accountTokens;\\n\\n /*\\n * Approved token transfer amounts on behalf of others\\n */\\n mapping(address => mapping(address => uint256)) internal transferAllowances;\\n\\n /**\\n * @notice Container for borrow balance information\\n * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action\\n * @member interestIndex Global borrowIndex as of the most recent balance-changing action\\n */\\n struct BorrowSnapshot {\\n uint256 principal;\\n uint256 interestIndex;\\n }\\n\\n /*\\n * Mapping of account addresses to outstanding borrow balances\\n */\\n mapping(address => BorrowSnapshot) internal accountBorrows;\\n\\n /*\\n * Share of seized collateral that is added to reserves\\n */\\n uint256 public constant protocolSeizeShareMantissa = 2.8e16; //2.8%\\n\\n /*\\n * Share of seized collateral taken as fees\\n */\\n uint256 public constant feeSeizeShareMantissa = 1e17; //10%\\n\\n /**\\n * @notice Underlying asset for this CToken\\n */\\n address public underlying;\\n\\n /**\\n * @notice Addresses Provider\\n */\\n AddressesProvider public ap;\\n}\\n\\nabstract contract CTokenBaseEvents {\\n /* ERC20 */\\n\\n /**\\n * @notice EIP20 Transfer event\\n */\\n event Transfer(address indexed from, address indexed to, uint256 amount);\\n\\n /*** Admin Events ***/\\n\\n /**\\n * @notice Event emitted when interestRateModel is changed\\n */\\n event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);\\n\\n /**\\n * @notice Event emitted when the reserve factor is changed\\n */\\n event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);\\n\\n /**\\n * @notice Event emitted when the admin fee is changed\\n */\\n event NewAdminFee(uint256 oldAdminFeeMantissa, uint256 newAdminFeeMantissa);\\n\\n /**\\n * @notice Event emitted when the Ionic fee is changed\\n */\\n event NewIonicFee(uint256 oldIonicFeeMantissa, uint256 newIonicFeeMantissa);\\n\\n /**\\n * @notice EIP20 Approval event\\n */\\n event Approval(address indexed owner, address indexed spender, uint256 amount);\\n\\n /**\\n * @notice Event emitted when interest is accrued\\n */\\n event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);\\n}\\n\\nabstract contract CTokenFirstExtensionEvents is CTokenBaseEvents {\\n event Flash(address receiver, uint256 amount);\\n}\\n\\nabstract contract CTokenSecondExtensionEvents is CTokenBaseEvents {\\n /*** Market Events ***/\\n\\n /**\\n * @notice Event emitted when tokens are minted\\n */\\n event Mint(address minter, uint256 mintAmount, uint256 mintTokens);\\n\\n /**\\n * @notice Event emitted when tokens are redeemed\\n */\\n event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);\\n\\n /**\\n * @notice Event emitted when underlying is borrowed\\n */\\n event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);\\n\\n /**\\n * @notice Event emitted when a borrow is repaid\\n */\\n event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows);\\n\\n /**\\n * @notice Event emitted when a borrow is liquidated\\n */\\n event LiquidateBorrow(\\n address liquidator,\\n address borrower,\\n uint256 repayAmount,\\n address cTokenCollateral,\\n uint256 seizeTokens\\n );\\n\\n /**\\n * @notice Event emitted when the reserves are added\\n */\\n event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);\\n\\n /**\\n * @notice Event emitted when the reserves are reduced\\n */\\n event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);\\n}\\n\\ninterface CTokenFirstExtensionInterface {\\n /*** User Interface ***/\\n\\n function transfer(address dst, uint256 amount) external returns (bool);\\n\\n function transferFrom(\\n address src,\\n address dst,\\n uint256 amount\\n ) external returns (bool);\\n\\n function approve(address spender, uint256 amount) external returns (bool);\\n\\n function allowance(address owner, address spender) external view returns (uint256);\\n\\n function balanceOf(address owner) external view returns (uint256);\\n\\n /*** Admin Functions ***/\\n\\n function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);\\n\\n function _setAdminFee(uint256 newAdminFeeMantissa) external returns (uint256);\\n\\n function _setInterestRateModel(InterestRateModel newInterestRateModel) external returns (uint256);\\n\\n function getAccountSnapshot(address account)\\n external\\n view\\n returns (\\n uint256,\\n uint256,\\n uint256,\\n uint256\\n );\\n\\n function borrowRatePerBlock() external view returns (uint256);\\n\\n function supplyRatePerBlock() external view returns (uint256);\\n\\n function exchangeRateCurrent() external view returns (uint256);\\n\\n function accrueInterest() external returns (uint256);\\n\\n function totalBorrowsCurrent() external view returns (uint256);\\n\\n function borrowBalanceCurrent(address account) external view returns (uint256);\\n\\n function getTotalUnderlyingSupplied() external view returns (uint256);\\n\\n function balanceOfUnderlying(address owner) external view returns (uint256);\\n\\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\\n\\n function flash(uint256 amount, bytes calldata data) external;\\n\\n function supplyRatePerBlockAfterDeposit(uint256 mintAmount) external view returns (uint256);\\n\\n function supplyRatePerBlockAfterWithdraw(uint256 withdrawAmount) external view returns (uint256);\\n\\n function borrowRatePerBlockAfterBorrow(uint256 borrowAmount) external view returns (uint256);\\n\\n function registerInSFS() external returns (uint256);\\n}\\n\\ninterface CTokenSecondExtensionInterface {\\n function mint(uint256 mintAmount) external returns (uint256);\\n\\n function redeem(uint256 redeemTokens) external returns (uint256);\\n\\n function redeemUnderlying(uint256 redeemAmount) external returns (uint256);\\n\\n function borrow(uint256 borrowAmount) external returns (uint256);\\n\\n function repayBorrow(uint256 repayAmount) external returns (uint256);\\n\\n function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);\\n\\n function liquidateBorrow(\\n address borrower,\\n uint256 repayAmount,\\n address cTokenCollateral\\n ) external returns (uint256);\\n\\n function getCash() external view returns (uint256);\\n\\n function seize(\\n address liquidator,\\n address borrower,\\n uint256 seizeTokens\\n ) external returns (uint256);\\n\\n /*** Admin Functions ***/\\n\\n function _withdrawAdminFees(uint256 withdrawAmount) external returns (uint256);\\n\\n function _withdrawIonicFees(uint256 withdrawAmount) external returns (uint256);\\n\\n function selfTransferOut(address to, uint256 amount) external;\\n\\n function selfTransferIn(address from, uint256 amount) external returns (uint256);\\n}\\n\\ninterface CDelegatorInterface {\\n function implementation() external view returns (address);\\n\\n /**\\n * @notice Called by the admin to update the implementation of the delegator\\n * @param implementation_ The address of the new implementation for delegation\\n * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\\n */\\n function _setImplementationSafe(address implementation_, bytes calldata becomeImplementationData) external;\\n\\n /**\\n * @dev upgrades the implementation if necessary\\n */\\n function _upgrade() external;\\n}\\n\\ninterface CDelegateInterface {\\n /**\\n * @notice Called by the delegator on a delegate to initialize it for duty\\n * @dev Should revert if any issues arise which make it unfit for delegation\\n * @param data The encoded bytes data for any initialization\\n */\\n function _becomeImplementation(bytes calldata data) external;\\n\\n function delegateType() external pure returns (uint8);\\n\\n function contractType() external pure returns (string memory);\\n}\\n\\nabstract contract CErc20AdminBase is CErc20Storage {\\n /**\\n * @notice Returns a boolean indicating if the sender has admin rights\\n */\\n function hasAdminRights() internal view returns (bool) {\\n ComptrollerV3Storage comptrollerStorage = ComptrollerV3Storage(address(comptroller));\\n return\\n (msg.sender == comptrollerStorage.admin() && comptrollerStorage.adminHasRights()) ||\\n (msg.sender == address(ionicAdmin) && comptrollerStorage.ionicAdminHasRights());\\n }\\n}\\n\\nabstract contract CErc20FirstExtensionBase is\\n CErc20AdminBase,\\n CTokenFirstExtensionEvents,\\n CTokenFirstExtensionInterface\\n{}\\n\\nabstract contract CTokenSecondExtensionBase is\\n CErc20AdminBase,\\n CTokenSecondExtensionEvents,\\n CTokenSecondExtensionInterface,\\n CDelegateInterface\\n{}\\n\\nabstract contract CErc20DelegatorBase is CErc20AdminBase, CTokenSecondExtensionEvents, CDelegatorInterface {}\\n\\ninterface CErc20StorageInterface {\\n function admin() external view returns (address);\\n\\n function adminHasRights() external view returns (bool);\\n\\n function ionicAdmin() external view returns (address);\\n\\n function ionicAdminHasRights() external view returns (bool);\\n\\n function comptroller() external view returns (IonicComptroller);\\n\\n function name() external view returns (string memory);\\n\\n function symbol() external view returns (string memory);\\n\\n function decimals() external view returns (uint8);\\n\\n function totalSupply() external view returns (uint256);\\n\\n function adminFeeMantissa() external view returns (uint256);\\n\\n function ionicFeeMantissa() external view returns (uint256);\\n\\n function reserveFactorMantissa() external view returns (uint256);\\n\\n function protocolSeizeShareMantissa() external view returns (uint256);\\n\\n function feeSeizeShareMantissa() external view returns (uint256);\\n\\n function totalReserves() external view returns (uint256);\\n\\n function totalAdminFees() external view returns (uint256);\\n\\n function totalIonicFees() external view returns (uint256);\\n\\n function totalBorrows() external view returns (uint256);\\n\\n function accrualBlockNumber() external view returns (uint256);\\n\\n function underlying() external view returns (address);\\n\\n function borrowIndex() external view returns (uint256);\\n\\n function interestRateModel() external view returns (address);\\n}\\n\\ninterface CErc20PluginStorageInterface is CErc20StorageInterface {\\n function plugin() external view returns (address);\\n}\\n\\ninterface CErc20PluginRewardsInterface is CErc20PluginStorageInterface {\\n function approve(address, address) external;\\n}\\n\\ninterface ICErc20 is\\n CErc20StorageInterface,\\n CTokenSecondExtensionInterface,\\n CTokenFirstExtensionInterface,\\n CDelegatorInterface,\\n CDelegateInterface\\n{}\\n\\ninterface ICErc20Plugin is CErc20PluginStorageInterface, ICErc20 {\\n function _updatePlugin(address _plugin) external;\\n}\\n\\ninterface ICErc20PluginRewards is CErc20PluginRewardsInterface, ICErc20 {}\\n\",\"keccak256\":\"0x7cc75051a5fa860b9ee93d0ba1ac0608921f02308aeff786ce8bbd8d8a70489a\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/ComptrollerInterface.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport { BasePriceOracle } from \\\"../oracles/BasePriceOracle.sol\\\";\\nimport { ICErc20 } from \\\"./CTokenInterfaces.sol\\\";\\nimport { DiamondExtension } from \\\"../ionic/DiamondExtension.sol\\\";\\nimport { ComptrollerV4Storage } from \\\"../compound/ComptrollerStorage.sol\\\";\\nimport { PrudentiaLib } from \\\"../adrastia/PrudentiaLib.sol\\\";\\nimport { IHistoricalRates } from \\\"adrastia-periphery/rates/IHistoricalRates.sol\\\";\\n\\ninterface ComptrollerInterface {\\n function isDeprecated(ICErc20 cToken) external view returns (bool);\\n\\n function _becomeImplementation() external;\\n\\n function _deployMarket(\\n uint8 delegateType,\\n bytes memory constructorData,\\n bytes calldata becomeImplData,\\n uint256 collateralFactorMantissa\\n ) external returns (uint256);\\n\\n function getAssetsIn(address account) external view returns (ICErc20[] memory);\\n\\n function checkMembership(address account, ICErc20 cToken) external view returns (bool);\\n\\n function _setPriceOracle(BasePriceOracle newOracle) external returns (uint256);\\n\\n function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256);\\n\\n function _setCollateralFactor(ICErc20 market, uint256 newCollateralFactorMantissa) external returns (uint256);\\n\\n function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256);\\n\\n function _setWhitelistEnforcement(bool enforce) external returns (uint256);\\n\\n function _setWhitelistStatuses(address[] calldata _suppliers, bool[] calldata statuses) external returns (uint256);\\n\\n function _addRewardsDistributor(address distributor) external returns (uint256);\\n\\n function getHypotheticalAccountLiquidity(\\n address account,\\n address cTokenModify,\\n uint256 redeemTokens,\\n uint256 borrowAmount,\\n uint256 repayAmount\\n ) external view returns (uint256, uint256, uint256, uint256);\\n\\n function getMaxRedeemOrBorrow(address account, ICErc20 cToken, bool isBorrow) external view returns (uint256);\\n\\n /*** Assets You Are In ***/\\n\\n function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);\\n\\n function exitMarket(address cToken) external returns (uint256);\\n\\n /*** Policy Hooks ***/\\n\\n function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256);\\n\\n function redeemAllowed(address cToken, address redeemer, uint256 redeemTokens) external returns (uint256);\\n\\n function redeemVerify(address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens) external;\\n\\n function borrowAllowed(address cToken, address borrower, uint256 borrowAmount) external returns (uint256);\\n\\n function borrowVerify(address cToken, address borrower) external;\\n\\n function borrowWithinLimits(address cToken, uint256 accountBorrowsNew) external view returns (uint256);\\n\\n function repayBorrowAllowed(\\n address cToken,\\n address payer,\\n address borrower,\\n uint256 repayAmount\\n ) external returns (uint256);\\n\\n function repayBorrowVerify(\\n address cToken,\\n address payer,\\n address borrower,\\n uint256 repayAmount\\n ) external;\\n\\n function liquidateBorrowAllowed(\\n address cTokenBorrowed,\\n address cTokenCollateral,\\n address liquidator,\\n address borrower,\\n uint256 repayAmount\\n ) external returns (uint256);\\n\\n function seizeAllowed(\\n address cTokenCollateral,\\n address cTokenBorrowed,\\n address liquidator,\\n address borrower,\\n uint256 seizeTokens\\n ) external returns (uint256);\\n \\n function seizeVerify(\\n address cTokenCollateral,\\n address cTokenBorrowed,\\n address liquidator,\\n address borrower,\\n uint256 seizeTokens\\n ) external;\\n\\n function transferAllowed(address cToken, address src, address dst, uint256 transferTokens) external returns (uint256);\\n \\n function transferVerify(address cToken, address src, address dst, uint256 transferTokens) external;\\n\\n function mintVerify(address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens) external;\\n\\n /*** Liquidity/Liquidation Calculations ***/\\n\\n function getAccountLiquidity(\\n address account\\n ) external view returns (uint256 error, uint256 collateralValue, uint256 liquidity, uint256 shortfall);\\n\\n function liquidateCalculateSeizeTokens(\\n address cTokenBorrowed,\\n address cTokenCollateral,\\n uint256 repayAmount\\n ) external view returns (uint256, uint256);\\n\\n /*** Pool-Wide/Cross-Asset Reentrancy Prevention ***/\\n\\n function _beforeNonReentrant() external;\\n\\n function _afterNonReentrant() external;\\n\\n /*** New supply and borrow cap view functions ***/\\n\\n /**\\n * @notice Gets the supply cap of a cToken in the units of the underlying asset.\\n * @param cToken The address of the cToken.\\n */\\n function effectiveSupplyCaps(address cToken) external view returns (uint256 supplyCap);\\n\\n /**\\n * @notice Gets the borrow cap of a cToken in the units of the underlying asset.\\n * @param cToken The address of the cToken.\\n */\\n function effectiveBorrowCaps(address cToken) external view returns (uint256 borrowCap);\\n}\\n\\ninterface ComptrollerStorageInterface {\\n function admin() external view returns (address);\\n\\n function adminHasRights() external view returns (bool);\\n\\n function ionicAdmin() external view returns (address);\\n\\n function ionicAdminHasRights() external view returns (bool);\\n\\n function pendingAdmin() external view returns (address);\\n\\n function oracle() external view returns (BasePriceOracle);\\n\\n function pauseGuardian() external view returns (address);\\n\\n function closeFactorMantissa() external view returns (uint256);\\n\\n function liquidationIncentiveMantissa() external view returns (uint256);\\n\\n function isUserOfPool(address user) external view returns (bool);\\n\\n function whitelist(address account) external view returns (bool);\\n\\n function enforceWhitelist() external view returns (bool);\\n\\n function borrowCapForCollateral(address borrowed, address collateral) external view returns (uint256);\\n\\n function borrowingAgainstCollateralBlacklist(address borrowed, address collateral) external view returns (bool);\\n\\n function suppliers(address account) external view returns (bool);\\n\\n function cTokensByUnderlying(address) external view returns (address);\\n\\n /**\\n * Gets the supply cap of a cToken in the units of the underlying asset.\\n * @dev WARNING: This function is misleading if Adrastia Prudentia is being used for the supply cap. Instead, use\\n * `effectiveSupplyCaps` to get the correct supply cap.\\n * @param cToken The address of the cToken.\\n * @return The supply cap in the units of the underlying asset.\\n */\\n function supplyCaps(address cToken) external view returns (uint256);\\n\\n /**\\n * Gets the borrow cap of a cToken in the units of the underlying asset.\\n * @dev WARNING: This function is misleading if Adrastia Prudentia is being used for the borrow cap. Instead, use\\n * `effectiveBorrowCaps` to get the correct borrow cap.\\n * @param cToken The address of the cToken.\\n * @return The borrow cap in the units of the underlying asset.\\n */\\n function borrowCaps(address cToken) external view returns (uint256);\\n\\n function markets(address cToken) external view returns (bool, uint256);\\n\\n function accountAssets(address, uint256) external view returns (address);\\n\\n function borrowGuardianPaused(address cToken) external view returns (bool);\\n\\n function mintGuardianPaused(address cToken) external view returns (bool);\\n\\n function rewardsDistributors(uint256) external view returns (address);\\n}\\n\\ninterface SFSRegister {\\n function register(address _recipient) external returns (uint256 tokenId);\\n}\\n\\ninterface ComptrollerExtensionInterface {\\n function getWhitelistedSuppliersSupply(address cToken) external view returns (uint256 supplied);\\n\\n function getWhitelistedBorrowersBorrows(address cToken) external view returns (uint256 borrowed);\\n\\n function getAllMarkets() external view returns (ICErc20[] memory);\\n\\n function getAllBorrowers() external view returns (address[] memory);\\n\\n function getAllBorrowersCount() external view returns (uint256);\\n\\n function getPaginatedBorrowers(\\n uint256 page,\\n uint256 pageSize\\n ) external view returns (uint256 _totalPages, address[] memory _pageOfBorrowers);\\n\\n function getRewardsDistributors() external view returns (address[] memory);\\n\\n function getAccruingFlywheels() external view returns (address[] memory);\\n\\n function _supplyCapWhitelist(address cToken, address account, bool whitelisted) external;\\n\\n function _setBorrowCapForCollateral(address cTokenBorrow, address cTokenCollateral, uint256 borrowCap) external;\\n\\n function _setBorrowCapForCollateralWhitelist(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n address account,\\n bool whitelisted\\n ) external;\\n\\n function isBorrowCapForCollateralWhitelisted(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n address account\\n ) external view returns (bool);\\n\\n function _blacklistBorrowingAgainstCollateral(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n bool blacklisted\\n ) external;\\n\\n function _blacklistBorrowingAgainstCollateralWhitelist(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n address account,\\n bool whitelisted\\n ) external;\\n\\n function isBlacklistBorrowingAgainstCollateralWhitelisted(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n address account\\n ) external view returns (bool);\\n\\n function isSupplyCapWhitelisted(address cToken, address account) external view returns (bool);\\n\\n function _borrowCapWhitelist(address cToken, address account, bool whitelisted) external;\\n\\n function isBorrowCapWhitelisted(address cToken, address account) external view returns (bool);\\n\\n function _removeFlywheel(address flywheelAddress) external returns (bool);\\n\\n function getWhitelist() external view returns (address[] memory);\\n\\n function addNonAccruingFlywheel(address flywheelAddress) external returns (bool);\\n\\n function _setMarketSupplyCaps(ICErc20[] calldata cTokens, uint256[] calldata newSupplyCaps) external;\\n\\n function _setMarketBorrowCaps(ICErc20[] calldata cTokens, uint256[] calldata newBorrowCaps) external;\\n\\n function _setBorrowCapGuardian(address newBorrowCapGuardian) external;\\n\\n function _setPauseGuardian(address newPauseGuardian) external returns (uint256);\\n\\n function _setMintPaused(ICErc20 cToken, bool state) external returns (bool);\\n\\n function _setBorrowPaused(ICErc20 cToken, bool state) external returns (bool);\\n\\n function _setTransferPaused(bool state) external returns (bool);\\n\\n function _setSeizePaused(bool state) external returns (bool);\\n\\n function _unsupportMarket(ICErc20 cToken) external returns (uint256);\\n\\n function getAssetAsCollateralValueCap(\\n ICErc20 collateral,\\n ICErc20 cTokenModify,\\n bool redeeming,\\n address account\\n ) external view returns (uint256);\\n\\n function registerInSFS() external returns (uint256);\\n}\\n\\ninterface ComptrollerPrudentiaCapsExtInterface {\\n /**\\n * @notice Retrieves Adrastia Prudentia borrow cap config from storage.\\n * @return The config.\\n */\\n function getBorrowCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory);\\n\\n /**\\n * @notice Retrieves Adrastia Prudentia supply cap config from storage.\\n * @return The config.\\n */\\n function getSupplyCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory);\\n\\n /**\\n * @notice Sets the Adrastia Prudentia supply cap config.\\n * @dev Specifying a zero address for the `controller` parameter will make the Comptroller use the native supply caps.\\n * @param newConfig The new config.\\n */\\n function _setSupplyCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external;\\n\\n /**\\n * @notice Sets the Adrastia Prudentia supply cap config.\\n * @dev Specifying a zero address for the `controller` parameter will make the Comptroller use the native borrow caps.\\n * @param newConfig The new config.\\n */\\n function _setBorrowCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external;\\n}\\n\\ninterface UnitrollerInterface {\\n function comptrollerImplementation() external view returns (address);\\n\\n function _upgrade() external;\\n\\n function _acceptAdmin() external returns (uint256);\\n\\n function _setPendingAdmin(address newPendingAdmin) external returns (uint256);\\n\\n function _toggleAdminRights(bool hasRights) external returns (uint256);\\n}\\n\\ninterface IComptrollerExtension is ComptrollerExtensionInterface, ComptrollerStorageInterface {}\\n\\n//interface IComptrollerBase is ComptrollerInterface, ComptrollerStorageInterface {}\\n\\ninterface IonicComptroller is\\n ComptrollerInterface,\\n ComptrollerExtensionInterface,\\n UnitrollerInterface,\\n ComptrollerStorageInterface\\n{\\n\\n}\\n\\nabstract contract ComptrollerBase is ComptrollerV4Storage {\\n /// @notice Indicator that this is a Comptroller contract (for inspection)\\n bool public constant isComptroller = true;\\n\\n /**\\n * @notice Gets the supply cap of a cToken in the units of the underlying asset.\\n * @param cToken The address of the cToken.\\n */\\n function effectiveSupplyCaps(address cToken) public view virtual returns (uint256 supplyCap) {\\n PrudentiaLib.PrudentiaConfig memory capConfig = supplyCapConfig;\\n\\n // Check if we're using Adrastia Prudentia for the supply cap\\n if (capConfig.controller != address(0)) {\\n // We have a controller, so we're using Adrastia Prudentia\\n\\n address underlyingToken = ICErc20(cToken).underlying();\\n\\n // Get the supply cap from Adrastia Prudentia\\n supplyCap = IHistoricalRates(capConfig.controller).getRateAt(underlyingToken, capConfig.offset).current;\\n\\n // Prudentia trims decimal points from amounts while our code requires the mantissa amount, so we\\n // must scale the supply cap to get the correct amount\\n\\n int256 scaleByDecimals = 18;\\n // Not all ERC20s implement decimals(), so we use a staticcall and check the return data\\n (bool success, bytes memory data) = underlyingToken.staticcall(abi.encodeWithSignature(\\\"decimals()\\\"));\\n if (success && data.length == 32) {\\n scaleByDecimals = int256(uint256(abi.decode(data, (uint8))));\\n }\\n\\n scaleByDecimals += capConfig.decimalShift;\\n\\n if (scaleByDecimals >= 0) {\\n // We're scaling up, so we need to multiply\\n supplyCap *= 10 ** uint256(scaleByDecimals);\\n } else {\\n // We're scaling down, so we need to divide\\n supplyCap /= 10 ** uint256(-scaleByDecimals);\\n }\\n } else {\\n // We don't have a controller, so we're using the local supply cap\\n\\n // Get the supply cap from the local supply cap\\n supplyCap = supplyCaps[cToken];\\n }\\n }\\n\\n /**\\n * @notice Gets the borrow cap of a cToken in the units of the underlying asset.\\n * @param cToken The address of the cToken.\\n */\\n function effectiveBorrowCaps(address cToken) public view virtual returns (uint256 borrowCap) {\\n PrudentiaLib.PrudentiaConfig memory capConfig = borrowCapConfig;\\n\\n // Check if we're using Adrastia Prudentia for the borrow cap\\n if (capConfig.controller != address(0)) {\\n // We have a controller, so we're using Adrastia Prudentia\\n\\n address underlyingToken = ICErc20(cToken).underlying();\\n\\n // Get the borrow cap from Adrastia Prudentia\\n borrowCap = IHistoricalRates(capConfig.controller).getRateAt(underlyingToken, capConfig.offset).current;\\n\\n // Prudentia trims decimal points from amounts while our code requires the mantissa amount, so we\\n // must scale the supply cap to get the correct amount\\n\\n int256 scaleByDecimals = 18;\\n // Not all ERC20s implement decimals(), so we use a staticcall and check the return data\\n (bool success, bytes memory data) = underlyingToken.staticcall(abi.encodeWithSignature(\\\"decimals()\\\"));\\n if (success && data.length == 32) {\\n scaleByDecimals = int256(uint256(abi.decode(data, (uint8))));\\n }\\n\\n scaleByDecimals += capConfig.decimalShift;\\n\\n if (scaleByDecimals >= 0) {\\n // We're scaling up, so we need to multiply\\n borrowCap *= 10 ** uint256(scaleByDecimals);\\n } else {\\n // We're scaling down, so we need to divide\\n borrowCap /= 10 ** uint256(-scaleByDecimals);\\n }\\n } else {\\n // We don't have a controller, so we're using the local borrow cap\\n borrowCap = borrowCaps[cToken];\\n }\\n }\\n}\\n\",\"keccak256\":\"0x266ec3c26b454cfa72bab45fa8e0bc9e3d44e8ec0cd4770304a14cc84c8f80d3\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/ComptrollerStorage.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport \\\"./IFeeDistributor.sol\\\";\\nimport \\\"../oracles/BasePriceOracle.sol\\\";\\nimport { ICErc20 } from \\\"./CTokenInterfaces.sol\\\";\\nimport { PrudentiaLib } from \\\"../adrastia/PrudentiaLib.sol\\\";\\n\\nimport \\\"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\\\";\\n\\ncontract UnitrollerAdminStorage {\\n /*\\n * Administrator for Ionic\\n */\\n address payable public ionicAdmin;\\n\\n /**\\n * @notice Administrator for this contract\\n */\\n address public admin;\\n\\n /**\\n * @notice Pending administrator for this contract\\n */\\n address public pendingAdmin;\\n\\n /**\\n * @notice Whether or not the Ionic admin has admin rights\\n */\\n bool public ionicAdminHasRights = true;\\n\\n /**\\n * @notice Whether or not the admin has admin rights\\n */\\n bool public adminHasRights = true;\\n\\n /**\\n * @notice Returns a boolean indicating if the sender has admin rights\\n */\\n function hasAdminRights() internal view returns (bool) {\\n return (msg.sender == admin && adminHasRights) || (msg.sender == address(ionicAdmin) && ionicAdminHasRights);\\n }\\n}\\n\\ncontract ComptrollerV1Storage is UnitrollerAdminStorage {\\n /**\\n * @notice Oracle which gives the price of any given asset\\n */\\n BasePriceOracle public oracle;\\n\\n /**\\n * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow\\n */\\n uint256 public closeFactorMantissa;\\n\\n /**\\n * @notice Multiplier representing the discount on collateral that a liquidator receives\\n */\\n uint256 public liquidationIncentiveMantissa;\\n\\n /*\\n * UNUSED AFTER UPGRADE: Max number of assets a single account can participate in (borrow or use as collateral)\\n */\\n uint256 internal maxAssets;\\n\\n /**\\n * @notice Per-account mapping of \\\"assets you are in\\\", capped by maxAssets\\n */\\n mapping(address => ICErc20[]) public accountAssets;\\n}\\n\\ncontract ComptrollerV2Storage is ComptrollerV1Storage {\\n struct Market {\\n // Whether or not this market is listed\\n bool isListed;\\n // Multiplier representing the most one can borrow against their collateral in this market.\\n // For instance, 0.9 to allow borrowing 90% of collateral value.\\n // Must be between 0 and 1, and stored as a mantissa.\\n uint256 collateralFactorMantissa;\\n // Per-market mapping of \\\"accounts in this asset\\\"\\n mapping(address => bool) accountMembership;\\n }\\n\\n /**\\n * @notice Official mapping of cTokens -> Market metadata\\n * @dev Used e.g. to determine if a market is supported\\n */\\n mapping(address => Market) public markets;\\n\\n /// @notice A list of all markets\\n ICErc20[] public allMarkets;\\n\\n /**\\n * @dev Maps borrowers to booleans indicating if they have entered any markets\\n */\\n mapping(address => bool) internal borrowers;\\n\\n /// @notice A list of all borrowers who have entered markets\\n address[] public allBorrowers;\\n\\n // Indexes of borrower account addresses in the `allBorrowers` array\\n mapping(address => uint256) internal borrowerIndexes;\\n\\n /**\\n * @dev Maps suppliers to booleans indicating if they have ever supplied to any markets\\n */\\n mapping(address => bool) public suppliers;\\n\\n /// @notice All cTokens addresses mapped by their underlying token addresses\\n mapping(address => ICErc20) public cTokensByUnderlying;\\n\\n /// @notice Whether or not the supplier whitelist is enforced\\n bool public enforceWhitelist;\\n\\n /// @notice Maps addresses to booleans indicating if they are allowed to supply assets (i.e., mint cTokens)\\n mapping(address => bool) public whitelist;\\n\\n /// @notice An array of all whitelisted accounts\\n address[] public whitelistArray;\\n\\n // Indexes of account addresses in the `whitelistArray` array\\n mapping(address => uint256) internal whitelistIndexes;\\n\\n /**\\n * @notice The Pause Guardian can pause certain actions as a safety mechanism.\\n * Actions which allow users to remove their own assets cannot be paused.\\n * Liquidation / seizing / transfer can only be paused globally, not by market.\\n */\\n address public pauseGuardian;\\n bool public _mintGuardianPaused;\\n bool public _borrowGuardianPaused;\\n bool public transferGuardianPaused;\\n bool public seizeGuardianPaused;\\n mapping(address => bool) public mintGuardianPaused;\\n mapping(address => bool) public borrowGuardianPaused;\\n}\\n\\ncontract ComptrollerV3Storage is ComptrollerV2Storage {\\n /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.\\n /// @dev If Adrastia Prudentia is enabled, the values the borrow cap guardian sets are ignored.\\n address public borrowCapGuardian;\\n\\n /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing.\\n /// @dev If Adrastia Prudentia is enabled, this value is ignored. Use `effectiveBorrowCaps` instead.\\n mapping(address => uint256) public borrowCaps;\\n\\n /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying.\\n /// @dev If Adrastia Prudentia is enabled, this value is ignored. Use `effectiveSupplyCaps` instead.\\n mapping(address => uint256) public supplyCaps;\\n\\n /// @notice RewardsDistributor contracts to notify of flywheel changes.\\n address[] public rewardsDistributors;\\n\\n /// @dev Guard variable for pool-wide/cross-asset re-entrancy checks\\n bool internal _notEntered;\\n\\n /// @dev Whether or not _notEntered has been initialized\\n bool internal _notEnteredInitialized;\\n\\n /// @notice RewardsDistributor to list for claiming, but not to notify of flywheel changes.\\n address[] public nonAccruingRewardsDistributors;\\n\\n /// @dev cap for each user's borrows against specific assets - denominated in the borrowed asset\\n mapping(address => mapping(address => uint256)) public borrowCapForCollateral;\\n\\n /// @dev blacklist to disallow the borrowing of an asset against specific collateral\\n mapping(address => mapping(address => bool)) public borrowingAgainstCollateralBlacklist;\\n\\n /// @dev set of whitelisted accounts that are allowed to bypass the borrowing against specific collateral cap\\n mapping(address => mapping(address => EnumerableSet.AddressSet)) internal borrowCapForCollateralWhitelist;\\n\\n /// @dev set of whitelisted accounts that are allowed to bypass the borrow cap\\n mapping(address => mapping(address => EnumerableSet.AddressSet))\\n internal borrowingAgainstCollateralBlacklistWhitelist;\\n\\n /// @dev set of whitelisted accounts that are allowed to bypass the supply cap\\n mapping(address => EnumerableSet.AddressSet) internal supplyCapWhitelist;\\n\\n /// @dev set of whitelisted accounts that are allowed to bypass the borrow cap\\n mapping(address => EnumerableSet.AddressSet) internal borrowCapWhitelist;\\n}\\n\\ncontract ComptrollerV4Storage is ComptrollerV3Storage {\\n /// @dev Adrastia Prudentia config for controlling borrow caps.\\n PrudentiaLib.PrudentiaConfig internal borrowCapConfig;\\n\\n /// @dev Adrastia Prudentia config for controlling supply caps.\\n PrudentiaLib.PrudentiaConfig internal supplyCapConfig;\\n}\\n\",\"keccak256\":\"0xa4a8110e666a93c1228c914f1414131e0f3b93385826bb72f6f93d429e514286\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/ErrorReporter.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\ncontract ComptrollerErrorReporter {\\n enum Error {\\n NO_ERROR,\\n UNAUTHORIZED,\\n COMPTROLLER_MISMATCH,\\n INSUFFICIENT_SHORTFALL,\\n INSUFFICIENT_LIQUIDITY,\\n INVALID_CLOSE_FACTOR,\\n INVALID_COLLATERAL_FACTOR,\\n INVALID_LIQUIDATION_INCENTIVE,\\n MARKET_NOT_LISTED,\\n MARKET_ALREADY_LISTED,\\n MATH_ERROR,\\n NONZERO_BORROW_BALANCE,\\n PRICE_ERROR,\\n REJECTION,\\n SNAPSHOT_ERROR,\\n TOO_MANY_ASSETS,\\n TOO_MUCH_REPAY,\\n SUPPLIER_NOT_WHITELISTED,\\n BORROW_BELOW_MIN,\\n SUPPLY_ABOVE_MAX,\\n NONZERO_TOTAL_SUPPLY\\n }\\n\\n enum FailureInfo {\\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\\n ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,\\n ADD_REWARDS_DISTRIBUTOR_OWNER_CHECK,\\n EXIT_MARKET_BALANCE_OWED,\\n EXIT_MARKET_REJECTION,\\n TOGGLE_ADMIN_RIGHTS_OWNER_CHECK,\\n TOGGLE_AUTO_IMPLEMENTATIONS_ENABLED_OWNER_CHECK,\\n SET_CLOSE_FACTOR_OWNER_CHECK,\\n SET_CLOSE_FACTOR_VALIDATION,\\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\\n SET_COLLATERAL_FACTOR_NO_EXISTS,\\n SET_COLLATERAL_FACTOR_VALIDATION,\\n SET_COLLATERAL_FACTOR_WITHOUT_PRICE,\\n SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,\\n SET_LIQUIDATION_INCENTIVE_VALIDATION,\\n SET_PENDING_ADMIN_OWNER_CHECK,\\n SET_PENDING_IMPLEMENTATION_CONTRACT_CHECK,\\n SET_PENDING_IMPLEMENTATION_OWNER_CHECK,\\n SET_PRICE_ORACLE_OWNER_CHECK,\\n SET_WHITELIST_ENFORCEMENT_OWNER_CHECK,\\n SET_WHITELIST_STATUS_OWNER_CHECK,\\n SUPPORT_MARKET_EXISTS,\\n SUPPORT_MARKET_OWNER_CHECK,\\n SET_PAUSE_GUARDIAN_OWNER_CHECK,\\n UNSUPPORT_MARKET_OWNER_CHECK,\\n UNSUPPORT_MARKET_DOES_NOT_EXIST,\\n UNSUPPORT_MARKET_IN_USE\\n }\\n\\n /**\\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\\n **/\\n event Failure(uint256 error, uint256 info, uint256 detail);\\n\\n /**\\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\\n */\\n function fail(Error err, FailureInfo info) internal returns (uint256) {\\n emit Failure(uint256(err), uint256(info), 0);\\n\\n return uint256(err);\\n }\\n\\n /**\\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\\n */\\n function failOpaque(\\n Error err,\\n FailureInfo info,\\n uint256 opaqueError\\n ) internal returns (uint256) {\\n emit Failure(uint256(err), uint256(info), opaqueError);\\n\\n return uint256(err);\\n }\\n}\\n\\ncontract TokenErrorReporter {\\n enum Error {\\n NO_ERROR,\\n UNAUTHORIZED,\\n BAD_INPUT,\\n COMPTROLLER_REJECTION,\\n COMPTROLLER_CALCULATION_ERROR,\\n INTEREST_RATE_MODEL_ERROR,\\n INVALID_ACCOUNT_PAIR,\\n INVALID_CLOSE_AMOUNT_REQUESTED,\\n INVALID_COLLATERAL_FACTOR,\\n MATH_ERROR,\\n MARKET_NOT_FRESH,\\n MARKET_NOT_LISTED,\\n TOKEN_INSUFFICIENT_ALLOWANCE,\\n TOKEN_INSUFFICIENT_BALANCE,\\n TOKEN_INSUFFICIENT_CASH,\\n TOKEN_TRANSFER_IN_FAILED,\\n TOKEN_TRANSFER_OUT_FAILED,\\n UTILIZATION_ABOVE_MAX\\n }\\n\\n /*\\n * Note: FailureInfo (but not Error) is kept in alphabetical order\\n * This is because FailureInfo grows significantly faster, and\\n * the order of Error has some meaning, while the order of FailureInfo\\n * is entirely arbitrary.\\n */\\n enum FailureInfo {\\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\\n ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,\\n ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_TOTAL_IONIC_FEES_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_TOTAL_ADMIN_FEES_CALCULATION_FAILED,\\n ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,\\n BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\\n BORROW_ACCRUE_INTEREST_FAILED,\\n BORROW_CASH_NOT_AVAILABLE,\\n BORROW_FRESHNESS_CHECK,\\n BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\\n BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\\n BORROW_MARKET_NOT_LISTED,\\n BORROW_COMPTROLLER_REJECTION,\\n LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,\\n LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,\\n LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,\\n LIQUIDATE_COMPTROLLER_REJECTION,\\n LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,\\n LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,\\n LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,\\n LIQUIDATE_FRESHNESS_CHECK,\\n LIQUIDATE_LIQUIDATOR_IS_BORROWER,\\n LIQUIDATE_REPAY_BORROW_FRESH_FAILED,\\n LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,\\n LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,\\n LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,\\n LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,\\n LIQUIDATE_SEIZE_TOO_MUCH,\\n MINT_ACCRUE_INTEREST_FAILED,\\n MINT_COMPTROLLER_REJECTION,\\n MINT_EXCHANGE_CALCULATION_FAILED,\\n MINT_EXCHANGE_RATE_READ_FAILED,\\n MINT_FRESHNESS_CHECK,\\n MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\\n MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\\n MINT_TRANSFER_IN_FAILED,\\n MINT_TRANSFER_IN_NOT_POSSIBLE,\\n NEW_UTILIZATION_RATE_ABOVE_MAX,\\n REDEEM_ACCRUE_INTEREST_FAILED,\\n REDEEM_COMPTROLLER_REJECTION,\\n REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,\\n REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,\\n REDEEM_EXCHANGE_RATE_READ_FAILED,\\n REDEEM_FRESHNESS_CHECK,\\n REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\\n REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\\n REDEEM_TRANSFER_OUT_NOT_POSSIBLE,\\n WITHDRAW_IONIC_FEES_ACCRUE_INTEREST_FAILED,\\n WITHDRAW_IONIC_FEES_CASH_NOT_AVAILABLE,\\n WITHDRAW_IONIC_FEES_FRESH_CHECK,\\n WITHDRAW_IONIC_FEES_VALIDATION,\\n WITHDRAW_ADMIN_FEES_ACCRUE_INTEREST_FAILED,\\n WITHDRAW_ADMIN_FEES_CASH_NOT_AVAILABLE,\\n WITHDRAW_ADMIN_FEES_FRESH_CHECK,\\n WITHDRAW_ADMIN_FEES_VALIDATION,\\n REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,\\n REDUCE_RESERVES_ADMIN_CHECK,\\n REDUCE_RESERVES_CASH_NOT_AVAILABLE,\\n REDUCE_RESERVES_FRESH_CHECK,\\n REDUCE_RESERVES_VALIDATION,\\n REPAY_BEHALF_ACCRUE_INTEREST_FAILED,\\n REPAY_BORROW_ACCRUE_INTEREST_FAILED,\\n REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\\n REPAY_BORROW_COMPTROLLER_REJECTION,\\n REPAY_BORROW_FRESHNESS_CHECK,\\n REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\\n REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\\n REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,\\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\\n SET_COLLATERAL_FACTOR_VALIDATION,\\n SET_COMPTROLLER_OWNER_CHECK,\\n SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,\\n SET_INTEREST_RATE_MODEL_FRESH_CHECK,\\n SET_INTEREST_RATE_MODEL_OWNER_CHECK,\\n TOGGLE_ADMIN_RIGHTS_OWNER_CHECK,\\n SET_PENDING_ADMIN_OWNER_CHECK,\\n SET_ADMIN_FEE_ACCRUE_INTEREST_FAILED,\\n SET_ADMIN_FEE_ADMIN_CHECK,\\n SET_ADMIN_FEE_FRESH_CHECK,\\n SET_ADMIN_FEE_BOUNDS_CHECK,\\n SET_IONIC_FEE_ACCRUE_INTEREST_FAILED,\\n SET_IONIC_FEE_FRESH_CHECK,\\n SET_IONIC_FEE_BOUNDS_CHECK,\\n SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,\\n SET_RESERVE_FACTOR_ADMIN_CHECK,\\n SET_RESERVE_FACTOR_FRESH_CHECK,\\n SET_RESERVE_FACTOR_BOUNDS_CHECK,\\n TRANSFER_COMPTROLLER_REJECTION,\\n TRANSFER_NOT_ALLOWED,\\n TRANSFER_NOT_ENOUGH,\\n TRANSFER_TOO_MUCH,\\n ADD_RESERVES_ACCRUE_INTEREST_FAILED,\\n ADD_RESERVES_FRESH_CHECK,\\n ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE\\n }\\n\\n /**\\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\\n **/\\n event Failure(uint256 error, uint256 info, uint256 detail);\\n\\n /**\\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\\n */\\n function fail(Error err, FailureInfo info) internal returns (uint256) {\\n emit Failure(uint256(err), uint256(info), 0);\\n\\n return uint256(err);\\n }\\n\\n /**\\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\\n */\\n function failOpaque(\\n Error err,\\n FailureInfo info,\\n uint256 opaqueError\\n ) internal returns (uint256) {\\n emit Failure(uint256(err), uint256(info), opaqueError);\\n\\n return err == Error.COMPTROLLER_REJECTION ? 1000 + opaqueError : uint256(err);\\n }\\n}\\n\",\"keccak256\":\"0xad342553cda4d7b7e40678c636a406bc2785be2117a29d9b1cb52e747726745e\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/IFeeDistributor.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport \\\"../ionic/AuthoritiesRegistry.sol\\\";\\n\\ninterface IFeeDistributor {\\n function minBorrowEth() external view returns (uint256);\\n\\n function maxUtilizationRate() external view returns (uint256);\\n\\n function interestFeeRate() external view returns (uint256);\\n\\n function latestComptrollerImplementation(address oldImplementation) external view returns (address);\\n\\n function latestCErc20Delegate(uint8 delegateType)\\n external\\n view\\n returns (address cErc20Delegate, bytes memory becomeImplementationData);\\n\\n function latestPluginImplementation(address oldImplementation) external view returns (address);\\n\\n function getComptrollerExtensions(address comptroller) external view returns (address[] memory);\\n\\n function getCErc20DelegateExtensions(address cErc20Delegate) external view returns (address[] memory);\\n\\n function deployCErc20(\\n uint8 delegateType,\\n bytes calldata constructorData,\\n bytes calldata becomeImplData\\n ) external returns (address);\\n\\n function canCall(\\n address pool,\\n address user,\\n address target,\\n bytes4 functionSig\\n ) external view returns (bool);\\n\\n function authoritiesRegistry() external view returns (AuthoritiesRegistry);\\n\\n fallback() external payable;\\n\\n receive() external payable;\\n}\\n\",\"keccak256\":\"0xa822e2942e6a88851968d5f3bda48709713c84d556031a1dd3db5dfd06121d3e\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/InterestRateModel.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\n/**\\n * @title Compound's InterestRateModel Interface\\n * @author Compound\\n */\\nabstract contract InterestRateModel {\\n /// @notice Indicator that this is an InterestRateModel contract (for inspection)\\n bool public constant isInterestRateModel = true;\\n\\n /**\\n * @notice Calculates the current borrow interest rate per block\\n * @param cash The total amount of cash the market has\\n * @param borrows The total amount of borrows the market has outstanding\\n * @param reserves The total amount of reserves the market has\\n * @return The borrow rate per block (as a percentage, and scaled by 1e18)\\n */\\n function getBorrowRate(\\n uint256 cash,\\n uint256 borrows,\\n uint256 reserves\\n ) public view virtual returns (uint256);\\n\\n /**\\n * @notice Calculates the current supply interest rate per block\\n * @param cash The total amount of cash the market has\\n * @param borrows The total amount of borrows the market has outstanding\\n * @param reserves The total amount of reserves the market has\\n * @param reserveFactorMantissa The current reserve factor the market has\\n * @return The supply rate per block (as a percentage, and scaled by 1e18)\\n */\\n function getSupplyRate(\\n uint256 cash,\\n uint256 borrows,\\n uint256 reserves,\\n uint256 reserveFactorMantissa\\n ) public view virtual returns (uint256);\\n}\\n\",\"keccak256\":\"0x587a54b49d48df2cd91583eac93ddde4e2849f79d0441f179bf835e9dffe24e9\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/AddressesProvider.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\nimport { SafeOwnableUpgradeable } from \\\"../ionic/SafeOwnableUpgradeable.sol\\\";\\n\\n/**\\n * @title AddressesProvider\\n * @notice The Addresses Provider serves as a central storage of system internal and external\\n * contract addresses that change between deploys and across chains\\n * @author Veliko Minkov \\n */\\ncontract AddressesProvider is SafeOwnableUpgradeable {\\n mapping(string => address) private _addresses;\\n mapping(address => Contract) public plugins;\\n mapping(address => Contract) public flywheelRewards;\\n mapping(address => RedemptionStrategy) public redemptionStrategiesConfig;\\n mapping(address => FundingStrategy) public fundingStrategiesConfig;\\n JarvisPool[] public jarvisPoolsConfig;\\n CurveSwapPool[] public curveSwapPoolsConfig;\\n mapping(address => mapping(address => address)) public balancerPoolForTokens;\\n\\n /// @dev Initializer to set the admin that can set and change contracts addresses\\n function initialize(address owner) public initializer {\\n __SafeOwnable_init(owner);\\n }\\n\\n /**\\n * @dev The contract address and a string that uniquely identifies the contract's interface\\n */\\n struct Contract {\\n address addr;\\n string contractInterface;\\n }\\n\\n struct RedemptionStrategy {\\n address addr;\\n string contractInterface;\\n address outputToken;\\n }\\n\\n struct FundingStrategy {\\n address addr;\\n string contractInterface;\\n address inputToken;\\n }\\n\\n struct JarvisPool {\\n address syntheticToken;\\n address collateralToken;\\n address liquidityPool;\\n uint256 expirationTime;\\n }\\n\\n struct CurveSwapPool {\\n address poolAddress;\\n address[] coins;\\n }\\n\\n /**\\n * @dev sets the address and contract interface ID of the flywheel for the reward token\\n * @param rewardToken the reward token address\\n * @param flywheelRewardsModule the flywheel rewards module address\\n * @param contractInterface a string that uniquely identifies the contract's interface\\n */\\n function setFlywheelRewards(\\n address rewardToken,\\n address flywheelRewardsModule,\\n string calldata contractInterface\\n ) public onlyOwner {\\n flywheelRewards[rewardToken] = Contract(flywheelRewardsModule, contractInterface);\\n }\\n\\n /**\\n * @dev sets the address and contract interface ID of the ERC4626 plugin for the asset\\n * @param asset the asset address\\n * @param plugin the ERC4626 plugin address\\n * @param contractInterface a string that uniquely identifies the contract's interface\\n */\\n function setPlugin(\\n address asset,\\n address plugin,\\n string calldata contractInterface\\n ) public onlyOwner {\\n plugins[asset] = Contract(plugin, contractInterface);\\n }\\n\\n /**\\n * @dev sets the address and contract interface ID of the redemption strategy for the asset\\n * @param asset the asset address\\n * @param strategy redemption strategy address\\n * @param contractInterface a string that uniquely identifies the contract's interface\\n */\\n function setRedemptionStrategy(\\n address asset,\\n address strategy,\\n string calldata contractInterface,\\n address outputToken\\n ) public onlyOwner {\\n redemptionStrategiesConfig[asset] = RedemptionStrategy(strategy, contractInterface, outputToken);\\n }\\n\\n function getRedemptionStrategy(address asset) public view returns (RedemptionStrategy memory) {\\n return redemptionStrategiesConfig[asset];\\n }\\n\\n /**\\n * @dev sets the address and contract interface ID of the funding strategy for the asset\\n * @param asset the asset address\\n * @param strategy funding strategy address\\n * @param contractInterface a string that uniquely identifies the contract's interface\\n */\\n function setFundingStrategy(\\n address asset,\\n address strategy,\\n string calldata contractInterface,\\n address inputToken\\n ) public onlyOwner {\\n fundingStrategiesConfig[asset] = FundingStrategy(strategy, contractInterface, inputToken);\\n }\\n\\n function getFundingStrategy(address asset) public view returns (FundingStrategy memory) {\\n return fundingStrategiesConfig[asset];\\n }\\n\\n /**\\n * @dev configures the Jarvis pool of a Jarvis synthetic token\\n * @param syntheticToken the synthetic token address\\n * @param collateralToken the collateral token address\\n * @param liquidityPool the liquidity pool address\\n * @param expirationTime the operation expiration time\\n */\\n function setJarvisPool(\\n address syntheticToken,\\n address collateralToken,\\n address liquidityPool,\\n uint256 expirationTime\\n ) public onlyOwner {\\n jarvisPoolsConfig.push(JarvisPool(syntheticToken, collateralToken, liquidityPool, expirationTime));\\n }\\n\\n function setCurveSwapPool(address poolAddress, address[] calldata coins) public onlyOwner {\\n curveSwapPoolsConfig.push(CurveSwapPool(poolAddress, coins));\\n }\\n\\n /**\\n * @dev Sets an address for an id replacing the address saved in the addresses map\\n * @param id The id\\n * @param newAddress The address to set\\n */\\n function setAddress(string calldata id, address newAddress) external onlyOwner {\\n _addresses[id] = newAddress;\\n }\\n\\n /**\\n * @dev Returns an address by id\\n * @return The address\\n */\\n function getAddress(string calldata id) public view returns (address) {\\n return _addresses[id];\\n }\\n\\n function getCurveSwapPools() public view returns (CurveSwapPool[] memory) {\\n return curveSwapPoolsConfig;\\n }\\n\\n function getJarvisPools() public view returns (JarvisPool[] memory) {\\n return jarvisPoolsConfig;\\n }\\n\\n function setBalancerPoolForTokens(\\n address inputToken,\\n address outputToken,\\n address pool\\n ) external onlyOwner {\\n balancerPoolForTokens[inputToken][outputToken] = pool;\\n }\\n\\n function getBalancerPoolForTokens(address inputToken, address outputToken) external view returns (address) {\\n return balancerPoolForTokens[inputToken][outputToken];\\n }\\n}\\n\",\"keccak256\":\"0xf48e9e8b2150408c1c6b68dd957226c342ba47396da792fdaa0922f539a7e163\",\"license\":\"AGPL-3.0-only\"},\"contracts/src/ionic/AuthoritiesRegistry.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport { PoolRolesAuthority } from \\\"../ionic/PoolRolesAuthority.sol\\\";\\nimport { SafeOwnableUpgradeable } from \\\"../ionic/SafeOwnableUpgradeable.sol\\\";\\nimport { IonicComptroller } from \\\"../compound/ComptrollerInterface.sol\\\";\\n\\nimport { TransparentUpgradeableProxy } from \\\"@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol\\\";\\n\\ncontract AuthoritiesRegistry is SafeOwnableUpgradeable {\\n mapping(address => PoolRolesAuthority) public poolsAuthorities;\\n PoolRolesAuthority public poolAuthLogic;\\n address public leveredPositionsFactory;\\n bool public noAuthRequired;\\n\\n function initialize(address _leveredPositionsFactory) public initializer {\\n __SafeOwnable_init(msg.sender);\\n leveredPositionsFactory = _leveredPositionsFactory;\\n poolAuthLogic = new PoolRolesAuthority();\\n }\\n\\n function reinitialize(address _leveredPositionsFactory) public onlyOwnerOrAdmin {\\n leveredPositionsFactory = _leveredPositionsFactory;\\n poolAuthLogic = new PoolRolesAuthority();\\n // for Neon the auth is not required\\n noAuthRequired = block.chainid == 245022934;\\n }\\n\\n function createPoolAuthority(address pool) public onlyOwner returns (PoolRolesAuthority auth) {\\n require(address(poolsAuthorities[pool]) == address(0), \\\"already created\\\");\\n\\n TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(address(poolAuthLogic), _getProxyAdmin(), \\\"\\\");\\n auth = PoolRolesAuthority(address(proxy));\\n auth.initialize(address(this));\\n poolsAuthorities[pool] = auth;\\n\\n auth.openPoolSupplierCapabilities(IonicComptroller(pool));\\n auth.setUserRole(address(this), auth.REGISTRY_ROLE(), true);\\n // sets the registry owner as the auth owner\\n reconfigureAuthority(pool);\\n }\\n\\n function reconfigureAuthority(address poolAddress) public {\\n IonicComptroller pool = IonicComptroller(poolAddress);\\n PoolRolesAuthority auth = poolsAuthorities[address(pool)];\\n\\n if (msg.sender != poolAddress || address(auth) != address(0)) {\\n require(address(auth) != address(0), \\\"no such authority\\\");\\n require(msg.sender == owner() || msg.sender == poolAddress, \\\"not owner or pool\\\");\\n\\n auth.configureRegistryCapabilities();\\n auth.configurePoolSupplierCapabilities(pool);\\n auth.configurePoolBorrowerCapabilities(pool);\\n // everyone can be a liquidator\\n auth.configureOpenPoolLiquidatorCapabilities(pool);\\n auth.configureLeveredPositionCapabilities(pool);\\n\\n if (auth.owner() != owner()) {\\n auth.setOwner(owner());\\n }\\n }\\n }\\n\\n function canCall(\\n address pool,\\n address user,\\n address target,\\n bytes4 functionSig\\n ) external view returns (bool) {\\n PoolRolesAuthority authorityForPool = poolsAuthorities[pool];\\n if (address(authorityForPool) == address(0)) {\\n return noAuthRequired;\\n } else {\\n // allow only if an auth exists and it allows the action\\n return authorityForPool.canCall(user, target, functionSig);\\n }\\n }\\n\\n function setUserRole(\\n address pool,\\n address user,\\n uint8 role,\\n bool enabled\\n ) external {\\n PoolRolesAuthority poolAuth = poolsAuthorities[pool];\\n\\n require(address(poolAuth) != address(0), \\\"auth does not exist\\\");\\n require(msg.sender == owner() || msg.sender == leveredPositionsFactory, \\\"not owner or factory\\\");\\n require(msg.sender != leveredPositionsFactory || role == poolAuth.LEVERED_POSITION_ROLE(), \\\"only lev pos role\\\");\\n\\n poolAuth.setUserRole(user, role, enabled);\\n }\\n}\\n\",\"keccak256\":\"0x98fc1f8a735b5759fc7524e3065ae322703d2771e7ec429e1cc9b60a4b1028dd\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/DiamondExtension.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\n/**\\n * @notice a base contract for logic extensions that use the diamond pattern storage\\n * to map the functions when looking up the extension contract to delegate to.\\n */\\nabstract contract DiamondExtension {\\n /**\\n * @return a list of all the function selectors that this logic extension exposes\\n */\\n function _getExtensionFunctions() external pure virtual returns (bytes4[] memory);\\n}\\n\\n// When no function exists for function called\\nerror FunctionNotFound(bytes4 _functionSelector);\\n\\n// When no extension exists for function called\\nerror ExtensionNotFound(bytes4 _functionSelector);\\n\\n// When the function is already added\\nerror FunctionAlreadyAdded(bytes4 _functionSelector, address _currentImpl);\\n\\nabstract contract DiamondBase {\\n /**\\n * @dev register a logic extension\\n * @param extensionToAdd the extension whose functions are to be added\\n * @param extensionToReplace the extension whose functions are to be removed/replaced\\n */\\n function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) external virtual;\\n\\n function _listExtensions() public view returns (address[] memory) {\\n return LibDiamond.listExtensions();\\n }\\n\\n fallback() external {\\n address extension = LibDiamond.getExtensionForFunction(msg.sig);\\n if (extension == address(0)) revert FunctionNotFound(msg.sig);\\n // Execute external function from extension using delegatecall and return any value.\\n assembly {\\n // copy function selector and any arguments\\n calldatacopy(0, 0, calldatasize())\\n // execute function call using the extension\\n let result := delegatecall(gas(), extension, 0, calldatasize(), 0, 0)\\n // get any return value\\n returndatacopy(0, 0, returndatasize())\\n // return any return value or error back to the caller\\n switch result\\n case 0 {\\n revert(0, returndatasize())\\n }\\n default {\\n return(0, returndatasize())\\n }\\n }\\n }\\n}\\n\\n/**\\n * @notice a library to use in a contract, whose logic is extended with diamond extension\\n */\\nlibrary LibDiamond {\\n bytes32 constant DIAMOND_STORAGE_POSITION = keccak256(\\\"diamond.extensions.diamond.storage\\\");\\n\\n struct Function {\\n address extension;\\n bytes4 selector;\\n }\\n\\n struct LogicStorage {\\n Function[] functions;\\n address[] extensions;\\n }\\n\\n function getExtensionForFunction(bytes4 msgSig) internal view returns (address) {\\n return getExtensionForSelector(msgSig, diamondStorage());\\n }\\n\\n function diamondStorage() internal pure returns (LogicStorage storage ds) {\\n bytes32 position = DIAMOND_STORAGE_POSITION;\\n assembly {\\n ds.slot := position\\n }\\n }\\n\\n function listExtensions() internal view returns (address[] memory) {\\n return diamondStorage().extensions;\\n }\\n\\n function registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) internal {\\n if (address(extensionToReplace) != address(0)) {\\n removeExtension(extensionToReplace);\\n }\\n addExtension(extensionToAdd);\\n }\\n\\n function removeExtension(DiamondExtension extension) internal {\\n LogicStorage storage ds = diamondStorage();\\n // remove all functions of the extension to replace\\n removeExtensionFunctions(extension);\\n for (uint8 i = 0; i < ds.extensions.length; i++) {\\n if (ds.extensions[i] == address(extension)) {\\n ds.extensions[i] = ds.extensions[ds.extensions.length - 1];\\n ds.extensions.pop();\\n }\\n }\\n }\\n\\n function addExtension(DiamondExtension extension) internal {\\n LogicStorage storage ds = diamondStorage();\\n for (uint8 i = 0; i < ds.extensions.length; i++) {\\n require(ds.extensions[i] != address(extension), \\\"extension already added\\\");\\n }\\n addExtensionFunctions(extension);\\n ds.extensions.push(address(extension));\\n }\\n\\n function removeExtensionFunctions(DiamondExtension extension) internal {\\n bytes4[] memory fnsToRemove = extension._getExtensionFunctions();\\n LogicStorage storage ds = diamondStorage();\\n for (uint16 i = 0; i < fnsToRemove.length; i++) {\\n bytes4 selectorToRemove = fnsToRemove[i];\\n // must never fail\\n assert(address(extension) == getExtensionForSelector(selectorToRemove, ds));\\n // swap with the last element in the selectorAtIndex array and remove the last element\\n uint16 indexToKeep = getIndexForSelector(selectorToRemove, ds);\\n ds.functions[indexToKeep] = ds.functions[ds.functions.length - 1];\\n ds.functions.pop();\\n }\\n }\\n\\n function addExtensionFunctions(DiamondExtension extension) internal {\\n bytes4[] memory fnsToAdd = extension._getExtensionFunctions();\\n LogicStorage storage ds = diamondStorage();\\n uint16 functionsCount = uint16(ds.functions.length);\\n for (uint256 functionsIndex = 0; functionsIndex < fnsToAdd.length; functionsIndex++) {\\n bytes4 selector = fnsToAdd[functionsIndex];\\n address oldImplementation = getExtensionForSelector(selector, ds);\\n if (oldImplementation != address(0)) revert FunctionAlreadyAdded(selector, oldImplementation);\\n ds.functions.push(Function(address(extension), selector));\\n functionsCount++;\\n }\\n }\\n\\n function getExtensionForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (address) {\\n uint256 fnsLen = ds.functions.length;\\n for (uint256 i = 0; i < fnsLen; i++) {\\n if (ds.functions[i].selector == selector) return ds.functions[i].extension;\\n }\\n\\n return address(0);\\n }\\n\\n function getIndexForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (uint16) {\\n uint16 fnsLen = uint16(ds.functions.length);\\n for (uint16 i = 0; i < fnsLen; i++) {\\n if (ds.functions[i].selector == selector) return i;\\n }\\n\\n return type(uint16).max;\\n }\\n}\\n\",\"keccak256\":\"0x6d33291928e3c255f0276fa465dcc5ea88d74a6562241a39ad2e52ae8abaf7bc\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/PoolRolesAuthority.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport { IonicComptroller, ComptrollerInterface } from \\\"../compound/ComptrollerInterface.sol\\\";\\nimport { ICErc20, CTokenSecondExtensionInterface, CTokenFirstExtensionInterface } from \\\"../compound/CTokenInterfaces.sol\\\";\\n\\nimport { RolesAuthority, Authority } from \\\"solmate/auth/authorities/RolesAuthority.sol\\\";\\n\\nimport \\\"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\\\";\\n\\ncontract PoolRolesAuthority is RolesAuthority, Initializable {\\n constructor() RolesAuthority(address(0), Authority(address(0))) {\\n _disableInitializers();\\n }\\n\\n function initialize(address _owner) public initializer {\\n owner = _owner;\\n authority = this;\\n }\\n\\n // up to 256 roles\\n uint8 public constant REGISTRY_ROLE = 0;\\n uint8 public constant SUPPLIER_ROLE = 1;\\n uint8 public constant BORROWER_ROLE = 2;\\n uint8 public constant LIQUIDATOR_ROLE = 3;\\n uint8 public constant LEVERED_POSITION_ROLE = 4;\\n\\n function configureRegistryCapabilities() external requiresAuth {\\n setRoleCapability(REGISTRY_ROLE, address(this), PoolRolesAuthority.configureRegistryCapabilities.selector, true);\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configurePoolSupplierCapabilities.selector,\\n true\\n );\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configurePoolBorrowerCapabilities.selector,\\n true\\n );\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configureClosedPoolLiquidatorCapabilities.selector,\\n true\\n );\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configureOpenPoolLiquidatorCapabilities.selector,\\n true\\n );\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configureLeveredPositionCapabilities.selector,\\n true\\n );\\n setRoleCapability(REGISTRY_ROLE, address(this), RolesAuthority.setUserRole.selector, true);\\n }\\n\\n function openPoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {\\n _setPublicPoolSupplierCapabilities(pool, true);\\n }\\n\\n function closePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {\\n _setPublicPoolSupplierCapabilities(pool, false);\\n }\\n\\n function _setPublicPoolSupplierCapabilities(IonicComptroller pool, bool setPublic) internal {\\n setPublicCapability(address(pool), pool.enterMarkets.selector, setPublic);\\n setPublicCapability(address(pool), pool.exitMarket.selector, setPublic);\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n bytes4[] memory selectors = getSupplierMarketSelectors();\\n for (uint256 j = 0; j < selectors.length; j++) {\\n setPublicCapability(address(allMarkets[i]), selectors[j], setPublic);\\n }\\n }\\n }\\n\\n function configurePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {\\n _configurePoolSupplierCapabilities(pool, SUPPLIER_ROLE);\\n }\\n\\n function getSupplierMarketSelectors() internal pure returns (bytes4[] memory selectors) {\\n uint8 fnsCount = 6;\\n selectors = new bytes4[](fnsCount);\\n selectors[--fnsCount] = CTokenSecondExtensionInterface.mint.selector;\\n selectors[--fnsCount] = CTokenSecondExtensionInterface.redeem.selector;\\n selectors[--fnsCount] = CTokenSecondExtensionInterface.redeemUnderlying.selector;\\n selectors[--fnsCount] = CTokenFirstExtensionInterface.transfer.selector;\\n selectors[--fnsCount] = CTokenFirstExtensionInterface.transferFrom.selector;\\n selectors[--fnsCount] = CTokenFirstExtensionInterface.approve.selector;\\n\\n require(fnsCount == 0, \\\"use the correct array length\\\");\\n return selectors;\\n }\\n\\n function _configurePoolSupplierCapabilities(IonicComptroller pool, uint8 role) internal {\\n setRoleCapability(role, address(pool), pool.enterMarkets.selector, true);\\n setRoleCapability(role, address(pool), pool.exitMarket.selector, true);\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n bytes4[] memory selectors = getSupplierMarketSelectors();\\n for (uint256 j = 0; j < selectors.length; j++) {\\n setRoleCapability(role, address(allMarkets[i]), selectors[j], true);\\n }\\n }\\n }\\n\\n function openPoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {\\n _setPublicPoolBorrowerCapabilities(pool, true);\\n }\\n\\n function closePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {\\n _setPublicPoolBorrowerCapabilities(pool, false);\\n }\\n\\n function _setPublicPoolBorrowerCapabilities(IonicComptroller pool, bool setPublic) internal {\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].borrow.selector, setPublic);\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrow.selector, setPublic);\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, setPublic);\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].flash.selector, setPublic);\\n }\\n }\\n\\n function configurePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {\\n // borrowers have the SUPPLIER_ROLE capabilities by default\\n _configurePoolSupplierCapabilities(pool, BORROWER_ROLE);\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true);\\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true);\\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, true);\\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true);\\n }\\n }\\n\\n function configureClosedPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth {\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, false);\\n setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true);\\n setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true);\\n }\\n }\\n\\n function configureOpenPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth {\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true);\\n // TODO this leaves redeeming open for everyone\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].redeem.selector, true);\\n }\\n }\\n\\n function configureLeveredPositionCapabilities(IonicComptroller pool) external requiresAuth {\\n setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.enterMarkets.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.exitMarket.selector, true);\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].mint.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeemUnderlying.selector, true);\\n\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x233d26db3755cf0c7bf0bba3a695a742bbfc15fd168fb76bbe307c5ac259b5bf\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/SafeOwnableUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport \\\"@openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol\\\";\\n\\n/**\\n * @dev Ownable extension that requires a two-step process of setting the pending owner and the owner accepting it.\\n * @notice Existing OwnableUpgradeable contracts cannot be upgraded due to the extra storage variable\\n * that will shift the other.\\n */\\nabstract contract SafeOwnableUpgradeable is OwnableUpgradeable {\\n /**\\n * @notice Pending owner of this contract\\n */\\n address public pendingOwner;\\n\\n function __SafeOwnable_init(address owner_) internal onlyInitializing {\\n __Ownable_init();\\n _transferOwnership(owner_);\\n }\\n\\n struct AddressSlot {\\n address value;\\n }\\n\\n modifier onlyOwnerOrAdmin() {\\n bool isOwner = owner() == _msgSender();\\n if (!isOwner) {\\n address admin = _getProxyAdmin();\\n bool isAdmin = admin == _msgSender();\\n require(isAdmin, \\\"Ownable: caller is neither the owner nor the admin\\\");\\n }\\n _;\\n }\\n\\n /**\\n * @notice Emitted when pendingOwner is changed\\n */\\n event NewPendingOwner(address oldPendingOwner, address newPendingOwner);\\n\\n /**\\n * @notice Emitted when pendingOwner is accepted, which means owner is updated\\n */\\n event NewOwner(address oldOwner, address newOwner);\\n\\n /**\\n * @notice Begins transfer of owner rights. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\\n * @dev Owner function to begin change of owner. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\\n * @param newPendingOwner New pending owner.\\n */\\n function _setPendingOwner(address newPendingOwner) public onlyOwner {\\n // Save current value, if any, for inclusion in log\\n address oldPendingOwner = pendingOwner;\\n\\n // Store pendingOwner with value newPendingOwner\\n pendingOwner = newPendingOwner;\\n\\n // Emit NewPendingOwner(oldPendingOwner, newPendingOwner)\\n emit NewPendingOwner(oldPendingOwner, newPendingOwner);\\n }\\n\\n /**\\n * @notice Accepts transfer of owner rights. msg.sender must be pendingOwner\\n * @dev Owner function for pending owner to accept role and update owner\\n */\\n function _acceptOwner() public {\\n // Check caller is pendingOwner and pendingOwner \\u2260 address(0)\\n require(msg.sender == pendingOwner, \\\"not the pending owner\\\");\\n\\n // Save current values for inclusion in log\\n address oldOwner = owner();\\n address oldPendingOwner = pendingOwner;\\n\\n // Store owner with value pendingOwner\\n _transferOwnership(pendingOwner);\\n\\n // Clear the pending value\\n pendingOwner = address(0);\\n\\n emit NewOwner(oldOwner, pendingOwner);\\n emit NewPendingOwner(oldPendingOwner, pendingOwner);\\n }\\n\\n function renounceOwnership() public override onlyOwner {\\n // do not remove this overriding fn\\n revert(\\\"not used anymore\\\");\\n }\\n\\n function transferOwnership(address newOwner) public override onlyOwner {\\n emit NewPendingOwner(pendingOwner, newOwner);\\n pendingOwner = newOwner;\\n }\\n\\n function _getProxyAdmin() internal view returns (address admin) {\\n bytes32 _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\\n AddressSlot storage adminSlot;\\n assembly {\\n adminSlot.slot := _ADMIN_SLOT\\n }\\n admin = adminSlot.value;\\n }\\n}\\n\",\"keccak256\":\"0x74641db987b6d12c8c412818b8a7708332778736193b2cb127ea54e80b334186\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/strategies/IonicERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\nimport { FixedPointMathLib } from \\\"solmate/utils/FixedPointMathLib.sol\\\";\\n\\nimport { PausableUpgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/security/PausableUpgradeable.sol\\\";\\nimport { ERC4626Upgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol\\\";\\nimport { ERC20Upgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\\\";\\nimport { SafeERC20Upgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\\\";\\n\\nimport { SafeOwnableUpgradeable } from \\\"../../ionic/SafeOwnableUpgradeable.sol\\\";\\n\\nabstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, ERC4626Upgradeable {\\n using FixedPointMathLib for uint256;\\n using SafeERC20Upgradeable for ERC20Upgradeable;\\n\\n /* ========== STATE VARIABLES ========== */\\n\\n uint256 public vaultShareHWM;\\n uint256 public performanceFee;\\n address public feeRecipient;\\n\\n /* ========== EVENTS ========== */\\n\\n event UpdatedFeeSettings(\\n uint256 oldPerformanceFee,\\n uint256 newPerformanceFee,\\n address oldFeeRecipient,\\n address newFeeRecipient\\n );\\n\\n event UpdatedRewardsRecipient(address oldRewardsRecipient, address newRewardsRecipient);\\n\\n /* ========== INITIALIZER ========== */\\n\\n function __IonicER4626_init(ERC20Upgradeable asset_) internal onlyInitializing {\\n __SafeOwnable_init(msg.sender);\\n __Pausable_init();\\n __Context_init();\\n __ERC20_init(\\n string(abi.encodePacked(\\\"Ionic \\\", asset_.name(), \\\" Vault\\\")),\\n string(abi.encodePacked(\\\"iv\\\", asset_.symbol()))\\n );\\n __ERC4626_init(asset_);\\n\\n vaultShareHWM = 10 ** asset_.decimals();\\n feeRecipient = msg.sender;\\n }\\n\\n function _asset() internal view returns (ERC20Upgradeable) {\\n return ERC20Upgradeable(super.asset());\\n }\\n\\n /* ========== DEPOSIT/WITHDRAW FUNCTIONS ========== */\\n\\n function deposit(uint256 assets, address receiver) public override whenNotPaused returns (uint256 shares) {\\n // Check for rounding error since we round down in previewDeposit.\\n require((shares = previewDeposit(assets)) != 0, \\\"ZERO_SHARES\\\");\\n\\n // Need to transfer before minting or ERC777s could reenter.\\n _asset().safeTransferFrom(msg.sender, address(this), assets);\\n\\n _mint(receiver, shares);\\n\\n emit Deposit(msg.sender, receiver, assets, shares);\\n\\n afterDeposit(assets, shares);\\n }\\n\\n function mint(uint256 shares, address receiver) public override whenNotPaused returns (uint256 assets) {\\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\\n\\n // Need to transfer before minting or ERC777s could reenter.\\n _asset().safeTransferFrom(msg.sender, address(this), assets);\\n\\n _mint(receiver, shares);\\n\\n emit Deposit(msg.sender, receiver, assets, shares);\\n\\n afterDeposit(assets, shares);\\n }\\n\\n function withdraw(uint256 assets, address receiver, address owner) public override returns (uint256 shares) {\\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\\n\\n if (msg.sender != owner) {\\n uint256 allowed = allowance(owner, msg.sender); // Saves gas for limited approvals.\\n\\n if (allowed != type(uint256).max) _approve(owner, msg.sender, allowed - shares);\\n }\\n\\n if (!paused()) {\\n uint256 balanceBeforeWithdraw = _asset().balanceOf(address(this));\\n\\n beforeWithdraw(assets, shares);\\n\\n assets = _asset().balanceOf(address(this)) - balanceBeforeWithdraw;\\n }\\n\\n _burn(owner, shares);\\n\\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\\n\\n _asset().safeTransfer(receiver, assets);\\n }\\n\\n function redeem(uint256 shares, address receiver, address owner) public override returns (uint256 assets) {\\n if (msg.sender != owner) {\\n uint256 allowed = allowance(owner, msg.sender); // Saves gas for limited approvals.\\n\\n if (allowed != type(uint256).max) _approve(owner, msg.sender, allowed - shares);\\n }\\n\\n // Check for rounding error since we round down in previewRedeem.\\n require((assets = previewRedeem(shares)) != 0, \\\"ZERO_ASSETS\\\");\\n\\n if (!paused()) {\\n uint256 balanceBeforeWithdraw = _asset().balanceOf(address(this));\\n\\n beforeWithdraw(assets, shares);\\n\\n assets = _asset().balanceOf(address(this)) - balanceBeforeWithdraw;\\n }\\n\\n _burn(owner, shares);\\n\\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\\n\\n _asset().safeTransfer(receiver, assets);\\n }\\n\\n /* ========== FEE FUNCTIONS ========== */\\n\\n /**\\n * @notice Take the performance fee that has accrued since last fee harvest.\\n * @dev Performance fee is based on a vault share high water mark value. If vault share value has increased above the\\n * HWM in a fee period, issue fee shares to the vault equal to the performance fee.\\n */\\n function takePerformanceFee() external onlyOwner {\\n require(feeRecipient != address(0), \\\"fee recipient not initialized\\\");\\n\\n uint256 currentAssets = totalAssets();\\n uint256 shareValue = convertToAssets(10 ** _asset().decimals());\\n\\n require(shareValue > vaultShareHWM, \\\"shareValue !> vaultShareHWM\\\");\\n // cache value\\n uint256 supply = totalSupply();\\n\\n uint256 accruedPerformanceFee = (performanceFee * (shareValue - vaultShareHWM) * supply) / 1e36;\\n _mint(feeRecipient, accruedPerformanceFee.mulDivDown(supply, (currentAssets - accruedPerformanceFee)));\\n\\n vaultShareHWM = convertToAssets(10 ** _asset().decimals());\\n }\\n\\n /**\\n * @notice Transfer accrued fees to rewards manager contract. Caller must be a registered keeper.\\n * @dev We must make sure that feeRecipient is not address(0) before withdrawing fees\\n */\\n function withdrawAccruedFees() external onlyOwner {\\n redeem(balanceOf(feeRecipient), feeRecipient, feeRecipient);\\n }\\n\\n /**\\n * @notice Update performanceFee and/or feeRecipient\\n */\\n function updateFeeSettings(uint256 newPerformanceFee, address newFeeRecipient) external onlyOwner {\\n emit UpdatedFeeSettings(performanceFee, newPerformanceFee, feeRecipient, newFeeRecipient);\\n\\n performanceFee = newPerformanceFee;\\n\\n if (newFeeRecipient != feeRecipient) {\\n if (feeRecipient != address(0)) {\\n uint256 oldFees = balanceOf(feeRecipient);\\n\\n _burn(feeRecipient, oldFees);\\n _approve(feeRecipient, owner(), 0);\\n _mint(newFeeRecipient, oldFees);\\n }\\n\\n _approve(newFeeRecipient, owner(), type(uint256).max);\\n }\\n\\n feeRecipient = newFeeRecipient;\\n }\\n\\n /* ========== EMERGENCY FUNCTIONS ========== */\\n\\n // Should withdraw all funds from the strategy and pause the contract\\n function emergencyWithdrawAndPause() external virtual;\\n\\n function unpause() external virtual;\\n\\n function shutdown(address market) external onlyOwner whenPaused returns (uint256) {\\n ERC20Upgradeable theAsset = _asset();\\n uint256 endBalance = theAsset.balanceOf(address(this));\\n theAsset.transfer(market, endBalance);\\n return endBalance;\\n }\\n\\n /* ========== INTERNAL HOOKS LOGIC ========== */\\n\\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual;\\n\\n function afterDeposit(uint256 assets, uint256 shares) internal virtual;\\n}\\n\",\"keccak256\":\"0x1d5626eba320157d52a75cc2e86518bf82b5e8017efc42649094f3115b6a6927\",\"license\":\"AGPL-3.0-only\"},\"contracts/src/ionic/strategies/IonicMarketERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: Unlicense\\npragma solidity ^0.8.22;\\nimport { IonicERC4626, ERC20Upgradeable } from \\\"./IonicERC4626.sol\\\";\\nimport { SafeERC20Upgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\\\";\\nimport { ICErc20 } from \\\"../../compound/CTokenInterfaces.sol\\\";\\nimport { ComptrollerErrorReporter } from \\\"../../compound/ErrorReporter.sol\\\";\\n\\ninterface IonicFlywheelLensRouter_4626 {\\n function claimAllRewardTokens(address user) external returns (address[] memory, uint256[] memory);\\n}\\n\\ncontract IonicMarketERC4626 is IonicERC4626 {\\n using SafeERC20Upgradeable for ERC20Upgradeable;\\n\\n error IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error);\\n\\n // STATE VARIABLES\\n address public rewardsRecipient;\\n IonicFlywheelLensRouter_4626 public flywheelLensRouter;\\n ICErc20 public cToken;\\n\\n function initialize(\\n ICErc20 cToken_,\\n address flywheelLensRouter_,\\n address rewardsRecipient_\\n ) public initializer {\\n __IonicER4626_init(ERC20Upgradeable(cToken_.underlying()));\\n cToken = cToken_;\\n rewardsRecipient = rewardsRecipient_;\\n flywheelLensRouter = IonicFlywheelLensRouter_4626(flywheelLensRouter_);\\n }\\n\\n /* ========== VIEW FUNCTIONS ========== */\\n function totalAssets() public view virtual override returns (uint256) {\\n return cToken.balanceOfUnderlying(address(this));\\n }\\n\\n /// @notice maximum amount of underlying tokens that can be deposited into the underlying protocol\\n function maxDeposit(address) public view override returns (uint256) {\\n if (cToken.comptroller().mintGuardianPaused(address(cToken))) {\\n return 0;\\n }\\n\\n uint256 supplyCap = cToken.comptroller().supplyCaps(address(cToken));\\n if (supplyCap != 0) {\\n uint256 currentExchangeRate = cToken.exchangeRateCurrent();\\n uint256 _totalSupply = cToken.totalSupply();\\n uint256 totalSupplies = (_totalSupply * currentExchangeRate) / 1e18; /// exchange rate is scaled up by 1e18, so needs to be divided off to get accurate total supply\\n\\n // uint256 totalCash = MToken(address(mToken)).getCash();\\n // uint256 totalBorrows = MToken(address(mToken)).totalBorrows();\\n // uint256 totalReserves = MToken(address(mToken)).totalReserves();\\n\\n // // (Pseudocode) totalSupplies = totalCash + totalBorrows - totalReserves\\n // uint256 totalSupplies = (totalCash + totalBorrows) - totalReserves;\\n\\n // supply cap is 3\\n // total supplies is 1\\n /// no room for additional supplies\\n\\n // supply cap is 3\\n // total supplies is 0\\n /// room for 1 additional supplies\\n\\n // supply cap is 4\\n // total supplies is 1\\n /// room for 1 additional supplies\\n\\n /// total supplies could exceed supply cap as interest accrues, need to handle this edge case\\n /// going to subtract 2 from supply cap to account for rounding errors\\n if (totalSupplies + 2 >= supplyCap) {\\n return 0;\\n }\\n\\n return supplyCap - totalSupplies - 2;\\n }\\n\\n return type(uint256).max;\\n }\\n\\n /// @notice Returns the maximum amount of tokens that can be supplied\\n /// no way for this function to ever revert unless comptroller or mToken is broken\\n /// @dev accrue interest must be called before this function is called, otherwise\\n /// an outdated value will be fetched, and the returned value will be incorrect\\n /// (greater than actual amount available to be minted will be returned)\\n function maxMint(address) public view override returns (uint256) {\\n uint256 mintAmount = maxDeposit(address(0));\\n\\n return mintAmount == type(uint256).max ? mintAmount : convertToShares(mintAmount);\\n }\\n\\n /// @notice maximum amount of underlying tokens that can be withdrawn\\n /// @param owner The address that owns the shares\\n function maxWithdraw(address owner) public view override returns (uint256) {\\n uint256 cash = cToken.getCash();\\n uint256 assetsBalance = convertToAssets(balanceOf(owner));\\n return cash < assetsBalance ? cash : assetsBalance;\\n }\\n\\n /// @notice maximum amount of shares that can be withdrawn\\n /// @param owner The address that owns the shares\\n function maxRedeem(address owner) public view override returns (uint256) {\\n uint256 cash = cToken.getCash();\\n uint256 cashInShares = convertToShares(cash);\\n uint256 shareBalance = balanceOf(owner);\\n return cashInShares < shareBalance ? cashInShares : shareBalance;\\n }\\n\\n /* ========== REWARDS FUNCTIONS ========== */\\n\\n function updateRewardsRecipient(address newRewardsRecipient) external onlyOwner {\\n emit UpdatedRewardsRecipient(rewardsRecipient, newRewardsRecipient);\\n rewardsRecipient = newRewardsRecipient;\\n }\\n\\n function claimRewards() external {\\n (address[] memory tokens, uint256[] memory amounts) = flywheelLensRouter.claimAllRewardTokens(address(this));\\n for (uint256 i = 0; i < tokens.length; i++) {\\n _asset().safeTransfer(rewardsRecipient, amounts[i]);\\n }\\n }\\n\\n /* ========== EMERGENCY FUNCTIONS ========== */\\n\\n // Should withdraw all funds from the strategy and pause the contract\\n function emergencyWithdrawAndPause() external override onlyOwner {\\n _pause();\\n }\\n\\n function unpause() external override onlyOwner {\\n _unpause();\\n }\\n\\n /* ========== INTERNAL HOOKS LOGIC ========== */\\n\\n function beforeWithdraw(uint256 assets, uint256 /*shares*/) internal override {\\n /// -----------------------------------------------------------------------\\n /// Withdraw assets from Ionic\\n /// -----------------------------------------------------------------------\\n\\n uint256 errorCode = cToken.redeemUnderlying(assets);\\n if (errorCode != uint256(ComptrollerErrorReporter.Error.NO_ERROR)) {\\n revert IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error(errorCode));\\n }\\n }\\n\\n function afterDeposit(uint256 assets, uint256 /*shares*/) internal override {\\n /// -----------------------------------------------------------------------\\n /// Deposit assets into Ionic\\n /// -----------------------------------------------------------------------\\n\\n // approve to cToken\\n _asset().safeApprove(address(cToken), assets);\\n\\n // deposit into cToken\\n uint256 errorCode = cToken.mint(assets);\\n if (errorCode != uint256(ComptrollerErrorReporter.Error.NO_ERROR)) {\\n revert IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error(errorCode));\\n }\\n }\\n}\\n\",\"keccak256\":\"0x7e7102541f79cdad000e9de32145a080a1150dfad9b4b55ec87cb475c83d8858\",\"license\":\"Unlicense\"},\"contracts/src/oracles/BasePriceOracle.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport \\\"../compound/CTokenInterfaces.sol\\\";\\n\\n/**\\n * @title BasePriceOracle\\n * @notice Returns prices of underlying tokens directly without the caller having to specify a cToken address.\\n * @dev Implements the `PriceOracle` interface.\\n * @author David Lucid (https://github.com/davidlucid)\\n */\\ninterface BasePriceOracle {\\n /**\\n * @notice Get the price of an underlying asset.\\n * @param underlying The underlying asset to get the price of.\\n * @return The underlying asset price in ETH as a mantissa (scaled by 1e18).\\n * Zero means the price is unavailable.\\n */\\n function price(address underlying) external view returns (uint256);\\n\\n /**\\n * @notice Get the underlying price of a cToken asset\\n * @param cToken The cToken to get the underlying price of\\n * @return The underlying asset price mantissa (scaled by 1e18).\\n * Zero means the price is unavailable.\\n */\\n function getUnderlyingPrice(ICErc20 cToken) external view returns (uint256);\\n}\\n\",\"keccak256\":\"0xed2a27a8dc71a4280c0ef19d3165ff237d8066ae782e750b071bb39d12e73404\",\"license\":\"UNLICENSED\"},\"solmate/auth/Auth.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)\\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\\nabstract contract Auth {\\n event OwnerUpdated(address indexed user, address indexed newOwner);\\n\\n event AuthorityUpdated(address indexed user, Authority indexed newAuthority);\\n\\n address public owner;\\n\\n Authority public authority;\\n\\n constructor(address _owner, Authority _authority) {\\n owner = _owner;\\n authority = _authority;\\n\\n emit OwnerUpdated(msg.sender, _owner);\\n emit AuthorityUpdated(msg.sender, _authority);\\n }\\n\\n modifier requiresAuth() virtual {\\n require(isAuthorized(msg.sender, msg.sig), \\\"UNAUTHORIZED\\\");\\n\\n _;\\n }\\n\\n function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {\\n Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.\\n\\n // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be\\n // aware that this makes protected functions uncallable even to the owner if the authority is out of order.\\n return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;\\n }\\n\\n function setAuthority(Authority newAuthority) public virtual {\\n // We check if the caller is the owner first because we want to ensure they can\\n // always swap out the authority even if it's reverting or using up a lot of gas.\\n require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));\\n\\n authority = newAuthority;\\n\\n emit AuthorityUpdated(msg.sender, newAuthority);\\n }\\n\\n function setOwner(address newOwner) public virtual requiresAuth {\\n owner = newOwner;\\n\\n emit OwnerUpdated(msg.sender, newOwner);\\n }\\n}\\n\\n/// @notice A generic interface for a contract which provides authorization data to an Auth instance.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)\\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\\ninterface Authority {\\n function canCall(\\n address user,\\n address target,\\n bytes4 functionSig\\n ) external view returns (bool);\\n}\\n\",\"keccak256\":\"0xd5cf8213a40d727af89c93dd359ad68984c123c1a1a93fc9ad7ba62b3436fb75\",\"license\":\"AGPL-3.0-only\"},\"solmate/auth/authorities/RolesAuthority.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\nimport {Auth, Authority} from \\\"../Auth.sol\\\";\\n\\n/// @notice Role based Authority that supports up to 256 roles.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/authorities/RolesAuthority.sol)\\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-roles/blob/master/src/roles.sol)\\ncontract RolesAuthority is Auth, Authority {\\n /*//////////////////////////////////////////////////////////////\\n EVENTS\\n //////////////////////////////////////////////////////////////*/\\n\\n event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled);\\n\\n event PublicCapabilityUpdated(address indexed target, bytes4 indexed functionSig, bool enabled);\\n\\n event RoleCapabilityUpdated(uint8 indexed role, address indexed target, bytes4 indexed functionSig, bool enabled);\\n\\n /*//////////////////////////////////////////////////////////////\\n CONSTRUCTOR\\n //////////////////////////////////////////////////////////////*/\\n\\n constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}\\n\\n /*//////////////////////////////////////////////////////////////\\n ROLE/USER STORAGE\\n //////////////////////////////////////////////////////////////*/\\n\\n mapping(address => bytes32) public getUserRoles;\\n\\n mapping(address => mapping(bytes4 => bool)) public isCapabilityPublic;\\n\\n mapping(address => mapping(bytes4 => bytes32)) public getRolesWithCapability;\\n\\n function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) {\\n return (uint256(getUserRoles[user]) >> role) & 1 != 0;\\n }\\n\\n function doesRoleHaveCapability(\\n uint8 role,\\n address target,\\n bytes4 functionSig\\n ) public view virtual returns (bool) {\\n return (uint256(getRolesWithCapability[target][functionSig]) >> role) & 1 != 0;\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n AUTHORIZATION LOGIC\\n //////////////////////////////////////////////////////////////*/\\n\\n function canCall(\\n address user,\\n address target,\\n bytes4 functionSig\\n ) public view virtual override returns (bool) {\\n return\\n isCapabilityPublic[target][functionSig] ||\\n bytes32(0) != getUserRoles[user] & getRolesWithCapability[target][functionSig];\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n ROLE CAPABILITY CONFIGURATION LOGIC\\n //////////////////////////////////////////////////////////////*/\\n\\n function setPublicCapability(\\n address target,\\n bytes4 functionSig,\\n bool enabled\\n ) public virtual requiresAuth {\\n isCapabilityPublic[target][functionSig] = enabled;\\n\\n emit PublicCapabilityUpdated(target, functionSig, enabled);\\n }\\n\\n function setRoleCapability(\\n uint8 role,\\n address target,\\n bytes4 functionSig,\\n bool enabled\\n ) public virtual requiresAuth {\\n if (enabled) {\\n getRolesWithCapability[target][functionSig] |= bytes32(1 << role);\\n } else {\\n getRolesWithCapability[target][functionSig] &= ~bytes32(1 << role);\\n }\\n\\n emit RoleCapabilityUpdated(role, target, functionSig, enabled);\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n USER ROLE ASSIGNMENT LOGIC\\n //////////////////////////////////////////////////////////////*/\\n\\n function setUserRole(\\n address user,\\n uint8 role,\\n bool enabled\\n ) public virtual requiresAuth {\\n if (enabled) {\\n getUserRoles[user] |= bytes32(1 << role);\\n } else {\\n getUserRoles[user] &= ~bytes32(1 << role);\\n }\\n\\n emit UserRoleUpdated(user, role, enabled);\\n }\\n}\\n\",\"keccak256\":\"0x278247a2c5b0accb60af8d3749e34ab5d4436ee4f35a8fff301aaa25ab690762\",\"license\":\"AGPL-3.0-only\"},\"solmate/utils/FixedPointMathLib.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Arithmetic library with operations for fixed-point numbers.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\\nlibrary FixedPointMathLib {\\n /*//////////////////////////////////////////////////////////////\\n SIMPLIFIED FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\\n\\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\\n }\\n\\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\\n }\\n\\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\\n }\\n\\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n LOW LEVEL FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n function mulDivDown(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n assembly {\\n // Store x * y in z for now.\\n z := mul(x, y)\\n\\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\\n revert(0, 0)\\n }\\n\\n // Divide z by the denominator.\\n z := div(z, denominator)\\n }\\n }\\n\\n function mulDivUp(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n assembly {\\n // Store x * y in z for now.\\n z := mul(x, y)\\n\\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\\n revert(0, 0)\\n }\\n\\n // First, divide z - 1 by the denominator and add 1.\\n // We allow z - 1 to underflow if z is 0, because we multiply the\\n // end result by 0 if z is zero, ensuring we return 0 if z is zero.\\n z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))\\n }\\n }\\n\\n function rpow(\\n uint256 x,\\n uint256 n,\\n uint256 scalar\\n ) internal pure returns (uint256 z) {\\n assembly {\\n switch x\\n case 0 {\\n switch n\\n case 0 {\\n // 0 ** 0 = 1\\n z := scalar\\n }\\n default {\\n // 0 ** n = 0\\n z := 0\\n }\\n }\\n default {\\n switch mod(n, 2)\\n case 0 {\\n // If n is even, store scalar in z for now.\\n z := scalar\\n }\\n default {\\n // If n is odd, store x in z for now.\\n z := x\\n }\\n\\n // Shifting right by 1 is like dividing by 2.\\n let half := shr(1, scalar)\\n\\n for {\\n // Shift n right by 1 before looping to halve it.\\n n := shr(1, n)\\n } n {\\n // Shift n right by 1 each iteration to halve it.\\n n := shr(1, n)\\n } {\\n // Revert immediately if x ** 2 would overflow.\\n // Equivalent to iszero(eq(div(xx, x), x)) here.\\n if shr(128, x) {\\n revert(0, 0)\\n }\\n\\n // Store x squared.\\n let xx := mul(x, x)\\n\\n // Round to the nearest number.\\n let xxRound := add(xx, half)\\n\\n // Revert if xx + half overflowed.\\n if lt(xxRound, xx) {\\n revert(0, 0)\\n }\\n\\n // Set x to scaled xxRound.\\n x := div(xxRound, scalar)\\n\\n // If n is even:\\n if mod(n, 2) {\\n // Compute z * x.\\n let zx := mul(z, x)\\n\\n // If z * x overflowed:\\n if iszero(eq(div(zx, x), z)) {\\n // Revert if x is non-zero.\\n if iszero(iszero(x)) {\\n revert(0, 0)\\n }\\n }\\n\\n // Round to the nearest number.\\n let zxRound := add(zx, half)\\n\\n // Revert if zx + half overflowed.\\n if lt(zxRound, zx) {\\n revert(0, 0)\\n }\\n\\n // Return properly scaled zxRound.\\n z := div(zxRound, scalar)\\n }\\n }\\n }\\n }\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n GENERAL NUMBER UTILITIES\\n //////////////////////////////////////////////////////////////*/\\n\\n function sqrt(uint256 x) internal pure returns (uint256 z) {\\n assembly {\\n let y := x // We start y at x, which will help us make our initial estimate.\\n\\n z := 181 // The \\\"correct\\\" value is 1, but this saves a multiplication later.\\n\\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\\n\\n // We check y >= 2^(k + 8) but shift right by k bits\\n // each branch to ensure that if x >= 256, then y >= 256.\\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\\n y := shr(128, y)\\n z := shl(64, z)\\n }\\n if iszero(lt(y, 0x1000000000000000000)) {\\n y := shr(64, y)\\n z := shl(32, z)\\n }\\n if iszero(lt(y, 0x10000000000)) {\\n y := shr(32, y)\\n z := shl(16, z)\\n }\\n if iszero(lt(y, 0x1000000)) {\\n y := shr(16, y)\\n z := shl(8, z)\\n }\\n\\n // Goal was to get z*z*y within a small factor of x. More iterations could\\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\\n\\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\\n\\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\\n\\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\\n\\n // There is no overflow risk here since y < 2^136 after the first branch above.\\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\\n\\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n\\n // If x+1 is a perfect square, the Babylonian method cycles between\\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\\n z := sub(z, lt(div(x, z), z))\\n }\\n }\\n\\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n assembly {\\n // Mod x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n z := mod(x, y)\\n }\\n }\\n\\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\\n assembly {\\n // Divide x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n r := div(x, y)\\n }\\n }\\n\\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n assembly {\\n // Add 1 to x * y if x % y > 0. Note this will\\n // return 0 instead of reverting if y is zero.\\n z := add(gt(mod(x, y), 0), div(x, y))\\n }\\n }\\n}\\n\",\"keccak256\":\"0xab8ca9afbb0f7412e1408d4f111b53cc00813bc752236638ad336050ea2188f8\",\"license\":\"AGPL-3.0-only\"}},\"version\":1}", + "bytecode": "0x608060405234801561001057600080fd5b5061373a806100206000396000f3fe608060405234801561001057600080fd5b50600436106102bb5760003560e01c8063715018a611610182578063c0c53b8b116100e9578063dd62ed3e116100a2578063f2eb2a4b1161007c578063f2eb2a4b146105d3578063f2fde38b146105e6578063fc4d33f9146105f9578063ff2a7d301461060157600080fd5b8063dd62ed3e146105ad578063e30c3978146105c0578063ef8b30f71461056157600080fd5b8063c0c53b8b1461053b578063c63d75b61461054e578063c6e6f59214610561578063cce2f3fb14610574578063ce96cb7714610587578063d905777e1461059a57600080fd5b8063a9059cbb1161013b578063a9059cbb146104d4578063ada82c7d146104e7578063b3d7f6b9146104ef578063b460af9414610502578063ba08765214610515578063bb83b0e91461052857600080fd5b8063715018a614610484578063877887821461048c5780638da5cb5b1461049557806394bf804d146104a657806395d89b41146104b9578063a457c2d7146104c157600080fd5b806338d52e0f1161022657806356f89ef9116101df57806356f89ef9146104075780635c975abb1461040f57806369e527da146104215780636e553f65146104355780636e96dfd71461044857806370a082311461045b57600080fd5b806338d52e0f146103a157806339509351146103c65780633f4ba83a146103d9578063402d267d146103e157806346904840146103f45780634cdad506146102f057600080fd5b806318160ddd1161027857806318160ddd1461034e578063211493c91461035657806323b872dd1461035f5780632835797814610372578063313ce5671461037a578063372500ab1461039957600080fd5b806301e1d114146102c057806306fdde03146102db57806307a2d13a146102f0578063095ea7b3146103035780630a28a4771461032657806310509aa914610339575b600080fd5b6102c8610614565b6040519081526020015b60405180910390f35b6102e3610687565b6040516102d29190612eb0565b6102c86102fe366004612ee3565b610719565b610316610311366004612f11565b61072c565b60405190151581526020016102d2565b6102c8610334366004612ee3565b610744565b61034c610347366004612f3d565b610751565b005b6099546102c8565b6102c860fb5481565b61031661036d366004612f6d565b610877565b61034c61089d565b60c954600160a01b900460ff1660405160ff90911681526020016102d2565b61034c6108af565b60c9546001600160a01b03165b6040516001600160a01b0390911681526020016102d2565b6103166103d4366004612f11565b610988565b61034c6109aa565b6102c86103ef366004612fae565b6109ba565b60fd546103ae906001600160a01b031681565b61034c610cde565b606554600160a01b900460ff16610316565b610100546103ae906001600160a01b031681565b6102c8610443366004612f3d565b610eac565b61034c610456366004612fae565b610f78565b6102c8610469366004612fae565b6001600160a01b031660009081526097602052604090205490565b61034c610fe2565b6102c860fc5481565b6033546001600160a01b03166103ae565b6102c86104b4366004612f3d565b611025565b6102e36110a2565b6103166104cf366004612f11565b6110b1565b6103166104e2366004612f11565b611137565b61034c611145565b6102c86104fd366004612ee3565b611175565b6102c8610510366004612fcb565b611182565b6102c8610523366004612fcb565b61133b565b61034c610536366004612fae565b611532565b61034c61054936600461300d565b6115a3565b6102c861055c366004612fae565b611757565b6102c861056f366004612ee3565b61177d565b6102c8610582366004612fae565b61178a565b6102c8610595366004612fae565b611893565b6102c86105a8366004612fae565b61194d565b6102c86105bb36600461303d565b611a12565b6065546103ae906001600160a01b031681565b60ff546103ae906001600160a01b031681565b61034c6105f4366004612fae565b611a3d565b61034c611aae565b60fe546103ae906001600160a01b031681565b61010054604051633af9e66960e01b81523060048201526000916001600160a01b031690633af9e66990602401602060405180830381865afa15801561065e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610682919061306b565b905090565b6060609a805461069690613084565b80601f01602080910402602001604051908101604052809291908181526020018280546106c290613084565b801561070f5780601f106106e45761010080835404028352916020019161070f565b820191906000526020600020905b8154815290600101906020018083116106f257829003601f168201915b5050505050905090565b6000610726826000611bc2565b92915050565b60003361073a818585611bf5565b5060019392505050565b6000610726826001611d19565b610759611d4b565b60fc5460fd5460408051928352602083018590526001600160a01b0391821690830152821660608201527fb3b62da5184b9e7e2f5d280014bb485d4444b66738025e5fb5738bbddcb6b8489060800160405180910390a160fc82905560fd546001600160a01b038281169116146108545760fd546001600160a01b0316156108365760fd546001600160a01b0316600081815260976020526040902054906108019082611da5565b60fd5461082a906001600160a01b03166108236033546001600160a01b031690565b6000611bf5565b6108348282611ed9565b505b6108548161084c6033546001600160a01b031690565b600019611bf5565b60fd80546001600160a01b0319166001600160a01b039290921691909117905550565b600033610885858285611f9b565b61089085858561200f565b60019150505b9392505050565b6108a5611d4b565b6108ad6121ba565b565b60ff54604051639cf1fd5360e01b815230600482015260009182916001600160a01b0390911690639cf1fd53906024016000604051808303816000875af11580156108fe573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526109269190810190613198565b9150915060005b82518110156109835760fe54825161097b916001600160a01b03169084908490811061095b5761095b61325d565b602002602001015161096b61221a565b6001600160a01b0316919061222e565b60010161092d565b505050565b60003361073a81858561099b8383611a12565b6109a59190613289565b611bf5565b6109b2611d4b565b6108ad612291565b6101005460408051635fe3b56760e01b815290516000926001600160a01b031691635fe3b5679160048083019260209291908290030181865afa158015610a05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a29919061329c565b6101005460405163731f0c2b60e01b81526001600160a01b03918216600482015291169063731f0c2b90602401602060405180830381865afa158015610a73573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a9791906132b9565b15610aa457506000919050565b6101005460408051635fe3b56760e01b815290516000926001600160a01b031691635fe3b5679160048083019260209291908290030181865afa158015610aef573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b13919061329c565b610100546040516302c3bcbb60e01b81526001600160a01b0391821660048201529116906302c3bcbb90602401602060405180830381865afa158015610b5d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b81919061306b565b90508015610cd457610100546040805163bd6d894d60e01b815290516000926001600160a01b03169163bd6d894d9160048083019260209291908290030181865afa158015610bd4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf8919061306b565b9050600061010060009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c50573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c74919061306b565b90506000670de0b6b3a7640000610c8b84846132db565b610c959190613308565b905083610ca3826002613289565b10610cb45750600095945050505050565b6002610cc0828661332a565b610cca919061332a565b9695505050505050565b5060001992915050565b610ce6611d4b565b60fd546001600160a01b0316610d435760405162461bcd60e51b815260206004820152601d60248201527f66656520726563697069656e74206e6f7420696e697469616c697a656400000060448201526064015b60405180910390fd5b6000610d4d610614565b90506000610dc8610d5c61221a565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d99573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dbd919061333d565b6102fe90600a613444565b905060fb548111610e1b5760405162461bcd60e51b815260206004820152601b60248201527f736861726556616c756520213e207661756c74536861726548574d00000000006044820152606401610d3a565b6000610e2660995490565b905060006ec097ce7bc90715b34b9f10000000008260fb5485610e49919061332a565b60fc54610e5691906132db565b610e6091906132db565b610e6a9190613308565b60fd54909150610e98906001600160a01b0316610e9384610e8b858961332a565b8591906122cd565b611ed9565b610ea3610d5c61221a565b60fb5550505050565b6000610eb66122ec565b610ebf8361177d565b905080600003610eff5760405162461bcd60e51b815260206004820152600b60248201526a5a45524f5f53484152455360a81b6044820152606401610d3a565b610f1e333085610f0d61221a565b6001600160a01b0316929190612339565b610f288282611ed9565b60408051848152602081018390526001600160a01b0384169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a36107268382612371565b610f80611d4b565b606580546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b91015b60405180910390a15050565b610fea611d4b565b60405162461bcd60e51b815260206004820152601060248201526f6e6f74207573656420616e796d6f726560801b6044820152606401610d3a565b600061102f6122ec565b61103883611175565b9050611048333083610f0d61221a565b6110528284611ed9565b60408051828152602081018590526001600160a01b0384169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a36107268184612371565b6060609b805461069690613084565b600033816110bf8286611a12565b90508381101561111f5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610d3a565b61112c8286868403611bf5565b506001949350505050565b60003361073a81858561200f565b61114d611d4b565b60fd546001600160a01b0316600081815260976020526040902054611172918061133b565b50565b6000610726826001611bc2565b600061118d84610744565b9050336001600160a01b038316146111c75760006111ab8333611a12565b905060001981146111c5576111c583336109a5858561332a565b505b606554600160a01b900460ff166112d95760006111e261221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015611228573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124c919061306b565b90506112588583612441565b8061126161221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa1580156112a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112cb919061306b565b6112d5919061332a565b9450505b6112e38282611da5565b60408051858152602081018390526001600160a01b03808516929086169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4610896838561096b61221a565b6000336001600160a01b038316146113755760006113598333611a12565b905060001981146113735761137383336109a5888561332a565b505b61137e84610719565b9050806000036113be5760405162461bcd60e51b815260206004820152600b60248201526a5a45524f5f41535345545360a81b6044820152606401610d3a565b606554600160a01b900460ff166114d05760006113d961221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa15801561141f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611443919061306b565b905061144f8286612441565b8061145861221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa15801561149e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114c2919061306b565b6114cc919061332a565b9150505b6114da8285611da5565b60408051828152602081018690526001600160a01b03808516929086169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4610896838261096b61221a565b61153a611d4b565b60fe54604080516001600160a01b03928316815291831660208301527f2d9427f2d488d8f8716dae31ad2f0d476bcea0664cce8822d8dc76dde104b09e910160405180910390a160fe80546001600160a01b0319166001600160a01b0392909216919091179055565b600054610100900460ff16158080156115c35750600054600160ff909116105b806115dd5750303b1580156115dd575060005460ff166001145b6116405760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610d3a565b6000805460ff191660011790558015611663576000805461ff0019166101001790555b6116cd846001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116c8919061329c565b612474565b61010080546001600160a01b038087166001600160a01b03199283161790925560fe805485841690831617905560ff8054928616929091169190911790558015611751576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050565b60008061176460006109ba565b90506000198114610726576117788161177d565b610896565b6000610726826000611d19565b6000611794611d4b565b61179c612654565b60006117a661221a565b6040516370a0823160e01b81523060048201529091506000906001600160a01b038316906370a0823190602401602060405180830381865afa1580156117f0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611814919061306b565b60405163a9059cbb60e01b81526001600160a01b038681166004830152602482018390529192509083169063a9059cbb906044016020604051808303816000875af1158015611867573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061188b91906132b9565b509392505050565b60008061010060009054906101000a90046001600160a01b03166001600160a01b0316633b1d21a26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061190e919061306b565b905060006119346102fe856001600160a01b031660009081526097602052604090205490565b90508082106119435780611945565b815b949350505050565b60008061010060009054906101000a90046001600160a01b03166001600160a01b0316633b1d21a26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156119a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119c8919061306b565b905060006119d58261177d565b905060006119f8856001600160a01b031660009081526097602052604090205490565b9050808210611a075780611a09565b815b95945050505050565b6001600160a01b03918216600090815260986020908152604080832093909416825291909152205490565b611a45611d4b565b606554604080516001600160a01b03928316815291831660208301527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b910160405180910390a1606580546001600160a01b0319166001600160a01b0392909216919091179055565b6065546001600160a01b03163314611b005760405162461bcd60e51b81526020600482015260156024820152743737ba103a3432903832b73234b7339037bbb732b960591b6044820152606401610d3a565b6000611b146033546001600160a01b031690565b6065549091506001600160a01b0316611b2c816126a4565b606580546001600160a01b0319169055604080516001600160a01b0384168152600060208201527f70aea8d848e8a90fb7661b227dc522eb6395c3dac71b63cb59edd5c9899b2364910160405180910390a1606554604080516001600160a01b03808516825290921660208301527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b9101610fd6565b600080611bce60995490565b90508015611bef57611bea611be1610614565b859083866126f6565b611945565b83611945565b6001600160a01b038316611c575760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610d3a565b6001600160a01b038216611cb85760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610d3a565b6001600160a01b0383811660008181526098602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b600080611d2560995490565b9050831580611d32575080155b611bef57611bea81611d42610614565b869190866126f6565b6033546001600160a01b031633146108ad5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610d3a565b6001600160a01b038216611e055760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610d3a565b6001600160a01b03821660009081526097602052604090205481811015611e795760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610d3a565b6001600160a01b03831660008181526097602090815260408083208686039055609980548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6001600160a01b038216611f2f5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610d3a565b8060996000828254611f419190613289565b90915550506001600160a01b0382166000818152609760209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35b5050565b6000611fa78484611a12565b9050600019811461175157818110156120025760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610d3a565b6117518484848403611bf5565b6001600160a01b0383166120735760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610d3a565b6001600160a01b0382166120d55760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610d3a565b6001600160a01b0383166000908152609760205260409020548181101561214d5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610d3a565b6001600160a01b0380851660008181526097602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906121ad9086815260200190565b60405180910390a3611751565b6121c26122ec565b6065805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586121fd3390565b6040516001600160a01b03909116815260200160405180910390a1565b600061068260c9546001600160a01b031690565b6040516001600160a01b03831660248201526044810182905261098390849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612747565b612299612654565b6065805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa336121fd565b8282028115158415858304851417166122e557600080fd5b0492915050565b606554600160a01b900460ff16156108ad5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606401610d3a565b6040516001600160a01b03808516602483015283166044820152606481018290526117519085906323b872dd60e01b9060840161225a565b6101005461239b906001600160a01b03168361238b61221a565b6001600160a01b03169190612819565b6101005460405163140e25ad60e31b8152600481018490526000916001600160a01b03169063a0712d68906024015b6020604051808303816000875af11580156123e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061240d919061306b565b905080156109835780601481111561242757612427613453565b604051633172b7f760e11b8152600401610d3a9190613469565b6101005460405163852a12e360e01b8152600481018490526000916001600160a01b03169063852a12e3906024016123ca565b600054610100900460ff1661249b5760405162461bcd60e51b8152600401610d3a90613491565b6124a43361292e565b6124ac612966565b6124b4612995565b6125c6816001600160a01b03166306fdde036040518163ffffffff1660e01b8152600401600060405180830381865afa1580156124f5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261251d91908101906134dc565b60405160200161252d9190613570565b604051602081830303815290604052826001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa15801561257a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526125a291908101906134dc565b6040516020016125b291906135ae565b6040516020818303038152906040526129bc565b6125cf816129ed565b806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561260d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612631919061333d565b61263c90600a613444565b60fb555060fd80546001600160a01b03191633179055565b606554600160a01b900460ff166108ad5760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401610d3a565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600080612704868686612a1d565b9050600183600281111561271a5761271a613453565b148015612737575060008480612732576127326132f2565b868809115b15611a0957610cca600182613289565b600061279c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612acc9092919063ffffffff16565b80519091501561098357808060200190518101906127ba91906132b9565b6109835760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610d3a565b8015806128935750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa15801561286d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612891919061306b565b155b6128fe5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610d3a565b6040516001600160a01b03831660248201526044810182905261098390849063095ea7b360e01b9060640161225a565b600054610100900460ff166129555760405162461bcd60e51b8152600401610d3a90613491565b61295d612adb565b611172816126a4565b600054610100900460ff1661298d5760405162461bcd60e51b8152600401610d3a90613491565b6108ad612b0a565b600054610100900460ff166108ad5760405162461bcd60e51b8152600401610d3a90613491565b600054610100900460ff166129e35760405162461bcd60e51b8152600401610d3a90613491565b611f978282612b40565b600054610100900460ff16612a145760405162461bcd60e51b8152600401610d3a90613491565b61117281612b80565b6000808060001985870985870292508281108382030391505080600003612a5757838281612a4d57612a4d6132f2565b0492505050610896565b808411612a6357600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b60606119458484600085612c05565b600054610100900460ff16612b025760405162461bcd60e51b8152600401610d3a90613491565b6108ad612ce0565b600054610100900460ff16612b315760405162461bcd60e51b8152600401610d3a90613491565b6065805460ff60a01b19169055565b600054610100900460ff16612b675760405162461bcd60e51b8152600401610d3a90613491565b609a612b738382613628565b50609b6109838282613628565b600054610100900460ff16612ba75760405162461bcd60e51b8152600401610d3a90613491565b600080612bb383612d10565b9150915081612bc3576012612bc5565b805b60c980546001600160a01b039095166001600160a01b031960ff93909316600160a01b02929092166001600160a81b031990951694909417179092555050565b606082471015612c665760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610d3a565b600080866001600160a01b03168587604051612c8291906136e8565b60006040518083038185875af1925050503d8060008114612cbf576040519150601f19603f3d011682016040523d82523d6000602084013e612cc4565b606091505b5091509150612cd587838387612dee565b979650505050505050565b600054610100900460ff16612d075760405162461bcd60e51b8152600401610d3a90613491565b6108ad336126a4565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290516000918291829182916001600160a01b03871691612d57916136e8565b6000604051808303816000865af19150503d8060008114612d94576040519150601f19603f3d011682016040523d82523d6000602084013e612d99565b606091505b5091509150818015612dad57506020815110155b15612de157600081806020019051810190612dc8919061306b565b905060ff8111612ddf576001969095509350505050565b505b5060009485945092505050565b60608315612e5d578251600003612e56576001600160a01b0385163b612e565760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610d3a565b5081611945565b6119458383815115612e725781518083602001fd5b8060405162461bcd60e51b8152600401610d3a9190612eb0565b60005b83811015612ea7578181015183820152602001612e8f565b50506000910152565b6020815260008251806020840152612ecf816040850160208701612e8c565b601f01601f19169190910160400192915050565b600060208284031215612ef557600080fd5b5035919050565b6001600160a01b038116811461117257600080fd5b60008060408385031215612f2457600080fd5b8235612f2f81612efc565b946020939093013593505050565b60008060408385031215612f5057600080fd5b823591506020830135612f6281612efc565b809150509250929050565b600080600060608486031215612f8257600080fd5b8335612f8d81612efc565b92506020840135612f9d81612efc565b929592945050506040919091013590565b600060208284031215612fc057600080fd5b813561089681612efc565b600080600060608486031215612fe057600080fd5b833592506020840135612ff281612efc565b9150604084013561300281612efc565b809150509250925092565b60008060006060848603121561302257600080fd5b833561302d81612efc565b92506020840135612ff281612efc565b6000806040838503121561305057600080fd5b823561305b81612efc565b91506020830135612f6281612efc565b60006020828403121561307d57600080fd5b5051919050565b600181811c9082168061309857607f821691505b6020821081036130b857634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156130fd576130fd6130be565b604052919050565b600067ffffffffffffffff82111561311f5761311f6130be565b5060051b60200190565b600082601f83011261313a57600080fd5b8151602061314f61314a83613105565b6130d4565b8083825260208201915060208460051b87010193508684111561317157600080fd5b602086015b8481101561318d5780518352918301918301613176565b509695505050505050565b600080604083850312156131ab57600080fd5b825167ffffffffffffffff808211156131c357600080fd5b818501915085601f8301126131d757600080fd5b815160206131e761314a83613105565b82815260059290921b8401810191818101908984111561320657600080fd5b948201945b8386101561322d57855161321e81612efc565b8252948201949082019061320b565b9188015191965090935050508082111561324657600080fd5b5061325385828601613129565b9150509250929050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8082018082111561072657610726613273565b6000602082840312156132ae57600080fd5b815161089681612efc565b6000602082840312156132cb57600080fd5b8151801515811461089657600080fd5b808202811582820484141761072657610726613273565b634e487b7160e01b600052601260045260246000fd5b60008261332557634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561072657610726613273565b60006020828403121561334f57600080fd5b815160ff8116811461089657600080fd5b600181815b8085111561339b57816000190482111561338157613381613273565b8085161561338e57918102915b93841c9390800290613365565b509250929050565b6000826133b257506001610726565b816133bf57506000610726565b81600181146133d557600281146133df576133fb565b6001915050610726565b60ff8411156133f0576133f0613273565b50506001821b610726565b5060208310610133831016604e8410600b841016171561341e575081810a610726565b6134288383613360565b806000190482111561343c5761343c613273565b029392505050565b600061089660ff8416836133a3565b634e487b7160e01b600052602160045260246000fd5b602081016015831061348b57634e487b7160e01b600052602160045260246000fd5b91905290565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b6000602082840312156134ee57600080fd5b815167ffffffffffffffff8082111561350657600080fd5b818401915084601f83011261351a57600080fd5b81518181111561352c5761352c6130be565b61353f601f8201601f19166020016130d4565b915080825285602082850101111561355657600080fd5b613567816020840160208601612e8c565b50949350505050565b65024b7b734b1960d51b815260008251613591816006850160208701612e8c565b650815985d5b1d60d21b6006939091019283015250600c01919050565b6134bb60f11b8152600082516135cb816002850160208701612e8c565b9190910160020192915050565b601f821115610983576000816000526020600020601f850160051c810160208610156136015750805b601f850160051c820191505b818110156136205782815560010161360d565b505050505050565b815167ffffffffffffffff811115613642576136426130be565b613656816136508454613084565b846135d8565b602080601f83116001811461368b57600084156136735750858301515b600019600386901b1c1916600185901b178555613620565b600085815260208120601f198616915b828110156136ba5788860151825594840194600190910190840161369b565b50858210156136d85787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b600082516136fa818460208701612e8c565b919091019291505056fea2646970667358221220e9c1329438f31472150b9c984d508926d8a8b93cd339e65570636454cde0a40a64736f6c63430008160033", + "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106102bb5760003560e01c8063715018a611610182578063c0c53b8b116100e9578063dd62ed3e116100a2578063f2eb2a4b1161007c578063f2eb2a4b146105d3578063f2fde38b146105e6578063fc4d33f9146105f9578063ff2a7d301461060157600080fd5b8063dd62ed3e146105ad578063e30c3978146105c0578063ef8b30f71461056157600080fd5b8063c0c53b8b1461053b578063c63d75b61461054e578063c6e6f59214610561578063cce2f3fb14610574578063ce96cb7714610587578063d905777e1461059a57600080fd5b8063a9059cbb1161013b578063a9059cbb146104d4578063ada82c7d146104e7578063b3d7f6b9146104ef578063b460af9414610502578063ba08765214610515578063bb83b0e91461052857600080fd5b8063715018a614610484578063877887821461048c5780638da5cb5b1461049557806394bf804d146104a657806395d89b41146104b9578063a457c2d7146104c157600080fd5b806338d52e0f1161022657806356f89ef9116101df57806356f89ef9146104075780635c975abb1461040f57806369e527da146104215780636e553f65146104355780636e96dfd71461044857806370a082311461045b57600080fd5b806338d52e0f146103a157806339509351146103c65780633f4ba83a146103d9578063402d267d146103e157806346904840146103f45780634cdad506146102f057600080fd5b806318160ddd1161027857806318160ddd1461034e578063211493c91461035657806323b872dd1461035f5780632835797814610372578063313ce5671461037a578063372500ab1461039957600080fd5b806301e1d114146102c057806306fdde03146102db57806307a2d13a146102f0578063095ea7b3146103035780630a28a4771461032657806310509aa914610339575b600080fd5b6102c8610614565b6040519081526020015b60405180910390f35b6102e3610687565b6040516102d29190612eb0565b6102c86102fe366004612ee3565b610719565b610316610311366004612f11565b61072c565b60405190151581526020016102d2565b6102c8610334366004612ee3565b610744565b61034c610347366004612f3d565b610751565b005b6099546102c8565b6102c860fb5481565b61031661036d366004612f6d565b610877565b61034c61089d565b60c954600160a01b900460ff1660405160ff90911681526020016102d2565b61034c6108af565b60c9546001600160a01b03165b6040516001600160a01b0390911681526020016102d2565b6103166103d4366004612f11565b610988565b61034c6109aa565b6102c86103ef366004612fae565b6109ba565b60fd546103ae906001600160a01b031681565b61034c610cde565b606554600160a01b900460ff16610316565b610100546103ae906001600160a01b031681565b6102c8610443366004612f3d565b610eac565b61034c610456366004612fae565b610f78565b6102c8610469366004612fae565b6001600160a01b031660009081526097602052604090205490565b61034c610fe2565b6102c860fc5481565b6033546001600160a01b03166103ae565b6102c86104b4366004612f3d565b611025565b6102e36110a2565b6103166104cf366004612f11565b6110b1565b6103166104e2366004612f11565b611137565b61034c611145565b6102c86104fd366004612ee3565b611175565b6102c8610510366004612fcb565b611182565b6102c8610523366004612fcb565b61133b565b61034c610536366004612fae565b611532565b61034c61054936600461300d565b6115a3565b6102c861055c366004612fae565b611757565b6102c861056f366004612ee3565b61177d565b6102c8610582366004612fae565b61178a565b6102c8610595366004612fae565b611893565b6102c86105a8366004612fae565b61194d565b6102c86105bb36600461303d565b611a12565b6065546103ae906001600160a01b031681565b60ff546103ae906001600160a01b031681565b61034c6105f4366004612fae565b611a3d565b61034c611aae565b60fe546103ae906001600160a01b031681565b61010054604051633af9e66960e01b81523060048201526000916001600160a01b031690633af9e66990602401602060405180830381865afa15801561065e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610682919061306b565b905090565b6060609a805461069690613084565b80601f01602080910402602001604051908101604052809291908181526020018280546106c290613084565b801561070f5780601f106106e45761010080835404028352916020019161070f565b820191906000526020600020905b8154815290600101906020018083116106f257829003601f168201915b5050505050905090565b6000610726826000611bc2565b92915050565b60003361073a818585611bf5565b5060019392505050565b6000610726826001611d19565b610759611d4b565b60fc5460fd5460408051928352602083018590526001600160a01b0391821690830152821660608201527fb3b62da5184b9e7e2f5d280014bb485d4444b66738025e5fb5738bbddcb6b8489060800160405180910390a160fc82905560fd546001600160a01b038281169116146108545760fd546001600160a01b0316156108365760fd546001600160a01b0316600081815260976020526040902054906108019082611da5565b60fd5461082a906001600160a01b03166108236033546001600160a01b031690565b6000611bf5565b6108348282611ed9565b505b6108548161084c6033546001600160a01b031690565b600019611bf5565b60fd80546001600160a01b0319166001600160a01b039290921691909117905550565b600033610885858285611f9b565b61089085858561200f565b60019150505b9392505050565b6108a5611d4b565b6108ad6121ba565b565b60ff54604051639cf1fd5360e01b815230600482015260009182916001600160a01b0390911690639cf1fd53906024016000604051808303816000875af11580156108fe573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526109269190810190613198565b9150915060005b82518110156109835760fe54825161097b916001600160a01b03169084908490811061095b5761095b61325d565b602002602001015161096b61221a565b6001600160a01b0316919061222e565b60010161092d565b505050565b60003361073a81858561099b8383611a12565b6109a59190613289565b611bf5565b6109b2611d4b565b6108ad612291565b6101005460408051635fe3b56760e01b815290516000926001600160a01b031691635fe3b5679160048083019260209291908290030181865afa158015610a05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a29919061329c565b6101005460405163731f0c2b60e01b81526001600160a01b03918216600482015291169063731f0c2b90602401602060405180830381865afa158015610a73573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a9791906132b9565b15610aa457506000919050565b6101005460408051635fe3b56760e01b815290516000926001600160a01b031691635fe3b5679160048083019260209291908290030181865afa158015610aef573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b13919061329c565b610100546040516302c3bcbb60e01b81526001600160a01b0391821660048201529116906302c3bcbb90602401602060405180830381865afa158015610b5d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b81919061306b565b90508015610cd457610100546040805163bd6d894d60e01b815290516000926001600160a01b03169163bd6d894d9160048083019260209291908290030181865afa158015610bd4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf8919061306b565b9050600061010060009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c50573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c74919061306b565b90506000670de0b6b3a7640000610c8b84846132db565b610c959190613308565b905083610ca3826002613289565b10610cb45750600095945050505050565b6002610cc0828661332a565b610cca919061332a565b9695505050505050565b5060001992915050565b610ce6611d4b565b60fd546001600160a01b0316610d435760405162461bcd60e51b815260206004820152601d60248201527f66656520726563697069656e74206e6f7420696e697469616c697a656400000060448201526064015b60405180910390fd5b6000610d4d610614565b90506000610dc8610d5c61221a565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d99573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dbd919061333d565b6102fe90600a613444565b905060fb548111610e1b5760405162461bcd60e51b815260206004820152601b60248201527f736861726556616c756520213e207661756c74536861726548574d00000000006044820152606401610d3a565b6000610e2660995490565b905060006ec097ce7bc90715b34b9f10000000008260fb5485610e49919061332a565b60fc54610e5691906132db565b610e6091906132db565b610e6a9190613308565b60fd54909150610e98906001600160a01b0316610e9384610e8b858961332a565b8591906122cd565b611ed9565b610ea3610d5c61221a565b60fb5550505050565b6000610eb66122ec565b610ebf8361177d565b905080600003610eff5760405162461bcd60e51b815260206004820152600b60248201526a5a45524f5f53484152455360a81b6044820152606401610d3a565b610f1e333085610f0d61221a565b6001600160a01b0316929190612339565b610f288282611ed9565b60408051848152602081018390526001600160a01b0384169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a36107268382612371565b610f80611d4b565b606580546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b91015b60405180910390a15050565b610fea611d4b565b60405162461bcd60e51b815260206004820152601060248201526f6e6f74207573656420616e796d6f726560801b6044820152606401610d3a565b600061102f6122ec565b61103883611175565b9050611048333083610f0d61221a565b6110528284611ed9565b60408051828152602081018590526001600160a01b0384169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a36107268184612371565b6060609b805461069690613084565b600033816110bf8286611a12565b90508381101561111f5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610d3a565b61112c8286868403611bf5565b506001949350505050565b60003361073a81858561200f565b61114d611d4b565b60fd546001600160a01b0316600081815260976020526040902054611172918061133b565b50565b6000610726826001611bc2565b600061118d84610744565b9050336001600160a01b038316146111c75760006111ab8333611a12565b905060001981146111c5576111c583336109a5858561332a565b505b606554600160a01b900460ff166112d95760006111e261221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015611228573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124c919061306b565b90506112588583612441565b8061126161221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa1580156112a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112cb919061306b565b6112d5919061332a565b9450505b6112e38282611da5565b60408051858152602081018390526001600160a01b03808516929086169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4610896838561096b61221a565b6000336001600160a01b038316146113755760006113598333611a12565b905060001981146113735761137383336109a5888561332a565b505b61137e84610719565b9050806000036113be5760405162461bcd60e51b815260206004820152600b60248201526a5a45524f5f41535345545360a81b6044820152606401610d3a565b606554600160a01b900460ff166114d05760006113d961221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa15801561141f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611443919061306b565b905061144f8286612441565b8061145861221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa15801561149e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114c2919061306b565b6114cc919061332a565b9150505b6114da8285611da5565b60408051828152602081018690526001600160a01b03808516929086169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4610896838261096b61221a565b61153a611d4b565b60fe54604080516001600160a01b03928316815291831660208301527f2d9427f2d488d8f8716dae31ad2f0d476bcea0664cce8822d8dc76dde104b09e910160405180910390a160fe80546001600160a01b0319166001600160a01b0392909216919091179055565b600054610100900460ff16158080156115c35750600054600160ff909116105b806115dd5750303b1580156115dd575060005460ff166001145b6116405760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610d3a565b6000805460ff191660011790558015611663576000805461ff0019166101001790555b6116cd846001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116c8919061329c565b612474565b61010080546001600160a01b038087166001600160a01b03199283161790925560fe805485841690831617905560ff8054928616929091169190911790558015611751576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050565b60008061176460006109ba565b90506000198114610726576117788161177d565b610896565b6000610726826000611d19565b6000611794611d4b565b61179c612654565b60006117a661221a565b6040516370a0823160e01b81523060048201529091506000906001600160a01b038316906370a0823190602401602060405180830381865afa1580156117f0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611814919061306b565b60405163a9059cbb60e01b81526001600160a01b038681166004830152602482018390529192509083169063a9059cbb906044016020604051808303816000875af1158015611867573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061188b91906132b9565b509392505050565b60008061010060009054906101000a90046001600160a01b03166001600160a01b0316633b1d21a26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061190e919061306b565b905060006119346102fe856001600160a01b031660009081526097602052604090205490565b90508082106119435780611945565b815b949350505050565b60008061010060009054906101000a90046001600160a01b03166001600160a01b0316633b1d21a26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156119a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119c8919061306b565b905060006119d58261177d565b905060006119f8856001600160a01b031660009081526097602052604090205490565b9050808210611a075780611a09565b815b95945050505050565b6001600160a01b03918216600090815260986020908152604080832093909416825291909152205490565b611a45611d4b565b606554604080516001600160a01b03928316815291831660208301527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b910160405180910390a1606580546001600160a01b0319166001600160a01b0392909216919091179055565b6065546001600160a01b03163314611b005760405162461bcd60e51b81526020600482015260156024820152743737ba103a3432903832b73234b7339037bbb732b960591b6044820152606401610d3a565b6000611b146033546001600160a01b031690565b6065549091506001600160a01b0316611b2c816126a4565b606580546001600160a01b0319169055604080516001600160a01b0384168152600060208201527f70aea8d848e8a90fb7661b227dc522eb6395c3dac71b63cb59edd5c9899b2364910160405180910390a1606554604080516001600160a01b03808516825290921660208301527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b9101610fd6565b600080611bce60995490565b90508015611bef57611bea611be1610614565b859083866126f6565b611945565b83611945565b6001600160a01b038316611c575760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610d3a565b6001600160a01b038216611cb85760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610d3a565b6001600160a01b0383811660008181526098602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b600080611d2560995490565b9050831580611d32575080155b611bef57611bea81611d42610614565b869190866126f6565b6033546001600160a01b031633146108ad5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610d3a565b6001600160a01b038216611e055760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610d3a565b6001600160a01b03821660009081526097602052604090205481811015611e795760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610d3a565b6001600160a01b03831660008181526097602090815260408083208686039055609980548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6001600160a01b038216611f2f5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610d3a565b8060996000828254611f419190613289565b90915550506001600160a01b0382166000818152609760209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35b5050565b6000611fa78484611a12565b9050600019811461175157818110156120025760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610d3a565b6117518484848403611bf5565b6001600160a01b0383166120735760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610d3a565b6001600160a01b0382166120d55760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610d3a565b6001600160a01b0383166000908152609760205260409020548181101561214d5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610d3a565b6001600160a01b0380851660008181526097602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906121ad9086815260200190565b60405180910390a3611751565b6121c26122ec565b6065805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586121fd3390565b6040516001600160a01b03909116815260200160405180910390a1565b600061068260c9546001600160a01b031690565b6040516001600160a01b03831660248201526044810182905261098390849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612747565b612299612654565b6065805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa336121fd565b8282028115158415858304851417166122e557600080fd5b0492915050565b606554600160a01b900460ff16156108ad5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606401610d3a565b6040516001600160a01b03808516602483015283166044820152606481018290526117519085906323b872dd60e01b9060840161225a565b6101005461239b906001600160a01b03168361238b61221a565b6001600160a01b03169190612819565b6101005460405163140e25ad60e31b8152600481018490526000916001600160a01b03169063a0712d68906024015b6020604051808303816000875af11580156123e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061240d919061306b565b905080156109835780601481111561242757612427613453565b604051633172b7f760e11b8152600401610d3a9190613469565b6101005460405163852a12e360e01b8152600481018490526000916001600160a01b03169063852a12e3906024016123ca565b600054610100900460ff1661249b5760405162461bcd60e51b8152600401610d3a90613491565b6124a43361292e565b6124ac612966565b6124b4612995565b6125c6816001600160a01b03166306fdde036040518163ffffffff1660e01b8152600401600060405180830381865afa1580156124f5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261251d91908101906134dc565b60405160200161252d9190613570565b604051602081830303815290604052826001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa15801561257a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526125a291908101906134dc565b6040516020016125b291906135ae565b6040516020818303038152906040526129bc565b6125cf816129ed565b806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561260d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612631919061333d565b61263c90600a613444565b60fb555060fd80546001600160a01b03191633179055565b606554600160a01b900460ff166108ad5760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401610d3a565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600080612704868686612a1d565b9050600183600281111561271a5761271a613453565b148015612737575060008480612732576127326132f2565b868809115b15611a0957610cca600182613289565b600061279c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612acc9092919063ffffffff16565b80519091501561098357808060200190518101906127ba91906132b9565b6109835760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610d3a565b8015806128935750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa15801561286d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612891919061306b565b155b6128fe5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610d3a565b6040516001600160a01b03831660248201526044810182905261098390849063095ea7b360e01b9060640161225a565b600054610100900460ff166129555760405162461bcd60e51b8152600401610d3a90613491565b61295d612adb565b611172816126a4565b600054610100900460ff1661298d5760405162461bcd60e51b8152600401610d3a90613491565b6108ad612b0a565b600054610100900460ff166108ad5760405162461bcd60e51b8152600401610d3a90613491565b600054610100900460ff166129e35760405162461bcd60e51b8152600401610d3a90613491565b611f978282612b40565b600054610100900460ff16612a145760405162461bcd60e51b8152600401610d3a90613491565b61117281612b80565b6000808060001985870985870292508281108382030391505080600003612a5757838281612a4d57612a4d6132f2565b0492505050610896565b808411612a6357600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b60606119458484600085612c05565b600054610100900460ff16612b025760405162461bcd60e51b8152600401610d3a90613491565b6108ad612ce0565b600054610100900460ff16612b315760405162461bcd60e51b8152600401610d3a90613491565b6065805460ff60a01b19169055565b600054610100900460ff16612b675760405162461bcd60e51b8152600401610d3a90613491565b609a612b738382613628565b50609b6109838282613628565b600054610100900460ff16612ba75760405162461bcd60e51b8152600401610d3a90613491565b600080612bb383612d10565b9150915081612bc3576012612bc5565b805b60c980546001600160a01b039095166001600160a01b031960ff93909316600160a01b02929092166001600160a81b031990951694909417179092555050565b606082471015612c665760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610d3a565b600080866001600160a01b03168587604051612c8291906136e8565b60006040518083038185875af1925050503d8060008114612cbf576040519150601f19603f3d011682016040523d82523d6000602084013e612cc4565b606091505b5091509150612cd587838387612dee565b979650505050505050565b600054610100900460ff16612d075760405162461bcd60e51b8152600401610d3a90613491565b6108ad336126a4565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290516000918291829182916001600160a01b03871691612d57916136e8565b6000604051808303816000865af19150503d8060008114612d94576040519150601f19603f3d011682016040523d82523d6000602084013e612d99565b606091505b5091509150818015612dad57506020815110155b15612de157600081806020019051810190612dc8919061306b565b905060ff8111612ddf576001969095509350505050565b505b5060009485945092505050565b60608315612e5d578251600003612e56576001600160a01b0385163b612e565760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610d3a565b5081611945565b6119458383815115612e725781518083602001fd5b8060405162461bcd60e51b8152600401610d3a9190612eb0565b60005b83811015612ea7578181015183820152602001612e8f565b50506000910152565b6020815260008251806020840152612ecf816040850160208701612e8c565b601f01601f19169190910160400192915050565b600060208284031215612ef557600080fd5b5035919050565b6001600160a01b038116811461117257600080fd5b60008060408385031215612f2457600080fd5b8235612f2f81612efc565b946020939093013593505050565b60008060408385031215612f5057600080fd5b823591506020830135612f6281612efc565b809150509250929050565b600080600060608486031215612f8257600080fd5b8335612f8d81612efc565b92506020840135612f9d81612efc565b929592945050506040919091013590565b600060208284031215612fc057600080fd5b813561089681612efc565b600080600060608486031215612fe057600080fd5b833592506020840135612ff281612efc565b9150604084013561300281612efc565b809150509250925092565b60008060006060848603121561302257600080fd5b833561302d81612efc565b92506020840135612ff281612efc565b6000806040838503121561305057600080fd5b823561305b81612efc565b91506020830135612f6281612efc565b60006020828403121561307d57600080fd5b5051919050565b600181811c9082168061309857607f821691505b6020821081036130b857634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156130fd576130fd6130be565b604052919050565b600067ffffffffffffffff82111561311f5761311f6130be565b5060051b60200190565b600082601f83011261313a57600080fd5b8151602061314f61314a83613105565b6130d4565b8083825260208201915060208460051b87010193508684111561317157600080fd5b602086015b8481101561318d5780518352918301918301613176565b509695505050505050565b600080604083850312156131ab57600080fd5b825167ffffffffffffffff808211156131c357600080fd5b818501915085601f8301126131d757600080fd5b815160206131e761314a83613105565b82815260059290921b8401810191818101908984111561320657600080fd5b948201945b8386101561322d57855161321e81612efc565b8252948201949082019061320b565b9188015191965090935050508082111561324657600080fd5b5061325385828601613129565b9150509250929050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8082018082111561072657610726613273565b6000602082840312156132ae57600080fd5b815161089681612efc565b6000602082840312156132cb57600080fd5b8151801515811461089657600080fd5b808202811582820484141761072657610726613273565b634e487b7160e01b600052601260045260246000fd5b60008261332557634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561072657610726613273565b60006020828403121561334f57600080fd5b815160ff8116811461089657600080fd5b600181815b8085111561339b57816000190482111561338157613381613273565b8085161561338e57918102915b93841c9390800290613365565b509250929050565b6000826133b257506001610726565b816133bf57506000610726565b81600181146133d557600281146133df576133fb565b6001915050610726565b60ff8411156133f0576133f0613273565b50506001821b610726565b5060208310610133831016604e8410600b841016171561341e575081810a610726565b6134288383613360565b806000190482111561343c5761343c613273565b029392505050565b600061089660ff8416836133a3565b634e487b7160e01b600052602160045260246000fd5b602081016015831061348b57634e487b7160e01b600052602160045260246000fd5b91905290565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b6000602082840312156134ee57600080fd5b815167ffffffffffffffff8082111561350657600080fd5b818401915084601f83011261351a57600080fd5b81518181111561352c5761352c6130be565b61353f601f8201601f19166020016130d4565b915080825285602082850101111561355657600080fd5b613567816020840160208601612e8c565b50949350505050565b65024b7b734b1960d51b815260008251613591816006850160208701612e8c565b650815985d5b1d60d21b6006939091019283015250600c01919050565b6134bb60f11b8152600082516135cb816002850160208701612e8c565b9190910160020192915050565b601f821115610983576000816000526020600020601f850160051c810160208610156136015750805b601f850160051c820191505b818110156136205782815560010161360d565b505050505050565b815167ffffffffffffffff811115613642576136426130be565b613656816136508454613084565b846135d8565b602080601f83116001811461368b57600084156136735750858301515b600019600386901b1c1916600185901b178555613620565b600085815260208120601f198616915b828110156136ba5788860151825594840194600190910190840161369b565b50858210156136d85787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b600082516136fa818460208701612e8c565b919091019291505056fea2646970667358221220e9c1329438f31472150b9c984d508926d8a8b93cd339e65570636454cde0a40a64736f6c63430008160033", + "devdoc": { + "events": { + "Approval(address,address,uint256)": { + "details": "Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance." + }, + "Initialized(uint8)": { + "details": "Triggered when the contract has been initialized or reinitialized." + }, + "Paused(address)": { + "details": "Emitted when the pause is triggered by `account`." + }, + "Transfer(address,address,uint256)": { + "details": "Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero." + }, + "Unpaused(address)": { + "details": "Emitted when the pause is lifted by `account`." + } + }, + "kind": "dev", + "methods": { + "_acceptOwner()": { + "details": "Owner function for pending owner to accept role and update owner" + }, + "_setPendingOwner(address)": { + "details": "Owner function to begin change of owner. The newPendingOwner must call `_acceptOwner` to finalize the transfer.", + "params": { + "newPendingOwner": "New pending owner." + } + }, + "allowance(address,address)": { + "details": "See {IERC20-allowance}." + }, + "approve(address,uint256)": { + "details": "See {IERC20-approve}. NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address." + }, + "asset()": { + "details": "See {IERC4626-asset}. " + }, + "balanceOf(address)": { + "details": "See {IERC20-balanceOf}." + }, + "convertToAssets(uint256)": { + "details": "See {IERC4626-convertToAssets}. " + }, + "convertToShares(uint256)": { + "details": "See {IERC4626-convertToShares}. " + }, + "decimals()": { + "details": "Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value. See {IERC20Metadata-decimals}." + }, + "decreaseAllowance(address,uint256)": { + "details": "Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`." + }, + "deposit(uint256,address)": { + "details": "See {IERC4626-deposit}. " + }, + "increaseAllowance(address,uint256)": { + "details": "Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address." + }, + "maxMint(address)": { + "details": "accrue interest must be called before this function is called, otherwise an outdated value will be fetched, and the returned value will be incorrect (greater than actual amount available to be minted will be returned)" + }, + "maxRedeem(address)": { + "params": { + "owner": "The address that owns the shares" + } + }, + "maxWithdraw(address)": { + "params": { + "owner": "The address that owns the shares" + } + }, + "mint(uint256,address)": { + "details": "See {IERC4626-mint}. " + }, + "name()": { + "details": "Returns the name of the token." + }, + "owner()": { + "details": "Returns the address of the current owner." + }, + "paused()": { + "details": "Returns true if the contract is paused, and false otherwise." + }, + "previewDeposit(uint256)": { + "details": "See {IERC4626-previewDeposit}. " + }, + "previewMint(uint256)": { + "details": "See {IERC4626-previewMint}. " + }, + "previewRedeem(uint256)": { + "details": "See {IERC4626-previewRedeem}. " + }, + "previewWithdraw(uint256)": { + "details": "See {IERC4626-previewWithdraw}. " + }, + "redeem(uint256,address,address)": { + "details": "See {IERC4626-redeem}. " + }, + "renounceOwnership()": { + "details": "Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner." + }, + "symbol()": { + "details": "Returns the symbol of the token, usually a shorter version of the name." + }, + "takePerformanceFee()": { + "details": "Performance fee is based on a vault share high water mark value. If vault share value has increased above the HWM in a fee period, issue fee shares to the vault equal to the performance fee." + }, + "totalAssets()": { + "details": "See {IERC4626-totalAssets}. " + }, + "totalSupply()": { + "details": "See {IERC20-totalSupply}." + }, + "transfer(address,uint256)": { + "details": "See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `amount`." + }, + "transferFrom(address,address,uint256)": { + "details": "See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `amount`. - the caller must have allowance for ``from``'s tokens of at least `amount`." + }, + "transferOwnership(address)": { + "details": "Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner." + }, + "withdraw(uint256,address,address)": { + "details": "See {IERC4626-withdraw}. " + }, + "withdrawAccruedFees()": { + "details": "We must make sure that feeRecipient is not address(0) before withdrawing fees" + } + }, + "version": 1 + }, + "userdoc": { + "events": { + "NewOwner(address,address)": { + "notice": "Emitted when pendingOwner is accepted, which means owner is updated" + }, + "NewPendingOwner(address,address)": { + "notice": "Emitted when pendingOwner is changed" + } + }, + "kind": "user", + "methods": { + "_acceptOwner()": { + "notice": "Accepts transfer of owner rights. msg.sender must be pendingOwner" + }, + "_setPendingOwner(address)": { + "notice": "Begins transfer of owner rights. The newPendingOwner must call `_acceptOwner` to finalize the transfer." + }, + "maxDeposit(address)": { + "notice": "maximum amount of underlying tokens that can be deposited into the underlying protocol" + }, + "maxMint(address)": { + "notice": "Returns the maximum amount of tokens that can be supplied no way for this function to ever revert unless comptroller or mToken is broken" + }, + "maxRedeem(address)": { + "notice": "maximum amount of shares that can be withdrawn" + }, + "maxWithdraw(address)": { + "notice": "maximum amount of underlying tokens that can be withdrawn" + }, + "pendingOwner()": { + "notice": "Pending owner of this contract" + }, + "takePerformanceFee()": { + "notice": "Take the performance fee that has accrued since last fee harvest." + }, + "updateFeeSettings(uint256,address)": { + "notice": "Update performanceFee and/or feeRecipient" + }, + "withdrawAccruedFees()": { + "notice": "Transfer accrued fees to rewards manager contract. Caller must be a registered keeper." + } + }, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 3343, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8" + }, + { + "astId": 3346, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool" + }, + { + "astId": 6909, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage" + }, + { + "astId": 2967, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address" + }, + { + "astId": 3087, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage" + }, + { + "astId": 55662, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "pendingOwner", + "offset": 0, + "slot": "101", + "type": "t_address" + }, + { + "astId": 3526, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_paused", + "offset": 20, + "slot": "101", + "type": "t_bool" + }, + { + "astId": 3631, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "102", + "type": "t_array(t_uint256)49_storage" + }, + { + "astId": 3724, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_balances", + "offset": 0, + "slot": "151", + "type": "t_mapping(t_address,t_uint256)" + }, + { + "astId": 3730, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_allowances", + "offset": 0, + "slot": "152", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" + }, + { + "astId": 3732, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_totalSupply", + "offset": 0, + "slot": "153", + "type": "t_uint256" + }, + { + "astId": 3734, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_name", + "offset": 0, + "slot": "154", + "type": "t_string_storage" + }, + { + "astId": 3736, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_symbol", + "offset": 0, + "slot": "155", + "type": "t_string_storage" + }, + { + "astId": 4316, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "156", + "type": "t_array(t_uint256)45_storage" + }, + { + "astId": 4415, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_asset", + "offset": 0, + "slot": "201", + "type": "t_contract(IERC20Upgradeable)4395" + }, + { + "astId": 4417, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_decimals", + "offset": 20, + "slot": "201", + "type": "t_uint8" + }, + { + "astId": 5099, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "202", + "type": "t_array(t_uint256)49_storage" + }, + { + "astId": 60776, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "vaultShareHWM", + "offset": 0, + "slot": "251", + "type": "t_uint256" + }, + { + "astId": 60778, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "performanceFee", + "offset": 0, + "slot": "252", + "type": "t_uint256" + }, + { + "astId": 60780, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "feeRecipient", + "offset": 0, + "slot": "253", + "type": "t_address" + }, + { + "astId": 61454, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "rewardsRecipient", + "offset": 0, + "slot": "254", + "type": "t_address" + }, + { + "astId": 61457, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "flywheelLensRouter", + "offset": 0, + "slot": "255", + "type": "t_contract(IonicFlywheelLensRouter_4626)61441" + }, + { + "astId": 61460, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "cToken", + "offset": 0, + "slot": "256", + "type": "t_contract(ICErc20)32392" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_uint256)45_storage": { + "base": "t_uint256", + "encoding": "inplace", + "label": "uint256[45]", + "numberOfBytes": "1440" + }, + "t_array(t_uint256)49_storage": { + "base": "t_uint256", + "encoding": "inplace", + "label": "uint256[49]", + "numberOfBytes": "1568" + }, + "t_array(t_uint256)50_storage": { + "base": "t_uint256", + "encoding": "inplace", + "label": "uint256[50]", + "numberOfBytes": "1600" + }, + "t_bool": { + "encoding": "inplace", + "label": "bool", + "numberOfBytes": "1" + }, + "t_contract(ICErc20)32392": { + "encoding": "inplace", + "label": "contract ICErc20", + "numberOfBytes": "20" + }, + "t_contract(IERC20Upgradeable)4395": { + "encoding": "inplace", + "label": "contract IERC20Upgradeable", + "numberOfBytes": "20" + }, + "t_contract(IonicFlywheelLensRouter_4626)61441": { + "encoding": "inplace", + "label": "contract IonicFlywheelLensRouter_4626", + "numberOfBytes": "20" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32", + "value": "t_mapping(t_address,t_uint256)" + }, + "t_mapping(t_address,t_uint256)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => uint256)", + "numberOfBytes": "32", + "value": "t_uint256" + }, + "t_string_storage": { + "encoding": "bytes", + "label": "string", + "numberOfBytes": "32" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "encoding": "inplace", + "label": "uint8", + "numberOfBytes": "1" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3_Proxy.json b/packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3_Proxy.json new file mode 100644 index 0000000000..b52b344041 --- /dev/null +++ b/packages/contracts/deployments/base/IonicMarketERC4626_0x49420311B518f3d0c94e897592014de53831cfA3_Proxy.json @@ -0,0 +1,275 @@ +{ + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "abi": [ + { + "inputs": [ + { + "internalType": "address", + "name": "_logic", + "type": "address" + }, + { + "internalType": "address", + "name": "admin_", + "type": "address" + }, + { + "internalType": "bytes", + "name": "_data", + "type": "bytes" + } + ], + "stateMutability": "payable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "previousAdmin", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newAdmin", + "type": "address" + } + ], + "name": "AdminChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "beacon", + "type": "address" + } + ], + "name": "BeaconUpgraded", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "implementation", + "type": "address" + } + ], + "name": "Upgraded", + "type": "event" + }, + { + "stateMutability": "payable", + "type": "fallback" + }, + { + "inputs": [], + "name": "admin", + "outputs": [ + { + "internalType": "address", + "name": "admin_", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newAdmin", + "type": "address" + } + ], + "name": "changeAdmin", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "implementation", + "outputs": [ + { + "internalType": "address", + "name": "implementation_", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newImplementation", + "type": "address" + } + ], + "name": "upgradeTo", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newImplementation", + "type": "address" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "upgradeToAndCall", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "stateMutability": "payable", + "type": "receive" + } + ], + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "receipt": { + "to": null, + "from": "0x1155b614971f16758C92c4890eD338C9e3ede6b7", + "contractAddress": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "transactionIndex": 102, + "gasUsed": "975823", + "logsBloom": "0x00000000000000000000000000000000400000040000000000800000000200000000000000000000000000000000000000000000100000000000000000000000000000000000000000000800000002000001000000000000000000000000000000000000020000000000000000000800000000800000000000000000000000400000000000000200000000000000000000000000000080000000000000c00000000020000000000000000000002400000000000000000000000000000000000000000020000000000000000000040000000000000400000000000000000020000000000000000000000000000080000000000000000000000000000000000000", + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932", + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "logs": [ + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b", + "0x000000000000000000000000986f1289b2e803b0bf7ac29b777bbacbdb3de872" + ], + "data": "0x", + "logIndex": 1313, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + }, + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "data": "0x", + "logIndex": 1314, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + }, + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "data": "0x", + "logIndex": 1315, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + }, + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498" + ], + "data": "0x0000000000000000000000000000000000000000000000000000000000000001", + "logIndex": 1316, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + }, + { + "transactionIndex": 102, + "blockNumber": 25464415, + "transactionHash": "0x1dd0c27b1b0dcf68558e2be8431490cc493d886d117574e896290389a8595921", + "address": "0xD0B2406421470db765F80Bc85Bb253460FAeE5EF", + "topics": [ + "0x7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f" + ], + "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000028df5636456049b891bf9d40fa46ef5ad20822c5", + "logIndex": 1317, + "blockHash": "0x3e1a14939d6e53b8d6c17c6fc4a0aa2d67b91b9c09f3ba97671852508206a932" + } + ], + "blockNumber": 25464415, + "cumulativeGasUsed": "55424046", + "status": 1, + "byzantium": true + }, + "args": [ + "0x986F1289B2E803B0bf7ac29b777bbAcBDb3dE872", + "0x28DF5636456049B891bF9D40fa46eF5ad20822C5", + "0xc0c53b8b00000000000000000000000049420311b518f3d0c94e897592014de53831cfa3000000000000000000000000b1402333b12fc066c3d7f55d37944d5e281a3e8b0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "numDeployments": 1, + "solcInputHash": "0e89febeebc7444140de8e67c9067d2c", + "metadata": "{\"compiler\":{\"version\":\"0.8.10+commit.fc410830\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_logic\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"admin_\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previousAdmin\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"AdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"beacon\",\"type\":\"address\"}],\"name\":\"BeaconUpgraded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"implementation\",\"type\":\"address\"}],\"name\":\"Upgraded\",\"type\":\"event\"},{\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"inputs\":[],\"name\":\"admin\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"admin_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"changeAdmin\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"implementation\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"implementation_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newImplementation\",\"type\":\"address\"}],\"name\":\"upgradeTo\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newImplementation\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"upgradeToAndCall\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}],\"devdoc\":{\"details\":\"This contract implements a proxy that is upgradeable by an admin. To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector clashing], which can potentially be used in an attack, this contract uses the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two things that go hand in hand: 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches one of the admin functions exposed by the proxy itself. 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error that says \\\"admin cannot fallback to proxy target\\\". These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to call a function from the proxy implementation. Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\",\"kind\":\"dev\",\"methods\":{\"admin()\":{\"details\":\"Returns the current admin. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\"},\"changeAdmin(address)\":{\"details\":\"Changes the admin of the proxy. Emits an {AdminChanged} event. NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\"},\"constructor\":{\"details\":\"Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\"},\"implementation()\":{\"details\":\"Returns the current implementation. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\"},\"upgradeTo(address)\":{\"details\":\"Upgrade the implementation of the proxy. NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\"},\"upgradeToAndCall(address,bytes)\":{\"details\":\"Upgrade the implementation of the proxy, and then call a function from the new implementation as specified by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the proxied contract. NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\"}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"solc_0.8/openzeppelin/proxy/transparent/TransparentUpgradeableProxy.sol\":\"TransparentUpgradeableProxy\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":999999},\"remappings\":[]},\"sources\":{\"solc_0.8/openzeppelin/interfaces/draft-IERC1822.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (interfaces/draft-IERC1822.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\\n * proxy whose upgrades are fully controlled by the current implementation.\\n */\\ninterface IERC1822Proxiable {\\n /**\\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\\n * address.\\n *\\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\\n * function revert if invoked through a proxy.\\n */\\n function proxiableUUID() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x93b4e21c931252739a1ec13ea31d3d35a5c068be3163ccab83e4d70c40355f03\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../Proxy.sol\\\";\\nimport \\\"./ERC1967Upgrade.sol\\\";\\n\\n/**\\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\\n * implementation address that can be changed. This address is stored in storage in the location specified by\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\\n * implementation behind the proxy.\\n */\\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\\n /**\\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\\n *\\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\\n * function call, and allows initializating the storage of the proxy like a Solidity constructor.\\n */\\n constructor(address _logic, bytes memory _data) payable {\\n assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256(\\\"eip1967.proxy.implementation\\\")) - 1));\\n _upgradeToAndCall(_logic, _data, false);\\n }\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _implementation() internal view virtual override returns (address impl) {\\n return ERC1967Upgrade._getImplementation();\\n }\\n}\\n\",\"keccak256\":\"0x6309f9f39dc6f4f45a24f296543867aa358e32946cd6b2874627a996d606b3a0\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Upgrade.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/ERC1967/ERC1967Upgrade.sol)\\n\\npragma solidity ^0.8.2;\\n\\nimport \\\"../beacon/IBeacon.sol\\\";\\nimport \\\"../../interfaces/draft-IERC1822.sol\\\";\\nimport \\\"../../utils/Address.sol\\\";\\nimport \\\"../../utils/StorageSlot.sol\\\";\\n\\n/**\\n * @dev This abstract contract provides getters and event emitting update functions for\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\\n *\\n * _Available since v4.1._\\n *\\n * @custom:oz-upgrades-unsafe-allow delegatecall\\n */\\nabstract contract ERC1967Upgrade {\\n // This is the keccak-256 hash of \\\"eip1967.proxy.rollback\\\" subtracted by 1\\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\\n\\n /**\\n * @dev Storage slot with the address of the current implementation.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.implementation\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n\\n /**\\n * @dev Emitted when the implementation is upgraded.\\n */\\n event Upgraded(address indexed implementation);\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _getImplementation() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 implementation slot.\\n */\\n function _setImplementation(address newImplementation) private {\\n require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n }\\n\\n /**\\n * @dev Perform implementation upgrade\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeTo(address newImplementation) internal {\\n _setImplementation(newImplementation);\\n emit Upgraded(newImplementation);\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCall(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _upgradeTo(newImplementation);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(newImplementation, data);\\n }\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCallUUPS(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n // Upgrades from old implementations will perform a rollback test. This test requires the new\\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\\n // this special case will break upgrade paths from old UUPS implementation to new ones.\\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\\n _setImplementation(newImplementation);\\n } else {\\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\\n require(slot == _IMPLEMENTATION_SLOT, \\\"ERC1967Upgrade: unsupported proxiableUUID\\\");\\n } catch {\\n revert(\\\"ERC1967Upgrade: new implementation is not UUPS\\\");\\n }\\n _upgradeToAndCall(newImplementation, data, forceCall);\\n }\\n }\\n\\n /**\\n * @dev Storage slot with the admin of the contract.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.admin\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\\n\\n /**\\n * @dev Emitted when the admin account has changed.\\n */\\n event AdminChanged(address previousAdmin, address newAdmin);\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _getAdmin() internal view virtual returns (address) {\\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 admin slot.\\n */\\n function _setAdmin(address newAdmin) private {\\n require(newAdmin != address(0), \\\"ERC1967: new admin is the zero address\\\");\\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n */\\n function _changeAdmin(address newAdmin) internal {\\n emit AdminChanged(_getAdmin(), newAdmin);\\n _setAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\\n */\\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\\n\\n /**\\n * @dev Emitted when the beacon is upgraded.\\n */\\n event BeaconUpgraded(address indexed beacon);\\n\\n /**\\n * @dev Returns the current beacon.\\n */\\n function _getBeacon() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new beacon in the EIP1967 beacon slot.\\n */\\n function _setBeacon(address newBeacon) private {\\n require(Address.isContract(newBeacon), \\\"ERC1967: new beacon is not a contract\\\");\\n require(Address.isContract(IBeacon(newBeacon).implementation()), \\\"ERC1967: beacon implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\\n }\\n\\n /**\\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\\n *\\n * Emits a {BeaconUpgraded} event.\\n */\\n function _upgradeBeaconToAndCall(\\n address newBeacon,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _setBeacon(newBeacon);\\n emit BeaconUpgraded(newBeacon);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x17668652127feebed0ce8d9431ef95ccc8c4292f03e3b8cf06c6ca16af396633\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\\n * be specified by overriding the virtual {_implementation} function.\\n *\\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\\n * different contract through the {_delegate} function.\\n *\\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\\n */\\nabstract contract Proxy {\\n /**\\n * @dev Delegates the current call to `implementation`.\\n *\\n * This function does not return to its internal call site, it will return directly to the external caller.\\n */\\n function _delegate(address implementation) internal virtual {\\n assembly {\\n // Copy msg.data. We take full control of memory in this inline assembly\\n // block because it will not return to Solidity code. We overwrite the\\n // Solidity scratch pad at memory position 0.\\n calldatacopy(0, 0, calldatasize())\\n\\n // Call the implementation.\\n // out and outsize are 0 because we don't know the size yet.\\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\\n\\n // Copy the returned data.\\n returndatacopy(0, 0, returndatasize())\\n\\n switch result\\n // delegatecall returns 0 on error.\\n case 0 {\\n revert(0, returndatasize())\\n }\\n default {\\n return(0, returndatasize())\\n }\\n }\\n }\\n\\n /**\\n * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function\\n * and {_fallback} should delegate.\\n */\\n function _implementation() internal view virtual returns (address);\\n\\n /**\\n * @dev Delegates the current call to the address returned by `_implementation()`.\\n *\\n * This function does not return to its internall call site, it will return directly to the external caller.\\n */\\n function _fallback() internal virtual {\\n _beforeFallback();\\n _delegate(_implementation());\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\\n * function in the contract matches the call data.\\n */\\n fallback() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\\n * is empty.\\n */\\n receive() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\\n * call, or as part of the Solidity `fallback` or `receive` functions.\\n *\\n * If overriden should call `super._beforeFallback()`.\\n */\\n function _beforeFallback() internal virtual {}\\n}\\n\",\"keccak256\":\"0xd5d1fd16e9faff7fcb3a52e02a8d49156f42a38a03f07b5f1810c21c2149a8ab\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/beacon/IBeacon.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\\n */\\ninterface IBeacon {\\n /**\\n * @dev Must return an address that can be used as a delegate call target.\\n *\\n * {BeaconProxy} will check that this address is a contract.\\n */\\n function implementation() external view returns (address);\\n}\\n\",\"keccak256\":\"0xd50a3421ac379ccb1be435fa646d66a65c986b4924f0849839f08692f39dde61\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/transparent/TransparentUpgradeableProxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../ERC1967/ERC1967Proxy.sol\\\";\\n\\n/**\\n * @dev This contract implements a proxy that is upgradeable by an admin.\\n *\\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\\n * clashing], which can potentially be used in an attack, this contract uses the\\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\\n * things that go hand in hand:\\n *\\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\\n * that call matches one of the admin functions exposed by the proxy itself.\\n * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the\\n * implementation. If the admin tries to call a function on the implementation it will fail with an error that says\\n * \\\"admin cannot fallback to proxy target\\\".\\n *\\n * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing\\n * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due\\n * to sudden errors when trying to call a function from the proxy implementation.\\n *\\n * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,\\n * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\\n */\\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\\n /**\\n * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and\\n * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\\n */\\n constructor(\\n address _logic,\\n address admin_,\\n bytes memory _data\\n ) payable ERC1967Proxy(_logic, _data) {\\n assert(_ADMIN_SLOT == bytes32(uint256(keccak256(\\\"eip1967.proxy.admin\\\")) - 1));\\n _changeAdmin(admin_);\\n }\\n\\n /**\\n * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.\\n */\\n modifier ifAdmin() {\\n if (msg.sender == _getAdmin()) {\\n _;\\n } else {\\n _fallback();\\n }\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\\n */\\n function admin() external ifAdmin returns (address admin_) {\\n admin_ = _getAdmin();\\n }\\n\\n /**\\n * @dev Returns the current implementation.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\\n */\\n function implementation() external ifAdmin returns (address implementation_) {\\n implementation_ = _implementation();\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\\n */\\n function changeAdmin(address newAdmin) external virtual ifAdmin {\\n _changeAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\\n */\\n function upgradeTo(address newImplementation) external ifAdmin {\\n _upgradeToAndCall(newImplementation, bytes(\\\"\\\"), false);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified\\n * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the\\n * proxied contract.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\\n */\\n function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {\\n _upgradeToAndCall(newImplementation, data, true);\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _admin() internal view virtual returns (address) {\\n return _getAdmin();\\n }\\n\\n /**\\n * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.\\n */\\n function _beforeFallback() internal virtual override {\\n require(msg.sender != _getAdmin(), \\\"TransparentUpgradeableProxy: admin cannot fallback to proxy target\\\");\\n super._beforeFallback();\\n }\\n}\\n\",\"keccak256\":\"0x140055a64cf579d622e04f5a198595832bf2cb193cd0005f4f2d4d61ca906253\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.1;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev Returns true if `account` is a contract.\\n *\\n * [IMPORTANT]\\n * ====\\n * It is unsafe to assume that an address for which this function returns\\n * false is an externally-owned account (EOA) and not a contract.\\n *\\n * Among others, `isContract` will return false for the following\\n * types of addresses:\\n *\\n * - an externally-owned account\\n * - a contract in construction\\n * - an address where a contract will be created\\n * - an address where a contract lived, but was destroyed\\n * ====\\n *\\n * [IMPORTANT]\\n * ====\\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\\n *\\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\\n * constructor.\\n * ====\\n */\\n function isContract(address account) internal view returns (bool) {\\n // This method relies on extcodesize/address.code.length, which returns 0\\n // for contracts in construction, since the code is only stored at the end\\n // of the constructor execution.\\n\\n return account.code.length > 0;\\n }\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n require(address(this).balance >= amount, \\\"Address: insufficient balance\\\");\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(success, \\\"Address: unable to send value, recipient may have reverted\\\");\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason, it is bubbled up by this\\n * function (like regular Solidity function calls).\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCall(target, data, \\\"Address: low-level call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\\n * `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, value, \\\"Address: low-level call with value failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\\n * with `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(address(this).balance >= value, \\\"Address: insufficient balance for call\\\");\\n require(isContract(target), \\\"Address: call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n return functionStaticCall(target, data, \\\"Address: low-level static call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n require(isContract(target), \\\"Address: static call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionDelegateCall(target, data, \\\"Address: low-level delegate call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(isContract(target), \\\"Address: delegate call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\\n * revert reason using the provided one.\\n *\\n * _Available since v4.3._\\n */\\n function verifyCallResult(\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal pure returns (bytes memory) {\\n if (success) {\\n return returndata;\\n } else {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n }\\n}\\n\",\"keccak256\":\"0x3777e696b62134e6177440dbe6e6601c0c156a443f57167194b67e75527439de\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/utils/StorageSlot.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Library for reading and writing primitive types to specific storage slots.\\n *\\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\\n * This library helps with reading and writing to such slots without the need for inline assembly.\\n *\\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\\n *\\n * Example usage to set ERC1967 implementation slot:\\n * ```\\n * contract ERC1967 {\\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n *\\n * function _getImplementation() internal view returns (address) {\\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n * }\\n *\\n * function _setImplementation(address newImplementation) internal {\\n * require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n * }\\n * }\\n * ```\\n *\\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\\n */\\nlibrary StorageSlot {\\n struct AddressSlot {\\n address value;\\n }\\n\\n struct BooleanSlot {\\n bool value;\\n }\\n\\n struct Bytes32Slot {\\n bytes32 value;\\n }\\n\\n struct Uint256Slot {\\n uint256 value;\\n }\\n\\n /**\\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\\n */\\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\\n */\\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\\n */\\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\\n */\\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n}\\n\",\"keccak256\":\"0xfe1b7a9aa2a530a9e705b220e26cd584e2fbdc9602a3a1066032b12816b46aca\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x6080604052604051620011b2380380620011b2833981016040819052620000269162000519565b82816200005560017f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbd620005f9565b6000805160206200116b833981519152146200007557620000756200061f565b6200008382826000620000e7565b50620000b3905060017fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6104620005f9565b6000805160206200114b83398151915214620000d357620000d36200061f565b620000de8262000124565b50505062000688565b620000f2836200017f565b600082511180620001005750805b156200011f576200011d8383620001c160201b620002ff1760201c565b505b505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6200014f620001f0565b604080516001600160a01b03928316815291841660208301520160405180910390a16200017c8162000229565b50565b6200018a81620002de565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b6060620001e983836040518060600160405280602781526020016200118b6027913962000381565b9392505050565b60006200021a6000805160206200114b83398151915260001b6200046760201b620002731760201c565b546001600160a01b0316919050565b6001600160a01b038116620002945760405162461bcd60e51b815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201526564647265737360d01b60648201526084015b60405180910390fd5b80620002bd6000805160206200114b83398151915260001b6200046760201b620002731760201c565b80546001600160a01b0319166001600160a01b039290921691909117905550565b620002f4816200046a60201b6200032b1760201c565b620003585760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084016200028b565b80620002bd6000805160206200116b83398151915260001b6200046760201b620002731760201c565b60606001600160a01b0384163b620003eb5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f6044820152651b9d1c9858dd60d21b60648201526084016200028b565b600080856001600160a01b03168560405162000408919062000635565b600060405180830381855af49150503d806000811462000445576040519150601f19603f3d011682016040523d82523d6000602084013e6200044a565b606091505b5090925090506200045d82828662000479565b9695505050505050565b90565b6001600160a01b03163b151590565b606083156200048a575081620001e9565b8251156200049b5782518084602001fd5b8160405162461bcd60e51b81526004016200028b919062000653565b80516001600160a01b0381168114620004cf57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101562000507578181015183820152602001620004ed565b838111156200011d5750506000910152565b6000806000606084860312156200052f57600080fd5b6200053a84620004b7565b92506200054a60208501620004b7565b60408501519092506001600160401b03808211156200056857600080fd5b818601915086601f8301126200057d57600080fd5b815181811115620005925762000592620004d4565b604051601f8201601f19908116603f01168101908382118183101715620005bd57620005bd620004d4565b81604052828152896020848701011115620005d757600080fd5b620005ea836020830160208801620004ea565b80955050505050509250925092565b6000828210156200061a57634e487b7160e01b600052601160045260246000fd5b500390565b634e487b7160e01b600052600160045260246000fd5b6000825162000649818460208701620004ea565b9190910192915050565b602081526000825180602084015262000674816040850160208701620004ea565b601f01601f19169190910160400192915050565b610ab380620006986000396000f3fe60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100a85780638f283970146100e6578063f851a440146101065761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61011b565b005b61006b61011b565b34801561008157600080fd5b5061006b61009036600461091f565b610135565b61006b6100a336600461093a565b610196565b3480156100b457600080fd5b506100bd610221565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b3480156100f257600080fd5b5061006b61010136600461091f565b610276565b34801561011257600080fd5b506100bd6102ba565b610123610347565b61013361012e610435565b61043f565b565b61013d610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816040518060200160405280600081525060006104a3565b50565b61018b61011b565b61019e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610219576102148383838080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250600192506104a3915050565b505050565b61021461011b565b600061022b610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610435565b905090565b61027361011b565b90565b61027e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816104ce565b60006102c4610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610463565b60606103248383604051806060016040528060278152602001610a576027913961052f565b9392505050565b73ffffffffffffffffffffffffffffffffffffffff163b151590565b61034f610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152604260248201527f5472616e73706172656e745570677261646561626c6550726f78793a2061646d60448201527f696e2063616e6e6f742066616c6c6261636b20746f2070726f7879207461726760648201527f6574000000000000000000000000000000000000000000000000000000000000608482015260a4015b60405180910390fd5b6000610266610657565b3660008037600080366000845af43d6000803e80801561045e573d6000f35b3d6000fd5b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b5473ffffffffffffffffffffffffffffffffffffffff16919050565b6104ac8361067f565b6000825111806104b95750805b15610214576104c883836102ff565b50505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6104f7610463565b6040805173ffffffffffffffffffffffffffffffffffffffff928316815291841660208301520160405180910390a161018b816106cc565b606073ffffffffffffffffffffffffffffffffffffffff84163b6105d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f60448201527f6e74726163740000000000000000000000000000000000000000000000000000606482015260840161042c565b6000808573ffffffffffffffffffffffffffffffffffffffff16856040516105fd91906109e9565b600060405180830381855af49150503d8060008114610638576040519150601f19603f3d011682016040523d82523d6000602084013e61063d565b606091505b509150915061064d8282866107d8565b9695505050505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610487565b6106888161082b565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b73ffffffffffffffffffffffffffffffffffffffff811661076f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201527f6464726573730000000000000000000000000000000000000000000000000000606482015260840161042c565b807fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff9290921691909117905550565b606083156107e7575081610324565b8251156107f75782518084602001fd5b816040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042c9190610a05565b73ffffffffffffffffffffffffffffffffffffffff81163b6108cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e747261637400000000000000000000000000000000000000606482015260840161042c565b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610792565b803573ffffffffffffffffffffffffffffffffffffffff8116811461091a57600080fd5b919050565b60006020828403121561093157600080fd5b610324826108f6565b60008060006040848603121561094f57600080fd5b610958846108f6565b9250602084013567ffffffffffffffff8082111561097557600080fd5b818601915086601f83011261098957600080fd5b81358181111561099857600080fd5b8760208285010111156109aa57600080fd5b6020830194508093505050509250925092565b60005b838110156109d85781810151838201526020016109c0565b838111156104c85750506000910152565b600082516109fb8184602087016109bd565b9190910192915050565b6020815260008251806020840152610a248160408501602087016109bd565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016919091016040019291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220b29caa54336b3ee836679675e9732ec5e526fb3f803cca2fe336cc3555aba62264736f6c634300080a0033b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564", + "deployedBytecode": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100a85780638f283970146100e6578063f851a440146101065761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61011b565b005b61006b61011b565b34801561008157600080fd5b5061006b61009036600461091f565b610135565b61006b6100a336600461093a565b610196565b3480156100b457600080fd5b506100bd610221565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b3480156100f257600080fd5b5061006b61010136600461091f565b610276565b34801561011257600080fd5b506100bd6102ba565b610123610347565b61013361012e610435565b61043f565b565b61013d610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816040518060200160405280600081525060006104a3565b50565b61018b61011b565b61019e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610219576102148383838080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250600192506104a3915050565b505050565b61021461011b565b600061022b610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610435565b905090565b61027361011b565b90565b61027e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816104ce565b60006102c4610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610463565b60606103248383604051806060016040528060278152602001610a576027913961052f565b9392505050565b73ffffffffffffffffffffffffffffffffffffffff163b151590565b61034f610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152604260248201527f5472616e73706172656e745570677261646561626c6550726f78793a2061646d60448201527f696e2063616e6e6f742066616c6c6261636b20746f2070726f7879207461726760648201527f6574000000000000000000000000000000000000000000000000000000000000608482015260a4015b60405180910390fd5b6000610266610657565b3660008037600080366000845af43d6000803e80801561045e573d6000f35b3d6000fd5b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b5473ffffffffffffffffffffffffffffffffffffffff16919050565b6104ac8361067f565b6000825111806104b95750805b15610214576104c883836102ff565b50505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6104f7610463565b6040805173ffffffffffffffffffffffffffffffffffffffff928316815291841660208301520160405180910390a161018b816106cc565b606073ffffffffffffffffffffffffffffffffffffffff84163b6105d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f60448201527f6e74726163740000000000000000000000000000000000000000000000000000606482015260840161042c565b6000808573ffffffffffffffffffffffffffffffffffffffff16856040516105fd91906109e9565b600060405180830381855af49150503d8060008114610638576040519150601f19603f3d011682016040523d82523d6000602084013e61063d565b606091505b509150915061064d8282866107d8565b9695505050505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610487565b6106888161082b565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b73ffffffffffffffffffffffffffffffffffffffff811661076f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201527f6464726573730000000000000000000000000000000000000000000000000000606482015260840161042c565b807fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff9290921691909117905550565b606083156107e7575081610324565b8251156107f75782518084602001fd5b816040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042c9190610a05565b73ffffffffffffffffffffffffffffffffffffffff81163b6108cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e747261637400000000000000000000000000000000000000606482015260840161042c565b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610792565b803573ffffffffffffffffffffffffffffffffffffffff8116811461091a57600080fd5b919050565b60006020828403121561093157600080fd5b610324826108f6565b60008060006040848603121561094f57600080fd5b610958846108f6565b9250602084013567ffffffffffffffff8082111561097557600080fd5b818601915086601f83011261098957600080fd5b81358181111561099857600080fd5b8760208285010111156109aa57600080fd5b6020830194508093505050509250925092565b60005b838110156109d85781810151838201526020016109c0565b838111156104c85750506000910152565b600082516109fb8184602087016109bd565b9190910192915050565b6020815260008251806020840152610a248160408501602087016109bd565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016919091016040019291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220b29caa54336b3ee836679675e9732ec5e526fb3f803cca2fe336cc3555aba62264736f6c634300080a0033", + "devdoc": { + "details": "This contract implements a proxy that is upgradeable by an admin. To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector clashing], which can potentially be used in an attack, this contract uses the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two things that go hand in hand: 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches one of the admin functions exposed by the proxy itself. 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error that says \"admin cannot fallback to proxy target\". These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to call a function from the proxy implementation. Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.", + "kind": "dev", + "methods": { + "admin()": { + "details": "Returns the current admin. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`" + }, + "changeAdmin(address)": { + "details": "Changes the admin of the proxy. Emits an {AdminChanged} event. NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}." + }, + "constructor": { + "details": "Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}." + }, + "implementation()": { + "details": "Returns the current implementation. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`" + }, + "upgradeTo(address)": { + "details": "Upgrade the implementation of the proxy. NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}." + }, + "upgradeToAndCall(address,bytes)": { + "details": "Upgrade the implementation of the proxy, and then call a function from the new implementation as specified by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the proxied contract. NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}." + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0.json b/packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0.json new file mode 100644 index 0000000000..bf2540c47f --- /dev/null +++ b/packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0.json @@ -0,0 +1,1366 @@ +{ + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "abi": [ + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "previousAdmin", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newAdmin", + "type": "address" + } + ], + "name": "AdminChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "beacon", + "type": "address" + } + ], + "name": "BeaconUpgraded", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "implementation", + "type": "address" + } + ], + "name": "Upgraded", + "type": "event" + }, + { + "stateMutability": "payable", + "type": "fallback" + }, + { + "inputs": [], + "name": "admin", + "outputs": [ + { + "internalType": "address", + "name": "admin_", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newAdmin", + "type": "address" + } + ], + "name": "changeAdmin", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "implementation", + "outputs": [ + { + "internalType": "address", + "name": "implementation_", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newImplementation", + "type": "address" + } + ], + "name": "upgradeTo", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newImplementation", + "type": "address" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "upgradeToAndCall", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "stateMutability": "payable", + "type": "receive" + }, + { + "inputs": [ + { + "internalType": "enum ComptrollerErrorReporter.Error", + "name": "", + "type": "uint8" + } + ], + "name": "IonicMarketERC4626__CompoundError", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Deposit", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint8", + "name": "version", + "type": "uint8" + } + ], + "name": "Initialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldOwner", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "NewOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldPendingOwner", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newPendingOwner", + "type": "address" + } + ], + "name": "NewPendingOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Paused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Unpaused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "oldPerformanceFee", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "newPerformanceFee", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "oldFeeRecipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newFeeRecipient", + "type": "address" + } + ], + "name": "UpdatedFeeSettings", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldRewardsRecipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newRewardsRecipient", + "type": "address" + } + ], + "name": "UpdatedRewardsRecipient", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Withdraw", + "type": "event" + }, + { + "inputs": [], + "name": "_acceptOwner", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newPendingOwner", + "type": "address" + } + ], + "name": "_setPendingOwner", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "asset", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "cToken", + "outputs": [ + { + "internalType": "contract ICErc20", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "claimRewards", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "convertToAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "convertToShares", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "decimals", + "outputs": [ + { + "internalType": "uint8", + "name": "", + "type": "uint8" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "subtractedValue", + "type": "uint256" + } + ], + "name": "decreaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "deposit", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "emergencyWithdrawAndPause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "feeRecipient", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "flywheelLensRouter", + "outputs": [ + { + "internalType": "contract IonicFlywheelLensRouter_4626", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "addedValue", + "type": "uint256" + } + ], + "name": "increaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "contract ICErc20", + "name": "cToken_", + "type": "address" + }, + { + "internalType": "address", + "name": "flywheelLensRouter_", + "type": "address" + }, + { + "internalType": "address", + "name": "rewardsRecipient_", + "type": "address" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "mint", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "name", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "paused", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pendingOwner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "performanceFee", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "redeem", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "rewardsRecipient", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "market", + "type": "address" + } + ], + "name": "shutdown", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "symbol", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "takePerformanceFee", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "totalAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "unpause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "newPerformanceFee", + "type": "uint256" + }, + { + "internalType": "address", + "name": "newFeeRecipient", + "type": "address" + } + ], + "name": "updateFeeSettings", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newRewardsRecipient", + "type": "address" + } + ], + "name": "updateRewardsRecipient", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "vaultShareHWM", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "withdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "withdrawAccruedFees", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "_logic", + "type": "address" + }, + { + "internalType": "address", + "name": "admin_", + "type": "address" + }, + { + "internalType": "bytes", + "name": "_data", + "type": "bytes" + } + ], + "stateMutability": "payable", + "type": "constructor" + } + ], + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "receipt": { + "to": null, + "from": "0x1155b614971f16758C92c4890eD338C9e3ede6b7", + "contractAddress": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "transactionIndex": 137, + "gasUsed": "985147", + "logsBloom": "0x00000000000000000000000000000000400000000000000000800000000220000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000002000001000000000000000000000000000000000000020000000000000000000800000000800000000000000000000000400000000001000000000000000000000000000000004080000000000000c00000000000000000100000000000000400000000000000000000000000000000000000000020000000000000000000040000000000000400000000000000000020000000000000000000000000000000000000000000100000004000000000000000", + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3", + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "logs": [ + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b", + "0x0000000000000000000000000014ce7973246b7a99ea95f0bd38156c19551880" + ], + "data": "0x", + "logIndex": 453, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + }, + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "data": "0x", + "logIndex": 454, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + }, + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "data": "0x", + "logIndex": 455, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + }, + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498" + ], + "data": "0x0000000000000000000000000000000000000000000000000000000000000001", + "logIndex": 456, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + }, + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0x7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f" + ], + "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000028df5636456049b891bf9d40fa46ef5ad20822c5", + "logIndex": 457, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + } + ], + "blockNumber": 25464425, + "cumulativeGasUsed": "29066749", + "status": 1, + "byzantium": true + }, + "args": [ + "0x0014cE7973246b7a99Ea95f0Bd38156C19551880", + "0x28DF5636456049B891bF9D40fa46eF5ad20822C5", + "0xc0c53b8b000000000000000000000000a900a17a49bc4d442ba7f72c39fa2108865671f0000000000000000000000000b1402333b12fc066c3d7f55d37944d5e281a3e8b0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "numDeployments": 1, + "solcInputHash": "0e89febeebc7444140de8e67c9067d2c", + "metadata": "{\"compiler\":{\"version\":\"0.8.10+commit.fc410830\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_logic\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"admin_\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previousAdmin\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"AdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"beacon\",\"type\":\"address\"}],\"name\":\"BeaconUpgraded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"implementation\",\"type\":\"address\"}],\"name\":\"Upgraded\",\"type\":\"event\"},{\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"inputs\":[],\"name\":\"admin\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"admin_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"changeAdmin\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"implementation\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"implementation_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newImplementation\",\"type\":\"address\"}],\"name\":\"upgradeTo\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newImplementation\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"upgradeToAndCall\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}],\"devdoc\":{\"details\":\"This contract implements a proxy that is upgradeable by an admin. To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector clashing], which can potentially be used in an attack, this contract uses the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two things that go hand in hand: 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches one of the admin functions exposed by the proxy itself. 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error that says \\\"admin cannot fallback to proxy target\\\". These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to call a function from the proxy implementation. Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\",\"kind\":\"dev\",\"methods\":{\"admin()\":{\"details\":\"Returns the current admin. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\"},\"changeAdmin(address)\":{\"details\":\"Changes the admin of the proxy. Emits an {AdminChanged} event. NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\"},\"constructor\":{\"details\":\"Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\"},\"implementation()\":{\"details\":\"Returns the current implementation. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\"},\"upgradeTo(address)\":{\"details\":\"Upgrade the implementation of the proxy. NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\"},\"upgradeToAndCall(address,bytes)\":{\"details\":\"Upgrade the implementation of the proxy, and then call a function from the new implementation as specified by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the proxied contract. NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\"}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"solc_0.8/openzeppelin/proxy/transparent/TransparentUpgradeableProxy.sol\":\"TransparentUpgradeableProxy\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":999999},\"remappings\":[]},\"sources\":{\"solc_0.8/openzeppelin/interfaces/draft-IERC1822.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (interfaces/draft-IERC1822.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\\n * proxy whose upgrades are fully controlled by the current implementation.\\n */\\ninterface IERC1822Proxiable {\\n /**\\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\\n * address.\\n *\\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\\n * function revert if invoked through a proxy.\\n */\\n function proxiableUUID() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x93b4e21c931252739a1ec13ea31d3d35a5c068be3163ccab83e4d70c40355f03\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../Proxy.sol\\\";\\nimport \\\"./ERC1967Upgrade.sol\\\";\\n\\n/**\\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\\n * implementation address that can be changed. This address is stored in storage in the location specified by\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\\n * implementation behind the proxy.\\n */\\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\\n /**\\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\\n *\\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\\n * function call, and allows initializating the storage of the proxy like a Solidity constructor.\\n */\\n constructor(address _logic, bytes memory _data) payable {\\n assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256(\\\"eip1967.proxy.implementation\\\")) - 1));\\n _upgradeToAndCall(_logic, _data, false);\\n }\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _implementation() internal view virtual override returns (address impl) {\\n return ERC1967Upgrade._getImplementation();\\n }\\n}\\n\",\"keccak256\":\"0x6309f9f39dc6f4f45a24f296543867aa358e32946cd6b2874627a996d606b3a0\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Upgrade.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/ERC1967/ERC1967Upgrade.sol)\\n\\npragma solidity ^0.8.2;\\n\\nimport \\\"../beacon/IBeacon.sol\\\";\\nimport \\\"../../interfaces/draft-IERC1822.sol\\\";\\nimport \\\"../../utils/Address.sol\\\";\\nimport \\\"../../utils/StorageSlot.sol\\\";\\n\\n/**\\n * @dev This abstract contract provides getters and event emitting update functions for\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\\n *\\n * _Available since v4.1._\\n *\\n * @custom:oz-upgrades-unsafe-allow delegatecall\\n */\\nabstract contract ERC1967Upgrade {\\n // This is the keccak-256 hash of \\\"eip1967.proxy.rollback\\\" subtracted by 1\\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\\n\\n /**\\n * @dev Storage slot with the address of the current implementation.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.implementation\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n\\n /**\\n * @dev Emitted when the implementation is upgraded.\\n */\\n event Upgraded(address indexed implementation);\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _getImplementation() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 implementation slot.\\n */\\n function _setImplementation(address newImplementation) private {\\n require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n }\\n\\n /**\\n * @dev Perform implementation upgrade\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeTo(address newImplementation) internal {\\n _setImplementation(newImplementation);\\n emit Upgraded(newImplementation);\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCall(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _upgradeTo(newImplementation);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(newImplementation, data);\\n }\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCallUUPS(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n // Upgrades from old implementations will perform a rollback test. This test requires the new\\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\\n // this special case will break upgrade paths from old UUPS implementation to new ones.\\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\\n _setImplementation(newImplementation);\\n } else {\\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\\n require(slot == _IMPLEMENTATION_SLOT, \\\"ERC1967Upgrade: unsupported proxiableUUID\\\");\\n } catch {\\n revert(\\\"ERC1967Upgrade: new implementation is not UUPS\\\");\\n }\\n _upgradeToAndCall(newImplementation, data, forceCall);\\n }\\n }\\n\\n /**\\n * @dev Storage slot with the admin of the contract.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.admin\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\\n\\n /**\\n * @dev Emitted when the admin account has changed.\\n */\\n event AdminChanged(address previousAdmin, address newAdmin);\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _getAdmin() internal view virtual returns (address) {\\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 admin slot.\\n */\\n function _setAdmin(address newAdmin) private {\\n require(newAdmin != address(0), \\\"ERC1967: new admin is the zero address\\\");\\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n */\\n function _changeAdmin(address newAdmin) internal {\\n emit AdminChanged(_getAdmin(), newAdmin);\\n _setAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\\n */\\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\\n\\n /**\\n * @dev Emitted when the beacon is upgraded.\\n */\\n event BeaconUpgraded(address indexed beacon);\\n\\n /**\\n * @dev Returns the current beacon.\\n */\\n function _getBeacon() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new beacon in the EIP1967 beacon slot.\\n */\\n function _setBeacon(address newBeacon) private {\\n require(Address.isContract(newBeacon), \\\"ERC1967: new beacon is not a contract\\\");\\n require(Address.isContract(IBeacon(newBeacon).implementation()), \\\"ERC1967: beacon implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\\n }\\n\\n /**\\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\\n *\\n * Emits a {BeaconUpgraded} event.\\n */\\n function _upgradeBeaconToAndCall(\\n address newBeacon,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _setBeacon(newBeacon);\\n emit BeaconUpgraded(newBeacon);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x17668652127feebed0ce8d9431ef95ccc8c4292f03e3b8cf06c6ca16af396633\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\\n * be specified by overriding the virtual {_implementation} function.\\n *\\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\\n * different contract through the {_delegate} function.\\n *\\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\\n */\\nabstract contract Proxy {\\n /**\\n * @dev Delegates the current call to `implementation`.\\n *\\n * This function does not return to its internal call site, it will return directly to the external caller.\\n */\\n function _delegate(address implementation) internal virtual {\\n assembly {\\n // Copy msg.data. We take full control of memory in this inline assembly\\n // block because it will not return to Solidity code. We overwrite the\\n // Solidity scratch pad at memory position 0.\\n calldatacopy(0, 0, calldatasize())\\n\\n // Call the implementation.\\n // out and outsize are 0 because we don't know the size yet.\\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\\n\\n // Copy the returned data.\\n returndatacopy(0, 0, returndatasize())\\n\\n switch result\\n // delegatecall returns 0 on error.\\n case 0 {\\n revert(0, returndatasize())\\n }\\n default {\\n return(0, returndatasize())\\n }\\n }\\n }\\n\\n /**\\n * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function\\n * and {_fallback} should delegate.\\n */\\n function _implementation() internal view virtual returns (address);\\n\\n /**\\n * @dev Delegates the current call to the address returned by `_implementation()`.\\n *\\n * This function does not return to its internall call site, it will return directly to the external caller.\\n */\\n function _fallback() internal virtual {\\n _beforeFallback();\\n _delegate(_implementation());\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\\n * function in the contract matches the call data.\\n */\\n fallback() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\\n * is empty.\\n */\\n receive() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\\n * call, or as part of the Solidity `fallback` or `receive` functions.\\n *\\n * If overriden should call `super._beforeFallback()`.\\n */\\n function _beforeFallback() internal virtual {}\\n}\\n\",\"keccak256\":\"0xd5d1fd16e9faff7fcb3a52e02a8d49156f42a38a03f07b5f1810c21c2149a8ab\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/beacon/IBeacon.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\\n */\\ninterface IBeacon {\\n /**\\n * @dev Must return an address that can be used as a delegate call target.\\n *\\n * {BeaconProxy} will check that this address is a contract.\\n */\\n function implementation() external view returns (address);\\n}\\n\",\"keccak256\":\"0xd50a3421ac379ccb1be435fa646d66a65c986b4924f0849839f08692f39dde61\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/transparent/TransparentUpgradeableProxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../ERC1967/ERC1967Proxy.sol\\\";\\n\\n/**\\n * @dev This contract implements a proxy that is upgradeable by an admin.\\n *\\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\\n * clashing], which can potentially be used in an attack, this contract uses the\\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\\n * things that go hand in hand:\\n *\\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\\n * that call matches one of the admin functions exposed by the proxy itself.\\n * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the\\n * implementation. If the admin tries to call a function on the implementation it will fail with an error that says\\n * \\\"admin cannot fallback to proxy target\\\".\\n *\\n * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing\\n * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due\\n * to sudden errors when trying to call a function from the proxy implementation.\\n *\\n * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,\\n * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\\n */\\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\\n /**\\n * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and\\n * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\\n */\\n constructor(\\n address _logic,\\n address admin_,\\n bytes memory _data\\n ) payable ERC1967Proxy(_logic, _data) {\\n assert(_ADMIN_SLOT == bytes32(uint256(keccak256(\\\"eip1967.proxy.admin\\\")) - 1));\\n _changeAdmin(admin_);\\n }\\n\\n /**\\n * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.\\n */\\n modifier ifAdmin() {\\n if (msg.sender == _getAdmin()) {\\n _;\\n } else {\\n _fallback();\\n }\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\\n */\\n function admin() external ifAdmin returns (address admin_) {\\n admin_ = _getAdmin();\\n }\\n\\n /**\\n * @dev Returns the current implementation.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\\n */\\n function implementation() external ifAdmin returns (address implementation_) {\\n implementation_ = _implementation();\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\\n */\\n function changeAdmin(address newAdmin) external virtual ifAdmin {\\n _changeAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\\n */\\n function upgradeTo(address newImplementation) external ifAdmin {\\n _upgradeToAndCall(newImplementation, bytes(\\\"\\\"), false);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified\\n * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the\\n * proxied contract.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\\n */\\n function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {\\n _upgradeToAndCall(newImplementation, data, true);\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _admin() internal view virtual returns (address) {\\n return _getAdmin();\\n }\\n\\n /**\\n * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.\\n */\\n function _beforeFallback() internal virtual override {\\n require(msg.sender != _getAdmin(), \\\"TransparentUpgradeableProxy: admin cannot fallback to proxy target\\\");\\n super._beforeFallback();\\n }\\n}\\n\",\"keccak256\":\"0x140055a64cf579d622e04f5a198595832bf2cb193cd0005f4f2d4d61ca906253\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.1;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev Returns true if `account` is a contract.\\n *\\n * [IMPORTANT]\\n * ====\\n * It is unsafe to assume that an address for which this function returns\\n * false is an externally-owned account (EOA) and not a contract.\\n *\\n * Among others, `isContract` will return false for the following\\n * types of addresses:\\n *\\n * - an externally-owned account\\n * - a contract in construction\\n * - an address where a contract will be created\\n * - an address where a contract lived, but was destroyed\\n * ====\\n *\\n * [IMPORTANT]\\n * ====\\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\\n *\\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\\n * constructor.\\n * ====\\n */\\n function isContract(address account) internal view returns (bool) {\\n // This method relies on extcodesize/address.code.length, which returns 0\\n // for contracts in construction, since the code is only stored at the end\\n // of the constructor execution.\\n\\n return account.code.length > 0;\\n }\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n require(address(this).balance >= amount, \\\"Address: insufficient balance\\\");\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(success, \\\"Address: unable to send value, recipient may have reverted\\\");\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason, it is bubbled up by this\\n * function (like regular Solidity function calls).\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCall(target, data, \\\"Address: low-level call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\\n * `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, value, \\\"Address: low-level call with value failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\\n * with `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(address(this).balance >= value, \\\"Address: insufficient balance for call\\\");\\n require(isContract(target), \\\"Address: call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n return functionStaticCall(target, data, \\\"Address: low-level static call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n require(isContract(target), \\\"Address: static call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionDelegateCall(target, data, \\\"Address: low-level delegate call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(isContract(target), \\\"Address: delegate call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\\n * revert reason using the provided one.\\n *\\n * _Available since v4.3._\\n */\\n function verifyCallResult(\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal pure returns (bytes memory) {\\n if (success) {\\n return returndata;\\n } else {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n }\\n}\\n\",\"keccak256\":\"0x3777e696b62134e6177440dbe6e6601c0c156a443f57167194b67e75527439de\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/utils/StorageSlot.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Library for reading and writing primitive types to specific storage slots.\\n *\\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\\n * This library helps with reading and writing to such slots without the need for inline assembly.\\n *\\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\\n *\\n * Example usage to set ERC1967 implementation slot:\\n * ```\\n * contract ERC1967 {\\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n *\\n * function _getImplementation() internal view returns (address) {\\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n * }\\n *\\n * function _setImplementation(address newImplementation) internal {\\n * require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n * }\\n * }\\n * ```\\n *\\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\\n */\\nlibrary StorageSlot {\\n struct AddressSlot {\\n address value;\\n }\\n\\n struct BooleanSlot {\\n bool value;\\n }\\n\\n struct Bytes32Slot {\\n bytes32 value;\\n }\\n\\n struct Uint256Slot {\\n uint256 value;\\n }\\n\\n /**\\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\\n */\\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\\n */\\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\\n */\\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\\n */\\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n}\\n\",\"keccak256\":\"0xfe1b7a9aa2a530a9e705b220e26cd584e2fbdc9602a3a1066032b12816b46aca\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x6080604052604051620011b2380380620011b2833981016040819052620000269162000519565b82816200005560017f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbd620005f9565b6000805160206200116b833981519152146200007557620000756200061f565b6200008382826000620000e7565b50620000b3905060017fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6104620005f9565b6000805160206200114b83398151915214620000d357620000d36200061f565b620000de8262000124565b50505062000688565b620000f2836200017f565b600082511180620001005750805b156200011f576200011d8383620001c160201b620002ff1760201c565b505b505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6200014f620001f0565b604080516001600160a01b03928316815291841660208301520160405180910390a16200017c8162000229565b50565b6200018a81620002de565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b6060620001e983836040518060600160405280602781526020016200118b6027913962000381565b9392505050565b60006200021a6000805160206200114b83398151915260001b6200046760201b620002731760201c565b546001600160a01b0316919050565b6001600160a01b038116620002945760405162461bcd60e51b815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201526564647265737360d01b60648201526084015b60405180910390fd5b80620002bd6000805160206200114b83398151915260001b6200046760201b620002731760201c565b80546001600160a01b0319166001600160a01b039290921691909117905550565b620002f4816200046a60201b6200032b1760201c565b620003585760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084016200028b565b80620002bd6000805160206200116b83398151915260001b6200046760201b620002731760201c565b60606001600160a01b0384163b620003eb5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f6044820152651b9d1c9858dd60d21b60648201526084016200028b565b600080856001600160a01b03168560405162000408919062000635565b600060405180830381855af49150503d806000811462000445576040519150601f19603f3d011682016040523d82523d6000602084013e6200044a565b606091505b5090925090506200045d82828662000479565b9695505050505050565b90565b6001600160a01b03163b151590565b606083156200048a575081620001e9565b8251156200049b5782518084602001fd5b8160405162461bcd60e51b81526004016200028b919062000653565b80516001600160a01b0381168114620004cf57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101562000507578181015183820152602001620004ed565b838111156200011d5750506000910152565b6000806000606084860312156200052f57600080fd5b6200053a84620004b7565b92506200054a60208501620004b7565b60408501519092506001600160401b03808211156200056857600080fd5b818601915086601f8301126200057d57600080fd5b815181811115620005925762000592620004d4565b604051601f8201601f19908116603f01168101908382118183101715620005bd57620005bd620004d4565b81604052828152896020848701011115620005d757600080fd5b620005ea836020830160208801620004ea565b80955050505050509250925092565b6000828210156200061a57634e487b7160e01b600052601160045260246000fd5b500390565b634e487b7160e01b600052600160045260246000fd5b6000825162000649818460208701620004ea565b9190910192915050565b602081526000825180602084015262000674816040850160208701620004ea565b601f01601f19169190910160400192915050565b610ab380620006986000396000f3fe60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100a85780638f283970146100e6578063f851a440146101065761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61011b565b005b61006b61011b565b34801561008157600080fd5b5061006b61009036600461091f565b610135565b61006b6100a336600461093a565b610196565b3480156100b457600080fd5b506100bd610221565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b3480156100f257600080fd5b5061006b61010136600461091f565b610276565b34801561011257600080fd5b506100bd6102ba565b610123610347565b61013361012e610435565b61043f565b565b61013d610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816040518060200160405280600081525060006104a3565b50565b61018b61011b565b61019e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610219576102148383838080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250600192506104a3915050565b505050565b61021461011b565b600061022b610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610435565b905090565b61027361011b565b90565b61027e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816104ce565b60006102c4610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610463565b60606103248383604051806060016040528060278152602001610a576027913961052f565b9392505050565b73ffffffffffffffffffffffffffffffffffffffff163b151590565b61034f610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152604260248201527f5472616e73706172656e745570677261646561626c6550726f78793a2061646d60448201527f696e2063616e6e6f742066616c6c6261636b20746f2070726f7879207461726760648201527f6574000000000000000000000000000000000000000000000000000000000000608482015260a4015b60405180910390fd5b6000610266610657565b3660008037600080366000845af43d6000803e80801561045e573d6000f35b3d6000fd5b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b5473ffffffffffffffffffffffffffffffffffffffff16919050565b6104ac8361067f565b6000825111806104b95750805b15610214576104c883836102ff565b50505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6104f7610463565b6040805173ffffffffffffffffffffffffffffffffffffffff928316815291841660208301520160405180910390a161018b816106cc565b606073ffffffffffffffffffffffffffffffffffffffff84163b6105d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f60448201527f6e74726163740000000000000000000000000000000000000000000000000000606482015260840161042c565b6000808573ffffffffffffffffffffffffffffffffffffffff16856040516105fd91906109e9565b600060405180830381855af49150503d8060008114610638576040519150601f19603f3d011682016040523d82523d6000602084013e61063d565b606091505b509150915061064d8282866107d8565b9695505050505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610487565b6106888161082b565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b73ffffffffffffffffffffffffffffffffffffffff811661076f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201527f6464726573730000000000000000000000000000000000000000000000000000606482015260840161042c565b807fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff9290921691909117905550565b606083156107e7575081610324565b8251156107f75782518084602001fd5b816040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042c9190610a05565b73ffffffffffffffffffffffffffffffffffffffff81163b6108cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e747261637400000000000000000000000000000000000000606482015260840161042c565b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610792565b803573ffffffffffffffffffffffffffffffffffffffff8116811461091a57600080fd5b919050565b60006020828403121561093157600080fd5b610324826108f6565b60008060006040848603121561094f57600080fd5b610958846108f6565b9250602084013567ffffffffffffffff8082111561097557600080fd5b818601915086601f83011261098957600080fd5b81358181111561099857600080fd5b8760208285010111156109aa57600080fd5b6020830194508093505050509250925092565b60005b838110156109d85781810151838201526020016109c0565b838111156104c85750506000910152565b600082516109fb8184602087016109bd565b9190910192915050565b6020815260008251806020840152610a248160408501602087016109bd565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016919091016040019291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220b29caa54336b3ee836679675e9732ec5e526fb3f803cca2fe336cc3555aba62264736f6c634300080a0033b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564", + "deployedBytecode": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100a85780638f283970146100e6578063f851a440146101065761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61011b565b005b61006b61011b565b34801561008157600080fd5b5061006b61009036600461091f565b610135565b61006b6100a336600461093a565b610196565b3480156100b457600080fd5b506100bd610221565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b3480156100f257600080fd5b5061006b61010136600461091f565b610276565b34801561011257600080fd5b506100bd6102ba565b610123610347565b61013361012e610435565b61043f565b565b61013d610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816040518060200160405280600081525060006104a3565b50565b61018b61011b565b61019e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610219576102148383838080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250600192506104a3915050565b505050565b61021461011b565b600061022b610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610435565b905090565b61027361011b565b90565b61027e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816104ce565b60006102c4610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610463565b60606103248383604051806060016040528060278152602001610a576027913961052f565b9392505050565b73ffffffffffffffffffffffffffffffffffffffff163b151590565b61034f610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152604260248201527f5472616e73706172656e745570677261646561626c6550726f78793a2061646d60448201527f696e2063616e6e6f742066616c6c6261636b20746f2070726f7879207461726760648201527f6574000000000000000000000000000000000000000000000000000000000000608482015260a4015b60405180910390fd5b6000610266610657565b3660008037600080366000845af43d6000803e80801561045e573d6000f35b3d6000fd5b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b5473ffffffffffffffffffffffffffffffffffffffff16919050565b6104ac8361067f565b6000825111806104b95750805b15610214576104c883836102ff565b50505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6104f7610463565b6040805173ffffffffffffffffffffffffffffffffffffffff928316815291841660208301520160405180910390a161018b816106cc565b606073ffffffffffffffffffffffffffffffffffffffff84163b6105d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f60448201527f6e74726163740000000000000000000000000000000000000000000000000000606482015260840161042c565b6000808573ffffffffffffffffffffffffffffffffffffffff16856040516105fd91906109e9565b600060405180830381855af49150503d8060008114610638576040519150601f19603f3d011682016040523d82523d6000602084013e61063d565b606091505b509150915061064d8282866107d8565b9695505050505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610487565b6106888161082b565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b73ffffffffffffffffffffffffffffffffffffffff811661076f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201527f6464726573730000000000000000000000000000000000000000000000000000606482015260840161042c565b807fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff9290921691909117905550565b606083156107e7575081610324565b8251156107f75782518084602001fd5b816040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042c9190610a05565b73ffffffffffffffffffffffffffffffffffffffff81163b6108cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e747261637400000000000000000000000000000000000000606482015260840161042c565b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610792565b803573ffffffffffffffffffffffffffffffffffffffff8116811461091a57600080fd5b919050565b60006020828403121561093157600080fd5b610324826108f6565b60008060006040848603121561094f57600080fd5b610958846108f6565b9250602084013567ffffffffffffffff8082111561097557600080fd5b818601915086601f83011261098957600080fd5b81358181111561099857600080fd5b8760208285010111156109aa57600080fd5b6020830194508093505050509250925092565b60005b838110156109d85781810151838201526020016109c0565b838111156104c85750506000910152565b600082516109fb8184602087016109bd565b9190910192915050565b6020815260008251806020840152610a248160408501602087016109bd565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016919091016040019291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220b29caa54336b3ee836679675e9732ec5e526fb3f803cca2fe336cc3555aba62264736f6c634300080a0033", + "execute": { + "methodName": "initialize", + "args": [ + "0xa900A17a49Bc4D442bA7F72c39FA2108865671f0", + "0xB1402333b12fc066C3D7F55d37944D5e281a3e8B", + "0x1155b614971f16758C92c4890eD338C9e3ede6b7" + ] + }, + "implementation": "0x0014cE7973246b7a99Ea95f0Bd38156C19551880", + "devdoc": { + "details": "This contract implements a proxy that is upgradeable by an admin. To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector clashing], which can potentially be used in an attack, this contract uses the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two things that go hand in hand: 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches one of the admin functions exposed by the proxy itself. 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error that says \"admin cannot fallback to proxy target\". These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to call a function from the proxy implementation. Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.", + "kind": "dev", + "methods": { + "admin()": { + "details": "Returns the current admin. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`" + }, + "changeAdmin(address)": { + "details": "Changes the admin of the proxy. Emits an {AdminChanged} event. NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}." + }, + "constructor": { + "details": "Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}." + }, + "implementation()": { + "details": "Returns the current implementation. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`" + }, + "upgradeTo(address)": { + "details": "Upgrade the implementation of the proxy. NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}." + }, + "upgradeToAndCall(address,bytes)": { + "details": "Upgrade the implementation of the proxy, and then call a function from the new implementation as specified by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the proxied contract. NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}." + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0_Implementation.json b/packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0_Implementation.json new file mode 100644 index 0000000000..6676d3a6d7 --- /dev/null +++ b/packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0_Implementation.json @@ -0,0 +1,1547 @@ +{ + "address": "0x0014cE7973246b7a99Ea95f0Bd38156C19551880", + "abi": [ + { + "inputs": [ + { + "internalType": "enum ComptrollerErrorReporter.Error", + "name": "", + "type": "uint8" + } + ], + "name": "IonicMarketERC4626__CompoundError", + "type": "error" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Approval", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Deposit", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint8", + "name": "version", + "type": "uint8" + } + ], + "name": "Initialized", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldOwner", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "NewOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldPendingOwner", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newPendingOwner", + "type": "address" + } + ], + "name": "NewPendingOwner", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "previousOwner", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "OwnershipTransferred", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Paused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "value", + "type": "uint256" + } + ], + "name": "Transfer", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "Unpaused", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "uint256", + "name": "oldPerformanceFee", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "newPerformanceFee", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "address", + "name": "oldFeeRecipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newFeeRecipient", + "type": "address" + } + ], + "name": "UpdatedFeeSettings", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "oldRewardsRecipient", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newRewardsRecipient", + "type": "address" + } + ], + "name": "UpdatedRewardsRecipient", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "sender", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "indexed": true, + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "indexed": false, + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "Withdraw", + "type": "event" + }, + { + "inputs": [], + "name": "_acceptOwner", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newPendingOwner", + "type": "address" + } + ], + "name": "_setPendingOwner", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + }, + { + "internalType": "address", + "name": "spender", + "type": "address" + } + ], + "name": "allowance", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "approve", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "asset", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "account", + "type": "address" + } + ], + "name": "balanceOf", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "cToken", + "outputs": [ + { + "internalType": "contract ICErc20", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "claimRewards", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "convertToAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "convertToShares", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "decimals", + "outputs": [ + { + "internalType": "uint8", + "name": "", + "type": "uint8" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "subtractedValue", + "type": "uint256" + } + ], + "name": "decreaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "deposit", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "emergencyWithdrawAndPause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "feeRecipient", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "flywheelLensRouter", + "outputs": [ + { + "internalType": "contract IonicFlywheelLensRouter_4626", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "spender", + "type": "address" + }, + { + "internalType": "uint256", + "name": "addedValue", + "type": "uint256" + } + ], + "name": "increaseAllowance", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "contract ICErc20", + "name": "cToken_", + "type": "address" + }, + { + "internalType": "address", + "name": "flywheelLensRouter_", + "type": "address" + }, + { + "internalType": "address", + "name": "rewardsRecipient_", + "type": "address" + } + ], + "name": "initialize", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "name": "maxMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "maxWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + } + ], + "name": "mint", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "name", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "owner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "paused", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "pendingOwner", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "performanceFee", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewDeposit", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewMint", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "name": "previewRedeem", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "name": "previewWithdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "redeem", + "outputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "renounceOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "rewardsRecipient", + "outputs": [ + { + "internalType": "address", + "name": "", + "type": "address" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "market", + "type": "address" + } + ], + "name": "shutdown", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "symbol", + "outputs": [ + { + "internalType": "string", + "name": "", + "type": "string" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "takePerformanceFee", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "totalAssets", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [], + "name": "totalSupply", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transfer", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "from", + "type": "address" + }, + { + "internalType": "address", + "name": "to", + "type": "address" + }, + { + "internalType": "uint256", + "name": "amount", + "type": "uint256" + } + ], + "name": "transferFrom", + "outputs": [ + { + "internalType": "bool", + "name": "", + "type": "bool" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newOwner", + "type": "address" + } + ], + "name": "transferOwnership", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "unpause", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "newPerformanceFee", + "type": "uint256" + }, + { + "internalType": "address", + "name": "newFeeRecipient", + "type": "address" + } + ], + "name": "updateFeeSettings", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newRewardsRecipient", + "type": "address" + } + ], + "name": "updateRewardsRecipient", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "vaultShareHWM", + "outputs": [ + { + "internalType": "uint256", + "name": "", + "type": "uint256" + } + ], + "stateMutability": "view", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "uint256", + "name": "assets", + "type": "uint256" + }, + { + "internalType": "address", + "name": "receiver", + "type": "address" + }, + { + "internalType": "address", + "name": "owner", + "type": "address" + } + ], + "name": "withdraw", + "outputs": [ + { + "internalType": "uint256", + "name": "shares", + "type": "uint256" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "withdrawAccruedFees", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + } + ], + "transactionHash": "0x93e9eed83cb07d84dbf0eaa0ea4b3a5119bf16bf1093452b2488fb261d0953e9", + "receipt": { + "to": null, + "from": "0x1155b614971f16758C92c4890eD338C9e3ede6b7", + "contractAddress": "0x0014cE7973246b7a99Ea95f0Bd38156C19551880", + "transactionIndex": 130, + "gasUsed": "3107222", + "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "blockHash": "0xf22cb92a09e912c8d6e1615890d409eeaf1325fcb25fae964361b34fc37fe726", + "transactionHash": "0x93e9eed83cb07d84dbf0eaa0ea4b3a5119bf16bf1093452b2488fb261d0953e9", + "logs": [], + "blockNumber": 25464421, + "cumulativeGasUsed": "31013326", + "status": 1, + "byzantium": true + }, + "args": [], + "numDeployments": 1, + "solcInputHash": "34a0d1556aea7d4f3124b66dedee8846", + "metadata": "{\"compiler\":{\"version\":\"0.8.22+commit.4fc1097e\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"enum ComptrollerErrorReporter.Error\",\"name\":\"\",\"type\":\"uint8\"}],\"name\":\"IonicMarketERC4626__CompoundError\",\"type\":\"error\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"Deposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint8\",\"name\":\"version\",\"type\":\"uint8\"}],\"name\":\"Initialized\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldOwner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"NewOwner\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldPendingOwner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newPendingOwner\",\"type\":\"address\"}],\"name\":\"NewPendingOwner\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Paused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"Unpaused\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"oldPerformanceFee\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"newPerformanceFee\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldFeeRecipient\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newFeeRecipient\",\"type\":\"address\"}],\"name\":\"UpdatedFeeSettings\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"oldRewardsRecipient\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newRewardsRecipient\",\"type\":\"address\"}],\"name\":\"UpdatedRewardsRecipient\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"Withdraw\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"_acceptOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newPendingOwner\",\"type\":\"address\"}],\"name\":\"_setPendingOwner\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"asset\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"cToken\",\"outputs\":[{\"internalType\":\"contract ICErc20\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"claimRewards\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"convertToAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"convertToShares\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"subtractedValue\",\"type\":\"uint256\"}],\"name\":\"decreaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"deposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"emergencyWithdrawAndPause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"feeRecipient\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"flywheelLensRouter\",\"outputs\":[{\"internalType\":\"contract IonicFlywheelLensRouter_4626\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"spender\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"addedValue\",\"type\":\"uint256\"}],\"name\":\"increaseAllowance\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contract ICErc20\",\"name\":\"cToken_\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"flywheelLensRouter_\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"rewardsRecipient_\",\"type\":\"address\"}],\"name\":\"initialize\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"maxDeposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"maxMint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"maxRedeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"maxWithdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"mint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"pendingOwner\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"performanceFee\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"previewDeposit\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"previewMint\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"name\":\"previewRedeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"name\":\"previewWithdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"redeem\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"rewardsRecipient\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"market\",\"type\":\"address\"}],\"name\":\"shutdown\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"takePerformanceFee\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalAssets\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"newPerformanceFee\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"newFeeRecipient\",\"type\":\"address\"}],\"name\":\"updateFeeSettings\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newRewardsRecipient\",\"type\":\"address\"}],\"name\":\"updateRewardsRecipient\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"vaultShareHWM\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"assets\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"withdraw\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"shares\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"withdrawAccruedFees\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"events\":{\"Approval(address,address,uint256)\":{\"details\":\"Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance.\"},\"Initialized(uint8)\":{\"details\":\"Triggered when the contract has been initialized or reinitialized.\"},\"Paused(address)\":{\"details\":\"Emitted when the pause is triggered by `account`.\"},\"Transfer(address,address,uint256)\":{\"details\":\"Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero.\"},\"Unpaused(address)\":{\"details\":\"Emitted when the pause is lifted by `account`.\"}},\"kind\":\"dev\",\"methods\":{\"_acceptOwner()\":{\"details\":\"Owner function for pending owner to accept role and update owner\"},\"_setPendingOwner(address)\":{\"details\":\"Owner function to begin change of owner. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\",\"params\":{\"newPendingOwner\":\"New pending owner.\"}},\"allowance(address,address)\":{\"details\":\"See {IERC20-allowance}.\"},\"approve(address,uint256)\":{\"details\":\"See {IERC20-approve}. NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address.\"},\"asset()\":{\"details\":\"See {IERC4626-asset}. \"},\"balanceOf(address)\":{\"details\":\"See {IERC20-balanceOf}.\"},\"convertToAssets(uint256)\":{\"details\":\"See {IERC4626-convertToAssets}. \"},\"convertToShares(uint256)\":{\"details\":\"See {IERC4626-convertToShares}. \"},\"decimals()\":{\"details\":\"Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value. See {IERC20Metadata-decimals}.\"},\"decreaseAllowance(address,uint256)\":{\"details\":\"Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`.\"},\"deposit(uint256,address)\":{\"details\":\"See {IERC4626-deposit}. \"},\"increaseAllowance(address,uint256)\":{\"details\":\"Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address.\"},\"maxMint(address)\":{\"details\":\"accrue interest must be called before this function is called, otherwise an outdated value will be fetched, and the returned value will be incorrect (greater than actual amount available to be minted will be returned)\"},\"maxRedeem(address)\":{\"params\":{\"owner\":\"The address that owns the shares\"}},\"maxWithdraw(address)\":{\"params\":{\"owner\":\"The address that owns the shares\"}},\"mint(uint256,address)\":{\"details\":\"See {IERC4626-mint}. \"},\"name()\":{\"details\":\"Returns the name of the token.\"},\"owner()\":{\"details\":\"Returns the address of the current owner.\"},\"paused()\":{\"details\":\"Returns true if the contract is paused, and false otherwise.\"},\"previewDeposit(uint256)\":{\"details\":\"See {IERC4626-previewDeposit}. \"},\"previewMint(uint256)\":{\"details\":\"See {IERC4626-previewMint}. \"},\"previewRedeem(uint256)\":{\"details\":\"See {IERC4626-previewRedeem}. \"},\"previewWithdraw(uint256)\":{\"details\":\"See {IERC4626-previewWithdraw}. \"},\"redeem(uint256,address,address)\":{\"details\":\"See {IERC4626-redeem}. \"},\"renounceOwnership()\":{\"details\":\"Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner.\"},\"symbol()\":{\"details\":\"Returns the symbol of the token, usually a shorter version of the name.\"},\"takePerformanceFee()\":{\"details\":\"Performance fee is based on a vault share high water mark value. If vault share value has increased above the HWM in a fee period, issue fee shares to the vault equal to the performance fee.\"},\"totalAssets()\":{\"details\":\"See {IERC4626-totalAssets}. \"},\"totalSupply()\":{\"details\":\"See {IERC20-totalSupply}.\"},\"transfer(address,uint256)\":{\"details\":\"See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `amount`.\"},\"transferFrom(address,address,uint256)\":{\"details\":\"See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `amount`. - the caller must have allowance for ``from``'s tokens of at least `amount`.\"},\"transferOwnership(address)\":{\"details\":\"Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.\"},\"withdraw(uint256,address,address)\":{\"details\":\"See {IERC4626-withdraw}. \"},\"withdrawAccruedFees()\":{\"details\":\"We must make sure that feeRecipient is not address(0) before withdrawing fees\"}},\"version\":1},\"userdoc\":{\"events\":{\"NewOwner(address,address)\":{\"notice\":\"Emitted when pendingOwner is accepted, which means owner is updated\"},\"NewPendingOwner(address,address)\":{\"notice\":\"Emitted when pendingOwner is changed\"}},\"kind\":\"user\",\"methods\":{\"_acceptOwner()\":{\"notice\":\"Accepts transfer of owner rights. msg.sender must be pendingOwner\"},\"_setPendingOwner(address)\":{\"notice\":\"Begins transfer of owner rights. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\"},\"maxDeposit(address)\":{\"notice\":\"maximum amount of underlying tokens that can be deposited into the underlying protocol\"},\"maxMint(address)\":{\"notice\":\"Returns the maximum amount of tokens that can be supplied no way for this function to ever revert unless comptroller or mToken is broken\"},\"maxRedeem(address)\":{\"notice\":\"maximum amount of shares that can be withdrawn\"},\"maxWithdraw(address)\":{\"notice\":\"maximum amount of underlying tokens that can be withdrawn\"},\"pendingOwner()\":{\"notice\":\"Pending owner of this contract\"},\"takePerformanceFee()\":{\"notice\":\"Take the performance fee that has accrued since last fee harvest.\"},\"updateFeeSettings(uint256,address)\":{\"notice\":\"Update performanceFee and/or feeRecipient\"},\"withdrawAccruedFees()\":{\"notice\":\"Transfer accrued fees to rewards manager contract. Caller must be a registered keeper.\"}},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/src/ionic/strategies/IonicMarketERC4626.sol\":\"IonicMarketERC4626\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"@openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../utils/ContextUpgradeable.sol\\\";\\nimport \\\"../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Contract module which provides a basic access control mechanism, where\\n * there is an account (an owner) that can be granted exclusive access to\\n * specific functions.\\n *\\n * By default, the owner account will be the one that deploys the contract. This\\n * can later be changed with {transferOwnership}.\\n *\\n * This module is used through inheritance. It will make available the modifier\\n * `onlyOwner`, which can be applied to your functions to restrict their use to\\n * the owner.\\n */\\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\\n address private _owner;\\n\\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\\n\\n /**\\n * @dev Initializes the contract setting the deployer as the initial owner.\\n */\\n function __Ownable_init() internal onlyInitializing {\\n __Ownable_init_unchained();\\n }\\n\\n function __Ownable_init_unchained() internal onlyInitializing {\\n _transferOwnership(_msgSender());\\n }\\n\\n /**\\n * @dev Throws if called by any account other than the owner.\\n */\\n modifier onlyOwner() {\\n _checkOwner();\\n _;\\n }\\n\\n /**\\n * @dev Returns the address of the current owner.\\n */\\n function owner() public view virtual returns (address) {\\n return _owner;\\n }\\n\\n /**\\n * @dev Throws if the sender is not the owner.\\n */\\n function _checkOwner() internal view virtual {\\n require(owner() == _msgSender(), \\\"Ownable: caller is not the owner\\\");\\n }\\n\\n /**\\n * @dev Leaves the contract without owner. It will not be possible to call\\n * `onlyOwner` functions anymore. Can only be called by the current owner.\\n *\\n * NOTE: Renouncing ownership will leave the contract without an owner,\\n * thereby removing any functionality that is only available to the owner.\\n */\\n function renounceOwnership() public virtual onlyOwner {\\n _transferOwnership(address(0));\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Can only be called by the current owner.\\n */\\n function transferOwnership(address newOwner) public virtual onlyOwner {\\n require(newOwner != address(0), \\\"Ownable: new owner is the zero address\\\");\\n _transferOwnership(newOwner);\\n }\\n\\n /**\\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n * Internal function without access restriction.\\n */\\n function _transferOwnership(address newOwner) internal virtual {\\n address oldOwner = _owner;\\n _owner = newOwner;\\n emit OwnershipTransferred(oldOwner, newOwner);\\n }\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[49] private __gap;\\n}\\n\",\"keccak256\":\"0x247c62047745915c0af6b955470a72d1696ebad4352d7d3011aef1a2463cd888\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/interfaces/IERC4626Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC4626.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../token/ERC20/IERC20Upgradeable.sol\\\";\\nimport \\\"../token/ERC20/extensions/IERC20MetadataUpgradeable.sol\\\";\\n\\n/**\\n * @dev Interface of the ERC4626 \\\"Tokenized Vault Standard\\\", as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\\n *\\n * _Available since v4.7._\\n */\\ninterface IERC4626Upgradeable is IERC20Upgradeable, IERC20MetadataUpgradeable {\\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\\n\\n event Withdraw(\\n address indexed sender,\\n address indexed receiver,\\n address indexed owner,\\n uint256 assets,\\n uint256 shares\\n );\\n\\n /**\\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\\n *\\n * - MUST be an ERC-20 token contract.\\n * - MUST NOT revert.\\n */\\n function asset() external view returns (address assetTokenAddress);\\n\\n /**\\n * @dev Returns the total amount of the underlying asset that is \\u201cmanaged\\u201d by Vault.\\n *\\n * - SHOULD include any compounding that occurs from yield.\\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT revert.\\n */\\n function totalAssets() external view returns (uint256 totalManagedAssets);\\n\\n /**\\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToShares(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\\n * scenario where all the conditions are met.\\n *\\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\\n * - MUST NOT show any variations depending on the caller.\\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\\n * - MUST NOT revert.\\n *\\n * NOTE: This calculation MAY NOT reflect the \\u201cper-user\\u201d price-per-share, and instead should reflect the\\n * \\u201caverage-user\\u2019s\\u201d price-per-share, meaning what the average user should expect to see when exchanging to and\\n * from.\\n */\\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\\n * through a deposit call.\\n *\\n * - MUST return a limited value if receiver is subject to some deposit limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\\n * - MUST NOT revert.\\n */\\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\\n * in the same transaction.\\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * deposit execution, and are accounted for during deposit.\\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\\n * - MUST return a limited value if receiver is subject to some mint limit.\\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\\n * - MUST NOT revert.\\n */\\n function maxMint(address receiver) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\\n * current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\\n * same transaction.\\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\\n * would be accepted, regardless if the user has enough tokens approved, etc.\\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\\n */\\n function previewMint(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\\n *\\n * - MUST emit the Deposit event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\\n * execution, and are accounted for during mint.\\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\\n * approving enough underlying tokens to the Vault contract, etc).\\n *\\n * NOTE: most implementations will require pre-approval of the Vault with the Vault\\u2019s underlying asset token.\\n */\\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\\n\\n /**\\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\\n * Vault, through a withdraw call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\\n * called\\n * in the same transaction.\\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\\n */\\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\\n\\n /**\\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * withdraw execution, and are accounted for during withdraw.\\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function withdraw(\\n uint256 assets,\\n address receiver,\\n address owner\\n ) external returns (uint256 shares);\\n\\n /**\\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\\n * through a redeem call.\\n *\\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\\n * - MUST NOT revert.\\n */\\n function maxRedeem(address owner) external view returns (uint256 maxShares);\\n\\n /**\\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\\n * given current on-chain conditions.\\n *\\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\\n * same transaction.\\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\\n * redemption would be accepted, regardless if the user has enough shares, etc.\\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\\n * - MUST NOT revert.\\n *\\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\\n */\\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\\n\\n /**\\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\\n *\\n * - MUST emit the Withdraw event.\\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\\n * redeem execution, and are accounted for during redeem.\\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\\n * not having enough shares, etc).\\n *\\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\\n * Those methods should be performed separately.\\n */\\n function redeem(\\n uint256 shares,\\n address receiver,\\n address owner\\n ) external returns (uint256 assets);\\n}\\n\",\"keccak256\":\"0xe3d54e1a1a10fbc86fdfaf9100ba99c9c808588fd20d0c919457b903b5cae61a\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\\n\\npragma solidity ^0.8.2;\\n\\nimport \\\"../../utils/AddressUpgradeable.sol\\\";\\n\\n/**\\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\\n *\\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\\n * reused. This mechanism prevents re-execution of each \\\"step\\\" but allows the creation of new initialization steps in\\n * case an upgrade adds a module that needs to be initialized.\\n *\\n * For example:\\n *\\n * [.hljs-theme-light.nopadding]\\n * ```\\n * contract MyToken is ERC20Upgradeable {\\n * function initialize() initializer public {\\n * __ERC20_init(\\\"MyToken\\\", \\\"MTK\\\");\\n * }\\n * }\\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\\n * function initializeV2() reinitializer(2) public {\\n * __ERC20Permit_init(\\\"MyToken\\\");\\n * }\\n * }\\n * ```\\n *\\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\\n *\\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\\n *\\n * [CAUTION]\\n * ====\\n * Avoid leaving a contract uninitialized.\\n *\\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\\n *\\n * [.hljs-theme-light.nopadding]\\n * ```\\n * /// @custom:oz-upgrades-unsafe-allow constructor\\n * constructor() {\\n * _disableInitializers();\\n * }\\n * ```\\n * ====\\n */\\nabstract contract Initializable {\\n /**\\n * @dev Indicates that the contract has been initialized.\\n * @custom:oz-retyped-from bool\\n */\\n uint8 private _initialized;\\n\\n /**\\n * @dev Indicates that the contract is in the process of being initialized.\\n */\\n bool private _initializing;\\n\\n /**\\n * @dev Triggered when the contract has been initialized or reinitialized.\\n */\\n event Initialized(uint8 version);\\n\\n /**\\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\\n * `onlyInitializing` functions can be used to initialize parent contracts.\\n *\\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\\n * constructor.\\n *\\n * Emits an {Initialized} event.\\n */\\n modifier initializer() {\\n bool isTopLevelCall = !_initializing;\\n require(\\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\\n \\\"Initializable: contract is already initialized\\\"\\n );\\n _initialized = 1;\\n if (isTopLevelCall) {\\n _initializing = true;\\n }\\n _;\\n if (isTopLevelCall) {\\n _initializing = false;\\n emit Initialized(1);\\n }\\n }\\n\\n /**\\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\\n * used to initialize parent contracts.\\n *\\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\\n * are added through upgrades and that require initialization.\\n *\\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\\n * cannot be nested. If one is invoked in the context of another, execution will revert.\\n *\\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\\n * a contract, executing them in the right order is up to the developer or operator.\\n *\\n * WARNING: setting the version to 255 will prevent any future reinitialization.\\n *\\n * Emits an {Initialized} event.\\n */\\n modifier reinitializer(uint8 version) {\\n require(!_initializing && _initialized < version, \\\"Initializable: contract is already initialized\\\");\\n _initialized = version;\\n _initializing = true;\\n _;\\n _initializing = false;\\n emit Initialized(version);\\n }\\n\\n /**\\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\\n */\\n modifier onlyInitializing() {\\n require(_initializing, \\\"Initializable: contract is not initializing\\\");\\n _;\\n }\\n\\n /**\\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\\n * through proxies.\\n *\\n * Emits an {Initialized} event the first time it is successfully executed.\\n */\\n function _disableInitializers() internal virtual {\\n require(!_initializing, \\\"Initializable: contract is initializing\\\");\\n if (_initialized < type(uint8).max) {\\n _initialized = type(uint8).max;\\n emit Initialized(type(uint8).max);\\n }\\n }\\n\\n /**\\n * @dev Internal function that returns the initialized version. Returns `_initialized`\\n */\\n function _getInitializedVersion() internal view returns (uint8) {\\n return _initialized;\\n }\\n\\n /**\\n * @dev Internal function that returns the initialized version. Returns `_initializing`\\n */\\n function _isInitializing() internal view returns (bool) {\\n return _initializing;\\n }\\n}\\n\",\"keccak256\":\"0x6c2b54ec184943843041ab77f61988b5060f6f03acbfe92cdc125f95f00891da\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/security/PausableUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../utils/ContextUpgradeable.sol\\\";\\nimport \\\"../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Contract module which allows children to implement an emergency stop\\n * mechanism that can be triggered by an authorized account.\\n *\\n * This module is used through inheritance. It will make available the\\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\\n * the functions of your contract. Note that they will not be pausable by\\n * simply including this module, only once the modifiers are put in place.\\n */\\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\\n /**\\n * @dev Emitted when the pause is triggered by `account`.\\n */\\n event Paused(address account);\\n\\n /**\\n * @dev Emitted when the pause is lifted by `account`.\\n */\\n event Unpaused(address account);\\n\\n bool private _paused;\\n\\n /**\\n * @dev Initializes the contract in unpaused state.\\n */\\n function __Pausable_init() internal onlyInitializing {\\n __Pausable_init_unchained();\\n }\\n\\n function __Pausable_init_unchained() internal onlyInitializing {\\n _paused = false;\\n }\\n\\n /**\\n * @dev Modifier to make a function callable only when the contract is not paused.\\n *\\n * Requirements:\\n *\\n * - The contract must not be paused.\\n */\\n modifier whenNotPaused() {\\n _requireNotPaused();\\n _;\\n }\\n\\n /**\\n * @dev Modifier to make a function callable only when the contract is paused.\\n *\\n * Requirements:\\n *\\n * - The contract must be paused.\\n */\\n modifier whenPaused() {\\n _requirePaused();\\n _;\\n }\\n\\n /**\\n * @dev Returns true if the contract is paused, and false otherwise.\\n */\\n function paused() public view virtual returns (bool) {\\n return _paused;\\n }\\n\\n /**\\n * @dev Throws if the contract is paused.\\n */\\n function _requireNotPaused() internal view virtual {\\n require(!paused(), \\\"Pausable: paused\\\");\\n }\\n\\n /**\\n * @dev Throws if the contract is not paused.\\n */\\n function _requirePaused() internal view virtual {\\n require(paused(), \\\"Pausable: not paused\\\");\\n }\\n\\n /**\\n * @dev Triggers stopped state.\\n *\\n * Requirements:\\n *\\n * - The contract must not be paused.\\n */\\n function _pause() internal virtual whenNotPaused {\\n _paused = true;\\n emit Paused(_msgSender());\\n }\\n\\n /**\\n * @dev Returns to normal state.\\n *\\n * Requirements:\\n *\\n * - The contract must be paused.\\n */\\n function _unpause() internal virtual whenPaused {\\n _paused = false;\\n emit Unpaused(_msgSender());\\n }\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[49] private __gap;\\n}\\n\",\"keccak256\":\"0x40c636b4572ff5f1dc50cf22097e93c0723ee14eff87e99ac2b02636eeca1250\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"./IERC20Upgradeable.sol\\\";\\nimport \\\"./extensions/IERC20MetadataUpgradeable.sol\\\";\\nimport \\\"../../utils/ContextUpgradeable.sol\\\";\\nimport \\\"../../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Implementation of the {IERC20} interface.\\n *\\n * This implementation is agnostic to the way tokens are created. This means\\n * that a supply mechanism has to be added in a derived contract using {_mint}.\\n * For a generic mechanism see {ERC20PresetMinterPauser}.\\n *\\n * TIP: For a detailed writeup see our guide\\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\\n * to implement supply mechanisms].\\n *\\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\\n * instead returning `false` on failure. This behavior is nonetheless\\n * conventional and does not conflict with the expectations of ERC20\\n * applications.\\n *\\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\\n * This allows applications to reconstruct the allowance for all accounts just\\n * by listening to said events. Other implementations of the EIP may not emit\\n * these events, as it isn't required by the specification.\\n *\\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\\n * functions have been added to mitigate the well-known issues around setting\\n * allowances. See {IERC20-approve}.\\n */\\ncontract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\\n mapping(address => uint256) private _balances;\\n\\n mapping(address => mapping(address => uint256)) private _allowances;\\n\\n uint256 private _totalSupply;\\n\\n string private _name;\\n string private _symbol;\\n\\n /**\\n * @dev Sets the values for {name} and {symbol}.\\n *\\n * The default value of {decimals} is 18. To select a different value for\\n * {decimals} you should overload it.\\n *\\n * All two of these values are immutable: they can only be set once during\\n * construction.\\n */\\n function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\\n __ERC20_init_unchained(name_, symbol_);\\n }\\n\\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\\n _name = name_;\\n _symbol = symbol_;\\n }\\n\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() public view virtual override returns (string memory) {\\n return _name;\\n }\\n\\n /**\\n * @dev Returns the symbol of the token, usually a shorter version of the\\n * name.\\n */\\n function symbol() public view virtual override returns (string memory) {\\n return _symbol;\\n }\\n\\n /**\\n * @dev Returns the number of decimals used to get its user representation.\\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\\n *\\n * Tokens usually opt for a value of 18, imitating the relationship between\\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\\n * overridden;\\n *\\n * NOTE: This information is only used for _display_ purposes: it in\\n * no way affects any of the arithmetic of the contract, including\\n * {IERC20-balanceOf} and {IERC20-transfer}.\\n */\\n function decimals() public view virtual override returns (uint8) {\\n return 18;\\n }\\n\\n /**\\n * @dev See {IERC20-totalSupply}.\\n */\\n function totalSupply() public view virtual override returns (uint256) {\\n return _totalSupply;\\n }\\n\\n /**\\n * @dev See {IERC20-balanceOf}.\\n */\\n function balanceOf(address account) public view virtual override returns (uint256) {\\n return _balances[account];\\n }\\n\\n /**\\n * @dev See {IERC20-transfer}.\\n *\\n * Requirements:\\n *\\n * - `to` cannot be the zero address.\\n * - the caller must have a balance of at least `amount`.\\n */\\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\\n address owner = _msgSender();\\n _transfer(owner, to, amount);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-allowance}.\\n */\\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\\n return _allowances[owner][spender];\\n }\\n\\n /**\\n * @dev See {IERC20-approve}.\\n *\\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\\n * `transferFrom`. This is semantically equivalent to an infinite approval.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n */\\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\\n address owner = _msgSender();\\n _approve(owner, spender, amount);\\n return true;\\n }\\n\\n /**\\n * @dev See {IERC20-transferFrom}.\\n *\\n * Emits an {Approval} event indicating the updated allowance. This is not\\n * required by the EIP. See the note at the beginning of {ERC20}.\\n *\\n * NOTE: Does not update the allowance if the current allowance\\n * is the maximum `uint256`.\\n *\\n * Requirements:\\n *\\n * - `from` and `to` cannot be the zero address.\\n * - `from` must have a balance of at least `amount`.\\n * - the caller must have allowance for ``from``'s tokens of at least\\n * `amount`.\\n */\\n function transferFrom(\\n address from,\\n address to,\\n uint256 amount\\n ) public virtual override returns (bool) {\\n address spender = _msgSender();\\n _spendAllowance(from, spender, amount);\\n _transfer(from, to, amount);\\n return true;\\n }\\n\\n /**\\n * @dev Atomically increases the allowance granted to `spender` by the caller.\\n *\\n * This is an alternative to {approve} that can be used as a mitigation for\\n * problems described in {IERC20-approve}.\\n *\\n * Emits an {Approval} event indicating the updated allowance.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n */\\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\\n address owner = _msgSender();\\n _approve(owner, spender, allowance(owner, spender) + addedValue);\\n return true;\\n }\\n\\n /**\\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\\n *\\n * This is an alternative to {approve} that can be used as a mitigation for\\n * problems described in {IERC20-approve}.\\n *\\n * Emits an {Approval} event indicating the updated allowance.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n * - `spender` must have allowance for the caller of at least\\n * `subtractedValue`.\\n */\\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\\n address owner = _msgSender();\\n uint256 currentAllowance = allowance(owner, spender);\\n require(currentAllowance >= subtractedValue, \\\"ERC20: decreased allowance below zero\\\");\\n unchecked {\\n _approve(owner, spender, currentAllowance - subtractedValue);\\n }\\n\\n return true;\\n }\\n\\n /**\\n * @dev Moves `amount` of tokens from `from` to `to`.\\n *\\n * This internal function is equivalent to {transfer}, and can be used to\\n * e.g. implement automatic token fees, slashing mechanisms, etc.\\n *\\n * Emits a {Transfer} event.\\n *\\n * Requirements:\\n *\\n * - `from` cannot be the zero address.\\n * - `to` cannot be the zero address.\\n * - `from` must have a balance of at least `amount`.\\n */\\n function _transfer(\\n address from,\\n address to,\\n uint256 amount\\n ) internal virtual {\\n require(from != address(0), \\\"ERC20: transfer from the zero address\\\");\\n require(to != address(0), \\\"ERC20: transfer to the zero address\\\");\\n\\n _beforeTokenTransfer(from, to, amount);\\n\\n uint256 fromBalance = _balances[from];\\n require(fromBalance >= amount, \\\"ERC20: transfer amount exceeds balance\\\");\\n unchecked {\\n _balances[from] = fromBalance - amount;\\n // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\\n // decrementing then incrementing.\\n _balances[to] += amount;\\n }\\n\\n emit Transfer(from, to, amount);\\n\\n _afterTokenTransfer(from, to, amount);\\n }\\n\\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\\n * the total supply.\\n *\\n * Emits a {Transfer} event with `from` set to the zero address.\\n *\\n * Requirements:\\n *\\n * - `account` cannot be the zero address.\\n */\\n function _mint(address account, uint256 amount) internal virtual {\\n require(account != address(0), \\\"ERC20: mint to the zero address\\\");\\n\\n _beforeTokenTransfer(address(0), account, amount);\\n\\n _totalSupply += amount;\\n unchecked {\\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\\n _balances[account] += amount;\\n }\\n emit Transfer(address(0), account, amount);\\n\\n _afterTokenTransfer(address(0), account, amount);\\n }\\n\\n /**\\n * @dev Destroys `amount` tokens from `account`, reducing the\\n * total supply.\\n *\\n * Emits a {Transfer} event with `to` set to the zero address.\\n *\\n * Requirements:\\n *\\n * - `account` cannot be the zero address.\\n * - `account` must have at least `amount` tokens.\\n */\\n function _burn(address account, uint256 amount) internal virtual {\\n require(account != address(0), \\\"ERC20: burn from the zero address\\\");\\n\\n _beforeTokenTransfer(account, address(0), amount);\\n\\n uint256 accountBalance = _balances[account];\\n require(accountBalance >= amount, \\\"ERC20: burn amount exceeds balance\\\");\\n unchecked {\\n _balances[account] = accountBalance - amount;\\n // Overflow not possible: amount <= accountBalance <= totalSupply.\\n _totalSupply -= amount;\\n }\\n\\n emit Transfer(account, address(0), amount);\\n\\n _afterTokenTransfer(account, address(0), amount);\\n }\\n\\n /**\\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\\n *\\n * This internal function is equivalent to `approve`, and can be used to\\n * e.g. set automatic allowances for certain subsystems, etc.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `owner` cannot be the zero address.\\n * - `spender` cannot be the zero address.\\n */\\n function _approve(\\n address owner,\\n address spender,\\n uint256 amount\\n ) internal virtual {\\n require(owner != address(0), \\\"ERC20: approve from the zero address\\\");\\n require(spender != address(0), \\\"ERC20: approve to the zero address\\\");\\n\\n _allowances[owner][spender] = amount;\\n emit Approval(owner, spender, amount);\\n }\\n\\n /**\\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\\n *\\n * Does not update the allowance amount in case of infinite allowance.\\n * Revert if not enough allowance is available.\\n *\\n * Might emit an {Approval} event.\\n */\\n function _spendAllowance(\\n address owner,\\n address spender,\\n uint256 amount\\n ) internal virtual {\\n uint256 currentAllowance = allowance(owner, spender);\\n if (currentAllowance != type(uint256).max) {\\n require(currentAllowance >= amount, \\\"ERC20: insufficient allowance\\\");\\n unchecked {\\n _approve(owner, spender, currentAllowance - amount);\\n }\\n }\\n }\\n\\n /**\\n * @dev Hook that is called before any transfer of tokens. This includes\\n * minting and burning.\\n *\\n * Calling conditions:\\n *\\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\\n * will be transferred to `to`.\\n * - when `from` is zero, `amount` tokens will be minted for `to`.\\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\\n * - `from` and `to` are never both zero.\\n *\\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\\n */\\n function _beforeTokenTransfer(\\n address from,\\n address to,\\n uint256 amount\\n ) internal virtual {}\\n\\n /**\\n * @dev Hook that is called after any transfer of tokens. This includes\\n * minting and burning.\\n *\\n * Calling conditions:\\n *\\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\\n * has been transferred to `to`.\\n * - when `from` is zero, `amount` tokens have been minted for `to`.\\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\\n * - `from` and `to` are never both zero.\\n *\\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\\n */\\n function _afterTokenTransfer(\\n address from,\\n address to,\\n uint256 amount\\n ) internal virtual {}\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[45] private __gap;\\n}\\n\",\"keccak256\":\"0x17aff86be546601617585e91fd98aad74cf39f1be65d8eb6f93b7f3c30181275\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Interface of the ERC20 standard as defined in the EIP.\\n */\\ninterface IERC20Upgradeable {\\n /**\\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\\n * another (`to`).\\n *\\n * Note that `value` may be zero.\\n */\\n event Transfer(address indexed from, address indexed to, uint256 value);\\n\\n /**\\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\\n * a call to {approve}. `value` is the new allowance.\\n */\\n event Approval(address indexed owner, address indexed spender, uint256 value);\\n\\n /**\\n * @dev Returns the amount of tokens in existence.\\n */\\n function totalSupply() external view returns (uint256);\\n\\n /**\\n * @dev Returns the amount of tokens owned by `account`.\\n */\\n function balanceOf(address account) external view returns (uint256);\\n\\n /**\\n * @dev Moves `amount` tokens from the caller's account to `to`.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transfer(address to, uint256 amount) external returns (bool);\\n\\n /**\\n * @dev Returns the remaining number of tokens that `spender` will be\\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\\n * zero by default.\\n *\\n * This value changes when {approve} or {transferFrom} are called.\\n */\\n function allowance(address owner, address spender) external view returns (uint256);\\n\\n /**\\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\\n * that someone may use both the old and the new allowance by unfortunate\\n * transaction ordering. One possible solution to mitigate this race\\n * condition is to first reduce the spender's allowance to 0 and set the\\n * desired value afterwards:\\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\\n *\\n * Emits an {Approval} event.\\n */\\n function approve(address spender, uint256 amount) external returns (bool);\\n\\n /**\\n * @dev Moves `amount` tokens from `from` to `to` using the\\n * allowance mechanism. `amount` is then deducted from the caller's\\n * allowance.\\n *\\n * Returns a boolean value indicating whether the operation succeeded.\\n *\\n * Emits a {Transfer} event.\\n */\\n function transferFrom(\\n address from,\\n address to,\\n uint256 amount\\n ) external returns (bool);\\n}\\n\",\"keccak256\":\"0x4e733d3164f73f461eaf9d8087a7ad1ea180bdc8ba0d3d61b0e1ae16d8e63dff\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/extensions/ERC4626.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../ERC20Upgradeable.sol\\\";\\nimport \\\"../utils/SafeERC20Upgradeable.sol\\\";\\nimport \\\"../../../interfaces/IERC4626Upgradeable.sol\\\";\\nimport \\\"../../../utils/math/MathUpgradeable.sol\\\";\\nimport \\\"../../../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Implementation of the ERC4626 \\\"Tokenized Vault Standard\\\" as defined in\\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\\n *\\n * This extension allows the minting and burning of \\\"shares\\\" (represented using the ERC20 inheritance) in exchange for\\n * underlying \\\"assets\\\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\\n * the ERC20 standard. Any additional extensions included along it would affect the \\\"shares\\\" token represented by this\\n * contract and not the \\\"assets\\\" token which is an independent contract.\\n *\\n * CAUTION: Deposits and withdrawals may incur unexpected slippage. Users should verify that the amount received of\\n * shares or assets is as expected. EOAs should operate through a wrapper that performs these checks such as\\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\\n *\\n * _Available since v4.7._\\n */\\nabstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626Upgradeable {\\n using MathUpgradeable for uint256;\\n\\n IERC20Upgradeable private _asset;\\n uint8 private _decimals;\\n\\n /**\\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\\n */\\n function __ERC4626_init(IERC20Upgradeable asset_) internal onlyInitializing {\\n __ERC4626_init_unchained(asset_);\\n }\\n\\n function __ERC4626_init_unchained(IERC20Upgradeable asset_) internal onlyInitializing {\\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\\n _decimals = success ? assetDecimals : super.decimals();\\n _asset = asset_;\\n }\\n\\n /**\\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\\n */\\n function _tryGetAssetDecimals(IERC20Upgradeable asset_) private returns (bool, uint8) {\\n (bool success, bytes memory encodedDecimals) = address(asset_).call(\\n abi.encodeWithSelector(IERC20MetadataUpgradeable.decimals.selector)\\n );\\n if (success && encodedDecimals.length >= 32) {\\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\\n if (returnedDecimals <= type(uint8).max) {\\n return (true, uint8(returnedDecimals));\\n }\\n }\\n return (false, 0);\\n }\\n\\n /**\\n * @dev Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset\\n * has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on\\n * inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value.\\n * See {IERC20Metadata-decimals}.\\n */\\n function decimals() public view virtual override(IERC20MetadataUpgradeable, ERC20Upgradeable) returns (uint8) {\\n return _decimals;\\n }\\n\\n /** @dev See {IERC4626-asset}. */\\n function asset() public view virtual override returns (address) {\\n return address(_asset);\\n }\\n\\n /** @dev See {IERC4626-totalAssets}. */\\n function totalAssets() public view virtual override returns (uint256) {\\n return _asset.balanceOf(address(this));\\n }\\n\\n /** @dev See {IERC4626-convertToShares}. */\\n function convertToShares(uint256 assets) public view virtual override returns (uint256 shares) {\\n return _convertToShares(assets, MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-convertToAssets}. */\\n function convertToAssets(uint256 shares) public view virtual override returns (uint256 assets) {\\n return _convertToAssets(shares, MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-maxDeposit}. */\\n function maxDeposit(address) public view virtual override returns (uint256) {\\n return _isVaultCollateralized() ? type(uint256).max : 0;\\n }\\n\\n /** @dev See {IERC4626-maxMint}. */\\n function maxMint(address) public view virtual override returns (uint256) {\\n return type(uint256).max;\\n }\\n\\n /** @dev See {IERC4626-maxWithdraw}. */\\n function maxWithdraw(address owner) public view virtual override returns (uint256) {\\n return _convertToAssets(balanceOf(owner), MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-maxRedeem}. */\\n function maxRedeem(address owner) public view virtual override returns (uint256) {\\n return balanceOf(owner);\\n }\\n\\n /** @dev See {IERC4626-previewDeposit}. */\\n function previewDeposit(uint256 assets) public view virtual override returns (uint256) {\\n return _convertToShares(assets, MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-previewMint}. */\\n function previewMint(uint256 shares) public view virtual override returns (uint256) {\\n return _convertToAssets(shares, MathUpgradeable.Rounding.Up);\\n }\\n\\n /** @dev See {IERC4626-previewWithdraw}. */\\n function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {\\n return _convertToShares(assets, MathUpgradeable.Rounding.Up);\\n }\\n\\n /** @dev See {IERC4626-previewRedeem}. */\\n function previewRedeem(uint256 shares) public view virtual override returns (uint256) {\\n return _convertToAssets(shares, MathUpgradeable.Rounding.Down);\\n }\\n\\n /** @dev See {IERC4626-deposit}. */\\n function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {\\n require(assets <= maxDeposit(receiver), \\\"ERC4626: deposit more than max\\\");\\n\\n uint256 shares = previewDeposit(assets);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-mint}. */\\n function mint(uint256 shares, address receiver) public virtual override returns (uint256) {\\n require(shares <= maxMint(receiver), \\\"ERC4626: mint more than max\\\");\\n\\n uint256 assets = previewMint(shares);\\n _deposit(_msgSender(), receiver, assets, shares);\\n\\n return assets;\\n }\\n\\n /** @dev See {IERC4626-withdraw}. */\\n function withdraw(\\n uint256 assets,\\n address receiver,\\n address owner\\n ) public virtual override returns (uint256) {\\n require(assets <= maxWithdraw(owner), \\\"ERC4626: withdraw more than max\\\");\\n\\n uint256 shares = previewWithdraw(assets);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return shares;\\n }\\n\\n /** @dev See {IERC4626-redeem}. */\\n function redeem(\\n uint256 shares,\\n address receiver,\\n address owner\\n ) public virtual override returns (uint256) {\\n require(shares <= maxRedeem(owner), \\\"ERC4626: redeem more than max\\\");\\n\\n uint256 assets = previewRedeem(shares);\\n _withdraw(_msgSender(), receiver, owner, assets, shares);\\n\\n return assets;\\n }\\n\\n /**\\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\\n *\\n * Will revert if assets > 0, totalSupply > 0 and totalAssets = 0. That corresponds to a case where any asset\\n * would represent an infinite amount of shares.\\n */\\n function _convertToShares(uint256 assets, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256 shares) {\\n uint256 supply = totalSupply();\\n return\\n (assets == 0 || supply == 0)\\n ? _initialConvertToShares(assets, rounding)\\n : assets.mulDiv(supply, totalAssets(), rounding);\\n }\\n\\n /**\\n * @dev Internal conversion function (from assets to shares) to apply when the vault is empty.\\n *\\n * NOTE: Make sure to keep this function consistent with {_initialConvertToAssets} when overriding it.\\n */\\n function _initialConvertToShares(\\n uint256 assets,\\n MathUpgradeable.Rounding /*rounding*/\\n ) internal view virtual returns (uint256 shares) {\\n return assets;\\n }\\n\\n /**\\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\\n */\\n function _convertToAssets(uint256 shares, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256 assets) {\\n uint256 supply = totalSupply();\\n return\\n (supply == 0) ? _initialConvertToAssets(shares, rounding) : shares.mulDiv(totalAssets(), supply, rounding);\\n }\\n\\n /**\\n * @dev Internal conversion function (from shares to assets) to apply when the vault is empty.\\n *\\n * NOTE: Make sure to keep this function consistent with {_initialConvertToShares} when overriding it.\\n */\\n function _initialConvertToAssets(\\n uint256 shares,\\n MathUpgradeable.Rounding /*rounding*/\\n ) internal view virtual returns (uint256 assets) {\\n return shares;\\n }\\n\\n /**\\n * @dev Deposit/mint common workflow.\\n */\\n function _deposit(\\n address caller,\\n address receiver,\\n uint256 assets,\\n uint256 shares\\n ) internal virtual {\\n // If _asset is ERC777, `transferFrom` can trigger a reenterancy BEFORE the transfer happens through the\\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\\n // assets are transferred and before the shares are minted, which is a valid state.\\n // slither-disable-next-line reentrancy-no-eth\\n SafeERC20Upgradeable.safeTransferFrom(_asset, caller, address(this), assets);\\n _mint(receiver, shares);\\n\\n emit Deposit(caller, receiver, assets, shares);\\n }\\n\\n /**\\n * @dev Withdraw/redeem common workflow.\\n */\\n function _withdraw(\\n address caller,\\n address receiver,\\n address owner,\\n uint256 assets,\\n uint256 shares\\n ) internal virtual {\\n if (caller != owner) {\\n _spendAllowance(owner, caller, shares);\\n }\\n\\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\\n // calls the vault, which is assumed not malicious.\\n //\\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\\n // shares are burned and after the assets are transferred, which is a valid state.\\n _burn(owner, shares);\\n SafeERC20Upgradeable.safeTransfer(_asset, receiver, assets);\\n\\n emit Withdraw(caller, receiver, owner, assets, shares);\\n }\\n\\n function _isVaultCollateralized() private view returns (bool) {\\n return totalAssets() > 0 || totalSupply() == 0;\\n }\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[49] private __gap;\\n}\\n\",\"keccak256\":\"0x82dd1556d6774b8bdaec0fb70d09c9d9cb0d75e9f2ffc183bb09a16b86d7c598\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../IERC20Upgradeable.sol\\\";\\n\\n/**\\n * @dev Interface for the optional metadata functions from the ERC20 standard.\\n *\\n * _Available since v4.1._\\n */\\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\\n /**\\n * @dev Returns the name of the token.\\n */\\n function name() external view returns (string memory);\\n\\n /**\\n * @dev Returns the symbol of the token.\\n */\\n function symbol() external view returns (string memory);\\n\\n /**\\n * @dev Returns the decimals places of the token.\\n */\\n function decimals() external view returns (uint8);\\n}\\n\",\"keccak256\":\"0x605434219ebbe4653f703640f06969faa5a1d78f0bfef878e5ddbb1ca369ceeb\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\\n *\\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\\n * need to send a transaction, and thus is not required to hold Ether at all.\\n */\\ninterface IERC20PermitUpgradeable {\\n /**\\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\\n * given ``owner``'s signed approval.\\n *\\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\\n * ordering also apply here.\\n *\\n * Emits an {Approval} event.\\n *\\n * Requirements:\\n *\\n * - `spender` cannot be the zero address.\\n * - `deadline` must be a timestamp in the future.\\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\\n * over the EIP712-formatted function arguments.\\n * - the signature must use ``owner``'s current nonce (see {nonces}).\\n *\\n * For more information on the signature format, see the\\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\\n * section].\\n */\\n function permit(\\n address owner,\\n address spender,\\n uint256 value,\\n uint256 deadline,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) external;\\n\\n /**\\n * @dev Returns the current nonce for `owner`. This value must be\\n * included whenever a signature is generated for {permit}.\\n *\\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\\n * prevents a signature from being used multiple times.\\n */\\n function nonces(address owner) external view returns (uint256);\\n\\n /**\\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\\n */\\n // solhint-disable-next-line func-name-mixedcase\\n function DOMAIN_SEPARATOR() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0xcc70d8e2281fb3ff69e8ab242500f10142cd0a7fa8dd9e45882be270d4d09024\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../IERC20Upgradeable.sol\\\";\\nimport \\\"../extensions/draft-IERC20PermitUpgradeable.sol\\\";\\nimport \\\"../../../utils/AddressUpgradeable.sol\\\";\\n\\n/**\\n * @title SafeERC20\\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\\n * contract returns false). Tokens that return no value (and instead revert or\\n * throw on failure) are also supported, non-reverting calls are assumed to be\\n * successful.\\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\\n */\\nlibrary SafeERC20Upgradeable {\\n using AddressUpgradeable for address;\\n\\n function safeTransfer(\\n IERC20Upgradeable token,\\n address to,\\n uint256 value\\n ) internal {\\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\\n }\\n\\n function safeTransferFrom(\\n IERC20Upgradeable token,\\n address from,\\n address to,\\n uint256 value\\n ) internal {\\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\\n }\\n\\n /**\\n * @dev Deprecated. This function has issues similar to the ones found in\\n * {IERC20-approve}, and its usage is discouraged.\\n *\\n * Whenever possible, use {safeIncreaseAllowance} and\\n * {safeDecreaseAllowance} instead.\\n */\\n function safeApprove(\\n IERC20Upgradeable token,\\n address spender,\\n uint256 value\\n ) internal {\\n // safeApprove should only be called when setting an initial allowance,\\n // or when resetting it to zero. To increase and decrease it, use\\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\\n require(\\n (value == 0) || (token.allowance(address(this), spender) == 0),\\n \\\"SafeERC20: approve from non-zero to non-zero allowance\\\"\\n );\\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\\n }\\n\\n function safeIncreaseAllowance(\\n IERC20Upgradeable token,\\n address spender,\\n uint256 value\\n ) internal {\\n uint256 newAllowance = token.allowance(address(this), spender) + value;\\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\\n }\\n\\n function safeDecreaseAllowance(\\n IERC20Upgradeable token,\\n address spender,\\n uint256 value\\n ) internal {\\n unchecked {\\n uint256 oldAllowance = token.allowance(address(this), spender);\\n require(oldAllowance >= value, \\\"SafeERC20: decreased allowance below zero\\\");\\n uint256 newAllowance = oldAllowance - value;\\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\\n }\\n }\\n\\n function safePermit(\\n IERC20PermitUpgradeable token,\\n address owner,\\n address spender,\\n uint256 value,\\n uint256 deadline,\\n uint8 v,\\n bytes32 r,\\n bytes32 s\\n ) internal {\\n uint256 nonceBefore = token.nonces(owner);\\n token.permit(owner, spender, value, deadline, v, r, s);\\n uint256 nonceAfter = token.nonces(owner);\\n require(nonceAfter == nonceBefore + 1, \\\"SafeERC20: permit did not succeed\\\");\\n }\\n\\n /**\\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\\n * on the return value: the return value is optional (but if data is returned, it must not be false).\\n * @param token The token targeted by the call.\\n * @param data The call data (encoded using abi.encode or one of its variants).\\n */\\n function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {\\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\\n // the target address contains contract code and also asserts for success in the low-level call.\\n\\n bytes memory returndata = address(token).functionCall(data, \\\"SafeERC20: low-level call failed\\\");\\n if (returndata.length > 0) {\\n // Return data is optional\\n require(abi.decode(returndata, (bool)), \\\"SafeERC20: ERC20 operation did not succeed\\\");\\n }\\n }\\n}\\n\",\"keccak256\":\"0x4586689c55edb37fc3cac296d75d3851b3aee3f378aaa54d8a9258a384fbf541\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.1;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary AddressUpgradeable {\\n /**\\n * @dev Returns true if `account` is a contract.\\n *\\n * [IMPORTANT]\\n * ====\\n * It is unsafe to assume that an address for which this function returns\\n * false is an externally-owned account (EOA) and not a contract.\\n *\\n * Among others, `isContract` will return false for the following\\n * types of addresses:\\n *\\n * - an externally-owned account\\n * - a contract in construction\\n * - an address where a contract will be created\\n * - an address where a contract lived, but was destroyed\\n * ====\\n *\\n * [IMPORTANT]\\n * ====\\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\\n *\\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\\n * constructor.\\n * ====\\n */\\n function isContract(address account) internal view returns (bool) {\\n // This method relies on extcodesize/address.code.length, which returns 0\\n // for contracts in construction, since the code is only stored at the end\\n // of the constructor execution.\\n\\n return account.code.length > 0;\\n }\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n require(address(this).balance >= amount, \\\"Address: insufficient balance\\\");\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(success, \\\"Address: unable to send value, recipient may have reverted\\\");\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason, it is bubbled up by this\\n * function (like regular Solidity function calls).\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, \\\"Address: low-level call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\\n * `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, value, \\\"Address: low-level call with value failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\\n * with `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(address(this).balance >= value, \\\"Address: insufficient balance for call\\\");\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n return functionStaticCall(target, data, \\\"Address: low-level static call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\\n *\\n * _Available since v4.8._\\n */\\n function verifyCallResultFromTarget(\\n address target,\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n if (success) {\\n if (returndata.length == 0) {\\n // only check isContract if the call was successful and the return data is empty\\n // otherwise we already know that it was a contract\\n require(isContract(target), \\\"Address: call to non-contract\\\");\\n }\\n return returndata;\\n } else {\\n _revert(returndata, errorMessage);\\n }\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\\n * revert reason or using the provided one.\\n *\\n * _Available since v4.3._\\n */\\n function verifyCallResult(\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal pure returns (bytes memory) {\\n if (success) {\\n return returndata;\\n } else {\\n _revert(returndata, errorMessage);\\n }\\n }\\n\\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x0a3b4afc301241e2629ad192fa02e0f8626e3cf38ab6f45342bfd7afbde16ee0\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\\n\\npragma solidity ^0.8.0;\\nimport \\\"../proxy/utils/Initializable.sol\\\";\\n\\n/**\\n * @dev Provides information about the current execution context, including the\\n * sender of the transaction and its data. While these are generally available\\n * via msg.sender and msg.data, they should not be accessed in such a direct\\n * manner, since when dealing with meta-transactions the account sending and\\n * paying for execution may not be the actual sender (as far as an application\\n * is concerned).\\n *\\n * This contract is only required for intermediate, library-like contracts.\\n */\\nabstract contract ContextUpgradeable is Initializable {\\n function __Context_init() internal onlyInitializing {\\n }\\n\\n function __Context_init_unchained() internal onlyInitializing {\\n }\\n function _msgSender() internal view virtual returns (address) {\\n return msg.sender;\\n }\\n\\n function _msgData() internal view virtual returns (bytes calldata) {\\n return msg.data;\\n }\\n\\n /**\\n * @dev This empty reserved space is put in place to allow future versions to add new\\n * variables without shifting down storage in the inheritance chain.\\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\\n */\\n uint256[50] private __gap;\\n}\\n\",\"keccak256\":\"0x963ea7f0b48b032eef72fe3a7582edf78408d6f834115b9feadd673a4d5bd149\",\"license\":\"MIT\"},\"@openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Standard math utilities missing in the Solidity language.\\n */\\nlibrary MathUpgradeable {\\n enum Rounding {\\n Down, // Toward negative infinity\\n Up, // Toward infinity\\n Zero // Toward zero\\n }\\n\\n /**\\n * @dev Returns the largest of two numbers.\\n */\\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a > b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the smallest of two numbers.\\n */\\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\\n return a < b ? a : b;\\n }\\n\\n /**\\n * @dev Returns the average of two numbers. The result is rounded towards\\n * zero.\\n */\\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\\n // (a + b) / 2 can overflow.\\n return (a & b) + (a ^ b) / 2;\\n }\\n\\n /**\\n * @dev Returns the ceiling of the division of two numbers.\\n *\\n * This differs from standard division with `/` in that it rounds up instead\\n * of rounding down.\\n */\\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\\n // (a + b - 1) / b can overflow on addition, so we distribute.\\n return a == 0 ? 0 : (a - 1) / b + 1;\\n }\\n\\n /**\\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\\n * with further edits by Uniswap Labs also under MIT license.\\n */\\n function mulDiv(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 result) {\\n unchecked {\\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\\n // variables such that product = prod1 * 2^256 + prod0.\\n uint256 prod0; // Least significant 256 bits of the product\\n uint256 prod1; // Most significant 256 bits of the product\\n assembly {\\n let mm := mulmod(x, y, not(0))\\n prod0 := mul(x, y)\\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\\n }\\n\\n // Handle non-overflow cases, 256 by 256 division.\\n if (prod1 == 0) {\\n return prod0 / denominator;\\n }\\n\\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\\n require(denominator > prod1);\\n\\n ///////////////////////////////////////////////\\n // 512 by 256 division.\\n ///////////////////////////////////////////////\\n\\n // Make division exact by subtracting the remainder from [prod1 prod0].\\n uint256 remainder;\\n assembly {\\n // Compute remainder using mulmod.\\n remainder := mulmod(x, y, denominator)\\n\\n // Subtract 256 bit number from 512 bit number.\\n prod1 := sub(prod1, gt(remainder, prod0))\\n prod0 := sub(prod0, remainder)\\n }\\n\\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\\n // See https://cs.stackexchange.com/q/138556/92363.\\n\\n // Does not overflow because the denominator cannot be zero at this stage in the function.\\n uint256 twos = denominator & (~denominator + 1);\\n assembly {\\n // Divide denominator by twos.\\n denominator := div(denominator, twos)\\n\\n // Divide [prod1 prod0] by twos.\\n prod0 := div(prod0, twos)\\n\\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\\n twos := add(div(sub(0, twos), twos), 1)\\n }\\n\\n // Shift in bits from prod1 into prod0.\\n prod0 |= prod1 * twos;\\n\\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\\n // four bits. That is, denominator * inv = 1 mod 2^4.\\n uint256 inverse = (3 * denominator) ^ 2;\\n\\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\\n // in modular arithmetic, doubling the correct bits in each step.\\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\\n\\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\\n // is no longer required.\\n result = prod0 * inverse;\\n return result;\\n }\\n }\\n\\n /**\\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\\n */\\n function mulDiv(\\n uint256 x,\\n uint256 y,\\n uint256 denominator,\\n Rounding rounding\\n ) internal pure returns (uint256) {\\n uint256 result = mulDiv(x, y, denominator);\\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\\n result += 1;\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\\n *\\n * Inspired by Henry S. Warren, Jr.'s \\\"Hacker's Delight\\\" (Chapter 11).\\n */\\n function sqrt(uint256 a) internal pure returns (uint256) {\\n if (a == 0) {\\n return 0;\\n }\\n\\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\\n //\\n // We know that the \\\"msb\\\" (most significant bit) of our target number `a` is a power of 2 such that we have\\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\\n //\\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\\n // \\u2192 `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\\n // \\u2192 `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\\n //\\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\\n uint256 result = 1 << (log2(a) >> 1);\\n\\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\\n // into the expected uint128 result.\\n unchecked {\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n result = (result + a / result) >> 1;\\n return min(result, a / result);\\n }\\n }\\n\\n /**\\n * @notice Calculates sqrt(a), following the selected rounding direction.\\n */\\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = sqrt(a);\\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 2, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 128;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 64;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 32;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 16;\\n }\\n if (value >> 8 > 0) {\\n value >>= 8;\\n result += 8;\\n }\\n if (value >> 4 > 0) {\\n value >>= 4;\\n result += 4;\\n }\\n if (value >> 2 > 0) {\\n value >>= 2;\\n result += 2;\\n }\\n if (value >> 1 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log2(value);\\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 10, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >= 10**64) {\\n value /= 10**64;\\n result += 64;\\n }\\n if (value >= 10**32) {\\n value /= 10**32;\\n result += 32;\\n }\\n if (value >= 10**16) {\\n value /= 10**16;\\n result += 16;\\n }\\n if (value >= 10**8) {\\n value /= 10**8;\\n result += 8;\\n }\\n if (value >= 10**4) {\\n value /= 10**4;\\n result += 4;\\n }\\n if (value >= 10**2) {\\n value /= 10**2;\\n result += 2;\\n }\\n if (value >= 10**1) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log10(value);\\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\\n }\\n }\\n\\n /**\\n * @dev Return the log in base 256, rounded down, of a positive value.\\n * Returns 0 if given 0.\\n *\\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\\n */\\n function log256(uint256 value) internal pure returns (uint256) {\\n uint256 result = 0;\\n unchecked {\\n if (value >> 128 > 0) {\\n value >>= 128;\\n result += 16;\\n }\\n if (value >> 64 > 0) {\\n value >>= 64;\\n result += 8;\\n }\\n if (value >> 32 > 0) {\\n value >>= 32;\\n result += 4;\\n }\\n if (value >> 16 > 0) {\\n value >>= 16;\\n result += 2;\\n }\\n if (value >> 8 > 0) {\\n result += 1;\\n }\\n }\\n return result;\\n }\\n\\n /**\\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\\n * Returns 0 if given 0.\\n */\\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\\n unchecked {\\n uint256 result = log256(value);\\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\\n }\\n }\\n}\\n\",\"keccak256\":\"0xb49137b771712774960cca0acf428499e2aa85f179fe03712e5c06c5a6ab6316\",\"license\":\"MIT\"},\"@openzeppelin/contracts/interfaces/draft-IERC1822.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\\n * proxy whose upgrades are fully controlled by the current implementation.\\n */\\ninterface IERC1822Proxiable {\\n /**\\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\\n * address.\\n *\\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\\n * function revert if invoked through a proxy.\\n */\\n function proxiableUUID() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x1d4afe6cb24200cc4545eed814ecf5847277dfe5d613a1707aad5fceecebcfff\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../Proxy.sol\\\";\\nimport \\\"./ERC1967Upgrade.sol\\\";\\n\\n/**\\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\\n * implementation address that can be changed. This address is stored in storage in the location specified by\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\\n * implementation behind the proxy.\\n */\\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\\n /**\\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\\n *\\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\\n * function call, and allows initializing the storage of the proxy like a Solidity constructor.\\n */\\n constructor(address _logic, bytes memory _data) payable {\\n _upgradeToAndCall(_logic, _data, false);\\n }\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _implementation() internal view virtual override returns (address impl) {\\n return ERC1967Upgrade._getImplementation();\\n }\\n}\\n\",\"keccak256\":\"0xa2b22da3032e50b55f95ec1d13336102d675f341167aa76db571ef7f8bb7975d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\\n\\npragma solidity ^0.8.2;\\n\\nimport \\\"../beacon/IBeacon.sol\\\";\\nimport \\\"../../interfaces/draft-IERC1822.sol\\\";\\nimport \\\"../../utils/Address.sol\\\";\\nimport \\\"../../utils/StorageSlot.sol\\\";\\n\\n/**\\n * @dev This abstract contract provides getters and event emitting update functions for\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\\n *\\n * _Available since v4.1._\\n *\\n * @custom:oz-upgrades-unsafe-allow delegatecall\\n */\\nabstract contract ERC1967Upgrade {\\n // This is the keccak-256 hash of \\\"eip1967.proxy.rollback\\\" subtracted by 1\\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\\n\\n /**\\n * @dev Storage slot with the address of the current implementation.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.implementation\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n\\n /**\\n * @dev Emitted when the implementation is upgraded.\\n */\\n event Upgraded(address indexed implementation);\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _getImplementation() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 implementation slot.\\n */\\n function _setImplementation(address newImplementation) private {\\n require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n }\\n\\n /**\\n * @dev Perform implementation upgrade\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeTo(address newImplementation) internal {\\n _setImplementation(newImplementation);\\n emit Upgraded(newImplementation);\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCall(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _upgradeTo(newImplementation);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(newImplementation, data);\\n }\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCallUUPS(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n // Upgrades from old implementations will perform a rollback test. This test requires the new\\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\\n // this special case will break upgrade paths from old UUPS implementation to new ones.\\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\\n _setImplementation(newImplementation);\\n } else {\\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\\n require(slot == _IMPLEMENTATION_SLOT, \\\"ERC1967Upgrade: unsupported proxiableUUID\\\");\\n } catch {\\n revert(\\\"ERC1967Upgrade: new implementation is not UUPS\\\");\\n }\\n _upgradeToAndCall(newImplementation, data, forceCall);\\n }\\n }\\n\\n /**\\n * @dev Storage slot with the admin of the contract.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.admin\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\\n\\n /**\\n * @dev Emitted when the admin account has changed.\\n */\\n event AdminChanged(address previousAdmin, address newAdmin);\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _getAdmin() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 admin slot.\\n */\\n function _setAdmin(address newAdmin) private {\\n require(newAdmin != address(0), \\\"ERC1967: new admin is the zero address\\\");\\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n */\\n function _changeAdmin(address newAdmin) internal {\\n emit AdminChanged(_getAdmin(), newAdmin);\\n _setAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\\n */\\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\\n\\n /**\\n * @dev Emitted when the beacon is upgraded.\\n */\\n event BeaconUpgraded(address indexed beacon);\\n\\n /**\\n * @dev Returns the current beacon.\\n */\\n function _getBeacon() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new beacon in the EIP1967 beacon slot.\\n */\\n function _setBeacon(address newBeacon) private {\\n require(Address.isContract(newBeacon), \\\"ERC1967: new beacon is not a contract\\\");\\n require(\\n Address.isContract(IBeacon(newBeacon).implementation()),\\n \\\"ERC1967: beacon implementation is not a contract\\\"\\n );\\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\\n }\\n\\n /**\\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\\n *\\n * Emits a {BeaconUpgraded} event.\\n */\\n function _upgradeBeaconToAndCall(\\n address newBeacon,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _setBeacon(newBeacon);\\n emit BeaconUpgraded(newBeacon);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\\n }\\n }\\n}\\n\",\"keccak256\":\"0xabf3f59bc0e5423eae45e459dbe92e7052c6983628d39008590edc852a62f94a\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\\n * be specified by overriding the virtual {_implementation} function.\\n *\\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\\n * different contract through the {_delegate} function.\\n *\\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\\n */\\nabstract contract Proxy {\\n /**\\n * @dev Delegates the current call to `implementation`.\\n *\\n * This function does not return to its internal call site, it will return directly to the external caller.\\n */\\n function _delegate(address implementation) internal virtual {\\n assembly {\\n // Copy msg.data. We take full control of memory in this inline assembly\\n // block because it will not return to Solidity code. We overwrite the\\n // Solidity scratch pad at memory position 0.\\n calldatacopy(0, 0, calldatasize())\\n\\n // Call the implementation.\\n // out and outsize are 0 because we don't know the size yet.\\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\\n\\n // Copy the returned data.\\n returndatacopy(0, 0, returndatasize())\\n\\n switch result\\n // delegatecall returns 0 on error.\\n case 0 {\\n revert(0, returndatasize())\\n }\\n default {\\n return(0, returndatasize())\\n }\\n }\\n }\\n\\n /**\\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\\n * and {_fallback} should delegate.\\n */\\n function _implementation() internal view virtual returns (address);\\n\\n /**\\n * @dev Delegates the current call to the address returned by `_implementation()`.\\n *\\n * This function does not return to its internal call site, it will return directly to the external caller.\\n */\\n function _fallback() internal virtual {\\n _beforeFallback();\\n _delegate(_implementation());\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\\n * function in the contract matches the call data.\\n */\\n fallback() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\\n * is empty.\\n */\\n receive() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\\n * call, or as part of the Solidity `fallback` or `receive` functions.\\n *\\n * If overridden should call `super._beforeFallback()`.\\n */\\n function _beforeFallback() internal virtual {}\\n}\\n\",\"keccak256\":\"0xc130fe33f1b2132158531a87734153293f6d07bc263ff4ac90e85da9c82c0e27\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/beacon/IBeacon.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\\n */\\ninterface IBeacon {\\n /**\\n * @dev Must return an address that can be used as a delegate call target.\\n *\\n * {BeaconProxy} will check that this address is a contract.\\n */\\n function implementation() external view returns (address);\\n}\\n\",\"keccak256\":\"0xd50a3421ac379ccb1be435fa646d66a65c986b4924f0849839f08692f39dde61\",\"license\":\"MIT\"},\"@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../ERC1967/ERC1967Proxy.sol\\\";\\n\\n/**\\n * @dev This contract implements a proxy that is upgradeable by an admin.\\n *\\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\\n * clashing], which can potentially be used in an attack, this contract uses the\\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\\n * things that go hand in hand:\\n *\\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\\n * that call matches one of the admin functions exposed by the proxy itself.\\n * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the\\n * implementation. If the admin tries to call a function on the implementation it will fail with an error that says\\n * \\\"admin cannot fallback to proxy target\\\".\\n *\\n * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing\\n * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due\\n * to sudden errors when trying to call a function from the proxy implementation.\\n *\\n * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,\\n * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\\n */\\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\\n /**\\n * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and\\n * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\\n */\\n constructor(\\n address _logic,\\n address admin_,\\n bytes memory _data\\n ) payable ERC1967Proxy(_logic, _data) {\\n _changeAdmin(admin_);\\n }\\n\\n /**\\n * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.\\n */\\n modifier ifAdmin() {\\n if (msg.sender == _getAdmin()) {\\n _;\\n } else {\\n _fallback();\\n }\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\\n */\\n function admin() external ifAdmin returns (address admin_) {\\n admin_ = _getAdmin();\\n }\\n\\n /**\\n * @dev Returns the current implementation.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\\n */\\n function implementation() external ifAdmin returns (address implementation_) {\\n implementation_ = _implementation();\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\\n */\\n function changeAdmin(address newAdmin) external virtual ifAdmin {\\n _changeAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\\n */\\n function upgradeTo(address newImplementation) external ifAdmin {\\n _upgradeToAndCall(newImplementation, bytes(\\\"\\\"), false);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified\\n * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the\\n * proxied contract.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\\n */\\n function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {\\n _upgradeToAndCall(newImplementation, data, true);\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _admin() internal view virtual returns (address) {\\n return _getAdmin();\\n }\\n\\n /**\\n * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.\\n */\\n function _beforeFallback() internal virtual override {\\n require(msg.sender != _getAdmin(), \\\"TransparentUpgradeableProxy: admin cannot fallback to proxy target\\\");\\n super._beforeFallback();\\n }\\n}\\n\",\"keccak256\":\"0xa6a787e7a901af6511e19aa53e1a00352db215a011d2c7a438d0582dd5da76f9\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.1;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev Returns true if `account` is a contract.\\n *\\n * [IMPORTANT]\\n * ====\\n * It is unsafe to assume that an address for which this function returns\\n * false is an externally-owned account (EOA) and not a contract.\\n *\\n * Among others, `isContract` will return false for the following\\n * types of addresses:\\n *\\n * - an externally-owned account\\n * - a contract in construction\\n * - an address where a contract will be created\\n * - an address where a contract lived, but was destroyed\\n * ====\\n *\\n * [IMPORTANT]\\n * ====\\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\\n *\\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\\n * constructor.\\n * ====\\n */\\n function isContract(address account) internal view returns (bool) {\\n // This method relies on extcodesize/address.code.length, which returns 0\\n // for contracts in construction, since the code is only stored at the end\\n // of the constructor execution.\\n\\n return account.code.length > 0;\\n }\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n require(address(this).balance >= amount, \\\"Address: insufficient balance\\\");\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(success, \\\"Address: unable to send value, recipient may have reverted\\\");\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason, it is bubbled up by this\\n * function (like regular Solidity function calls).\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, \\\"Address: low-level call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\\n * `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, value, \\\"Address: low-level call with value failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\\n * with `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(address(this).balance >= value, \\\"Address: insufficient balance for call\\\");\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n return functionStaticCall(target, data, \\\"Address: low-level static call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionDelegateCall(target, data, \\\"Address: low-level delegate call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\\n *\\n * _Available since v4.8._\\n */\\n function verifyCallResultFromTarget(\\n address target,\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n if (success) {\\n if (returndata.length == 0) {\\n // only check isContract if the call was successful and the return data is empty\\n // otherwise we already know that it was a contract\\n require(isContract(target), \\\"Address: call to non-contract\\\");\\n }\\n return returndata;\\n } else {\\n _revert(returndata, errorMessage);\\n }\\n }\\n\\n /**\\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\\n * revert reason or using the provided one.\\n *\\n * _Available since v4.3._\\n */\\n function verifyCallResult(\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal pure returns (bytes memory) {\\n if (success) {\\n return returndata;\\n } else {\\n _revert(returndata, errorMessage);\\n }\\n }\\n\\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n /// @solidity memory-safe-assembly\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n}\\n\",\"keccak256\":\"0xb94eac067c85cd79a4195c0a1f4a878e9827329045c12475a0199f1ae17b9700\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/StorageSlot.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Library for reading and writing primitive types to specific storage slots.\\n *\\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\\n * This library helps with reading and writing to such slots without the need for inline assembly.\\n *\\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\\n *\\n * Example usage to set ERC1967 implementation slot:\\n * ```\\n * contract ERC1967 {\\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n *\\n * function _getImplementation() internal view returns (address) {\\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n * }\\n *\\n * function _setImplementation(address newImplementation) internal {\\n * require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n * }\\n * }\\n * ```\\n *\\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\\n */\\nlibrary StorageSlot {\\n struct AddressSlot {\\n address value;\\n }\\n\\n struct BooleanSlot {\\n bool value;\\n }\\n\\n struct Bytes32Slot {\\n bytes32 value;\\n }\\n\\n struct Uint256Slot {\\n uint256 value;\\n }\\n\\n /**\\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\\n */\\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\\n */\\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\\n */\\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\\n */\\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\\n /// @solidity memory-safe-assembly\\n assembly {\\n r.slot := slot\\n }\\n }\\n}\\n\",\"keccak256\":\"0xd5c50c54bf02740ebd122ff06832546cb5fa84486d52695a9ccfd11666e0c81d\",\"license\":\"MIT\"},\"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)\\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Library for managing\\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\\n * types.\\n *\\n * Sets have the following properties:\\n *\\n * - Elements are added, removed, and checked for existence in constant time\\n * (O(1)).\\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\\n *\\n * ```\\n * contract Example {\\n * // Add the library methods\\n * using EnumerableSet for EnumerableSet.AddressSet;\\n *\\n * // Declare a set state variable\\n * EnumerableSet.AddressSet private mySet;\\n * }\\n * ```\\n *\\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\\n * and `uint256` (`UintSet`) are supported.\\n *\\n * [WARNING]\\n * ====\\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\\n * unusable.\\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\\n *\\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\\n * array of EnumerableSet.\\n * ====\\n */\\nlibrary EnumerableSet {\\n // To implement this library for multiple types with as little code\\n // repetition as possible, we write it in terms of a generic Set type with\\n // bytes32 values.\\n // The Set implementation uses private functions, and user-facing\\n // implementations (such as AddressSet) are just wrappers around the\\n // underlying Set.\\n // This means that we can only create new EnumerableSets for types that fit\\n // in bytes32.\\n\\n struct Set {\\n // Storage of set values\\n bytes32[] _values;\\n // Position of the value in the `values` array, plus 1 because index 0\\n // means a value is not in the set.\\n mapping(bytes32 => uint256) _indexes;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function _add(Set storage set, bytes32 value) private returns (bool) {\\n if (!_contains(set, value)) {\\n set._values.push(value);\\n // The value is stored at length-1, but we add 1 to all indexes\\n // and use 0 as a sentinel value\\n set._indexes[value] = set._values.length;\\n return true;\\n } else {\\n return false;\\n }\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function _remove(Set storage set, bytes32 value) private returns (bool) {\\n // We read and store the value's index to prevent multiple reads from the same storage slot\\n uint256 valueIndex = set._indexes[value];\\n\\n if (valueIndex != 0) {\\n // Equivalent to contains(set, value)\\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\\n // the array, and then remove the last element (sometimes called as 'swap and pop').\\n // This modifies the order of the array, as noted in {at}.\\n\\n uint256 toDeleteIndex = valueIndex - 1;\\n uint256 lastIndex = set._values.length - 1;\\n\\n if (lastIndex != toDeleteIndex) {\\n bytes32 lastValue = set._values[lastIndex];\\n\\n // Move the last value to the index where the value to delete is\\n set._values[toDeleteIndex] = lastValue;\\n // Update the index for the moved value\\n set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\\n }\\n\\n // Delete the slot where the moved value was stored\\n set._values.pop();\\n\\n // Delete the index for the deleted slot\\n delete set._indexes[value];\\n\\n return true;\\n } else {\\n return false;\\n }\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\\n return set._indexes[value] != 0;\\n }\\n\\n /**\\n * @dev Returns the number of values on the set. O(1).\\n */\\n function _length(Set storage set) private view returns (uint256) {\\n return set._values.length;\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\\n return set._values[index];\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function _values(Set storage set) private view returns (bytes32[] memory) {\\n return set._values;\\n }\\n\\n // Bytes32Set\\n\\n struct Bytes32Set {\\n Set _inner;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\\n return _add(set._inner, value);\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\\n return _remove(set._inner, value);\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\\n return _contains(set._inner, value);\\n }\\n\\n /**\\n * @dev Returns the number of values in the set. O(1).\\n */\\n function length(Bytes32Set storage set) internal view returns (uint256) {\\n return _length(set._inner);\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\\n return _at(set._inner, index);\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\\n bytes32[] memory store = _values(set._inner);\\n bytes32[] memory result;\\n\\n /// @solidity memory-safe-assembly\\n assembly {\\n result := store\\n }\\n\\n return result;\\n }\\n\\n // AddressSet\\n\\n struct AddressSet {\\n Set _inner;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function add(AddressSet storage set, address value) internal returns (bool) {\\n return _add(set._inner, bytes32(uint256(uint160(value))));\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function remove(AddressSet storage set, address value) internal returns (bool) {\\n return _remove(set._inner, bytes32(uint256(uint160(value))));\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function contains(AddressSet storage set, address value) internal view returns (bool) {\\n return _contains(set._inner, bytes32(uint256(uint160(value))));\\n }\\n\\n /**\\n * @dev Returns the number of values in the set. O(1).\\n */\\n function length(AddressSet storage set) internal view returns (uint256) {\\n return _length(set._inner);\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\\n return address(uint160(uint256(_at(set._inner, index))));\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function values(AddressSet storage set) internal view returns (address[] memory) {\\n bytes32[] memory store = _values(set._inner);\\n address[] memory result;\\n\\n /// @solidity memory-safe-assembly\\n assembly {\\n result := store\\n }\\n\\n return result;\\n }\\n\\n // UintSet\\n\\n struct UintSet {\\n Set _inner;\\n }\\n\\n /**\\n * @dev Add a value to a set. O(1).\\n *\\n * Returns true if the value was added to the set, that is if it was not\\n * already present.\\n */\\n function add(UintSet storage set, uint256 value) internal returns (bool) {\\n return _add(set._inner, bytes32(value));\\n }\\n\\n /**\\n * @dev Removes a value from a set. O(1).\\n *\\n * Returns true if the value was removed from the set, that is if it was\\n * present.\\n */\\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\\n return _remove(set._inner, bytes32(value));\\n }\\n\\n /**\\n * @dev Returns true if the value is in the set. O(1).\\n */\\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\\n return _contains(set._inner, bytes32(value));\\n }\\n\\n /**\\n * @dev Returns the number of values in the set. O(1).\\n */\\n function length(UintSet storage set) internal view returns (uint256) {\\n return _length(set._inner);\\n }\\n\\n /**\\n * @dev Returns the value stored at position `index` in the set. O(1).\\n *\\n * Note that there are no guarantees on the ordering of values inside the\\n * array, and it may change when more values are added or removed.\\n *\\n * Requirements:\\n *\\n * - `index` must be strictly less than {length}.\\n */\\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\\n return uint256(_at(set._inner, index));\\n }\\n\\n /**\\n * @dev Return the entire set in an array\\n *\\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\\n */\\n function values(UintSet storage set) internal view returns (uint256[] memory) {\\n bytes32[] memory store = _values(set._inner);\\n uint256[] memory result;\\n\\n /// @solidity memory-safe-assembly\\n assembly {\\n result := store\\n }\\n\\n return result;\\n }\\n}\\n\",\"keccak256\":\"0x636eab608b4563c01e88042aba9330e6fe69af2c567fe1adf4d85731974ac81d\",\"license\":\"MIT\"},\"adrastia-periphery/rates/IHistoricalRates.sol\":{\"content\":\"//SPDX-License-Identifier: MIT\\npragma solidity >=0.5.0 <0.9.0;\\n\\nimport \\\"./RateLibrary.sol\\\";\\n\\n/**\\n * @title IHistoricalRates\\n * @notice An interface that defines a contract that stores historical rates.\\n */\\ninterface IHistoricalRates {\\n /// @notice Gets an rate for a token at a specific index.\\n /// @param token The address of the token to get the rates for.\\n /// @param index The index of the rate to get, where index 0 contains the latest rate, and the last\\n /// index contains the oldest rate (uses reverse chronological ordering).\\n /// @return rate The rate for the token at the specified index.\\n function getRateAt(address token, uint256 index) external view returns (RateLibrary.Rate memory);\\n\\n /// @notice Gets the latest rates for a token.\\n /// @param token The address of the token to get the rates for.\\n /// @param amount The number of rates to get.\\n /// @return rates The latest rates for the token, in reverse chronological order, from newest to oldest.\\n function getRates(address token, uint256 amount) external view returns (RateLibrary.Rate[] memory);\\n\\n /// @notice Gets the latest rates for a token.\\n /// @param token The address of the token to get the rates for.\\n /// @param amount The number of rates to get.\\n /// @param offset The index of the first rate to get (default: 0).\\n /// @param increment The increment between rates to get (default: 1).\\n /// @return rates The latest rates for the token, in reverse chronological order, from newest to oldest.\\n function getRates(\\n address token,\\n uint256 amount,\\n uint256 offset,\\n uint256 increment\\n ) external view returns (RateLibrary.Rate[] memory);\\n\\n /// @notice Gets the number of rates for a token.\\n /// @param token The address of the token to get the number of rates for.\\n /// @return count The number of rates for the token.\\n function getRatesCount(address token) external view returns (uint256);\\n\\n /// @notice Gets the capacity of rates for a token.\\n /// @param token The address of the token to get the capacity of rates for.\\n /// @return capacity The capacity of rates for the token.\\n function getRatesCapacity(address token) external view returns (uint256);\\n\\n /// @notice Sets the capacity of rates for a token.\\n /// @param token The address of the token to set the capacity of rates for.\\n /// @param amount The new capacity of rates for the token.\\n function setRatesCapacity(address token, uint256 amount) external;\\n}\\n\",\"keccak256\":\"0x2754968c368df628f1ed00c2016b1a73f0f9b44f29e48d405887ad108723b3af\",\"license\":\"MIT\"},\"adrastia-periphery/rates/RateLibrary.sol\":{\"content\":\"//SPDX-License-Identifier: MIT\\npragma solidity >=0.5.0 <0.9.0;\\n\\npragma experimental ABIEncoderV2;\\n\\nlibrary RateLibrary {\\n struct Rate {\\n uint64 target;\\n uint64 current;\\n uint32 timestamp;\\n }\\n}\\n\",\"keccak256\":\"0x397b79cf9f183afa76db3c8d10cffb408e31ba154900f671a7e93c071bacbff4\",\"license\":\"MIT\"},\"contracts/src/adrastia/PrudentiaLib.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nlibrary PrudentiaLib {\\n struct PrudentiaConfig {\\n address controller; // Adrastia Prudentia controller address\\n uint8 offset; // Offset for delayed rate activation\\n int8 decimalShift; // Positive values scale the rate up (in powers of 10), negative values scale the rate down\\n }\\n}\\n\",\"keccak256\":\"0x8cc50f1a5dab30e0c205b0bba5f58c18eda9ebf01c661895c8f40678b86bf31f\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/CTokenInterfaces.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport { IonicComptroller } from \\\"./ComptrollerInterface.sol\\\";\\nimport { InterestRateModel } from \\\"./InterestRateModel.sol\\\";\\nimport { ComptrollerV3Storage } from \\\"./ComptrollerStorage.sol\\\";\\nimport { AddressesProvider } from \\\"../ionic/AddressesProvider.sol\\\";\\n\\nabstract contract CTokenAdminStorage {\\n /*\\n * Administrator for Ionic\\n */\\n address payable public ionicAdmin;\\n}\\n\\nabstract contract CErc20Storage is CTokenAdminStorage {\\n /**\\n * @dev Guard variable for re-entrancy checks\\n */\\n bool internal _notEntered;\\n\\n /**\\n * @notice EIP-20 token name for this token\\n */\\n string public name;\\n\\n /**\\n * @notice EIP-20 token symbol for this token\\n */\\n string public symbol;\\n\\n /**\\n * @notice EIP-20 token decimals for this token\\n */\\n uint8 public decimals;\\n\\n /*\\n * Maximum borrow rate that can ever be applied (.0005% / block)\\n */\\n uint256 internal constant borrowRateMaxMantissa = 0.0005e16;\\n\\n /*\\n * Maximum fraction of interest that can be set aside for reserves + fees\\n */\\n uint256 internal constant reserveFactorPlusFeesMaxMantissa = 1e18;\\n\\n /**\\n * @notice Contract which oversees inter-cToken operations\\n */\\n IonicComptroller public comptroller;\\n\\n /**\\n * @notice Model which tells what the current interest rate should be\\n */\\n InterestRateModel public interestRateModel;\\n\\n /*\\n * Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)\\n */\\n uint256 internal initialExchangeRateMantissa;\\n\\n /**\\n * @notice Fraction of interest currently set aside for admin fees\\n */\\n uint256 public adminFeeMantissa;\\n\\n /**\\n * @notice Fraction of interest currently set aside for Ionic fees\\n */\\n uint256 public ionicFeeMantissa;\\n\\n /**\\n * @notice Fraction of interest currently set aside for reserves\\n */\\n uint256 public reserveFactorMantissa;\\n\\n /**\\n * @notice Block number that interest was last accrued at\\n */\\n uint256 public accrualBlockNumber;\\n\\n /**\\n * @notice Accumulator of the total earned interest rate since the opening of the market\\n */\\n uint256 public borrowIndex;\\n\\n /**\\n * @notice Total amount of outstanding borrows of the underlying in this market\\n */\\n uint256 public totalBorrows;\\n\\n /**\\n * @notice Total amount of reserves of the underlying held in this market\\n */\\n uint256 public totalReserves;\\n\\n /**\\n * @notice Total amount of admin fees of the underlying held in this market\\n */\\n uint256 public totalAdminFees;\\n\\n /**\\n * @notice Total amount of Ionic fees of the underlying held in this market\\n */\\n uint256 public totalIonicFees;\\n\\n /**\\n * @notice Total number of tokens in circulation\\n */\\n uint256 public totalSupply;\\n\\n /*\\n * Official record of token balances for each account\\n */\\n mapping(address => uint256) internal accountTokens;\\n\\n /*\\n * Approved token transfer amounts on behalf of others\\n */\\n mapping(address => mapping(address => uint256)) internal transferAllowances;\\n\\n /**\\n * @notice Container for borrow balance information\\n * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action\\n * @member interestIndex Global borrowIndex as of the most recent balance-changing action\\n */\\n struct BorrowSnapshot {\\n uint256 principal;\\n uint256 interestIndex;\\n }\\n\\n /*\\n * Mapping of account addresses to outstanding borrow balances\\n */\\n mapping(address => BorrowSnapshot) internal accountBorrows;\\n\\n /*\\n * Share of seized collateral that is added to reserves\\n */\\n uint256 public constant protocolSeizeShareMantissa = 2.8e16; //2.8%\\n\\n /*\\n * Share of seized collateral taken as fees\\n */\\n uint256 public constant feeSeizeShareMantissa = 1e17; //10%\\n\\n /**\\n * @notice Underlying asset for this CToken\\n */\\n address public underlying;\\n\\n /**\\n * @notice Addresses Provider\\n */\\n AddressesProvider public ap;\\n}\\n\\nabstract contract CTokenBaseEvents {\\n /* ERC20 */\\n\\n /**\\n * @notice EIP20 Transfer event\\n */\\n event Transfer(address indexed from, address indexed to, uint256 amount);\\n\\n /*** Admin Events ***/\\n\\n /**\\n * @notice Event emitted when interestRateModel is changed\\n */\\n event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);\\n\\n /**\\n * @notice Event emitted when the reserve factor is changed\\n */\\n event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);\\n\\n /**\\n * @notice Event emitted when the admin fee is changed\\n */\\n event NewAdminFee(uint256 oldAdminFeeMantissa, uint256 newAdminFeeMantissa);\\n\\n /**\\n * @notice Event emitted when the Ionic fee is changed\\n */\\n event NewIonicFee(uint256 oldIonicFeeMantissa, uint256 newIonicFeeMantissa);\\n\\n /**\\n * @notice EIP20 Approval event\\n */\\n event Approval(address indexed owner, address indexed spender, uint256 amount);\\n\\n /**\\n * @notice Event emitted when interest is accrued\\n */\\n event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);\\n}\\n\\nabstract contract CTokenFirstExtensionEvents is CTokenBaseEvents {\\n event Flash(address receiver, uint256 amount);\\n}\\n\\nabstract contract CTokenSecondExtensionEvents is CTokenBaseEvents {\\n /*** Market Events ***/\\n\\n /**\\n * @notice Event emitted when tokens are minted\\n */\\n event Mint(address minter, uint256 mintAmount, uint256 mintTokens);\\n\\n /**\\n * @notice Event emitted when tokens are redeemed\\n */\\n event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);\\n\\n /**\\n * @notice Event emitted when underlying is borrowed\\n */\\n event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);\\n\\n /**\\n * @notice Event emitted when a borrow is repaid\\n */\\n event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows);\\n\\n /**\\n * @notice Event emitted when a borrow is liquidated\\n */\\n event LiquidateBorrow(\\n address liquidator,\\n address borrower,\\n uint256 repayAmount,\\n address cTokenCollateral,\\n uint256 seizeTokens\\n );\\n\\n /**\\n * @notice Event emitted when the reserves are added\\n */\\n event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);\\n\\n /**\\n * @notice Event emitted when the reserves are reduced\\n */\\n event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);\\n}\\n\\ninterface CTokenFirstExtensionInterface {\\n /*** User Interface ***/\\n\\n function transfer(address dst, uint256 amount) external returns (bool);\\n\\n function transferFrom(\\n address src,\\n address dst,\\n uint256 amount\\n ) external returns (bool);\\n\\n function approve(address spender, uint256 amount) external returns (bool);\\n\\n function allowance(address owner, address spender) external view returns (uint256);\\n\\n function balanceOf(address owner) external view returns (uint256);\\n\\n /*** Admin Functions ***/\\n\\n function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);\\n\\n function _setAdminFee(uint256 newAdminFeeMantissa) external returns (uint256);\\n\\n function _setInterestRateModel(InterestRateModel newInterestRateModel) external returns (uint256);\\n\\n function getAccountSnapshot(address account)\\n external\\n view\\n returns (\\n uint256,\\n uint256,\\n uint256,\\n uint256\\n );\\n\\n function borrowRatePerBlock() external view returns (uint256);\\n\\n function supplyRatePerBlock() external view returns (uint256);\\n\\n function exchangeRateCurrent() external view returns (uint256);\\n\\n function accrueInterest() external returns (uint256);\\n\\n function totalBorrowsCurrent() external view returns (uint256);\\n\\n function borrowBalanceCurrent(address account) external view returns (uint256);\\n\\n function getTotalUnderlyingSupplied() external view returns (uint256);\\n\\n function balanceOfUnderlying(address owner) external view returns (uint256);\\n\\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\\n\\n function flash(uint256 amount, bytes calldata data) external;\\n\\n function supplyRatePerBlockAfterDeposit(uint256 mintAmount) external view returns (uint256);\\n\\n function supplyRatePerBlockAfterWithdraw(uint256 withdrawAmount) external view returns (uint256);\\n\\n function borrowRatePerBlockAfterBorrow(uint256 borrowAmount) external view returns (uint256);\\n\\n function registerInSFS() external returns (uint256);\\n}\\n\\ninterface CTokenSecondExtensionInterface {\\n function mint(uint256 mintAmount) external returns (uint256);\\n\\n function redeem(uint256 redeemTokens) external returns (uint256);\\n\\n function redeemUnderlying(uint256 redeemAmount) external returns (uint256);\\n\\n function borrow(uint256 borrowAmount) external returns (uint256);\\n\\n function repayBorrow(uint256 repayAmount) external returns (uint256);\\n\\n function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);\\n\\n function liquidateBorrow(\\n address borrower,\\n uint256 repayAmount,\\n address cTokenCollateral\\n ) external returns (uint256);\\n\\n function getCash() external view returns (uint256);\\n\\n function seize(\\n address liquidator,\\n address borrower,\\n uint256 seizeTokens\\n ) external returns (uint256);\\n\\n /*** Admin Functions ***/\\n\\n function _withdrawAdminFees(uint256 withdrawAmount) external returns (uint256);\\n\\n function _withdrawIonicFees(uint256 withdrawAmount) external returns (uint256);\\n\\n function selfTransferOut(address to, uint256 amount) external;\\n\\n function selfTransferIn(address from, uint256 amount) external returns (uint256);\\n}\\n\\ninterface CDelegatorInterface {\\n function implementation() external view returns (address);\\n\\n /**\\n * @notice Called by the admin to update the implementation of the delegator\\n * @param implementation_ The address of the new implementation for delegation\\n * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\\n */\\n function _setImplementationSafe(address implementation_, bytes calldata becomeImplementationData) external;\\n\\n /**\\n * @dev upgrades the implementation if necessary\\n */\\n function _upgrade() external;\\n}\\n\\ninterface CDelegateInterface {\\n /**\\n * @notice Called by the delegator on a delegate to initialize it for duty\\n * @dev Should revert if any issues arise which make it unfit for delegation\\n * @param data The encoded bytes data for any initialization\\n */\\n function _becomeImplementation(bytes calldata data) external;\\n\\n function delegateType() external pure returns (uint8);\\n\\n function contractType() external pure returns (string memory);\\n}\\n\\nabstract contract CErc20AdminBase is CErc20Storage {\\n /**\\n * @notice Returns a boolean indicating if the sender has admin rights\\n */\\n function hasAdminRights() internal view returns (bool) {\\n ComptrollerV3Storage comptrollerStorage = ComptrollerV3Storage(address(comptroller));\\n return\\n (msg.sender == comptrollerStorage.admin() && comptrollerStorage.adminHasRights()) ||\\n (msg.sender == address(ionicAdmin) && comptrollerStorage.ionicAdminHasRights());\\n }\\n}\\n\\nabstract contract CErc20FirstExtensionBase is\\n CErc20AdminBase,\\n CTokenFirstExtensionEvents,\\n CTokenFirstExtensionInterface\\n{}\\n\\nabstract contract CTokenSecondExtensionBase is\\n CErc20AdminBase,\\n CTokenSecondExtensionEvents,\\n CTokenSecondExtensionInterface,\\n CDelegateInterface\\n{}\\n\\nabstract contract CErc20DelegatorBase is CErc20AdminBase, CTokenSecondExtensionEvents, CDelegatorInterface {}\\n\\ninterface CErc20StorageInterface {\\n function admin() external view returns (address);\\n\\n function adminHasRights() external view returns (bool);\\n\\n function ionicAdmin() external view returns (address);\\n\\n function ionicAdminHasRights() external view returns (bool);\\n\\n function comptroller() external view returns (IonicComptroller);\\n\\n function name() external view returns (string memory);\\n\\n function symbol() external view returns (string memory);\\n\\n function decimals() external view returns (uint8);\\n\\n function totalSupply() external view returns (uint256);\\n\\n function adminFeeMantissa() external view returns (uint256);\\n\\n function ionicFeeMantissa() external view returns (uint256);\\n\\n function reserveFactorMantissa() external view returns (uint256);\\n\\n function protocolSeizeShareMantissa() external view returns (uint256);\\n\\n function feeSeizeShareMantissa() external view returns (uint256);\\n\\n function totalReserves() external view returns (uint256);\\n\\n function totalAdminFees() external view returns (uint256);\\n\\n function totalIonicFees() external view returns (uint256);\\n\\n function totalBorrows() external view returns (uint256);\\n\\n function accrualBlockNumber() external view returns (uint256);\\n\\n function underlying() external view returns (address);\\n\\n function borrowIndex() external view returns (uint256);\\n\\n function interestRateModel() external view returns (address);\\n}\\n\\ninterface CErc20PluginStorageInterface is CErc20StorageInterface {\\n function plugin() external view returns (address);\\n}\\n\\ninterface CErc20PluginRewardsInterface is CErc20PluginStorageInterface {\\n function approve(address, address) external;\\n}\\n\\ninterface ICErc20 is\\n CErc20StorageInterface,\\n CTokenSecondExtensionInterface,\\n CTokenFirstExtensionInterface,\\n CDelegatorInterface,\\n CDelegateInterface\\n{}\\n\\ninterface ICErc20Plugin is CErc20PluginStorageInterface, ICErc20 {\\n function _updatePlugin(address _plugin) external;\\n}\\n\\ninterface ICErc20PluginRewards is CErc20PluginRewardsInterface, ICErc20 {}\\n\",\"keccak256\":\"0x7cc75051a5fa860b9ee93d0ba1ac0608921f02308aeff786ce8bbd8d8a70489a\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/ComptrollerInterface.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport { BasePriceOracle } from \\\"../oracles/BasePriceOracle.sol\\\";\\nimport { ICErc20 } from \\\"./CTokenInterfaces.sol\\\";\\nimport { DiamondExtension } from \\\"../ionic/DiamondExtension.sol\\\";\\nimport { ComptrollerV4Storage } from \\\"../compound/ComptrollerStorage.sol\\\";\\nimport { PrudentiaLib } from \\\"../adrastia/PrudentiaLib.sol\\\";\\nimport { IHistoricalRates } from \\\"adrastia-periphery/rates/IHistoricalRates.sol\\\";\\n\\ninterface ComptrollerInterface {\\n function isDeprecated(ICErc20 cToken) external view returns (bool);\\n\\n function _becomeImplementation() external;\\n\\n function _deployMarket(\\n uint8 delegateType,\\n bytes memory constructorData,\\n bytes calldata becomeImplData,\\n uint256 collateralFactorMantissa\\n ) external returns (uint256);\\n\\n function getAssetsIn(address account) external view returns (ICErc20[] memory);\\n\\n function checkMembership(address account, ICErc20 cToken) external view returns (bool);\\n\\n function _setPriceOracle(BasePriceOracle newOracle) external returns (uint256);\\n\\n function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256);\\n\\n function _setCollateralFactor(ICErc20 market, uint256 newCollateralFactorMantissa) external returns (uint256);\\n\\n function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256);\\n\\n function _setWhitelistEnforcement(bool enforce) external returns (uint256);\\n\\n function _setWhitelistStatuses(address[] calldata _suppliers, bool[] calldata statuses) external returns (uint256);\\n\\n function _addRewardsDistributor(address distributor) external returns (uint256);\\n\\n function getHypotheticalAccountLiquidity(\\n address account,\\n address cTokenModify,\\n uint256 redeemTokens,\\n uint256 borrowAmount,\\n uint256 repayAmount\\n ) external view returns (uint256, uint256, uint256, uint256);\\n\\n function getMaxRedeemOrBorrow(address account, ICErc20 cToken, bool isBorrow) external view returns (uint256);\\n\\n /*** Assets You Are In ***/\\n\\n function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);\\n\\n function exitMarket(address cToken) external returns (uint256);\\n\\n /*** Policy Hooks ***/\\n\\n function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256);\\n\\n function redeemAllowed(address cToken, address redeemer, uint256 redeemTokens) external returns (uint256);\\n\\n function redeemVerify(address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens) external;\\n\\n function borrowAllowed(address cToken, address borrower, uint256 borrowAmount) external returns (uint256);\\n\\n function borrowVerify(address cToken, address borrower) external;\\n\\n function borrowWithinLimits(address cToken, uint256 accountBorrowsNew) external view returns (uint256);\\n\\n function repayBorrowAllowed(\\n address cToken,\\n address payer,\\n address borrower,\\n uint256 repayAmount\\n ) external returns (uint256);\\n\\n function repayBorrowVerify(\\n address cToken,\\n address payer,\\n address borrower,\\n uint256 repayAmount\\n ) external;\\n\\n function liquidateBorrowAllowed(\\n address cTokenBorrowed,\\n address cTokenCollateral,\\n address liquidator,\\n address borrower,\\n uint256 repayAmount\\n ) external returns (uint256);\\n\\n function seizeAllowed(\\n address cTokenCollateral,\\n address cTokenBorrowed,\\n address liquidator,\\n address borrower,\\n uint256 seizeTokens\\n ) external returns (uint256);\\n \\n function seizeVerify(\\n address cTokenCollateral,\\n address cTokenBorrowed,\\n address liquidator,\\n address borrower,\\n uint256 seizeTokens\\n ) external;\\n\\n function transferAllowed(address cToken, address src, address dst, uint256 transferTokens) external returns (uint256);\\n \\n function transferVerify(address cToken, address src, address dst, uint256 transferTokens) external;\\n\\n function mintVerify(address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens) external;\\n\\n /*** Liquidity/Liquidation Calculations ***/\\n\\n function getAccountLiquidity(\\n address account\\n ) external view returns (uint256 error, uint256 collateralValue, uint256 liquidity, uint256 shortfall);\\n\\n function liquidateCalculateSeizeTokens(\\n address cTokenBorrowed,\\n address cTokenCollateral,\\n uint256 repayAmount\\n ) external view returns (uint256, uint256);\\n\\n /*** Pool-Wide/Cross-Asset Reentrancy Prevention ***/\\n\\n function _beforeNonReentrant() external;\\n\\n function _afterNonReentrant() external;\\n\\n /*** New supply and borrow cap view functions ***/\\n\\n /**\\n * @notice Gets the supply cap of a cToken in the units of the underlying asset.\\n * @param cToken The address of the cToken.\\n */\\n function effectiveSupplyCaps(address cToken) external view returns (uint256 supplyCap);\\n\\n /**\\n * @notice Gets the borrow cap of a cToken in the units of the underlying asset.\\n * @param cToken The address of the cToken.\\n */\\n function effectiveBorrowCaps(address cToken) external view returns (uint256 borrowCap);\\n}\\n\\ninterface ComptrollerStorageInterface {\\n function admin() external view returns (address);\\n\\n function adminHasRights() external view returns (bool);\\n\\n function ionicAdmin() external view returns (address);\\n\\n function ionicAdminHasRights() external view returns (bool);\\n\\n function pendingAdmin() external view returns (address);\\n\\n function oracle() external view returns (BasePriceOracle);\\n\\n function pauseGuardian() external view returns (address);\\n\\n function closeFactorMantissa() external view returns (uint256);\\n\\n function liquidationIncentiveMantissa() external view returns (uint256);\\n\\n function isUserOfPool(address user) external view returns (bool);\\n\\n function whitelist(address account) external view returns (bool);\\n\\n function enforceWhitelist() external view returns (bool);\\n\\n function borrowCapForCollateral(address borrowed, address collateral) external view returns (uint256);\\n\\n function borrowingAgainstCollateralBlacklist(address borrowed, address collateral) external view returns (bool);\\n\\n function suppliers(address account) external view returns (bool);\\n\\n function cTokensByUnderlying(address) external view returns (address);\\n\\n /**\\n * Gets the supply cap of a cToken in the units of the underlying asset.\\n * @dev WARNING: This function is misleading if Adrastia Prudentia is being used for the supply cap. Instead, use\\n * `effectiveSupplyCaps` to get the correct supply cap.\\n * @param cToken The address of the cToken.\\n * @return The supply cap in the units of the underlying asset.\\n */\\n function supplyCaps(address cToken) external view returns (uint256);\\n\\n /**\\n * Gets the borrow cap of a cToken in the units of the underlying asset.\\n * @dev WARNING: This function is misleading if Adrastia Prudentia is being used for the borrow cap. Instead, use\\n * `effectiveBorrowCaps` to get the correct borrow cap.\\n * @param cToken The address of the cToken.\\n * @return The borrow cap in the units of the underlying asset.\\n */\\n function borrowCaps(address cToken) external view returns (uint256);\\n\\n function markets(address cToken) external view returns (bool, uint256);\\n\\n function accountAssets(address, uint256) external view returns (address);\\n\\n function borrowGuardianPaused(address cToken) external view returns (bool);\\n\\n function mintGuardianPaused(address cToken) external view returns (bool);\\n\\n function rewardsDistributors(uint256) external view returns (address);\\n}\\n\\ninterface SFSRegister {\\n function register(address _recipient) external returns (uint256 tokenId);\\n}\\n\\ninterface ComptrollerExtensionInterface {\\n function getWhitelistedSuppliersSupply(address cToken) external view returns (uint256 supplied);\\n\\n function getWhitelistedBorrowersBorrows(address cToken) external view returns (uint256 borrowed);\\n\\n function getAllMarkets() external view returns (ICErc20[] memory);\\n\\n function getAllBorrowers() external view returns (address[] memory);\\n\\n function getAllBorrowersCount() external view returns (uint256);\\n\\n function getPaginatedBorrowers(\\n uint256 page,\\n uint256 pageSize\\n ) external view returns (uint256 _totalPages, address[] memory _pageOfBorrowers);\\n\\n function getRewardsDistributors() external view returns (address[] memory);\\n\\n function getAccruingFlywheels() external view returns (address[] memory);\\n\\n function _supplyCapWhitelist(address cToken, address account, bool whitelisted) external;\\n\\n function _setBorrowCapForCollateral(address cTokenBorrow, address cTokenCollateral, uint256 borrowCap) external;\\n\\n function _setBorrowCapForCollateralWhitelist(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n address account,\\n bool whitelisted\\n ) external;\\n\\n function isBorrowCapForCollateralWhitelisted(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n address account\\n ) external view returns (bool);\\n\\n function _blacklistBorrowingAgainstCollateral(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n bool blacklisted\\n ) external;\\n\\n function _blacklistBorrowingAgainstCollateralWhitelist(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n address account,\\n bool whitelisted\\n ) external;\\n\\n function isBlacklistBorrowingAgainstCollateralWhitelisted(\\n address cTokenBorrow,\\n address cTokenCollateral,\\n address account\\n ) external view returns (bool);\\n\\n function isSupplyCapWhitelisted(address cToken, address account) external view returns (bool);\\n\\n function _borrowCapWhitelist(address cToken, address account, bool whitelisted) external;\\n\\n function isBorrowCapWhitelisted(address cToken, address account) external view returns (bool);\\n\\n function _removeFlywheel(address flywheelAddress) external returns (bool);\\n\\n function getWhitelist() external view returns (address[] memory);\\n\\n function addNonAccruingFlywheel(address flywheelAddress) external returns (bool);\\n\\n function _setMarketSupplyCaps(ICErc20[] calldata cTokens, uint256[] calldata newSupplyCaps) external;\\n\\n function _setMarketBorrowCaps(ICErc20[] calldata cTokens, uint256[] calldata newBorrowCaps) external;\\n\\n function _setBorrowCapGuardian(address newBorrowCapGuardian) external;\\n\\n function _setPauseGuardian(address newPauseGuardian) external returns (uint256);\\n\\n function _setMintPaused(ICErc20 cToken, bool state) external returns (bool);\\n\\n function _setBorrowPaused(ICErc20 cToken, bool state) external returns (bool);\\n\\n function _setTransferPaused(bool state) external returns (bool);\\n\\n function _setSeizePaused(bool state) external returns (bool);\\n\\n function _unsupportMarket(ICErc20 cToken) external returns (uint256);\\n\\n function getAssetAsCollateralValueCap(\\n ICErc20 collateral,\\n ICErc20 cTokenModify,\\n bool redeeming,\\n address account\\n ) external view returns (uint256);\\n\\n function registerInSFS() external returns (uint256);\\n}\\n\\ninterface ComptrollerPrudentiaCapsExtInterface {\\n /**\\n * @notice Retrieves Adrastia Prudentia borrow cap config from storage.\\n * @return The config.\\n */\\n function getBorrowCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory);\\n\\n /**\\n * @notice Retrieves Adrastia Prudentia supply cap config from storage.\\n * @return The config.\\n */\\n function getSupplyCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory);\\n\\n /**\\n * @notice Sets the Adrastia Prudentia supply cap config.\\n * @dev Specifying a zero address for the `controller` parameter will make the Comptroller use the native supply caps.\\n * @param newConfig The new config.\\n */\\n function _setSupplyCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external;\\n\\n /**\\n * @notice Sets the Adrastia Prudentia supply cap config.\\n * @dev Specifying a zero address for the `controller` parameter will make the Comptroller use the native borrow caps.\\n * @param newConfig The new config.\\n */\\n function _setBorrowCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external;\\n}\\n\\ninterface UnitrollerInterface {\\n function comptrollerImplementation() external view returns (address);\\n\\n function _upgrade() external;\\n\\n function _acceptAdmin() external returns (uint256);\\n\\n function _setPendingAdmin(address newPendingAdmin) external returns (uint256);\\n\\n function _toggleAdminRights(bool hasRights) external returns (uint256);\\n}\\n\\ninterface IComptrollerExtension is ComptrollerExtensionInterface, ComptrollerStorageInterface {}\\n\\n//interface IComptrollerBase is ComptrollerInterface, ComptrollerStorageInterface {}\\n\\ninterface IonicComptroller is\\n ComptrollerInterface,\\n ComptrollerExtensionInterface,\\n UnitrollerInterface,\\n ComptrollerStorageInterface\\n{\\n\\n}\\n\\nabstract contract ComptrollerBase is ComptrollerV4Storage {\\n /// @notice Indicator that this is a Comptroller contract (for inspection)\\n bool public constant isComptroller = true;\\n\\n /**\\n * @notice Gets the supply cap of a cToken in the units of the underlying asset.\\n * @param cToken The address of the cToken.\\n */\\n function effectiveSupplyCaps(address cToken) public view virtual returns (uint256 supplyCap) {\\n PrudentiaLib.PrudentiaConfig memory capConfig = supplyCapConfig;\\n\\n // Check if we're using Adrastia Prudentia for the supply cap\\n if (capConfig.controller != address(0)) {\\n // We have a controller, so we're using Adrastia Prudentia\\n\\n address underlyingToken = ICErc20(cToken).underlying();\\n\\n // Get the supply cap from Adrastia Prudentia\\n supplyCap = IHistoricalRates(capConfig.controller).getRateAt(underlyingToken, capConfig.offset).current;\\n\\n // Prudentia trims decimal points from amounts while our code requires the mantissa amount, so we\\n // must scale the supply cap to get the correct amount\\n\\n int256 scaleByDecimals = 18;\\n // Not all ERC20s implement decimals(), so we use a staticcall and check the return data\\n (bool success, bytes memory data) = underlyingToken.staticcall(abi.encodeWithSignature(\\\"decimals()\\\"));\\n if (success && data.length == 32) {\\n scaleByDecimals = int256(uint256(abi.decode(data, (uint8))));\\n }\\n\\n scaleByDecimals += capConfig.decimalShift;\\n\\n if (scaleByDecimals >= 0) {\\n // We're scaling up, so we need to multiply\\n supplyCap *= 10 ** uint256(scaleByDecimals);\\n } else {\\n // We're scaling down, so we need to divide\\n supplyCap /= 10 ** uint256(-scaleByDecimals);\\n }\\n } else {\\n // We don't have a controller, so we're using the local supply cap\\n\\n // Get the supply cap from the local supply cap\\n supplyCap = supplyCaps[cToken];\\n }\\n }\\n\\n /**\\n * @notice Gets the borrow cap of a cToken in the units of the underlying asset.\\n * @param cToken The address of the cToken.\\n */\\n function effectiveBorrowCaps(address cToken) public view virtual returns (uint256 borrowCap) {\\n PrudentiaLib.PrudentiaConfig memory capConfig = borrowCapConfig;\\n\\n // Check if we're using Adrastia Prudentia for the borrow cap\\n if (capConfig.controller != address(0)) {\\n // We have a controller, so we're using Adrastia Prudentia\\n\\n address underlyingToken = ICErc20(cToken).underlying();\\n\\n // Get the borrow cap from Adrastia Prudentia\\n borrowCap = IHistoricalRates(capConfig.controller).getRateAt(underlyingToken, capConfig.offset).current;\\n\\n // Prudentia trims decimal points from amounts while our code requires the mantissa amount, so we\\n // must scale the supply cap to get the correct amount\\n\\n int256 scaleByDecimals = 18;\\n // Not all ERC20s implement decimals(), so we use a staticcall and check the return data\\n (bool success, bytes memory data) = underlyingToken.staticcall(abi.encodeWithSignature(\\\"decimals()\\\"));\\n if (success && data.length == 32) {\\n scaleByDecimals = int256(uint256(abi.decode(data, (uint8))));\\n }\\n\\n scaleByDecimals += capConfig.decimalShift;\\n\\n if (scaleByDecimals >= 0) {\\n // We're scaling up, so we need to multiply\\n borrowCap *= 10 ** uint256(scaleByDecimals);\\n } else {\\n // We're scaling down, so we need to divide\\n borrowCap /= 10 ** uint256(-scaleByDecimals);\\n }\\n } else {\\n // We don't have a controller, so we're using the local borrow cap\\n borrowCap = borrowCaps[cToken];\\n }\\n }\\n}\\n\",\"keccak256\":\"0x266ec3c26b454cfa72bab45fa8e0bc9e3d44e8ec0cd4770304a14cc84c8f80d3\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/ComptrollerStorage.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport \\\"./IFeeDistributor.sol\\\";\\nimport \\\"../oracles/BasePriceOracle.sol\\\";\\nimport { ICErc20 } from \\\"./CTokenInterfaces.sol\\\";\\nimport { PrudentiaLib } from \\\"../adrastia/PrudentiaLib.sol\\\";\\n\\nimport \\\"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\\\";\\n\\ncontract UnitrollerAdminStorage {\\n /*\\n * Administrator for Ionic\\n */\\n address payable public ionicAdmin;\\n\\n /**\\n * @notice Administrator for this contract\\n */\\n address public admin;\\n\\n /**\\n * @notice Pending administrator for this contract\\n */\\n address public pendingAdmin;\\n\\n /**\\n * @notice Whether or not the Ionic admin has admin rights\\n */\\n bool public ionicAdminHasRights = true;\\n\\n /**\\n * @notice Whether or not the admin has admin rights\\n */\\n bool public adminHasRights = true;\\n\\n /**\\n * @notice Returns a boolean indicating if the sender has admin rights\\n */\\n function hasAdminRights() internal view returns (bool) {\\n return (msg.sender == admin && adminHasRights) || (msg.sender == address(ionicAdmin) && ionicAdminHasRights);\\n }\\n}\\n\\ncontract ComptrollerV1Storage is UnitrollerAdminStorage {\\n /**\\n * @notice Oracle which gives the price of any given asset\\n */\\n BasePriceOracle public oracle;\\n\\n /**\\n * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow\\n */\\n uint256 public closeFactorMantissa;\\n\\n /**\\n * @notice Multiplier representing the discount on collateral that a liquidator receives\\n */\\n uint256 public liquidationIncentiveMantissa;\\n\\n /*\\n * UNUSED AFTER UPGRADE: Max number of assets a single account can participate in (borrow or use as collateral)\\n */\\n uint256 internal maxAssets;\\n\\n /**\\n * @notice Per-account mapping of \\\"assets you are in\\\", capped by maxAssets\\n */\\n mapping(address => ICErc20[]) public accountAssets;\\n}\\n\\ncontract ComptrollerV2Storage is ComptrollerV1Storage {\\n struct Market {\\n // Whether or not this market is listed\\n bool isListed;\\n // Multiplier representing the most one can borrow against their collateral in this market.\\n // For instance, 0.9 to allow borrowing 90% of collateral value.\\n // Must be between 0 and 1, and stored as a mantissa.\\n uint256 collateralFactorMantissa;\\n // Per-market mapping of \\\"accounts in this asset\\\"\\n mapping(address => bool) accountMembership;\\n }\\n\\n /**\\n * @notice Official mapping of cTokens -> Market metadata\\n * @dev Used e.g. to determine if a market is supported\\n */\\n mapping(address => Market) public markets;\\n\\n /// @notice A list of all markets\\n ICErc20[] public allMarkets;\\n\\n /**\\n * @dev Maps borrowers to booleans indicating if they have entered any markets\\n */\\n mapping(address => bool) internal borrowers;\\n\\n /// @notice A list of all borrowers who have entered markets\\n address[] public allBorrowers;\\n\\n // Indexes of borrower account addresses in the `allBorrowers` array\\n mapping(address => uint256) internal borrowerIndexes;\\n\\n /**\\n * @dev Maps suppliers to booleans indicating if they have ever supplied to any markets\\n */\\n mapping(address => bool) public suppliers;\\n\\n /// @notice All cTokens addresses mapped by their underlying token addresses\\n mapping(address => ICErc20) public cTokensByUnderlying;\\n\\n /// @notice Whether or not the supplier whitelist is enforced\\n bool public enforceWhitelist;\\n\\n /// @notice Maps addresses to booleans indicating if they are allowed to supply assets (i.e., mint cTokens)\\n mapping(address => bool) public whitelist;\\n\\n /// @notice An array of all whitelisted accounts\\n address[] public whitelistArray;\\n\\n // Indexes of account addresses in the `whitelistArray` array\\n mapping(address => uint256) internal whitelistIndexes;\\n\\n /**\\n * @notice The Pause Guardian can pause certain actions as a safety mechanism.\\n * Actions which allow users to remove their own assets cannot be paused.\\n * Liquidation / seizing / transfer can only be paused globally, not by market.\\n */\\n address public pauseGuardian;\\n bool public _mintGuardianPaused;\\n bool public _borrowGuardianPaused;\\n bool public transferGuardianPaused;\\n bool public seizeGuardianPaused;\\n mapping(address => bool) public mintGuardianPaused;\\n mapping(address => bool) public borrowGuardianPaused;\\n}\\n\\ncontract ComptrollerV3Storage is ComptrollerV2Storage {\\n /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.\\n /// @dev If Adrastia Prudentia is enabled, the values the borrow cap guardian sets are ignored.\\n address public borrowCapGuardian;\\n\\n /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing.\\n /// @dev If Adrastia Prudentia is enabled, this value is ignored. Use `effectiveBorrowCaps` instead.\\n mapping(address => uint256) public borrowCaps;\\n\\n /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying.\\n /// @dev If Adrastia Prudentia is enabled, this value is ignored. Use `effectiveSupplyCaps` instead.\\n mapping(address => uint256) public supplyCaps;\\n\\n /// @notice RewardsDistributor contracts to notify of flywheel changes.\\n address[] public rewardsDistributors;\\n\\n /// @dev Guard variable for pool-wide/cross-asset re-entrancy checks\\n bool internal _notEntered;\\n\\n /// @dev Whether or not _notEntered has been initialized\\n bool internal _notEnteredInitialized;\\n\\n /// @notice RewardsDistributor to list for claiming, but not to notify of flywheel changes.\\n address[] public nonAccruingRewardsDistributors;\\n\\n /// @dev cap for each user's borrows against specific assets - denominated in the borrowed asset\\n mapping(address => mapping(address => uint256)) public borrowCapForCollateral;\\n\\n /// @dev blacklist to disallow the borrowing of an asset against specific collateral\\n mapping(address => mapping(address => bool)) public borrowingAgainstCollateralBlacklist;\\n\\n /// @dev set of whitelisted accounts that are allowed to bypass the borrowing against specific collateral cap\\n mapping(address => mapping(address => EnumerableSet.AddressSet)) internal borrowCapForCollateralWhitelist;\\n\\n /// @dev set of whitelisted accounts that are allowed to bypass the borrow cap\\n mapping(address => mapping(address => EnumerableSet.AddressSet))\\n internal borrowingAgainstCollateralBlacklistWhitelist;\\n\\n /// @dev set of whitelisted accounts that are allowed to bypass the supply cap\\n mapping(address => EnumerableSet.AddressSet) internal supplyCapWhitelist;\\n\\n /// @dev set of whitelisted accounts that are allowed to bypass the borrow cap\\n mapping(address => EnumerableSet.AddressSet) internal borrowCapWhitelist;\\n}\\n\\ncontract ComptrollerV4Storage is ComptrollerV3Storage {\\n /// @dev Adrastia Prudentia config for controlling borrow caps.\\n PrudentiaLib.PrudentiaConfig internal borrowCapConfig;\\n\\n /// @dev Adrastia Prudentia config for controlling supply caps.\\n PrudentiaLib.PrudentiaConfig internal supplyCapConfig;\\n}\\n\",\"keccak256\":\"0xa4a8110e666a93c1228c914f1414131e0f3b93385826bb72f6f93d429e514286\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/ErrorReporter.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\ncontract ComptrollerErrorReporter {\\n enum Error {\\n NO_ERROR,\\n UNAUTHORIZED,\\n COMPTROLLER_MISMATCH,\\n INSUFFICIENT_SHORTFALL,\\n INSUFFICIENT_LIQUIDITY,\\n INVALID_CLOSE_FACTOR,\\n INVALID_COLLATERAL_FACTOR,\\n INVALID_LIQUIDATION_INCENTIVE,\\n MARKET_NOT_LISTED,\\n MARKET_ALREADY_LISTED,\\n MATH_ERROR,\\n NONZERO_BORROW_BALANCE,\\n PRICE_ERROR,\\n REJECTION,\\n SNAPSHOT_ERROR,\\n TOO_MANY_ASSETS,\\n TOO_MUCH_REPAY,\\n SUPPLIER_NOT_WHITELISTED,\\n BORROW_BELOW_MIN,\\n SUPPLY_ABOVE_MAX,\\n NONZERO_TOTAL_SUPPLY\\n }\\n\\n enum FailureInfo {\\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\\n ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,\\n ADD_REWARDS_DISTRIBUTOR_OWNER_CHECK,\\n EXIT_MARKET_BALANCE_OWED,\\n EXIT_MARKET_REJECTION,\\n TOGGLE_ADMIN_RIGHTS_OWNER_CHECK,\\n TOGGLE_AUTO_IMPLEMENTATIONS_ENABLED_OWNER_CHECK,\\n SET_CLOSE_FACTOR_OWNER_CHECK,\\n SET_CLOSE_FACTOR_VALIDATION,\\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\\n SET_COLLATERAL_FACTOR_NO_EXISTS,\\n SET_COLLATERAL_FACTOR_VALIDATION,\\n SET_COLLATERAL_FACTOR_WITHOUT_PRICE,\\n SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,\\n SET_LIQUIDATION_INCENTIVE_VALIDATION,\\n SET_PENDING_ADMIN_OWNER_CHECK,\\n SET_PENDING_IMPLEMENTATION_CONTRACT_CHECK,\\n SET_PENDING_IMPLEMENTATION_OWNER_CHECK,\\n SET_PRICE_ORACLE_OWNER_CHECK,\\n SET_WHITELIST_ENFORCEMENT_OWNER_CHECK,\\n SET_WHITELIST_STATUS_OWNER_CHECK,\\n SUPPORT_MARKET_EXISTS,\\n SUPPORT_MARKET_OWNER_CHECK,\\n SET_PAUSE_GUARDIAN_OWNER_CHECK,\\n UNSUPPORT_MARKET_OWNER_CHECK,\\n UNSUPPORT_MARKET_DOES_NOT_EXIST,\\n UNSUPPORT_MARKET_IN_USE\\n }\\n\\n /**\\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\\n **/\\n event Failure(uint256 error, uint256 info, uint256 detail);\\n\\n /**\\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\\n */\\n function fail(Error err, FailureInfo info) internal returns (uint256) {\\n emit Failure(uint256(err), uint256(info), 0);\\n\\n return uint256(err);\\n }\\n\\n /**\\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\\n */\\n function failOpaque(\\n Error err,\\n FailureInfo info,\\n uint256 opaqueError\\n ) internal returns (uint256) {\\n emit Failure(uint256(err), uint256(info), opaqueError);\\n\\n return uint256(err);\\n }\\n}\\n\\ncontract TokenErrorReporter {\\n enum Error {\\n NO_ERROR,\\n UNAUTHORIZED,\\n BAD_INPUT,\\n COMPTROLLER_REJECTION,\\n COMPTROLLER_CALCULATION_ERROR,\\n INTEREST_RATE_MODEL_ERROR,\\n INVALID_ACCOUNT_PAIR,\\n INVALID_CLOSE_AMOUNT_REQUESTED,\\n INVALID_COLLATERAL_FACTOR,\\n MATH_ERROR,\\n MARKET_NOT_FRESH,\\n MARKET_NOT_LISTED,\\n TOKEN_INSUFFICIENT_ALLOWANCE,\\n TOKEN_INSUFFICIENT_BALANCE,\\n TOKEN_INSUFFICIENT_CASH,\\n TOKEN_TRANSFER_IN_FAILED,\\n TOKEN_TRANSFER_OUT_FAILED,\\n UTILIZATION_ABOVE_MAX\\n }\\n\\n /*\\n * Note: FailureInfo (but not Error) is kept in alphabetical order\\n * This is because FailureInfo grows significantly faster, and\\n * the order of Error has some meaning, while the order of FailureInfo\\n * is entirely arbitrary.\\n */\\n enum FailureInfo {\\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\\n ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,\\n ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_TOTAL_IONIC_FEES_CALCULATION_FAILED,\\n ACCRUE_INTEREST_NEW_TOTAL_ADMIN_FEES_CALCULATION_FAILED,\\n ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,\\n BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\\n BORROW_ACCRUE_INTEREST_FAILED,\\n BORROW_CASH_NOT_AVAILABLE,\\n BORROW_FRESHNESS_CHECK,\\n BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\\n BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\\n BORROW_MARKET_NOT_LISTED,\\n BORROW_COMPTROLLER_REJECTION,\\n LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,\\n LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,\\n LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,\\n LIQUIDATE_COMPTROLLER_REJECTION,\\n LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,\\n LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,\\n LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,\\n LIQUIDATE_FRESHNESS_CHECK,\\n LIQUIDATE_LIQUIDATOR_IS_BORROWER,\\n LIQUIDATE_REPAY_BORROW_FRESH_FAILED,\\n LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,\\n LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,\\n LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,\\n LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,\\n LIQUIDATE_SEIZE_TOO_MUCH,\\n MINT_ACCRUE_INTEREST_FAILED,\\n MINT_COMPTROLLER_REJECTION,\\n MINT_EXCHANGE_CALCULATION_FAILED,\\n MINT_EXCHANGE_RATE_READ_FAILED,\\n MINT_FRESHNESS_CHECK,\\n MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\\n MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\\n MINT_TRANSFER_IN_FAILED,\\n MINT_TRANSFER_IN_NOT_POSSIBLE,\\n NEW_UTILIZATION_RATE_ABOVE_MAX,\\n REDEEM_ACCRUE_INTEREST_FAILED,\\n REDEEM_COMPTROLLER_REJECTION,\\n REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,\\n REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,\\n REDEEM_EXCHANGE_RATE_READ_FAILED,\\n REDEEM_FRESHNESS_CHECK,\\n REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\\n REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\\n REDEEM_TRANSFER_OUT_NOT_POSSIBLE,\\n WITHDRAW_IONIC_FEES_ACCRUE_INTEREST_FAILED,\\n WITHDRAW_IONIC_FEES_CASH_NOT_AVAILABLE,\\n WITHDRAW_IONIC_FEES_FRESH_CHECK,\\n WITHDRAW_IONIC_FEES_VALIDATION,\\n WITHDRAW_ADMIN_FEES_ACCRUE_INTEREST_FAILED,\\n WITHDRAW_ADMIN_FEES_CASH_NOT_AVAILABLE,\\n WITHDRAW_ADMIN_FEES_FRESH_CHECK,\\n WITHDRAW_ADMIN_FEES_VALIDATION,\\n REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,\\n REDUCE_RESERVES_ADMIN_CHECK,\\n REDUCE_RESERVES_CASH_NOT_AVAILABLE,\\n REDUCE_RESERVES_FRESH_CHECK,\\n REDUCE_RESERVES_VALIDATION,\\n REPAY_BEHALF_ACCRUE_INTEREST_FAILED,\\n REPAY_BORROW_ACCRUE_INTEREST_FAILED,\\n REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\\n REPAY_BORROW_COMPTROLLER_REJECTION,\\n REPAY_BORROW_FRESHNESS_CHECK,\\n REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\\n REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\\n REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,\\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\\n SET_COLLATERAL_FACTOR_VALIDATION,\\n SET_COMPTROLLER_OWNER_CHECK,\\n SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,\\n SET_INTEREST_RATE_MODEL_FRESH_CHECK,\\n SET_INTEREST_RATE_MODEL_OWNER_CHECK,\\n TOGGLE_ADMIN_RIGHTS_OWNER_CHECK,\\n SET_PENDING_ADMIN_OWNER_CHECK,\\n SET_ADMIN_FEE_ACCRUE_INTEREST_FAILED,\\n SET_ADMIN_FEE_ADMIN_CHECK,\\n SET_ADMIN_FEE_FRESH_CHECK,\\n SET_ADMIN_FEE_BOUNDS_CHECK,\\n SET_IONIC_FEE_ACCRUE_INTEREST_FAILED,\\n SET_IONIC_FEE_FRESH_CHECK,\\n SET_IONIC_FEE_BOUNDS_CHECK,\\n SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,\\n SET_RESERVE_FACTOR_ADMIN_CHECK,\\n SET_RESERVE_FACTOR_FRESH_CHECK,\\n SET_RESERVE_FACTOR_BOUNDS_CHECK,\\n TRANSFER_COMPTROLLER_REJECTION,\\n TRANSFER_NOT_ALLOWED,\\n TRANSFER_NOT_ENOUGH,\\n TRANSFER_TOO_MUCH,\\n ADD_RESERVES_ACCRUE_INTEREST_FAILED,\\n ADD_RESERVES_FRESH_CHECK,\\n ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE\\n }\\n\\n /**\\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\\n **/\\n event Failure(uint256 error, uint256 info, uint256 detail);\\n\\n /**\\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\\n */\\n function fail(Error err, FailureInfo info) internal returns (uint256) {\\n emit Failure(uint256(err), uint256(info), 0);\\n\\n return uint256(err);\\n }\\n\\n /**\\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\\n */\\n function failOpaque(\\n Error err,\\n FailureInfo info,\\n uint256 opaqueError\\n ) internal returns (uint256) {\\n emit Failure(uint256(err), uint256(info), opaqueError);\\n\\n return err == Error.COMPTROLLER_REJECTION ? 1000 + opaqueError : uint256(err);\\n }\\n}\\n\",\"keccak256\":\"0xad342553cda4d7b7e40678c636a406bc2785be2117a29d9b1cb52e747726745e\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/IFeeDistributor.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport \\\"../ionic/AuthoritiesRegistry.sol\\\";\\n\\ninterface IFeeDistributor {\\n function minBorrowEth() external view returns (uint256);\\n\\n function maxUtilizationRate() external view returns (uint256);\\n\\n function interestFeeRate() external view returns (uint256);\\n\\n function latestComptrollerImplementation(address oldImplementation) external view returns (address);\\n\\n function latestCErc20Delegate(uint8 delegateType)\\n external\\n view\\n returns (address cErc20Delegate, bytes memory becomeImplementationData);\\n\\n function latestPluginImplementation(address oldImplementation) external view returns (address);\\n\\n function getComptrollerExtensions(address comptroller) external view returns (address[] memory);\\n\\n function getCErc20DelegateExtensions(address cErc20Delegate) external view returns (address[] memory);\\n\\n function deployCErc20(\\n uint8 delegateType,\\n bytes calldata constructorData,\\n bytes calldata becomeImplData\\n ) external returns (address);\\n\\n function canCall(\\n address pool,\\n address user,\\n address target,\\n bytes4 functionSig\\n ) external view returns (bool);\\n\\n function authoritiesRegistry() external view returns (AuthoritiesRegistry);\\n\\n fallback() external payable;\\n\\n receive() external payable;\\n}\\n\",\"keccak256\":\"0xa822e2942e6a88851968d5f3bda48709713c84d556031a1dd3db5dfd06121d3e\",\"license\":\"UNLICENSED\"},\"contracts/src/compound/InterestRateModel.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\n/**\\n * @title Compound's InterestRateModel Interface\\n * @author Compound\\n */\\nabstract contract InterestRateModel {\\n /// @notice Indicator that this is an InterestRateModel contract (for inspection)\\n bool public constant isInterestRateModel = true;\\n\\n /**\\n * @notice Calculates the current borrow interest rate per block\\n * @param cash The total amount of cash the market has\\n * @param borrows The total amount of borrows the market has outstanding\\n * @param reserves The total amount of reserves the market has\\n * @return The borrow rate per block (as a percentage, and scaled by 1e18)\\n */\\n function getBorrowRate(\\n uint256 cash,\\n uint256 borrows,\\n uint256 reserves\\n ) public view virtual returns (uint256);\\n\\n /**\\n * @notice Calculates the current supply interest rate per block\\n * @param cash The total amount of cash the market has\\n * @param borrows The total amount of borrows the market has outstanding\\n * @param reserves The total amount of reserves the market has\\n * @param reserveFactorMantissa The current reserve factor the market has\\n * @return The supply rate per block (as a percentage, and scaled by 1e18)\\n */\\n function getSupplyRate(\\n uint256 cash,\\n uint256 borrows,\\n uint256 reserves,\\n uint256 reserveFactorMantissa\\n ) public view virtual returns (uint256);\\n}\\n\",\"keccak256\":\"0x587a54b49d48df2cd91583eac93ddde4e2849f79d0441f179bf835e9dffe24e9\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/AddressesProvider.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\nimport { SafeOwnableUpgradeable } from \\\"../ionic/SafeOwnableUpgradeable.sol\\\";\\n\\n/**\\n * @title AddressesProvider\\n * @notice The Addresses Provider serves as a central storage of system internal and external\\n * contract addresses that change between deploys and across chains\\n * @author Veliko Minkov \\n */\\ncontract AddressesProvider is SafeOwnableUpgradeable {\\n mapping(string => address) private _addresses;\\n mapping(address => Contract) public plugins;\\n mapping(address => Contract) public flywheelRewards;\\n mapping(address => RedemptionStrategy) public redemptionStrategiesConfig;\\n mapping(address => FundingStrategy) public fundingStrategiesConfig;\\n JarvisPool[] public jarvisPoolsConfig;\\n CurveSwapPool[] public curveSwapPoolsConfig;\\n mapping(address => mapping(address => address)) public balancerPoolForTokens;\\n\\n /// @dev Initializer to set the admin that can set and change contracts addresses\\n function initialize(address owner) public initializer {\\n __SafeOwnable_init(owner);\\n }\\n\\n /**\\n * @dev The contract address and a string that uniquely identifies the contract's interface\\n */\\n struct Contract {\\n address addr;\\n string contractInterface;\\n }\\n\\n struct RedemptionStrategy {\\n address addr;\\n string contractInterface;\\n address outputToken;\\n }\\n\\n struct FundingStrategy {\\n address addr;\\n string contractInterface;\\n address inputToken;\\n }\\n\\n struct JarvisPool {\\n address syntheticToken;\\n address collateralToken;\\n address liquidityPool;\\n uint256 expirationTime;\\n }\\n\\n struct CurveSwapPool {\\n address poolAddress;\\n address[] coins;\\n }\\n\\n /**\\n * @dev sets the address and contract interface ID of the flywheel for the reward token\\n * @param rewardToken the reward token address\\n * @param flywheelRewardsModule the flywheel rewards module address\\n * @param contractInterface a string that uniquely identifies the contract's interface\\n */\\n function setFlywheelRewards(\\n address rewardToken,\\n address flywheelRewardsModule,\\n string calldata contractInterface\\n ) public onlyOwner {\\n flywheelRewards[rewardToken] = Contract(flywheelRewardsModule, contractInterface);\\n }\\n\\n /**\\n * @dev sets the address and contract interface ID of the ERC4626 plugin for the asset\\n * @param asset the asset address\\n * @param plugin the ERC4626 plugin address\\n * @param contractInterface a string that uniquely identifies the contract's interface\\n */\\n function setPlugin(\\n address asset,\\n address plugin,\\n string calldata contractInterface\\n ) public onlyOwner {\\n plugins[asset] = Contract(plugin, contractInterface);\\n }\\n\\n /**\\n * @dev sets the address and contract interface ID of the redemption strategy for the asset\\n * @param asset the asset address\\n * @param strategy redemption strategy address\\n * @param contractInterface a string that uniquely identifies the contract's interface\\n */\\n function setRedemptionStrategy(\\n address asset,\\n address strategy,\\n string calldata contractInterface,\\n address outputToken\\n ) public onlyOwner {\\n redemptionStrategiesConfig[asset] = RedemptionStrategy(strategy, contractInterface, outputToken);\\n }\\n\\n function getRedemptionStrategy(address asset) public view returns (RedemptionStrategy memory) {\\n return redemptionStrategiesConfig[asset];\\n }\\n\\n /**\\n * @dev sets the address and contract interface ID of the funding strategy for the asset\\n * @param asset the asset address\\n * @param strategy funding strategy address\\n * @param contractInterface a string that uniquely identifies the contract's interface\\n */\\n function setFundingStrategy(\\n address asset,\\n address strategy,\\n string calldata contractInterface,\\n address inputToken\\n ) public onlyOwner {\\n fundingStrategiesConfig[asset] = FundingStrategy(strategy, contractInterface, inputToken);\\n }\\n\\n function getFundingStrategy(address asset) public view returns (FundingStrategy memory) {\\n return fundingStrategiesConfig[asset];\\n }\\n\\n /**\\n * @dev configures the Jarvis pool of a Jarvis synthetic token\\n * @param syntheticToken the synthetic token address\\n * @param collateralToken the collateral token address\\n * @param liquidityPool the liquidity pool address\\n * @param expirationTime the operation expiration time\\n */\\n function setJarvisPool(\\n address syntheticToken,\\n address collateralToken,\\n address liquidityPool,\\n uint256 expirationTime\\n ) public onlyOwner {\\n jarvisPoolsConfig.push(JarvisPool(syntheticToken, collateralToken, liquidityPool, expirationTime));\\n }\\n\\n function setCurveSwapPool(address poolAddress, address[] calldata coins) public onlyOwner {\\n curveSwapPoolsConfig.push(CurveSwapPool(poolAddress, coins));\\n }\\n\\n /**\\n * @dev Sets an address for an id replacing the address saved in the addresses map\\n * @param id The id\\n * @param newAddress The address to set\\n */\\n function setAddress(string calldata id, address newAddress) external onlyOwner {\\n _addresses[id] = newAddress;\\n }\\n\\n /**\\n * @dev Returns an address by id\\n * @return The address\\n */\\n function getAddress(string calldata id) public view returns (address) {\\n return _addresses[id];\\n }\\n\\n function getCurveSwapPools() public view returns (CurveSwapPool[] memory) {\\n return curveSwapPoolsConfig;\\n }\\n\\n function getJarvisPools() public view returns (JarvisPool[] memory) {\\n return jarvisPoolsConfig;\\n }\\n\\n function setBalancerPoolForTokens(\\n address inputToken,\\n address outputToken,\\n address pool\\n ) external onlyOwner {\\n balancerPoolForTokens[inputToken][outputToken] = pool;\\n }\\n\\n function getBalancerPoolForTokens(address inputToken, address outputToken) external view returns (address) {\\n return balancerPoolForTokens[inputToken][outputToken];\\n }\\n}\\n\",\"keccak256\":\"0xf48e9e8b2150408c1c6b68dd957226c342ba47396da792fdaa0922f539a7e163\",\"license\":\"AGPL-3.0-only\"},\"contracts/src/ionic/AuthoritiesRegistry.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport { PoolRolesAuthority } from \\\"../ionic/PoolRolesAuthority.sol\\\";\\nimport { SafeOwnableUpgradeable } from \\\"../ionic/SafeOwnableUpgradeable.sol\\\";\\nimport { IonicComptroller } from \\\"../compound/ComptrollerInterface.sol\\\";\\n\\nimport { TransparentUpgradeableProxy } from \\\"@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol\\\";\\n\\ncontract AuthoritiesRegistry is SafeOwnableUpgradeable {\\n mapping(address => PoolRolesAuthority) public poolsAuthorities;\\n PoolRolesAuthority public poolAuthLogic;\\n address public leveredPositionsFactory;\\n bool public noAuthRequired;\\n\\n function initialize(address _leveredPositionsFactory) public initializer {\\n __SafeOwnable_init(msg.sender);\\n leveredPositionsFactory = _leveredPositionsFactory;\\n poolAuthLogic = new PoolRolesAuthority();\\n }\\n\\n function reinitialize(address _leveredPositionsFactory) public onlyOwnerOrAdmin {\\n leveredPositionsFactory = _leveredPositionsFactory;\\n poolAuthLogic = new PoolRolesAuthority();\\n // for Neon the auth is not required\\n noAuthRequired = block.chainid == 245022934;\\n }\\n\\n function createPoolAuthority(address pool) public onlyOwner returns (PoolRolesAuthority auth) {\\n require(address(poolsAuthorities[pool]) == address(0), \\\"already created\\\");\\n\\n TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(address(poolAuthLogic), _getProxyAdmin(), \\\"\\\");\\n auth = PoolRolesAuthority(address(proxy));\\n auth.initialize(address(this));\\n poolsAuthorities[pool] = auth;\\n\\n auth.openPoolSupplierCapabilities(IonicComptroller(pool));\\n auth.setUserRole(address(this), auth.REGISTRY_ROLE(), true);\\n // sets the registry owner as the auth owner\\n reconfigureAuthority(pool);\\n }\\n\\n function reconfigureAuthority(address poolAddress) public {\\n IonicComptroller pool = IonicComptroller(poolAddress);\\n PoolRolesAuthority auth = poolsAuthorities[address(pool)];\\n\\n if (msg.sender != poolAddress || address(auth) != address(0)) {\\n require(address(auth) != address(0), \\\"no such authority\\\");\\n require(msg.sender == owner() || msg.sender == poolAddress, \\\"not owner or pool\\\");\\n\\n auth.configureRegistryCapabilities();\\n auth.configurePoolSupplierCapabilities(pool);\\n auth.configurePoolBorrowerCapabilities(pool);\\n // everyone can be a liquidator\\n auth.configureOpenPoolLiquidatorCapabilities(pool);\\n auth.configureLeveredPositionCapabilities(pool);\\n\\n if (auth.owner() != owner()) {\\n auth.setOwner(owner());\\n }\\n }\\n }\\n\\n function canCall(\\n address pool,\\n address user,\\n address target,\\n bytes4 functionSig\\n ) external view returns (bool) {\\n PoolRolesAuthority authorityForPool = poolsAuthorities[pool];\\n if (address(authorityForPool) == address(0)) {\\n return noAuthRequired;\\n } else {\\n // allow only if an auth exists and it allows the action\\n return authorityForPool.canCall(user, target, functionSig);\\n }\\n }\\n\\n function setUserRole(\\n address pool,\\n address user,\\n uint8 role,\\n bool enabled\\n ) external {\\n PoolRolesAuthority poolAuth = poolsAuthorities[pool];\\n\\n require(address(poolAuth) != address(0), \\\"auth does not exist\\\");\\n require(msg.sender == owner() || msg.sender == leveredPositionsFactory, \\\"not owner or factory\\\");\\n require(msg.sender != leveredPositionsFactory || role == poolAuth.LEVERED_POSITION_ROLE(), \\\"only lev pos role\\\");\\n\\n poolAuth.setUserRole(user, role, enabled);\\n }\\n}\\n\",\"keccak256\":\"0x98fc1f8a735b5759fc7524e3065ae322703d2771e7ec429e1cc9b60a4b1028dd\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/DiamondExtension.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\n/**\\n * @notice a base contract for logic extensions that use the diamond pattern storage\\n * to map the functions when looking up the extension contract to delegate to.\\n */\\nabstract contract DiamondExtension {\\n /**\\n * @return a list of all the function selectors that this logic extension exposes\\n */\\n function _getExtensionFunctions() external pure virtual returns (bytes4[] memory);\\n}\\n\\n// When no function exists for function called\\nerror FunctionNotFound(bytes4 _functionSelector);\\n\\n// When no extension exists for function called\\nerror ExtensionNotFound(bytes4 _functionSelector);\\n\\n// When the function is already added\\nerror FunctionAlreadyAdded(bytes4 _functionSelector, address _currentImpl);\\n\\nabstract contract DiamondBase {\\n /**\\n * @dev register a logic extension\\n * @param extensionToAdd the extension whose functions are to be added\\n * @param extensionToReplace the extension whose functions are to be removed/replaced\\n */\\n function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) external virtual;\\n\\n function _listExtensions() public view returns (address[] memory) {\\n return LibDiamond.listExtensions();\\n }\\n\\n fallback() external {\\n address extension = LibDiamond.getExtensionForFunction(msg.sig);\\n if (extension == address(0)) revert FunctionNotFound(msg.sig);\\n // Execute external function from extension using delegatecall and return any value.\\n assembly {\\n // copy function selector and any arguments\\n calldatacopy(0, 0, calldatasize())\\n // execute function call using the extension\\n let result := delegatecall(gas(), extension, 0, calldatasize(), 0, 0)\\n // get any return value\\n returndatacopy(0, 0, returndatasize())\\n // return any return value or error back to the caller\\n switch result\\n case 0 {\\n revert(0, returndatasize())\\n }\\n default {\\n return(0, returndatasize())\\n }\\n }\\n }\\n}\\n\\n/**\\n * @notice a library to use in a contract, whose logic is extended with diamond extension\\n */\\nlibrary LibDiamond {\\n bytes32 constant DIAMOND_STORAGE_POSITION = keccak256(\\\"diamond.extensions.diamond.storage\\\");\\n\\n struct Function {\\n address extension;\\n bytes4 selector;\\n }\\n\\n struct LogicStorage {\\n Function[] functions;\\n address[] extensions;\\n }\\n\\n function getExtensionForFunction(bytes4 msgSig) internal view returns (address) {\\n return getExtensionForSelector(msgSig, diamondStorage());\\n }\\n\\n function diamondStorage() internal pure returns (LogicStorage storage ds) {\\n bytes32 position = DIAMOND_STORAGE_POSITION;\\n assembly {\\n ds.slot := position\\n }\\n }\\n\\n function listExtensions() internal view returns (address[] memory) {\\n return diamondStorage().extensions;\\n }\\n\\n function registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) internal {\\n if (address(extensionToReplace) != address(0)) {\\n removeExtension(extensionToReplace);\\n }\\n addExtension(extensionToAdd);\\n }\\n\\n function removeExtension(DiamondExtension extension) internal {\\n LogicStorage storage ds = diamondStorage();\\n // remove all functions of the extension to replace\\n removeExtensionFunctions(extension);\\n for (uint8 i = 0; i < ds.extensions.length; i++) {\\n if (ds.extensions[i] == address(extension)) {\\n ds.extensions[i] = ds.extensions[ds.extensions.length - 1];\\n ds.extensions.pop();\\n }\\n }\\n }\\n\\n function addExtension(DiamondExtension extension) internal {\\n LogicStorage storage ds = diamondStorage();\\n for (uint8 i = 0; i < ds.extensions.length; i++) {\\n require(ds.extensions[i] != address(extension), \\\"extension already added\\\");\\n }\\n addExtensionFunctions(extension);\\n ds.extensions.push(address(extension));\\n }\\n\\n function removeExtensionFunctions(DiamondExtension extension) internal {\\n bytes4[] memory fnsToRemove = extension._getExtensionFunctions();\\n LogicStorage storage ds = diamondStorage();\\n for (uint16 i = 0; i < fnsToRemove.length; i++) {\\n bytes4 selectorToRemove = fnsToRemove[i];\\n // must never fail\\n assert(address(extension) == getExtensionForSelector(selectorToRemove, ds));\\n // swap with the last element in the selectorAtIndex array and remove the last element\\n uint16 indexToKeep = getIndexForSelector(selectorToRemove, ds);\\n ds.functions[indexToKeep] = ds.functions[ds.functions.length - 1];\\n ds.functions.pop();\\n }\\n }\\n\\n function addExtensionFunctions(DiamondExtension extension) internal {\\n bytes4[] memory fnsToAdd = extension._getExtensionFunctions();\\n LogicStorage storage ds = diamondStorage();\\n uint16 functionsCount = uint16(ds.functions.length);\\n for (uint256 functionsIndex = 0; functionsIndex < fnsToAdd.length; functionsIndex++) {\\n bytes4 selector = fnsToAdd[functionsIndex];\\n address oldImplementation = getExtensionForSelector(selector, ds);\\n if (oldImplementation != address(0)) revert FunctionAlreadyAdded(selector, oldImplementation);\\n ds.functions.push(Function(address(extension), selector));\\n functionsCount++;\\n }\\n }\\n\\n function getExtensionForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (address) {\\n uint256 fnsLen = ds.functions.length;\\n for (uint256 i = 0; i < fnsLen; i++) {\\n if (ds.functions[i].selector == selector) return ds.functions[i].extension;\\n }\\n\\n return address(0);\\n }\\n\\n function getIndexForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (uint16) {\\n uint16 fnsLen = uint16(ds.functions.length);\\n for (uint16 i = 0; i < fnsLen; i++) {\\n if (ds.functions[i].selector == selector) return i;\\n }\\n\\n return type(uint16).max;\\n }\\n}\\n\",\"keccak256\":\"0x6d33291928e3c255f0276fa465dcc5ea88d74a6562241a39ad2e52ae8abaf7bc\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/PoolRolesAuthority.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport { IonicComptroller, ComptrollerInterface } from \\\"../compound/ComptrollerInterface.sol\\\";\\nimport { ICErc20, CTokenSecondExtensionInterface, CTokenFirstExtensionInterface } from \\\"../compound/CTokenInterfaces.sol\\\";\\n\\nimport { RolesAuthority, Authority } from \\\"solmate/auth/authorities/RolesAuthority.sol\\\";\\n\\nimport \\\"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\\\";\\n\\ncontract PoolRolesAuthority is RolesAuthority, Initializable {\\n constructor() RolesAuthority(address(0), Authority(address(0))) {\\n _disableInitializers();\\n }\\n\\n function initialize(address _owner) public initializer {\\n owner = _owner;\\n authority = this;\\n }\\n\\n // up to 256 roles\\n uint8 public constant REGISTRY_ROLE = 0;\\n uint8 public constant SUPPLIER_ROLE = 1;\\n uint8 public constant BORROWER_ROLE = 2;\\n uint8 public constant LIQUIDATOR_ROLE = 3;\\n uint8 public constant LEVERED_POSITION_ROLE = 4;\\n\\n function configureRegistryCapabilities() external requiresAuth {\\n setRoleCapability(REGISTRY_ROLE, address(this), PoolRolesAuthority.configureRegistryCapabilities.selector, true);\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configurePoolSupplierCapabilities.selector,\\n true\\n );\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configurePoolBorrowerCapabilities.selector,\\n true\\n );\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configureClosedPoolLiquidatorCapabilities.selector,\\n true\\n );\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configureOpenPoolLiquidatorCapabilities.selector,\\n true\\n );\\n setRoleCapability(\\n REGISTRY_ROLE,\\n address(this),\\n PoolRolesAuthority.configureLeveredPositionCapabilities.selector,\\n true\\n );\\n setRoleCapability(REGISTRY_ROLE, address(this), RolesAuthority.setUserRole.selector, true);\\n }\\n\\n function openPoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {\\n _setPublicPoolSupplierCapabilities(pool, true);\\n }\\n\\n function closePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {\\n _setPublicPoolSupplierCapabilities(pool, false);\\n }\\n\\n function _setPublicPoolSupplierCapabilities(IonicComptroller pool, bool setPublic) internal {\\n setPublicCapability(address(pool), pool.enterMarkets.selector, setPublic);\\n setPublicCapability(address(pool), pool.exitMarket.selector, setPublic);\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n bytes4[] memory selectors = getSupplierMarketSelectors();\\n for (uint256 j = 0; j < selectors.length; j++) {\\n setPublicCapability(address(allMarkets[i]), selectors[j], setPublic);\\n }\\n }\\n }\\n\\n function configurePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {\\n _configurePoolSupplierCapabilities(pool, SUPPLIER_ROLE);\\n }\\n\\n function getSupplierMarketSelectors() internal pure returns (bytes4[] memory selectors) {\\n uint8 fnsCount = 6;\\n selectors = new bytes4[](fnsCount);\\n selectors[--fnsCount] = CTokenSecondExtensionInterface.mint.selector;\\n selectors[--fnsCount] = CTokenSecondExtensionInterface.redeem.selector;\\n selectors[--fnsCount] = CTokenSecondExtensionInterface.redeemUnderlying.selector;\\n selectors[--fnsCount] = CTokenFirstExtensionInterface.transfer.selector;\\n selectors[--fnsCount] = CTokenFirstExtensionInterface.transferFrom.selector;\\n selectors[--fnsCount] = CTokenFirstExtensionInterface.approve.selector;\\n\\n require(fnsCount == 0, \\\"use the correct array length\\\");\\n return selectors;\\n }\\n\\n function _configurePoolSupplierCapabilities(IonicComptroller pool, uint8 role) internal {\\n setRoleCapability(role, address(pool), pool.enterMarkets.selector, true);\\n setRoleCapability(role, address(pool), pool.exitMarket.selector, true);\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n bytes4[] memory selectors = getSupplierMarketSelectors();\\n for (uint256 j = 0; j < selectors.length; j++) {\\n setRoleCapability(role, address(allMarkets[i]), selectors[j], true);\\n }\\n }\\n }\\n\\n function openPoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {\\n _setPublicPoolBorrowerCapabilities(pool, true);\\n }\\n\\n function closePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {\\n _setPublicPoolBorrowerCapabilities(pool, false);\\n }\\n\\n function _setPublicPoolBorrowerCapabilities(IonicComptroller pool, bool setPublic) internal {\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].borrow.selector, setPublic);\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrow.selector, setPublic);\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, setPublic);\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].flash.selector, setPublic);\\n }\\n }\\n\\n function configurePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {\\n // borrowers have the SUPPLIER_ROLE capabilities by default\\n _configurePoolSupplierCapabilities(pool, BORROWER_ROLE);\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true);\\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true);\\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, true);\\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true);\\n }\\n }\\n\\n function configureClosedPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth {\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, false);\\n setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true);\\n setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true);\\n }\\n }\\n\\n function configureOpenPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth {\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true);\\n // TODO this leaves redeeming open for everyone\\n setPublicCapability(address(allMarkets[i]), allMarkets[i].redeem.selector, true);\\n }\\n }\\n\\n function configureLeveredPositionCapabilities(IonicComptroller pool) external requiresAuth {\\n setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.enterMarkets.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.exitMarket.selector, true);\\n ICErc20[] memory allMarkets = pool.getAllMarkets();\\n for (uint256 i = 0; i < allMarkets.length; i++) {\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].mint.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeemUnderlying.selector, true);\\n\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true);\\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x233d26db3755cf0c7bf0bba3a695a742bbfc15fd168fb76bbe307c5ac259b5bf\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/SafeOwnableUpgradeable.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport \\\"@openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol\\\";\\n\\n/**\\n * @dev Ownable extension that requires a two-step process of setting the pending owner and the owner accepting it.\\n * @notice Existing OwnableUpgradeable contracts cannot be upgraded due to the extra storage variable\\n * that will shift the other.\\n */\\nabstract contract SafeOwnableUpgradeable is OwnableUpgradeable {\\n /**\\n * @notice Pending owner of this contract\\n */\\n address public pendingOwner;\\n\\n function __SafeOwnable_init(address owner_) internal onlyInitializing {\\n __Ownable_init();\\n _transferOwnership(owner_);\\n }\\n\\n struct AddressSlot {\\n address value;\\n }\\n\\n modifier onlyOwnerOrAdmin() {\\n bool isOwner = owner() == _msgSender();\\n if (!isOwner) {\\n address admin = _getProxyAdmin();\\n bool isAdmin = admin == _msgSender();\\n require(isAdmin, \\\"Ownable: caller is neither the owner nor the admin\\\");\\n }\\n _;\\n }\\n\\n /**\\n * @notice Emitted when pendingOwner is changed\\n */\\n event NewPendingOwner(address oldPendingOwner, address newPendingOwner);\\n\\n /**\\n * @notice Emitted when pendingOwner is accepted, which means owner is updated\\n */\\n event NewOwner(address oldOwner, address newOwner);\\n\\n /**\\n * @notice Begins transfer of owner rights. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\\n * @dev Owner function to begin change of owner. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\\n * @param newPendingOwner New pending owner.\\n */\\n function _setPendingOwner(address newPendingOwner) public onlyOwner {\\n // Save current value, if any, for inclusion in log\\n address oldPendingOwner = pendingOwner;\\n\\n // Store pendingOwner with value newPendingOwner\\n pendingOwner = newPendingOwner;\\n\\n // Emit NewPendingOwner(oldPendingOwner, newPendingOwner)\\n emit NewPendingOwner(oldPendingOwner, newPendingOwner);\\n }\\n\\n /**\\n * @notice Accepts transfer of owner rights. msg.sender must be pendingOwner\\n * @dev Owner function for pending owner to accept role and update owner\\n */\\n function _acceptOwner() public {\\n // Check caller is pendingOwner and pendingOwner \\u2260 address(0)\\n require(msg.sender == pendingOwner, \\\"not the pending owner\\\");\\n\\n // Save current values for inclusion in log\\n address oldOwner = owner();\\n address oldPendingOwner = pendingOwner;\\n\\n // Store owner with value pendingOwner\\n _transferOwnership(pendingOwner);\\n\\n // Clear the pending value\\n pendingOwner = address(0);\\n\\n emit NewOwner(oldOwner, pendingOwner);\\n emit NewPendingOwner(oldPendingOwner, pendingOwner);\\n }\\n\\n function renounceOwnership() public override onlyOwner {\\n // do not remove this overriding fn\\n revert(\\\"not used anymore\\\");\\n }\\n\\n function transferOwnership(address newOwner) public override onlyOwner {\\n emit NewPendingOwner(pendingOwner, newOwner);\\n pendingOwner = newOwner;\\n }\\n\\n function _getProxyAdmin() internal view returns (address admin) {\\n bytes32 _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\\n AddressSlot storage adminSlot;\\n assembly {\\n adminSlot.slot := _ADMIN_SLOT\\n }\\n admin = adminSlot.value;\\n }\\n}\\n\",\"keccak256\":\"0x74641db987b6d12c8c412818b8a7708332778736193b2cb127ea54e80b334186\",\"license\":\"UNLICENSED\"},\"contracts/src/ionic/strategies/IonicERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\nimport { FixedPointMathLib } from \\\"solmate/utils/FixedPointMathLib.sol\\\";\\n\\nimport { PausableUpgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/security/PausableUpgradeable.sol\\\";\\nimport { ERC4626Upgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol\\\";\\nimport { ERC20Upgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\\\";\\nimport { SafeERC20Upgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\\\";\\n\\nimport { SafeOwnableUpgradeable } from \\\"../../ionic/SafeOwnableUpgradeable.sol\\\";\\n\\nabstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, ERC4626Upgradeable {\\n using FixedPointMathLib for uint256;\\n using SafeERC20Upgradeable for ERC20Upgradeable;\\n\\n /* ========== STATE VARIABLES ========== */\\n\\n uint256 public vaultShareHWM;\\n uint256 public performanceFee;\\n address public feeRecipient;\\n\\n /* ========== EVENTS ========== */\\n\\n event UpdatedFeeSettings(\\n uint256 oldPerformanceFee,\\n uint256 newPerformanceFee,\\n address oldFeeRecipient,\\n address newFeeRecipient\\n );\\n\\n event UpdatedRewardsRecipient(address oldRewardsRecipient, address newRewardsRecipient);\\n\\n /* ========== INITIALIZER ========== */\\n\\n function __IonicER4626_init(ERC20Upgradeable asset_) internal onlyInitializing {\\n __SafeOwnable_init(msg.sender);\\n __Pausable_init();\\n __Context_init();\\n __ERC20_init(\\n string(abi.encodePacked(\\\"Ionic \\\", asset_.name(), \\\" Vault\\\")),\\n string(abi.encodePacked(\\\"iv\\\", asset_.symbol()))\\n );\\n __ERC4626_init(asset_);\\n\\n vaultShareHWM = 10 ** asset_.decimals();\\n feeRecipient = msg.sender;\\n }\\n\\n function _asset() internal view returns (ERC20Upgradeable) {\\n return ERC20Upgradeable(super.asset());\\n }\\n\\n /* ========== DEPOSIT/WITHDRAW FUNCTIONS ========== */\\n\\n function deposit(uint256 assets, address receiver) public override whenNotPaused returns (uint256 shares) {\\n // Check for rounding error since we round down in previewDeposit.\\n require((shares = previewDeposit(assets)) != 0, \\\"ZERO_SHARES\\\");\\n\\n // Need to transfer before minting or ERC777s could reenter.\\n _asset().safeTransferFrom(msg.sender, address(this), assets);\\n\\n _mint(receiver, shares);\\n\\n emit Deposit(msg.sender, receiver, assets, shares);\\n\\n afterDeposit(assets, shares);\\n }\\n\\n function mint(uint256 shares, address receiver) public override whenNotPaused returns (uint256 assets) {\\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\\n\\n // Need to transfer before minting or ERC777s could reenter.\\n _asset().safeTransferFrom(msg.sender, address(this), assets);\\n\\n _mint(receiver, shares);\\n\\n emit Deposit(msg.sender, receiver, assets, shares);\\n\\n afterDeposit(assets, shares);\\n }\\n\\n function withdraw(uint256 assets, address receiver, address owner) public override returns (uint256 shares) {\\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\\n\\n if (msg.sender != owner) {\\n uint256 allowed = allowance(owner, msg.sender); // Saves gas for limited approvals.\\n\\n if (allowed != type(uint256).max) _approve(owner, msg.sender, allowed - shares);\\n }\\n\\n if (!paused()) {\\n uint256 balanceBeforeWithdraw = _asset().balanceOf(address(this));\\n\\n beforeWithdraw(assets, shares);\\n\\n assets = _asset().balanceOf(address(this)) - balanceBeforeWithdraw;\\n }\\n\\n _burn(owner, shares);\\n\\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\\n\\n _asset().safeTransfer(receiver, assets);\\n }\\n\\n function redeem(uint256 shares, address receiver, address owner) public override returns (uint256 assets) {\\n if (msg.sender != owner) {\\n uint256 allowed = allowance(owner, msg.sender); // Saves gas for limited approvals.\\n\\n if (allowed != type(uint256).max) _approve(owner, msg.sender, allowed - shares);\\n }\\n\\n // Check for rounding error since we round down in previewRedeem.\\n require((assets = previewRedeem(shares)) != 0, \\\"ZERO_ASSETS\\\");\\n\\n if (!paused()) {\\n uint256 balanceBeforeWithdraw = _asset().balanceOf(address(this));\\n\\n beforeWithdraw(assets, shares);\\n\\n assets = _asset().balanceOf(address(this)) - balanceBeforeWithdraw;\\n }\\n\\n _burn(owner, shares);\\n\\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\\n\\n _asset().safeTransfer(receiver, assets);\\n }\\n\\n /* ========== FEE FUNCTIONS ========== */\\n\\n /**\\n * @notice Take the performance fee that has accrued since last fee harvest.\\n * @dev Performance fee is based on a vault share high water mark value. If vault share value has increased above the\\n * HWM in a fee period, issue fee shares to the vault equal to the performance fee.\\n */\\n function takePerformanceFee() external onlyOwner {\\n require(feeRecipient != address(0), \\\"fee recipient not initialized\\\");\\n\\n uint256 currentAssets = totalAssets();\\n uint256 shareValue = convertToAssets(10 ** _asset().decimals());\\n\\n require(shareValue > vaultShareHWM, \\\"shareValue !> vaultShareHWM\\\");\\n // cache value\\n uint256 supply = totalSupply();\\n\\n uint256 accruedPerformanceFee = (performanceFee * (shareValue - vaultShareHWM) * supply) / 1e36;\\n _mint(feeRecipient, accruedPerformanceFee.mulDivDown(supply, (currentAssets - accruedPerformanceFee)));\\n\\n vaultShareHWM = convertToAssets(10 ** _asset().decimals());\\n }\\n\\n /**\\n * @notice Transfer accrued fees to rewards manager contract. Caller must be a registered keeper.\\n * @dev We must make sure that feeRecipient is not address(0) before withdrawing fees\\n */\\n function withdrawAccruedFees() external onlyOwner {\\n redeem(balanceOf(feeRecipient), feeRecipient, feeRecipient);\\n }\\n\\n /**\\n * @notice Update performanceFee and/or feeRecipient\\n */\\n function updateFeeSettings(uint256 newPerformanceFee, address newFeeRecipient) external onlyOwner {\\n emit UpdatedFeeSettings(performanceFee, newPerformanceFee, feeRecipient, newFeeRecipient);\\n\\n performanceFee = newPerformanceFee;\\n\\n if (newFeeRecipient != feeRecipient) {\\n if (feeRecipient != address(0)) {\\n uint256 oldFees = balanceOf(feeRecipient);\\n\\n _burn(feeRecipient, oldFees);\\n _approve(feeRecipient, owner(), 0);\\n _mint(newFeeRecipient, oldFees);\\n }\\n\\n _approve(newFeeRecipient, owner(), type(uint256).max);\\n }\\n\\n feeRecipient = newFeeRecipient;\\n }\\n\\n /* ========== EMERGENCY FUNCTIONS ========== */\\n\\n // Should withdraw all funds from the strategy and pause the contract\\n function emergencyWithdrawAndPause() external virtual;\\n\\n function unpause() external virtual;\\n\\n function shutdown(address market) external onlyOwner whenPaused returns (uint256) {\\n ERC20Upgradeable theAsset = _asset();\\n uint256 endBalance = theAsset.balanceOf(address(this));\\n theAsset.transfer(market, endBalance);\\n return endBalance;\\n }\\n\\n /* ========== INTERNAL HOOKS LOGIC ========== */\\n\\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual;\\n\\n function afterDeposit(uint256 assets, uint256 shares) internal virtual;\\n}\\n\",\"keccak256\":\"0x1d5626eba320157d52a75cc2e86518bf82b5e8017efc42649094f3115b6a6927\",\"license\":\"AGPL-3.0-only\"},\"contracts/src/ionic/strategies/IonicMarketERC4626.sol\":{\"content\":\"// SPDX-License-Identifier: Unlicense\\npragma solidity ^0.8.22;\\nimport { IonicERC4626, ERC20Upgradeable } from \\\"./IonicERC4626.sol\\\";\\nimport { SafeERC20Upgradeable } from \\\"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\\\";\\nimport { ICErc20 } from \\\"../../compound/CTokenInterfaces.sol\\\";\\nimport { ComptrollerErrorReporter } from \\\"../../compound/ErrorReporter.sol\\\";\\n\\ninterface IonicFlywheelLensRouter_4626 {\\n function claimAllRewardTokens(address user) external returns (address[] memory, uint256[] memory);\\n}\\n\\ncontract IonicMarketERC4626 is IonicERC4626 {\\n using SafeERC20Upgradeable for ERC20Upgradeable;\\n\\n error IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error);\\n\\n // STATE VARIABLES\\n address public rewardsRecipient;\\n IonicFlywheelLensRouter_4626 public flywheelLensRouter;\\n ICErc20 public cToken;\\n\\n function initialize(\\n ICErc20 cToken_,\\n address flywheelLensRouter_,\\n address rewardsRecipient_\\n ) public initializer {\\n __IonicER4626_init(ERC20Upgradeable(cToken_.underlying()));\\n cToken = cToken_;\\n rewardsRecipient = rewardsRecipient_;\\n flywheelLensRouter = IonicFlywheelLensRouter_4626(flywheelLensRouter_);\\n }\\n\\n /* ========== VIEW FUNCTIONS ========== */\\n function totalAssets() public view virtual override returns (uint256) {\\n return cToken.balanceOfUnderlying(address(this));\\n }\\n\\n /// @notice maximum amount of underlying tokens that can be deposited into the underlying protocol\\n function maxDeposit(address) public view override returns (uint256) {\\n if (cToken.comptroller().mintGuardianPaused(address(cToken))) {\\n return 0;\\n }\\n\\n uint256 supplyCap = cToken.comptroller().supplyCaps(address(cToken));\\n if (supplyCap != 0) {\\n uint256 currentExchangeRate = cToken.exchangeRateCurrent();\\n uint256 _totalSupply = cToken.totalSupply();\\n uint256 totalSupplies = (_totalSupply * currentExchangeRate) / 1e18; /// exchange rate is scaled up by 1e18, so needs to be divided off to get accurate total supply\\n\\n // uint256 totalCash = MToken(address(mToken)).getCash();\\n // uint256 totalBorrows = MToken(address(mToken)).totalBorrows();\\n // uint256 totalReserves = MToken(address(mToken)).totalReserves();\\n\\n // // (Pseudocode) totalSupplies = totalCash + totalBorrows - totalReserves\\n // uint256 totalSupplies = (totalCash + totalBorrows) - totalReserves;\\n\\n // supply cap is 3\\n // total supplies is 1\\n /// no room for additional supplies\\n\\n // supply cap is 3\\n // total supplies is 0\\n /// room for 1 additional supplies\\n\\n // supply cap is 4\\n // total supplies is 1\\n /// room for 1 additional supplies\\n\\n /// total supplies could exceed supply cap as interest accrues, need to handle this edge case\\n /// going to subtract 2 from supply cap to account for rounding errors\\n if (totalSupplies + 2 >= supplyCap) {\\n return 0;\\n }\\n\\n return supplyCap - totalSupplies - 2;\\n }\\n\\n return type(uint256).max;\\n }\\n\\n /// @notice Returns the maximum amount of tokens that can be supplied\\n /// no way for this function to ever revert unless comptroller or mToken is broken\\n /// @dev accrue interest must be called before this function is called, otherwise\\n /// an outdated value will be fetched, and the returned value will be incorrect\\n /// (greater than actual amount available to be minted will be returned)\\n function maxMint(address) public view override returns (uint256) {\\n uint256 mintAmount = maxDeposit(address(0));\\n\\n return mintAmount == type(uint256).max ? mintAmount : convertToShares(mintAmount);\\n }\\n\\n /// @notice maximum amount of underlying tokens that can be withdrawn\\n /// @param owner The address that owns the shares\\n function maxWithdraw(address owner) public view override returns (uint256) {\\n uint256 cash = cToken.getCash();\\n uint256 assetsBalance = convertToAssets(balanceOf(owner));\\n return cash < assetsBalance ? cash : assetsBalance;\\n }\\n\\n /// @notice maximum amount of shares that can be withdrawn\\n /// @param owner The address that owns the shares\\n function maxRedeem(address owner) public view override returns (uint256) {\\n uint256 cash = cToken.getCash();\\n uint256 cashInShares = convertToShares(cash);\\n uint256 shareBalance = balanceOf(owner);\\n return cashInShares < shareBalance ? cashInShares : shareBalance;\\n }\\n\\n /* ========== REWARDS FUNCTIONS ========== */\\n\\n function updateRewardsRecipient(address newRewardsRecipient) external onlyOwner {\\n emit UpdatedRewardsRecipient(rewardsRecipient, newRewardsRecipient);\\n rewardsRecipient = newRewardsRecipient;\\n }\\n\\n function claimRewards() external {\\n (address[] memory tokens, uint256[] memory amounts) = flywheelLensRouter.claimAllRewardTokens(address(this));\\n for (uint256 i = 0; i < tokens.length; i++) {\\n _asset().safeTransfer(rewardsRecipient, amounts[i]);\\n }\\n }\\n\\n /* ========== EMERGENCY FUNCTIONS ========== */\\n\\n // Should withdraw all funds from the strategy and pause the contract\\n function emergencyWithdrawAndPause() external override onlyOwner {\\n _pause();\\n }\\n\\n function unpause() external override onlyOwner {\\n _unpause();\\n }\\n\\n /* ========== INTERNAL HOOKS LOGIC ========== */\\n\\n function beforeWithdraw(uint256 assets, uint256 /*shares*/) internal override {\\n /// -----------------------------------------------------------------------\\n /// Withdraw assets from Ionic\\n /// -----------------------------------------------------------------------\\n\\n uint256 errorCode = cToken.redeemUnderlying(assets);\\n if (errorCode != uint256(ComptrollerErrorReporter.Error.NO_ERROR)) {\\n revert IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error(errorCode));\\n }\\n }\\n\\n function afterDeposit(uint256 assets, uint256 /*shares*/) internal override {\\n /// -----------------------------------------------------------------------\\n /// Deposit assets into Ionic\\n /// -----------------------------------------------------------------------\\n\\n // approve to cToken\\n _asset().safeApprove(address(cToken), assets);\\n\\n // deposit into cToken\\n uint256 errorCode = cToken.mint(assets);\\n if (errorCode != uint256(ComptrollerErrorReporter.Error.NO_ERROR)) {\\n revert IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error(errorCode));\\n }\\n }\\n}\\n\",\"keccak256\":\"0x7e7102541f79cdad000e9de32145a080a1150dfad9b4b55ec87cb475c83d8858\",\"license\":\"Unlicense\"},\"contracts/src/oracles/BasePriceOracle.sol\":{\"content\":\"// SPDX-License-Identifier: UNLICENSED\\npragma solidity >=0.8.0;\\n\\nimport \\\"../compound/CTokenInterfaces.sol\\\";\\n\\n/**\\n * @title BasePriceOracle\\n * @notice Returns prices of underlying tokens directly without the caller having to specify a cToken address.\\n * @dev Implements the `PriceOracle` interface.\\n * @author David Lucid (https://github.com/davidlucid)\\n */\\ninterface BasePriceOracle {\\n /**\\n * @notice Get the price of an underlying asset.\\n * @param underlying The underlying asset to get the price of.\\n * @return The underlying asset price in ETH as a mantissa (scaled by 1e18).\\n * Zero means the price is unavailable.\\n */\\n function price(address underlying) external view returns (uint256);\\n\\n /**\\n * @notice Get the underlying price of a cToken asset\\n * @param cToken The cToken to get the underlying price of\\n * @return The underlying asset price mantissa (scaled by 1e18).\\n * Zero means the price is unavailable.\\n */\\n function getUnderlyingPrice(ICErc20 cToken) external view returns (uint256);\\n}\\n\",\"keccak256\":\"0xed2a27a8dc71a4280c0ef19d3165ff237d8066ae782e750b071bb39d12e73404\",\"license\":\"UNLICENSED\"},\"solmate/auth/Auth.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)\\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\\nabstract contract Auth {\\n event OwnerUpdated(address indexed user, address indexed newOwner);\\n\\n event AuthorityUpdated(address indexed user, Authority indexed newAuthority);\\n\\n address public owner;\\n\\n Authority public authority;\\n\\n constructor(address _owner, Authority _authority) {\\n owner = _owner;\\n authority = _authority;\\n\\n emit OwnerUpdated(msg.sender, _owner);\\n emit AuthorityUpdated(msg.sender, _authority);\\n }\\n\\n modifier requiresAuth() virtual {\\n require(isAuthorized(msg.sender, msg.sig), \\\"UNAUTHORIZED\\\");\\n\\n _;\\n }\\n\\n function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {\\n Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.\\n\\n // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be\\n // aware that this makes protected functions uncallable even to the owner if the authority is out of order.\\n return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;\\n }\\n\\n function setAuthority(Authority newAuthority) public virtual {\\n // We check if the caller is the owner first because we want to ensure they can\\n // always swap out the authority even if it's reverting or using up a lot of gas.\\n require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));\\n\\n authority = newAuthority;\\n\\n emit AuthorityUpdated(msg.sender, newAuthority);\\n }\\n\\n function setOwner(address newOwner) public virtual requiresAuth {\\n owner = newOwner;\\n\\n emit OwnerUpdated(msg.sender, newOwner);\\n }\\n}\\n\\n/// @notice A generic interface for a contract which provides authorization data to an Auth instance.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)\\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\\ninterface Authority {\\n function canCall(\\n address user,\\n address target,\\n bytes4 functionSig\\n ) external view returns (bool);\\n}\\n\",\"keccak256\":\"0xd5cf8213a40d727af89c93dd359ad68984c123c1a1a93fc9ad7ba62b3436fb75\",\"license\":\"AGPL-3.0-only\"},\"solmate/auth/authorities/RolesAuthority.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\nimport {Auth, Authority} from \\\"../Auth.sol\\\";\\n\\n/// @notice Role based Authority that supports up to 256 roles.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/authorities/RolesAuthority.sol)\\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-roles/blob/master/src/roles.sol)\\ncontract RolesAuthority is Auth, Authority {\\n /*//////////////////////////////////////////////////////////////\\n EVENTS\\n //////////////////////////////////////////////////////////////*/\\n\\n event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled);\\n\\n event PublicCapabilityUpdated(address indexed target, bytes4 indexed functionSig, bool enabled);\\n\\n event RoleCapabilityUpdated(uint8 indexed role, address indexed target, bytes4 indexed functionSig, bool enabled);\\n\\n /*//////////////////////////////////////////////////////////////\\n CONSTRUCTOR\\n //////////////////////////////////////////////////////////////*/\\n\\n constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}\\n\\n /*//////////////////////////////////////////////////////////////\\n ROLE/USER STORAGE\\n //////////////////////////////////////////////////////////////*/\\n\\n mapping(address => bytes32) public getUserRoles;\\n\\n mapping(address => mapping(bytes4 => bool)) public isCapabilityPublic;\\n\\n mapping(address => mapping(bytes4 => bytes32)) public getRolesWithCapability;\\n\\n function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) {\\n return (uint256(getUserRoles[user]) >> role) & 1 != 0;\\n }\\n\\n function doesRoleHaveCapability(\\n uint8 role,\\n address target,\\n bytes4 functionSig\\n ) public view virtual returns (bool) {\\n return (uint256(getRolesWithCapability[target][functionSig]) >> role) & 1 != 0;\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n AUTHORIZATION LOGIC\\n //////////////////////////////////////////////////////////////*/\\n\\n function canCall(\\n address user,\\n address target,\\n bytes4 functionSig\\n ) public view virtual override returns (bool) {\\n return\\n isCapabilityPublic[target][functionSig] ||\\n bytes32(0) != getUserRoles[user] & getRolesWithCapability[target][functionSig];\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n ROLE CAPABILITY CONFIGURATION LOGIC\\n //////////////////////////////////////////////////////////////*/\\n\\n function setPublicCapability(\\n address target,\\n bytes4 functionSig,\\n bool enabled\\n ) public virtual requiresAuth {\\n isCapabilityPublic[target][functionSig] = enabled;\\n\\n emit PublicCapabilityUpdated(target, functionSig, enabled);\\n }\\n\\n function setRoleCapability(\\n uint8 role,\\n address target,\\n bytes4 functionSig,\\n bool enabled\\n ) public virtual requiresAuth {\\n if (enabled) {\\n getRolesWithCapability[target][functionSig] |= bytes32(1 << role);\\n } else {\\n getRolesWithCapability[target][functionSig] &= ~bytes32(1 << role);\\n }\\n\\n emit RoleCapabilityUpdated(role, target, functionSig, enabled);\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n USER ROLE ASSIGNMENT LOGIC\\n //////////////////////////////////////////////////////////////*/\\n\\n function setUserRole(\\n address user,\\n uint8 role,\\n bool enabled\\n ) public virtual requiresAuth {\\n if (enabled) {\\n getUserRoles[user] |= bytes32(1 << role);\\n } else {\\n getUserRoles[user] &= ~bytes32(1 << role);\\n }\\n\\n emit UserRoleUpdated(user, role, enabled);\\n }\\n}\\n\",\"keccak256\":\"0x278247a2c5b0accb60af8d3749e34ab5d4436ee4f35a8fff301aaa25ab690762\",\"license\":\"AGPL-3.0-only\"},\"solmate/utils/FixedPointMathLib.sol\":{\"content\":\"// SPDX-License-Identifier: AGPL-3.0-only\\npragma solidity >=0.8.0;\\n\\n/// @notice Arithmetic library with operations for fixed-point numbers.\\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\\nlibrary FixedPointMathLib {\\n /*//////////////////////////////////////////////////////////////\\n SIMPLIFIED FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\\n\\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\\n }\\n\\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\\n }\\n\\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\\n }\\n\\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n LOW LEVEL FIXED POINT OPERATIONS\\n //////////////////////////////////////////////////////////////*/\\n\\n function mulDivDown(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n assembly {\\n // Store x * y in z for now.\\n z := mul(x, y)\\n\\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\\n revert(0, 0)\\n }\\n\\n // Divide z by the denominator.\\n z := div(z, denominator)\\n }\\n }\\n\\n function mulDivUp(\\n uint256 x,\\n uint256 y,\\n uint256 denominator\\n ) internal pure returns (uint256 z) {\\n assembly {\\n // Store x * y in z for now.\\n z := mul(x, y)\\n\\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\\n revert(0, 0)\\n }\\n\\n // First, divide z - 1 by the denominator and add 1.\\n // We allow z - 1 to underflow if z is 0, because we multiply the\\n // end result by 0 if z is zero, ensuring we return 0 if z is zero.\\n z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))\\n }\\n }\\n\\n function rpow(\\n uint256 x,\\n uint256 n,\\n uint256 scalar\\n ) internal pure returns (uint256 z) {\\n assembly {\\n switch x\\n case 0 {\\n switch n\\n case 0 {\\n // 0 ** 0 = 1\\n z := scalar\\n }\\n default {\\n // 0 ** n = 0\\n z := 0\\n }\\n }\\n default {\\n switch mod(n, 2)\\n case 0 {\\n // If n is even, store scalar in z for now.\\n z := scalar\\n }\\n default {\\n // If n is odd, store x in z for now.\\n z := x\\n }\\n\\n // Shifting right by 1 is like dividing by 2.\\n let half := shr(1, scalar)\\n\\n for {\\n // Shift n right by 1 before looping to halve it.\\n n := shr(1, n)\\n } n {\\n // Shift n right by 1 each iteration to halve it.\\n n := shr(1, n)\\n } {\\n // Revert immediately if x ** 2 would overflow.\\n // Equivalent to iszero(eq(div(xx, x), x)) here.\\n if shr(128, x) {\\n revert(0, 0)\\n }\\n\\n // Store x squared.\\n let xx := mul(x, x)\\n\\n // Round to the nearest number.\\n let xxRound := add(xx, half)\\n\\n // Revert if xx + half overflowed.\\n if lt(xxRound, xx) {\\n revert(0, 0)\\n }\\n\\n // Set x to scaled xxRound.\\n x := div(xxRound, scalar)\\n\\n // If n is even:\\n if mod(n, 2) {\\n // Compute z * x.\\n let zx := mul(z, x)\\n\\n // If z * x overflowed:\\n if iszero(eq(div(zx, x), z)) {\\n // Revert if x is non-zero.\\n if iszero(iszero(x)) {\\n revert(0, 0)\\n }\\n }\\n\\n // Round to the nearest number.\\n let zxRound := add(zx, half)\\n\\n // Revert if zx + half overflowed.\\n if lt(zxRound, zx) {\\n revert(0, 0)\\n }\\n\\n // Return properly scaled zxRound.\\n z := div(zxRound, scalar)\\n }\\n }\\n }\\n }\\n }\\n\\n /*//////////////////////////////////////////////////////////////\\n GENERAL NUMBER UTILITIES\\n //////////////////////////////////////////////////////////////*/\\n\\n function sqrt(uint256 x) internal pure returns (uint256 z) {\\n assembly {\\n let y := x // We start y at x, which will help us make our initial estimate.\\n\\n z := 181 // The \\\"correct\\\" value is 1, but this saves a multiplication later.\\n\\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\\n\\n // We check y >= 2^(k + 8) but shift right by k bits\\n // each branch to ensure that if x >= 256, then y >= 256.\\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\\n y := shr(128, y)\\n z := shl(64, z)\\n }\\n if iszero(lt(y, 0x1000000000000000000)) {\\n y := shr(64, y)\\n z := shl(32, z)\\n }\\n if iszero(lt(y, 0x10000000000)) {\\n y := shr(32, y)\\n z := shl(16, z)\\n }\\n if iszero(lt(y, 0x1000000)) {\\n y := shr(16, y)\\n z := shl(8, z)\\n }\\n\\n // Goal was to get z*z*y within a small factor of x. More iterations could\\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\\n\\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\\n\\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\\n\\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\\n\\n // There is no overflow risk here since y < 2^136 after the first branch above.\\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\\n\\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n z := shr(1, add(z, div(x, z)))\\n\\n // If x+1 is a perfect square, the Babylonian method cycles between\\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\\n z := sub(z, lt(div(x, z), z))\\n }\\n }\\n\\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n assembly {\\n // Mod x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n z := mod(x, y)\\n }\\n }\\n\\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\\n assembly {\\n // Divide x by y. Note this will return\\n // 0 instead of reverting if y is zero.\\n r := div(x, y)\\n }\\n }\\n\\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\\n assembly {\\n // Add 1 to x * y if x % y > 0. Note this will\\n // return 0 instead of reverting if y is zero.\\n z := add(gt(mod(x, y), 0), div(x, y))\\n }\\n }\\n}\\n\",\"keccak256\":\"0xab8ca9afbb0f7412e1408d4f111b53cc00813bc752236638ad336050ea2188f8\",\"license\":\"AGPL-3.0-only\"}},\"version\":1}", + "bytecode": "0x608060405234801561001057600080fd5b5061373a806100206000396000f3fe608060405234801561001057600080fd5b50600436106102bb5760003560e01c8063715018a611610182578063c0c53b8b116100e9578063dd62ed3e116100a2578063f2eb2a4b1161007c578063f2eb2a4b146105d3578063f2fde38b146105e6578063fc4d33f9146105f9578063ff2a7d301461060157600080fd5b8063dd62ed3e146105ad578063e30c3978146105c0578063ef8b30f71461056157600080fd5b8063c0c53b8b1461053b578063c63d75b61461054e578063c6e6f59214610561578063cce2f3fb14610574578063ce96cb7714610587578063d905777e1461059a57600080fd5b8063a9059cbb1161013b578063a9059cbb146104d4578063ada82c7d146104e7578063b3d7f6b9146104ef578063b460af9414610502578063ba08765214610515578063bb83b0e91461052857600080fd5b8063715018a614610484578063877887821461048c5780638da5cb5b1461049557806394bf804d146104a657806395d89b41146104b9578063a457c2d7146104c157600080fd5b806338d52e0f1161022657806356f89ef9116101df57806356f89ef9146104075780635c975abb1461040f57806369e527da146104215780636e553f65146104355780636e96dfd71461044857806370a082311461045b57600080fd5b806338d52e0f146103a157806339509351146103c65780633f4ba83a146103d9578063402d267d146103e157806346904840146103f45780634cdad506146102f057600080fd5b806318160ddd1161027857806318160ddd1461034e578063211493c91461035657806323b872dd1461035f5780632835797814610372578063313ce5671461037a578063372500ab1461039957600080fd5b806301e1d114146102c057806306fdde03146102db57806307a2d13a146102f0578063095ea7b3146103035780630a28a4771461032657806310509aa914610339575b600080fd5b6102c8610614565b6040519081526020015b60405180910390f35b6102e3610687565b6040516102d29190612eb0565b6102c86102fe366004612ee3565b610719565b610316610311366004612f11565b61072c565b60405190151581526020016102d2565b6102c8610334366004612ee3565b610744565b61034c610347366004612f3d565b610751565b005b6099546102c8565b6102c860fb5481565b61031661036d366004612f6d565b610877565b61034c61089d565b60c954600160a01b900460ff1660405160ff90911681526020016102d2565b61034c6108af565b60c9546001600160a01b03165b6040516001600160a01b0390911681526020016102d2565b6103166103d4366004612f11565b610988565b61034c6109aa565b6102c86103ef366004612fae565b6109ba565b60fd546103ae906001600160a01b031681565b61034c610cde565b606554600160a01b900460ff16610316565b610100546103ae906001600160a01b031681565b6102c8610443366004612f3d565b610eac565b61034c610456366004612fae565b610f78565b6102c8610469366004612fae565b6001600160a01b031660009081526097602052604090205490565b61034c610fe2565b6102c860fc5481565b6033546001600160a01b03166103ae565b6102c86104b4366004612f3d565b611025565b6102e36110a2565b6103166104cf366004612f11565b6110b1565b6103166104e2366004612f11565b611137565b61034c611145565b6102c86104fd366004612ee3565b611175565b6102c8610510366004612fcb565b611182565b6102c8610523366004612fcb565b61133b565b61034c610536366004612fae565b611532565b61034c61054936600461300d565b6115a3565b6102c861055c366004612fae565b611757565b6102c861056f366004612ee3565b61177d565b6102c8610582366004612fae565b61178a565b6102c8610595366004612fae565b611893565b6102c86105a8366004612fae565b61194d565b6102c86105bb36600461303d565b611a12565b6065546103ae906001600160a01b031681565b60ff546103ae906001600160a01b031681565b61034c6105f4366004612fae565b611a3d565b61034c611aae565b60fe546103ae906001600160a01b031681565b61010054604051633af9e66960e01b81523060048201526000916001600160a01b031690633af9e66990602401602060405180830381865afa15801561065e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610682919061306b565b905090565b6060609a805461069690613084565b80601f01602080910402602001604051908101604052809291908181526020018280546106c290613084565b801561070f5780601f106106e45761010080835404028352916020019161070f565b820191906000526020600020905b8154815290600101906020018083116106f257829003601f168201915b5050505050905090565b6000610726826000611bc2565b92915050565b60003361073a818585611bf5565b5060019392505050565b6000610726826001611d19565b610759611d4b565b60fc5460fd5460408051928352602083018590526001600160a01b0391821690830152821660608201527fb3b62da5184b9e7e2f5d280014bb485d4444b66738025e5fb5738bbddcb6b8489060800160405180910390a160fc82905560fd546001600160a01b038281169116146108545760fd546001600160a01b0316156108365760fd546001600160a01b0316600081815260976020526040902054906108019082611da5565b60fd5461082a906001600160a01b03166108236033546001600160a01b031690565b6000611bf5565b6108348282611ed9565b505b6108548161084c6033546001600160a01b031690565b600019611bf5565b60fd80546001600160a01b0319166001600160a01b039290921691909117905550565b600033610885858285611f9b565b61089085858561200f565b60019150505b9392505050565b6108a5611d4b565b6108ad6121ba565b565b60ff54604051639cf1fd5360e01b815230600482015260009182916001600160a01b0390911690639cf1fd53906024016000604051808303816000875af11580156108fe573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526109269190810190613198565b9150915060005b82518110156109835760fe54825161097b916001600160a01b03169084908490811061095b5761095b61325d565b602002602001015161096b61221a565b6001600160a01b0316919061222e565b60010161092d565b505050565b60003361073a81858561099b8383611a12565b6109a59190613289565b611bf5565b6109b2611d4b565b6108ad612291565b6101005460408051635fe3b56760e01b815290516000926001600160a01b031691635fe3b5679160048083019260209291908290030181865afa158015610a05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a29919061329c565b6101005460405163731f0c2b60e01b81526001600160a01b03918216600482015291169063731f0c2b90602401602060405180830381865afa158015610a73573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a9791906132b9565b15610aa457506000919050565b6101005460408051635fe3b56760e01b815290516000926001600160a01b031691635fe3b5679160048083019260209291908290030181865afa158015610aef573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b13919061329c565b610100546040516302c3bcbb60e01b81526001600160a01b0391821660048201529116906302c3bcbb90602401602060405180830381865afa158015610b5d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b81919061306b565b90508015610cd457610100546040805163bd6d894d60e01b815290516000926001600160a01b03169163bd6d894d9160048083019260209291908290030181865afa158015610bd4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf8919061306b565b9050600061010060009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c50573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c74919061306b565b90506000670de0b6b3a7640000610c8b84846132db565b610c959190613308565b905083610ca3826002613289565b10610cb45750600095945050505050565b6002610cc0828661332a565b610cca919061332a565b9695505050505050565b5060001992915050565b610ce6611d4b565b60fd546001600160a01b0316610d435760405162461bcd60e51b815260206004820152601d60248201527f66656520726563697069656e74206e6f7420696e697469616c697a656400000060448201526064015b60405180910390fd5b6000610d4d610614565b90506000610dc8610d5c61221a565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d99573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dbd919061333d565b6102fe90600a613444565b905060fb548111610e1b5760405162461bcd60e51b815260206004820152601b60248201527f736861726556616c756520213e207661756c74536861726548574d00000000006044820152606401610d3a565b6000610e2660995490565b905060006ec097ce7bc90715b34b9f10000000008260fb5485610e49919061332a565b60fc54610e5691906132db565b610e6091906132db565b610e6a9190613308565b60fd54909150610e98906001600160a01b0316610e9384610e8b858961332a565b8591906122cd565b611ed9565b610ea3610d5c61221a565b60fb5550505050565b6000610eb66122ec565b610ebf8361177d565b905080600003610eff5760405162461bcd60e51b815260206004820152600b60248201526a5a45524f5f53484152455360a81b6044820152606401610d3a565b610f1e333085610f0d61221a565b6001600160a01b0316929190612339565b610f288282611ed9565b60408051848152602081018390526001600160a01b0384169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a36107268382612371565b610f80611d4b565b606580546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b91015b60405180910390a15050565b610fea611d4b565b60405162461bcd60e51b815260206004820152601060248201526f6e6f74207573656420616e796d6f726560801b6044820152606401610d3a565b600061102f6122ec565b61103883611175565b9050611048333083610f0d61221a565b6110528284611ed9565b60408051828152602081018590526001600160a01b0384169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a36107268184612371565b6060609b805461069690613084565b600033816110bf8286611a12565b90508381101561111f5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610d3a565b61112c8286868403611bf5565b506001949350505050565b60003361073a81858561200f565b61114d611d4b565b60fd546001600160a01b0316600081815260976020526040902054611172918061133b565b50565b6000610726826001611bc2565b600061118d84610744565b9050336001600160a01b038316146111c75760006111ab8333611a12565b905060001981146111c5576111c583336109a5858561332a565b505b606554600160a01b900460ff166112d95760006111e261221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015611228573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124c919061306b565b90506112588583612441565b8061126161221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa1580156112a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112cb919061306b565b6112d5919061332a565b9450505b6112e38282611da5565b60408051858152602081018390526001600160a01b03808516929086169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4610896838561096b61221a565b6000336001600160a01b038316146113755760006113598333611a12565b905060001981146113735761137383336109a5888561332a565b505b61137e84610719565b9050806000036113be5760405162461bcd60e51b815260206004820152600b60248201526a5a45524f5f41535345545360a81b6044820152606401610d3a565b606554600160a01b900460ff166114d05760006113d961221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa15801561141f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611443919061306b565b905061144f8286612441565b8061145861221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa15801561149e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114c2919061306b565b6114cc919061332a565b9150505b6114da8285611da5565b60408051828152602081018690526001600160a01b03808516929086169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4610896838261096b61221a565b61153a611d4b565b60fe54604080516001600160a01b03928316815291831660208301527f2d9427f2d488d8f8716dae31ad2f0d476bcea0664cce8822d8dc76dde104b09e910160405180910390a160fe80546001600160a01b0319166001600160a01b0392909216919091179055565b600054610100900460ff16158080156115c35750600054600160ff909116105b806115dd5750303b1580156115dd575060005460ff166001145b6116405760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610d3a565b6000805460ff191660011790558015611663576000805461ff0019166101001790555b6116cd846001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116c8919061329c565b612474565b61010080546001600160a01b038087166001600160a01b03199283161790925560fe805485841690831617905560ff8054928616929091169190911790558015611751576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050565b60008061176460006109ba565b90506000198114610726576117788161177d565b610896565b6000610726826000611d19565b6000611794611d4b565b61179c612654565b60006117a661221a565b6040516370a0823160e01b81523060048201529091506000906001600160a01b038316906370a0823190602401602060405180830381865afa1580156117f0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611814919061306b565b60405163a9059cbb60e01b81526001600160a01b038681166004830152602482018390529192509083169063a9059cbb906044016020604051808303816000875af1158015611867573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061188b91906132b9565b509392505050565b60008061010060009054906101000a90046001600160a01b03166001600160a01b0316633b1d21a26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061190e919061306b565b905060006119346102fe856001600160a01b031660009081526097602052604090205490565b90508082106119435780611945565b815b949350505050565b60008061010060009054906101000a90046001600160a01b03166001600160a01b0316633b1d21a26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156119a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119c8919061306b565b905060006119d58261177d565b905060006119f8856001600160a01b031660009081526097602052604090205490565b9050808210611a075780611a09565b815b95945050505050565b6001600160a01b03918216600090815260986020908152604080832093909416825291909152205490565b611a45611d4b565b606554604080516001600160a01b03928316815291831660208301527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b910160405180910390a1606580546001600160a01b0319166001600160a01b0392909216919091179055565b6065546001600160a01b03163314611b005760405162461bcd60e51b81526020600482015260156024820152743737ba103a3432903832b73234b7339037bbb732b960591b6044820152606401610d3a565b6000611b146033546001600160a01b031690565b6065549091506001600160a01b0316611b2c816126a4565b606580546001600160a01b0319169055604080516001600160a01b0384168152600060208201527f70aea8d848e8a90fb7661b227dc522eb6395c3dac71b63cb59edd5c9899b2364910160405180910390a1606554604080516001600160a01b03808516825290921660208301527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b9101610fd6565b600080611bce60995490565b90508015611bef57611bea611be1610614565b859083866126f6565b611945565b83611945565b6001600160a01b038316611c575760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610d3a565b6001600160a01b038216611cb85760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610d3a565b6001600160a01b0383811660008181526098602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b600080611d2560995490565b9050831580611d32575080155b611bef57611bea81611d42610614565b869190866126f6565b6033546001600160a01b031633146108ad5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610d3a565b6001600160a01b038216611e055760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610d3a565b6001600160a01b03821660009081526097602052604090205481811015611e795760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610d3a565b6001600160a01b03831660008181526097602090815260408083208686039055609980548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6001600160a01b038216611f2f5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610d3a565b8060996000828254611f419190613289565b90915550506001600160a01b0382166000818152609760209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35b5050565b6000611fa78484611a12565b9050600019811461175157818110156120025760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610d3a565b6117518484848403611bf5565b6001600160a01b0383166120735760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610d3a565b6001600160a01b0382166120d55760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610d3a565b6001600160a01b0383166000908152609760205260409020548181101561214d5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610d3a565b6001600160a01b0380851660008181526097602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906121ad9086815260200190565b60405180910390a3611751565b6121c26122ec565b6065805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586121fd3390565b6040516001600160a01b03909116815260200160405180910390a1565b600061068260c9546001600160a01b031690565b6040516001600160a01b03831660248201526044810182905261098390849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612747565b612299612654565b6065805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa336121fd565b8282028115158415858304851417166122e557600080fd5b0492915050565b606554600160a01b900460ff16156108ad5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606401610d3a565b6040516001600160a01b03808516602483015283166044820152606481018290526117519085906323b872dd60e01b9060840161225a565b6101005461239b906001600160a01b03168361238b61221a565b6001600160a01b03169190612819565b6101005460405163140e25ad60e31b8152600481018490526000916001600160a01b03169063a0712d68906024015b6020604051808303816000875af11580156123e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061240d919061306b565b905080156109835780601481111561242757612427613453565b604051633172b7f760e11b8152600401610d3a9190613469565b6101005460405163852a12e360e01b8152600481018490526000916001600160a01b03169063852a12e3906024016123ca565b600054610100900460ff1661249b5760405162461bcd60e51b8152600401610d3a90613491565b6124a43361292e565b6124ac612966565b6124b4612995565b6125c6816001600160a01b03166306fdde036040518163ffffffff1660e01b8152600401600060405180830381865afa1580156124f5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261251d91908101906134dc565b60405160200161252d9190613570565b604051602081830303815290604052826001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa15801561257a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526125a291908101906134dc565b6040516020016125b291906135ae565b6040516020818303038152906040526129bc565b6125cf816129ed565b806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561260d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612631919061333d565b61263c90600a613444565b60fb555060fd80546001600160a01b03191633179055565b606554600160a01b900460ff166108ad5760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401610d3a565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600080612704868686612a1d565b9050600183600281111561271a5761271a613453565b148015612737575060008480612732576127326132f2565b868809115b15611a0957610cca600182613289565b600061279c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612acc9092919063ffffffff16565b80519091501561098357808060200190518101906127ba91906132b9565b6109835760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610d3a565b8015806128935750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa15801561286d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612891919061306b565b155b6128fe5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610d3a565b6040516001600160a01b03831660248201526044810182905261098390849063095ea7b360e01b9060640161225a565b600054610100900460ff166129555760405162461bcd60e51b8152600401610d3a90613491565b61295d612adb565b611172816126a4565b600054610100900460ff1661298d5760405162461bcd60e51b8152600401610d3a90613491565b6108ad612b0a565b600054610100900460ff166108ad5760405162461bcd60e51b8152600401610d3a90613491565b600054610100900460ff166129e35760405162461bcd60e51b8152600401610d3a90613491565b611f978282612b40565b600054610100900460ff16612a145760405162461bcd60e51b8152600401610d3a90613491565b61117281612b80565b6000808060001985870985870292508281108382030391505080600003612a5757838281612a4d57612a4d6132f2565b0492505050610896565b808411612a6357600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b60606119458484600085612c05565b600054610100900460ff16612b025760405162461bcd60e51b8152600401610d3a90613491565b6108ad612ce0565b600054610100900460ff16612b315760405162461bcd60e51b8152600401610d3a90613491565b6065805460ff60a01b19169055565b600054610100900460ff16612b675760405162461bcd60e51b8152600401610d3a90613491565b609a612b738382613628565b50609b6109838282613628565b600054610100900460ff16612ba75760405162461bcd60e51b8152600401610d3a90613491565b600080612bb383612d10565b9150915081612bc3576012612bc5565b805b60c980546001600160a01b039095166001600160a01b031960ff93909316600160a01b02929092166001600160a81b031990951694909417179092555050565b606082471015612c665760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610d3a565b600080866001600160a01b03168587604051612c8291906136e8565b60006040518083038185875af1925050503d8060008114612cbf576040519150601f19603f3d011682016040523d82523d6000602084013e612cc4565b606091505b5091509150612cd587838387612dee565b979650505050505050565b600054610100900460ff16612d075760405162461bcd60e51b8152600401610d3a90613491565b6108ad336126a4565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290516000918291829182916001600160a01b03871691612d57916136e8565b6000604051808303816000865af19150503d8060008114612d94576040519150601f19603f3d011682016040523d82523d6000602084013e612d99565b606091505b5091509150818015612dad57506020815110155b15612de157600081806020019051810190612dc8919061306b565b905060ff8111612ddf576001969095509350505050565b505b5060009485945092505050565b60608315612e5d578251600003612e56576001600160a01b0385163b612e565760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610d3a565b5081611945565b6119458383815115612e725781518083602001fd5b8060405162461bcd60e51b8152600401610d3a9190612eb0565b60005b83811015612ea7578181015183820152602001612e8f565b50506000910152565b6020815260008251806020840152612ecf816040850160208701612e8c565b601f01601f19169190910160400192915050565b600060208284031215612ef557600080fd5b5035919050565b6001600160a01b038116811461117257600080fd5b60008060408385031215612f2457600080fd5b8235612f2f81612efc565b946020939093013593505050565b60008060408385031215612f5057600080fd5b823591506020830135612f6281612efc565b809150509250929050565b600080600060608486031215612f8257600080fd5b8335612f8d81612efc565b92506020840135612f9d81612efc565b929592945050506040919091013590565b600060208284031215612fc057600080fd5b813561089681612efc565b600080600060608486031215612fe057600080fd5b833592506020840135612ff281612efc565b9150604084013561300281612efc565b809150509250925092565b60008060006060848603121561302257600080fd5b833561302d81612efc565b92506020840135612ff281612efc565b6000806040838503121561305057600080fd5b823561305b81612efc565b91506020830135612f6281612efc565b60006020828403121561307d57600080fd5b5051919050565b600181811c9082168061309857607f821691505b6020821081036130b857634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156130fd576130fd6130be565b604052919050565b600067ffffffffffffffff82111561311f5761311f6130be565b5060051b60200190565b600082601f83011261313a57600080fd5b8151602061314f61314a83613105565b6130d4565b8083825260208201915060208460051b87010193508684111561317157600080fd5b602086015b8481101561318d5780518352918301918301613176565b509695505050505050565b600080604083850312156131ab57600080fd5b825167ffffffffffffffff808211156131c357600080fd5b818501915085601f8301126131d757600080fd5b815160206131e761314a83613105565b82815260059290921b8401810191818101908984111561320657600080fd5b948201945b8386101561322d57855161321e81612efc565b8252948201949082019061320b565b9188015191965090935050508082111561324657600080fd5b5061325385828601613129565b9150509250929050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8082018082111561072657610726613273565b6000602082840312156132ae57600080fd5b815161089681612efc565b6000602082840312156132cb57600080fd5b8151801515811461089657600080fd5b808202811582820484141761072657610726613273565b634e487b7160e01b600052601260045260246000fd5b60008261332557634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561072657610726613273565b60006020828403121561334f57600080fd5b815160ff8116811461089657600080fd5b600181815b8085111561339b57816000190482111561338157613381613273565b8085161561338e57918102915b93841c9390800290613365565b509250929050565b6000826133b257506001610726565b816133bf57506000610726565b81600181146133d557600281146133df576133fb565b6001915050610726565b60ff8411156133f0576133f0613273565b50506001821b610726565b5060208310610133831016604e8410600b841016171561341e575081810a610726565b6134288383613360565b806000190482111561343c5761343c613273565b029392505050565b600061089660ff8416836133a3565b634e487b7160e01b600052602160045260246000fd5b602081016015831061348b57634e487b7160e01b600052602160045260246000fd5b91905290565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b6000602082840312156134ee57600080fd5b815167ffffffffffffffff8082111561350657600080fd5b818401915084601f83011261351a57600080fd5b81518181111561352c5761352c6130be565b61353f601f8201601f19166020016130d4565b915080825285602082850101111561355657600080fd5b613567816020840160208601612e8c565b50949350505050565b65024b7b734b1960d51b815260008251613591816006850160208701612e8c565b650815985d5b1d60d21b6006939091019283015250600c01919050565b6134bb60f11b8152600082516135cb816002850160208701612e8c565b9190910160020192915050565b601f821115610983576000816000526020600020601f850160051c810160208610156136015750805b601f850160051c820191505b818110156136205782815560010161360d565b505050505050565b815167ffffffffffffffff811115613642576136426130be565b613656816136508454613084565b846135d8565b602080601f83116001811461368b57600084156136735750858301515b600019600386901b1c1916600185901b178555613620565b600085815260208120601f198616915b828110156136ba5788860151825594840194600190910190840161369b565b50858210156136d85787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b600082516136fa818460208701612e8c565b919091019291505056fea2646970667358221220e9c1329438f31472150b9c984d508926d8a8b93cd339e65570636454cde0a40a64736f6c63430008160033", + "deployedBytecode": "0x608060405234801561001057600080fd5b50600436106102bb5760003560e01c8063715018a611610182578063c0c53b8b116100e9578063dd62ed3e116100a2578063f2eb2a4b1161007c578063f2eb2a4b146105d3578063f2fde38b146105e6578063fc4d33f9146105f9578063ff2a7d301461060157600080fd5b8063dd62ed3e146105ad578063e30c3978146105c0578063ef8b30f71461056157600080fd5b8063c0c53b8b1461053b578063c63d75b61461054e578063c6e6f59214610561578063cce2f3fb14610574578063ce96cb7714610587578063d905777e1461059a57600080fd5b8063a9059cbb1161013b578063a9059cbb146104d4578063ada82c7d146104e7578063b3d7f6b9146104ef578063b460af9414610502578063ba08765214610515578063bb83b0e91461052857600080fd5b8063715018a614610484578063877887821461048c5780638da5cb5b1461049557806394bf804d146104a657806395d89b41146104b9578063a457c2d7146104c157600080fd5b806338d52e0f1161022657806356f89ef9116101df57806356f89ef9146104075780635c975abb1461040f57806369e527da146104215780636e553f65146104355780636e96dfd71461044857806370a082311461045b57600080fd5b806338d52e0f146103a157806339509351146103c65780633f4ba83a146103d9578063402d267d146103e157806346904840146103f45780634cdad506146102f057600080fd5b806318160ddd1161027857806318160ddd1461034e578063211493c91461035657806323b872dd1461035f5780632835797814610372578063313ce5671461037a578063372500ab1461039957600080fd5b806301e1d114146102c057806306fdde03146102db57806307a2d13a146102f0578063095ea7b3146103035780630a28a4771461032657806310509aa914610339575b600080fd5b6102c8610614565b6040519081526020015b60405180910390f35b6102e3610687565b6040516102d29190612eb0565b6102c86102fe366004612ee3565b610719565b610316610311366004612f11565b61072c565b60405190151581526020016102d2565b6102c8610334366004612ee3565b610744565b61034c610347366004612f3d565b610751565b005b6099546102c8565b6102c860fb5481565b61031661036d366004612f6d565b610877565b61034c61089d565b60c954600160a01b900460ff1660405160ff90911681526020016102d2565b61034c6108af565b60c9546001600160a01b03165b6040516001600160a01b0390911681526020016102d2565b6103166103d4366004612f11565b610988565b61034c6109aa565b6102c86103ef366004612fae565b6109ba565b60fd546103ae906001600160a01b031681565b61034c610cde565b606554600160a01b900460ff16610316565b610100546103ae906001600160a01b031681565b6102c8610443366004612f3d565b610eac565b61034c610456366004612fae565b610f78565b6102c8610469366004612fae565b6001600160a01b031660009081526097602052604090205490565b61034c610fe2565b6102c860fc5481565b6033546001600160a01b03166103ae565b6102c86104b4366004612f3d565b611025565b6102e36110a2565b6103166104cf366004612f11565b6110b1565b6103166104e2366004612f11565b611137565b61034c611145565b6102c86104fd366004612ee3565b611175565b6102c8610510366004612fcb565b611182565b6102c8610523366004612fcb565b61133b565b61034c610536366004612fae565b611532565b61034c61054936600461300d565b6115a3565b6102c861055c366004612fae565b611757565b6102c861056f366004612ee3565b61177d565b6102c8610582366004612fae565b61178a565b6102c8610595366004612fae565b611893565b6102c86105a8366004612fae565b61194d565b6102c86105bb36600461303d565b611a12565b6065546103ae906001600160a01b031681565b60ff546103ae906001600160a01b031681565b61034c6105f4366004612fae565b611a3d565b61034c611aae565b60fe546103ae906001600160a01b031681565b61010054604051633af9e66960e01b81523060048201526000916001600160a01b031690633af9e66990602401602060405180830381865afa15801561065e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610682919061306b565b905090565b6060609a805461069690613084565b80601f01602080910402602001604051908101604052809291908181526020018280546106c290613084565b801561070f5780601f106106e45761010080835404028352916020019161070f565b820191906000526020600020905b8154815290600101906020018083116106f257829003601f168201915b5050505050905090565b6000610726826000611bc2565b92915050565b60003361073a818585611bf5565b5060019392505050565b6000610726826001611d19565b610759611d4b565b60fc5460fd5460408051928352602083018590526001600160a01b0391821690830152821660608201527fb3b62da5184b9e7e2f5d280014bb485d4444b66738025e5fb5738bbddcb6b8489060800160405180910390a160fc82905560fd546001600160a01b038281169116146108545760fd546001600160a01b0316156108365760fd546001600160a01b0316600081815260976020526040902054906108019082611da5565b60fd5461082a906001600160a01b03166108236033546001600160a01b031690565b6000611bf5565b6108348282611ed9565b505b6108548161084c6033546001600160a01b031690565b600019611bf5565b60fd80546001600160a01b0319166001600160a01b039290921691909117905550565b600033610885858285611f9b565b61089085858561200f565b60019150505b9392505050565b6108a5611d4b565b6108ad6121ba565b565b60ff54604051639cf1fd5360e01b815230600482015260009182916001600160a01b0390911690639cf1fd53906024016000604051808303816000875af11580156108fe573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526109269190810190613198565b9150915060005b82518110156109835760fe54825161097b916001600160a01b03169084908490811061095b5761095b61325d565b602002602001015161096b61221a565b6001600160a01b0316919061222e565b60010161092d565b505050565b60003361073a81858561099b8383611a12565b6109a59190613289565b611bf5565b6109b2611d4b565b6108ad612291565b6101005460408051635fe3b56760e01b815290516000926001600160a01b031691635fe3b5679160048083019260209291908290030181865afa158015610a05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a29919061329c565b6101005460405163731f0c2b60e01b81526001600160a01b03918216600482015291169063731f0c2b90602401602060405180830381865afa158015610a73573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a9791906132b9565b15610aa457506000919050565b6101005460408051635fe3b56760e01b815290516000926001600160a01b031691635fe3b5679160048083019260209291908290030181865afa158015610aef573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b13919061329c565b610100546040516302c3bcbb60e01b81526001600160a01b0391821660048201529116906302c3bcbb90602401602060405180830381865afa158015610b5d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b81919061306b565b90508015610cd457610100546040805163bd6d894d60e01b815290516000926001600160a01b03169163bd6d894d9160048083019260209291908290030181865afa158015610bd4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bf8919061306b565b9050600061010060009054906101000a90046001600160a01b03166001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c50573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c74919061306b565b90506000670de0b6b3a7640000610c8b84846132db565b610c959190613308565b905083610ca3826002613289565b10610cb45750600095945050505050565b6002610cc0828661332a565b610cca919061332a565b9695505050505050565b5060001992915050565b610ce6611d4b565b60fd546001600160a01b0316610d435760405162461bcd60e51b815260206004820152601d60248201527f66656520726563697069656e74206e6f7420696e697469616c697a656400000060448201526064015b60405180910390fd5b6000610d4d610614565b90506000610dc8610d5c61221a565b6001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610d99573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dbd919061333d565b6102fe90600a613444565b905060fb548111610e1b5760405162461bcd60e51b815260206004820152601b60248201527f736861726556616c756520213e207661756c74536861726548574d00000000006044820152606401610d3a565b6000610e2660995490565b905060006ec097ce7bc90715b34b9f10000000008260fb5485610e49919061332a565b60fc54610e5691906132db565b610e6091906132db565b610e6a9190613308565b60fd54909150610e98906001600160a01b0316610e9384610e8b858961332a565b8591906122cd565b611ed9565b610ea3610d5c61221a565b60fb5550505050565b6000610eb66122ec565b610ebf8361177d565b905080600003610eff5760405162461bcd60e51b815260206004820152600b60248201526a5a45524f5f53484152455360a81b6044820152606401610d3a565b610f1e333085610f0d61221a565b6001600160a01b0316929190612339565b610f288282611ed9565b60408051848152602081018390526001600160a01b0384169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a36107268382612371565b610f80611d4b565b606580546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b91015b60405180910390a15050565b610fea611d4b565b60405162461bcd60e51b815260206004820152601060248201526f6e6f74207573656420616e796d6f726560801b6044820152606401610d3a565b600061102f6122ec565b61103883611175565b9050611048333083610f0d61221a565b6110528284611ed9565b60408051828152602081018590526001600160a01b0384169133917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a36107268184612371565b6060609b805461069690613084565b600033816110bf8286611a12565b90508381101561111f5760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610d3a565b61112c8286868403611bf5565b506001949350505050565b60003361073a81858561200f565b61114d611d4b565b60fd546001600160a01b0316600081815260976020526040902054611172918061133b565b50565b6000610726826001611bc2565b600061118d84610744565b9050336001600160a01b038316146111c75760006111ab8333611a12565b905060001981146111c5576111c583336109a5858561332a565b505b606554600160a01b900460ff166112d95760006111e261221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa158015611228573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124c919061306b565b90506112588583612441565b8061126161221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa1580156112a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112cb919061306b565b6112d5919061332a565b9450505b6112e38282611da5565b60408051858152602081018390526001600160a01b03808516929086169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4610896838561096b61221a565b6000336001600160a01b038316146113755760006113598333611a12565b905060001981146113735761137383336109a5888561332a565b505b61137e84610719565b9050806000036113be5760405162461bcd60e51b815260206004820152600b60248201526a5a45524f5f41535345545360a81b6044820152606401610d3a565b606554600160a01b900460ff166114d05760006113d961221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa15801561141f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611443919061306b565b905061144f8286612441565b8061145861221a565b6040516370a0823160e01b81523060048201526001600160a01b0391909116906370a0823190602401602060405180830381865afa15801561149e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906114c2919061306b565b6114cc919061332a565b9150505b6114da8285611da5565b60408051828152602081018690526001600160a01b03808516929086169133917ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db910160405180910390a4610896838261096b61221a565b61153a611d4b565b60fe54604080516001600160a01b03928316815291831660208301527f2d9427f2d488d8f8716dae31ad2f0d476bcea0664cce8822d8dc76dde104b09e910160405180910390a160fe80546001600160a01b0319166001600160a01b0392909216919091179055565b600054610100900460ff16158080156115c35750600054600160ff909116105b806115dd5750303b1580156115dd575060005460ff166001145b6116405760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610d3a565b6000805460ff191660011790558015611663576000805461ff0019166101001790555b6116cd846001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116c8919061329c565b612474565b61010080546001600160a01b038087166001600160a01b03199283161790925560fe805485841690831617905560ff8054928616929091169190911790558015611751576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b50505050565b60008061176460006109ba565b90506000198114610726576117788161177d565b610896565b6000610726826000611d19565b6000611794611d4b565b61179c612654565b60006117a661221a565b6040516370a0823160e01b81523060048201529091506000906001600160a01b038316906370a0823190602401602060405180830381865afa1580156117f0573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611814919061306b565b60405163a9059cbb60e01b81526001600160a01b038681166004830152602482018390529192509083169063a9059cbb906044016020604051808303816000875af1158015611867573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061188b91906132b9565b509392505050565b60008061010060009054906101000a90046001600160a01b03166001600160a01b0316633b1d21a26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061190e919061306b565b905060006119346102fe856001600160a01b031660009081526097602052604090205490565b90508082106119435780611945565b815b949350505050565b60008061010060009054906101000a90046001600160a01b03166001600160a01b0316633b1d21a26040518163ffffffff1660e01b8152600401602060405180830381865afa1580156119a4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119c8919061306b565b905060006119d58261177d565b905060006119f8856001600160a01b031660009081526097602052604090205490565b9050808210611a075780611a09565b815b95945050505050565b6001600160a01b03918216600090815260986020908152604080832093909416825291909152205490565b611a45611d4b565b606554604080516001600160a01b03928316815291831660208301527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b910160405180910390a1606580546001600160a01b0319166001600160a01b0392909216919091179055565b6065546001600160a01b03163314611b005760405162461bcd60e51b81526020600482015260156024820152743737ba103a3432903832b73234b7339037bbb732b960591b6044820152606401610d3a565b6000611b146033546001600160a01b031690565b6065549091506001600160a01b0316611b2c816126a4565b606580546001600160a01b0319169055604080516001600160a01b0384168152600060208201527f70aea8d848e8a90fb7661b227dc522eb6395c3dac71b63cb59edd5c9899b2364910160405180910390a1606554604080516001600160a01b03808516825290921660208301527fb3d55174552271a4f1aaf36b72f50381e892171636b3fb5447fe00e995e7a37b9101610fd6565b600080611bce60995490565b90508015611bef57611bea611be1610614565b859083866126f6565b611945565b83611945565b6001600160a01b038316611c575760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610d3a565b6001600160a01b038216611cb85760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610d3a565b6001600160a01b0383811660008181526098602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b600080611d2560995490565b9050831580611d32575080155b611bef57611bea81611d42610614565b869190866126f6565b6033546001600160a01b031633146108ad5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610d3a565b6001600160a01b038216611e055760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610d3a565b6001600160a01b03821660009081526097602052604090205481811015611e795760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610d3a565b6001600160a01b03831660008181526097602090815260408083208686039055609980548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6001600160a01b038216611f2f5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610d3a565b8060996000828254611f419190613289565b90915550506001600160a01b0382166000818152609760209081526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35b5050565b6000611fa78484611a12565b9050600019811461175157818110156120025760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610d3a565b6117518484848403611bf5565b6001600160a01b0383166120735760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610d3a565b6001600160a01b0382166120d55760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610d3a565b6001600160a01b0383166000908152609760205260409020548181101561214d5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610d3a565b6001600160a01b0380851660008181526097602052604080822086860390559286168082529083902080548601905591517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef906121ad9086815260200190565b60405180910390a3611751565b6121c26122ec565b6065805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586121fd3390565b6040516001600160a01b03909116815260200160405180910390a1565b600061068260c9546001600160a01b031690565b6040516001600160a01b03831660248201526044810182905261098390849063a9059cbb60e01b906064015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152612747565b612299612654565b6065805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa336121fd565b8282028115158415858304851417166122e557600080fd5b0492915050565b606554600160a01b900460ff16156108ad5760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606401610d3a565b6040516001600160a01b03808516602483015283166044820152606481018290526117519085906323b872dd60e01b9060840161225a565b6101005461239b906001600160a01b03168361238b61221a565b6001600160a01b03169190612819565b6101005460405163140e25ad60e31b8152600481018490526000916001600160a01b03169063a0712d68906024015b6020604051808303816000875af11580156123e9573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061240d919061306b565b905080156109835780601481111561242757612427613453565b604051633172b7f760e11b8152600401610d3a9190613469565b6101005460405163852a12e360e01b8152600481018490526000916001600160a01b03169063852a12e3906024016123ca565b600054610100900460ff1661249b5760405162461bcd60e51b8152600401610d3a90613491565b6124a43361292e565b6124ac612966565b6124b4612995565b6125c6816001600160a01b03166306fdde036040518163ffffffff1660e01b8152600401600060405180830381865afa1580156124f5573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261251d91908101906134dc565b60405160200161252d9190613570565b604051602081830303815290604052826001600160a01b03166395d89b416040518163ffffffff1660e01b8152600401600060405180830381865afa15801561257a573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526125a291908101906134dc565b6040516020016125b291906135ae565b6040516020818303038152906040526129bc565b6125cf816129ed565b806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561260d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612631919061333d565b61263c90600a613444565b60fb555060fd80546001600160a01b03191633179055565b606554600160a01b900460ff166108ad5760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401610d3a565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600080612704868686612a1d565b9050600183600281111561271a5761271a613453565b148015612737575060008480612732576127326132f2565b868809115b15611a0957610cca600182613289565b600061279c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612acc9092919063ffffffff16565b80519091501561098357808060200190518101906127ba91906132b9565b6109835760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610d3a565b8015806128935750604051636eb1769f60e11b81523060048201526001600160a01b03838116602483015284169063dd62ed3e90604401602060405180830381865afa15801561286d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612891919061306b565b155b6128fe5760405162461bcd60e51b815260206004820152603660248201527f5361666545524332303a20617070726f76652066726f6d206e6f6e2d7a65726f60448201527520746f206e6f6e2d7a65726f20616c6c6f77616e636560501b6064820152608401610d3a565b6040516001600160a01b03831660248201526044810182905261098390849063095ea7b360e01b9060640161225a565b600054610100900460ff166129555760405162461bcd60e51b8152600401610d3a90613491565b61295d612adb565b611172816126a4565b600054610100900460ff1661298d5760405162461bcd60e51b8152600401610d3a90613491565b6108ad612b0a565b600054610100900460ff166108ad5760405162461bcd60e51b8152600401610d3a90613491565b600054610100900460ff166129e35760405162461bcd60e51b8152600401610d3a90613491565b611f978282612b40565b600054610100900460ff16612a145760405162461bcd60e51b8152600401610d3a90613491565b61117281612b80565b6000808060001985870985870292508281108382030391505080600003612a5757838281612a4d57612a4d6132f2565b0492505050610896565b808411612a6357600080fd5b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b60606119458484600085612c05565b600054610100900460ff16612b025760405162461bcd60e51b8152600401610d3a90613491565b6108ad612ce0565b600054610100900460ff16612b315760405162461bcd60e51b8152600401610d3a90613491565b6065805460ff60a01b19169055565b600054610100900460ff16612b675760405162461bcd60e51b8152600401610d3a90613491565b609a612b738382613628565b50609b6109838282613628565b600054610100900460ff16612ba75760405162461bcd60e51b8152600401610d3a90613491565b600080612bb383612d10565b9150915081612bc3576012612bc5565b805b60c980546001600160a01b039095166001600160a01b031960ff93909316600160a01b02929092166001600160a81b031990951694909417179092555050565b606082471015612c665760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610d3a565b600080866001600160a01b03168587604051612c8291906136e8565b60006040518083038185875af1925050503d8060008114612cbf576040519150601f19603f3d011682016040523d82523d6000602084013e612cc4565b606091505b5091509150612cd587838387612dee565b979650505050505050565b600054610100900460ff16612d075760405162461bcd60e51b8152600401610d3a90613491565b6108ad336126a4565b60408051600481526024810182526020810180516001600160e01b031663313ce56760e01b17905290516000918291829182916001600160a01b03871691612d57916136e8565b6000604051808303816000865af19150503d8060008114612d94576040519150601f19603f3d011682016040523d82523d6000602084013e612d99565b606091505b5091509150818015612dad57506020815110155b15612de157600081806020019051810190612dc8919061306b565b905060ff8111612ddf576001969095509350505050565b505b5060009485945092505050565b60608315612e5d578251600003612e56576001600160a01b0385163b612e565760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610d3a565b5081611945565b6119458383815115612e725781518083602001fd5b8060405162461bcd60e51b8152600401610d3a9190612eb0565b60005b83811015612ea7578181015183820152602001612e8f565b50506000910152565b6020815260008251806020840152612ecf816040850160208701612e8c565b601f01601f19169190910160400192915050565b600060208284031215612ef557600080fd5b5035919050565b6001600160a01b038116811461117257600080fd5b60008060408385031215612f2457600080fd5b8235612f2f81612efc565b946020939093013593505050565b60008060408385031215612f5057600080fd5b823591506020830135612f6281612efc565b809150509250929050565b600080600060608486031215612f8257600080fd5b8335612f8d81612efc565b92506020840135612f9d81612efc565b929592945050506040919091013590565b600060208284031215612fc057600080fd5b813561089681612efc565b600080600060608486031215612fe057600080fd5b833592506020840135612ff281612efc565b9150604084013561300281612efc565b809150509250925092565b60008060006060848603121561302257600080fd5b833561302d81612efc565b92506020840135612ff281612efc565b6000806040838503121561305057600080fd5b823561305b81612efc565b91506020830135612f6281612efc565b60006020828403121561307d57600080fd5b5051919050565b600181811c9082168061309857607f821691505b6020821081036130b857634e487b7160e01b600052602260045260246000fd5b50919050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff811182821017156130fd576130fd6130be565b604052919050565b600067ffffffffffffffff82111561311f5761311f6130be565b5060051b60200190565b600082601f83011261313a57600080fd5b8151602061314f61314a83613105565b6130d4565b8083825260208201915060208460051b87010193508684111561317157600080fd5b602086015b8481101561318d5780518352918301918301613176565b509695505050505050565b600080604083850312156131ab57600080fd5b825167ffffffffffffffff808211156131c357600080fd5b818501915085601f8301126131d757600080fd5b815160206131e761314a83613105565b82815260059290921b8401810191818101908984111561320657600080fd5b948201945b8386101561322d57855161321e81612efc565b8252948201949082019061320b565b9188015191965090935050508082111561324657600080fd5b5061325385828601613129565b9150509250929050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8082018082111561072657610726613273565b6000602082840312156132ae57600080fd5b815161089681612efc565b6000602082840312156132cb57600080fd5b8151801515811461089657600080fd5b808202811582820484141761072657610726613273565b634e487b7160e01b600052601260045260246000fd5b60008261332557634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561072657610726613273565b60006020828403121561334f57600080fd5b815160ff8116811461089657600080fd5b600181815b8085111561339b57816000190482111561338157613381613273565b8085161561338e57918102915b93841c9390800290613365565b509250929050565b6000826133b257506001610726565b816133bf57506000610726565b81600181146133d557600281146133df576133fb565b6001915050610726565b60ff8411156133f0576133f0613273565b50506001821b610726565b5060208310610133831016604e8410600b841016171561341e575081810a610726565b6134288383613360565b806000190482111561343c5761343c613273565b029392505050565b600061089660ff8416836133a3565b634e487b7160e01b600052602160045260246000fd5b602081016015831061348b57634e487b7160e01b600052602160045260246000fd5b91905290565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b6000602082840312156134ee57600080fd5b815167ffffffffffffffff8082111561350657600080fd5b818401915084601f83011261351a57600080fd5b81518181111561352c5761352c6130be565b61353f601f8201601f19166020016130d4565b915080825285602082850101111561355657600080fd5b613567816020840160208601612e8c565b50949350505050565b65024b7b734b1960d51b815260008251613591816006850160208701612e8c565b650815985d5b1d60d21b6006939091019283015250600c01919050565b6134bb60f11b8152600082516135cb816002850160208701612e8c565b9190910160020192915050565b601f821115610983576000816000526020600020601f850160051c810160208610156136015750805b601f850160051c820191505b818110156136205782815560010161360d565b505050505050565b815167ffffffffffffffff811115613642576136426130be565b613656816136508454613084565b846135d8565b602080601f83116001811461368b57600084156136735750858301515b600019600386901b1c1916600185901b178555613620565b600085815260208120601f198616915b828110156136ba5788860151825594840194600190910190840161369b565b50858210156136d85787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b600082516136fa818460208701612e8c565b919091019291505056fea2646970667358221220e9c1329438f31472150b9c984d508926d8a8b93cd339e65570636454cde0a40a64736f6c63430008160033", + "devdoc": { + "events": { + "Approval(address,address,uint256)": { + "details": "Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance." + }, + "Initialized(uint8)": { + "details": "Triggered when the contract has been initialized or reinitialized." + }, + "Paused(address)": { + "details": "Emitted when the pause is triggered by `account`." + }, + "Transfer(address,address,uint256)": { + "details": "Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero." + }, + "Unpaused(address)": { + "details": "Emitted when the pause is lifted by `account`." + } + }, + "kind": "dev", + "methods": { + "_acceptOwner()": { + "details": "Owner function for pending owner to accept role and update owner" + }, + "_setPendingOwner(address)": { + "details": "Owner function to begin change of owner. The newPendingOwner must call `_acceptOwner` to finalize the transfer.", + "params": { + "newPendingOwner": "New pending owner." + } + }, + "allowance(address,address)": { + "details": "See {IERC20-allowance}." + }, + "approve(address,uint256)": { + "details": "See {IERC20-approve}. NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on `transferFrom`. This is semantically equivalent to an infinite approval. Requirements: - `spender` cannot be the zero address." + }, + "asset()": { + "details": "See {IERC4626-asset}. " + }, + "balanceOf(address)": { + "details": "See {IERC20-balanceOf}." + }, + "convertToAssets(uint256)": { + "details": "See {IERC4626-convertToAssets}. " + }, + "convertToShares(uint256)": { + "details": "See {IERC4626-convertToShares}. " + }, + "decimals()": { + "details": "Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value. See {IERC20Metadata-decimals}." + }, + "decreaseAllowance(address,uint256)": { + "details": "Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`." + }, + "deposit(uint256,address)": { + "details": "See {IERC4626-deposit}. " + }, + "increaseAllowance(address,uint256)": { + "details": "Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address." + }, + "maxMint(address)": { + "details": "accrue interest must be called before this function is called, otherwise an outdated value will be fetched, and the returned value will be incorrect (greater than actual amount available to be minted will be returned)" + }, + "maxRedeem(address)": { + "params": { + "owner": "The address that owns the shares" + } + }, + "maxWithdraw(address)": { + "params": { + "owner": "The address that owns the shares" + } + }, + "mint(uint256,address)": { + "details": "See {IERC4626-mint}. " + }, + "name()": { + "details": "Returns the name of the token." + }, + "owner()": { + "details": "Returns the address of the current owner." + }, + "paused()": { + "details": "Returns true if the contract is paused, and false otherwise." + }, + "previewDeposit(uint256)": { + "details": "See {IERC4626-previewDeposit}. " + }, + "previewMint(uint256)": { + "details": "See {IERC4626-previewMint}. " + }, + "previewRedeem(uint256)": { + "details": "See {IERC4626-previewRedeem}. " + }, + "previewWithdraw(uint256)": { + "details": "See {IERC4626-previewWithdraw}. " + }, + "redeem(uint256,address,address)": { + "details": "See {IERC4626-redeem}. " + }, + "renounceOwnership()": { + "details": "Leaves the contract without owner. It will not be possible to call `onlyOwner` functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner." + }, + "symbol()": { + "details": "Returns the symbol of the token, usually a shorter version of the name." + }, + "takePerformanceFee()": { + "details": "Performance fee is based on a vault share high water mark value. If vault share value has increased above the HWM in a fee period, issue fee shares to the vault equal to the performance fee." + }, + "totalAssets()": { + "details": "See {IERC4626-totalAssets}. " + }, + "totalSupply()": { + "details": "See {IERC20-totalSupply}." + }, + "transfer(address,uint256)": { + "details": "See {IERC20-transfer}. Requirements: - `to` cannot be the zero address. - the caller must have a balance of at least `amount`." + }, + "transferFrom(address,address,uint256)": { + "details": "See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. NOTE: Does not update the allowance if the current allowance is the maximum `uint256`. Requirements: - `from` and `to` cannot be the zero address. - `from` must have a balance of at least `amount`. - the caller must have allowance for ``from``'s tokens of at least `amount`." + }, + "transferOwnership(address)": { + "details": "Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner." + }, + "withdraw(uint256,address,address)": { + "details": "See {IERC4626-withdraw}. " + }, + "withdrawAccruedFees()": { + "details": "We must make sure that feeRecipient is not address(0) before withdrawing fees" + } + }, + "version": 1 + }, + "userdoc": { + "events": { + "NewOwner(address,address)": { + "notice": "Emitted when pendingOwner is accepted, which means owner is updated" + }, + "NewPendingOwner(address,address)": { + "notice": "Emitted when pendingOwner is changed" + } + }, + "kind": "user", + "methods": { + "_acceptOwner()": { + "notice": "Accepts transfer of owner rights. msg.sender must be pendingOwner" + }, + "_setPendingOwner(address)": { + "notice": "Begins transfer of owner rights. The newPendingOwner must call `_acceptOwner` to finalize the transfer." + }, + "maxDeposit(address)": { + "notice": "maximum amount of underlying tokens that can be deposited into the underlying protocol" + }, + "maxMint(address)": { + "notice": "Returns the maximum amount of tokens that can be supplied no way for this function to ever revert unless comptroller or mToken is broken" + }, + "maxRedeem(address)": { + "notice": "maximum amount of shares that can be withdrawn" + }, + "maxWithdraw(address)": { + "notice": "maximum amount of underlying tokens that can be withdrawn" + }, + "pendingOwner()": { + "notice": "Pending owner of this contract" + }, + "takePerformanceFee()": { + "notice": "Take the performance fee that has accrued since last fee harvest." + }, + "updateFeeSettings(uint256,address)": { + "notice": "Update performanceFee and/or feeRecipient" + }, + "withdrawAccruedFees()": { + "notice": "Transfer accrued fees to rewards manager contract. Caller must be a registered keeper." + } + }, + "version": 1 + }, + "storageLayout": { + "storage": [ + { + "astId": 3343, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_initialized", + "offset": 0, + "slot": "0", + "type": "t_uint8" + }, + { + "astId": 3346, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_initializing", + "offset": 1, + "slot": "0", + "type": "t_bool" + }, + { + "astId": 6909, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "1", + "type": "t_array(t_uint256)50_storage" + }, + { + "astId": 2967, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_owner", + "offset": 0, + "slot": "51", + "type": "t_address" + }, + { + "astId": 3087, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "52", + "type": "t_array(t_uint256)49_storage" + }, + { + "astId": 55662, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "pendingOwner", + "offset": 0, + "slot": "101", + "type": "t_address" + }, + { + "astId": 3526, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_paused", + "offset": 20, + "slot": "101", + "type": "t_bool" + }, + { + "astId": 3631, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "102", + "type": "t_array(t_uint256)49_storage" + }, + { + "astId": 3724, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_balances", + "offset": 0, + "slot": "151", + "type": "t_mapping(t_address,t_uint256)" + }, + { + "astId": 3730, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_allowances", + "offset": 0, + "slot": "152", + "type": "t_mapping(t_address,t_mapping(t_address,t_uint256))" + }, + { + "astId": 3732, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_totalSupply", + "offset": 0, + "slot": "153", + "type": "t_uint256" + }, + { + "astId": 3734, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_name", + "offset": 0, + "slot": "154", + "type": "t_string_storage" + }, + { + "astId": 3736, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_symbol", + "offset": 0, + "slot": "155", + "type": "t_string_storage" + }, + { + "astId": 4316, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "156", + "type": "t_array(t_uint256)45_storage" + }, + { + "astId": 4415, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_asset", + "offset": 0, + "slot": "201", + "type": "t_contract(IERC20Upgradeable)4395" + }, + { + "astId": 4417, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "_decimals", + "offset": 20, + "slot": "201", + "type": "t_uint8" + }, + { + "astId": 5099, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "__gap", + "offset": 0, + "slot": "202", + "type": "t_array(t_uint256)49_storage" + }, + { + "astId": 60776, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "vaultShareHWM", + "offset": 0, + "slot": "251", + "type": "t_uint256" + }, + { + "astId": 60778, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "performanceFee", + "offset": 0, + "slot": "252", + "type": "t_uint256" + }, + { + "astId": 60780, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "feeRecipient", + "offset": 0, + "slot": "253", + "type": "t_address" + }, + { + "astId": 61454, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "rewardsRecipient", + "offset": 0, + "slot": "254", + "type": "t_address" + }, + { + "astId": 61457, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "flywheelLensRouter", + "offset": 0, + "slot": "255", + "type": "t_contract(IonicFlywheelLensRouter_4626)61441" + }, + { + "astId": 61460, + "contract": "contracts/src/ionic/strategies/IonicMarketERC4626.sol:IonicMarketERC4626", + "label": "cToken", + "offset": 0, + "slot": "256", + "type": "t_contract(ICErc20)32392" + } + ], + "types": { + "t_address": { + "encoding": "inplace", + "label": "address", + "numberOfBytes": "20" + }, + "t_array(t_uint256)45_storage": { + "base": "t_uint256", + "encoding": "inplace", + "label": "uint256[45]", + "numberOfBytes": "1440" + }, + "t_array(t_uint256)49_storage": { + "base": "t_uint256", + "encoding": "inplace", + "label": "uint256[49]", + "numberOfBytes": "1568" + }, + "t_array(t_uint256)50_storage": { + "base": "t_uint256", + "encoding": "inplace", + "label": "uint256[50]", + "numberOfBytes": "1600" + }, + "t_bool": { + "encoding": "inplace", + "label": "bool", + "numberOfBytes": "1" + }, + "t_contract(ICErc20)32392": { + "encoding": "inplace", + "label": "contract ICErc20", + "numberOfBytes": "20" + }, + "t_contract(IERC20Upgradeable)4395": { + "encoding": "inplace", + "label": "contract IERC20Upgradeable", + "numberOfBytes": "20" + }, + "t_contract(IonicFlywheelLensRouter_4626)61441": { + "encoding": "inplace", + "label": "contract IonicFlywheelLensRouter_4626", + "numberOfBytes": "20" + }, + "t_mapping(t_address,t_mapping(t_address,t_uint256))": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => mapping(address => uint256))", + "numberOfBytes": "32", + "value": "t_mapping(t_address,t_uint256)" + }, + "t_mapping(t_address,t_uint256)": { + "encoding": "mapping", + "key": "t_address", + "label": "mapping(address => uint256)", + "numberOfBytes": "32", + "value": "t_uint256" + }, + "t_string_storage": { + "encoding": "bytes", + "label": "string", + "numberOfBytes": "32" + }, + "t_uint256": { + "encoding": "inplace", + "label": "uint256", + "numberOfBytes": "32" + }, + "t_uint8": { + "encoding": "inplace", + "label": "uint8", + "numberOfBytes": "1" + } + } + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0_Proxy.json b/packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0_Proxy.json new file mode 100644 index 0000000000..2827b58a81 --- /dev/null +++ b/packages/contracts/deployments/base/IonicMarketERC4626_0xa900A17a49Bc4D442bA7F72c39FA2108865671f0_Proxy.json @@ -0,0 +1,275 @@ +{ + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "abi": [ + { + "inputs": [ + { + "internalType": "address", + "name": "_logic", + "type": "address" + }, + { + "internalType": "address", + "name": "admin_", + "type": "address" + }, + { + "internalType": "bytes", + "name": "_data", + "type": "bytes" + } + ], + "stateMutability": "payable", + "type": "constructor" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": false, + "internalType": "address", + "name": "previousAdmin", + "type": "address" + }, + { + "indexed": false, + "internalType": "address", + "name": "newAdmin", + "type": "address" + } + ], + "name": "AdminChanged", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "beacon", + "type": "address" + } + ], + "name": "BeaconUpgraded", + "type": "event" + }, + { + "anonymous": false, + "inputs": [ + { + "indexed": true, + "internalType": "address", + "name": "implementation", + "type": "address" + } + ], + "name": "Upgraded", + "type": "event" + }, + { + "stateMutability": "payable", + "type": "fallback" + }, + { + "inputs": [], + "name": "admin", + "outputs": [ + { + "internalType": "address", + "name": "admin_", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newAdmin", + "type": "address" + } + ], + "name": "changeAdmin", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [], + "name": "implementation", + "outputs": [ + { + "internalType": "address", + "name": "implementation_", + "type": "address" + } + ], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newImplementation", + "type": "address" + } + ], + "name": "upgradeTo", + "outputs": [], + "stateMutability": "nonpayable", + "type": "function" + }, + { + "inputs": [ + { + "internalType": "address", + "name": "newImplementation", + "type": "address" + }, + { + "internalType": "bytes", + "name": "data", + "type": "bytes" + } + ], + "name": "upgradeToAndCall", + "outputs": [], + "stateMutability": "payable", + "type": "function" + }, + { + "stateMutability": "payable", + "type": "receive" + } + ], + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "receipt": { + "to": null, + "from": "0x1155b614971f16758C92c4890eD338C9e3ede6b7", + "contractAddress": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "transactionIndex": 137, + "gasUsed": "985147", + "logsBloom": "0x00000000000000000000000000000000400000000000000000800000000220000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000002000001000000000000000000000000000000000000020000000000000000000800000000800000000000000000000000400000000001000000000000000000000000000000004080000000000000c00000000000000000100000000000000400000000000000000000000000000000000000000020000000000000000000040000000000000400000000000000000020000000000000000000000000000000000000000000100000004000000000000000", + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3", + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "logs": [ + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b", + "0x0000000000000000000000000014ce7973246b7a99ea95f0bd38156c19551880" + ], + "data": "0x", + "logIndex": 453, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + }, + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "data": "0x", + "logIndex": 454, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + }, + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7", + "0x0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "data": "0x", + "logIndex": 455, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + }, + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498" + ], + "data": "0x0000000000000000000000000000000000000000000000000000000000000001", + "logIndex": 456, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + }, + { + "transactionIndex": 137, + "blockNumber": 25464425, + "transactionHash": "0xb25cb8e7769b84f3cd28f8d977a740fb1f0c397bf1f113cc1b9b11a75df5a897", + "address": "0x0beDB53713EBF4465DC2f485Df19BAd1EF04403B", + "topics": [ + "0x7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f" + ], + "data": "0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000028df5636456049b891bf9d40fa46ef5ad20822c5", + "logIndex": 457, + "blockHash": "0x9a1e74dec7fe4ae2f3bc0218451a62fc62e140a682745b0e8c16c399f28d81b3" + } + ], + "blockNumber": 25464425, + "cumulativeGasUsed": "29066749", + "status": 1, + "byzantium": true + }, + "args": [ + "0x0014cE7973246b7a99Ea95f0Bd38156C19551880", + "0x28DF5636456049B891bF9D40fa46eF5ad20822C5", + "0xc0c53b8b000000000000000000000000a900a17a49bc4d442ba7f72c39fa2108865671f0000000000000000000000000b1402333b12fc066c3d7f55d37944d5e281a3e8b0000000000000000000000001155b614971f16758c92c4890ed338c9e3ede6b7" + ], + "numDeployments": 1, + "solcInputHash": "0e89febeebc7444140de8e67c9067d2c", + "metadata": "{\"compiler\":{\"version\":\"0.8.10+commit.fc410830\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_logic\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"admin_\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"_data\",\"type\":\"bytes\"}],\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"previousAdmin\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"address\",\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"AdminChanged\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"beacon\",\"type\":\"address\"}],\"name\":\"BeaconUpgraded\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"implementation\",\"type\":\"address\"}],\"name\":\"Upgraded\",\"type\":\"event\"},{\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"inputs\":[],\"name\":\"admin\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"admin_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newAdmin\",\"type\":\"address\"}],\"name\":\"changeAdmin\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"implementation\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"implementation_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newImplementation\",\"type\":\"address\"}],\"name\":\"upgradeTo\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"newImplementation\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"upgradeToAndCall\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}],\"devdoc\":{\"details\":\"This contract implements a proxy that is upgradeable by an admin. To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector clashing], which can potentially be used in an attack, this contract uses the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two things that go hand in hand: 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches one of the admin functions exposed by the proxy itself. 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error that says \\\"admin cannot fallback to proxy target\\\". These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to call a function from the proxy implementation. Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\",\"kind\":\"dev\",\"methods\":{\"admin()\":{\"details\":\"Returns the current admin. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\"},\"changeAdmin(address)\":{\"details\":\"Changes the admin of the proxy. Emits an {AdminChanged} event. NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\"},\"constructor\":{\"details\":\"Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\"},\"implementation()\":{\"details\":\"Returns the current implementation. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\"},\"upgradeTo(address)\":{\"details\":\"Upgrade the implementation of the proxy. NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\"},\"upgradeToAndCall(address,bytes)\":{\"details\":\"Upgrade the implementation of the proxy, and then call a function from the new implementation as specified by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the proxied contract. NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\"}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"solc_0.8/openzeppelin/proxy/transparent/TransparentUpgradeableProxy.sol\":\"TransparentUpgradeableProxy\"},\"evmVersion\":\"london\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":999999},\"remappings\":[]},\"sources\":{\"solc_0.8/openzeppelin/interfaces/draft-IERC1822.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (interfaces/draft-IERC1822.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\\n * proxy whose upgrades are fully controlled by the current implementation.\\n */\\ninterface IERC1822Proxiable {\\n /**\\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\\n * address.\\n *\\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\\n * function revert if invoked through a proxy.\\n */\\n function proxiableUUID() external view returns (bytes32);\\n}\\n\",\"keccak256\":\"0x93b4e21c931252739a1ec13ea31d3d35a5c068be3163ccab83e4d70c40355f03\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../Proxy.sol\\\";\\nimport \\\"./ERC1967Upgrade.sol\\\";\\n\\n/**\\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\\n * implementation address that can be changed. This address is stored in storage in the location specified by\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\\n * implementation behind the proxy.\\n */\\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\\n /**\\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\\n *\\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\\n * function call, and allows initializating the storage of the proxy like a Solidity constructor.\\n */\\n constructor(address _logic, bytes memory _data) payable {\\n assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256(\\\"eip1967.proxy.implementation\\\")) - 1));\\n _upgradeToAndCall(_logic, _data, false);\\n }\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _implementation() internal view virtual override returns (address impl) {\\n return ERC1967Upgrade._getImplementation();\\n }\\n}\\n\",\"keccak256\":\"0x6309f9f39dc6f4f45a24f296543867aa358e32946cd6b2874627a996d606b3a0\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/ERC1967/ERC1967Upgrade.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/ERC1967/ERC1967Upgrade.sol)\\n\\npragma solidity ^0.8.2;\\n\\nimport \\\"../beacon/IBeacon.sol\\\";\\nimport \\\"../../interfaces/draft-IERC1822.sol\\\";\\nimport \\\"../../utils/Address.sol\\\";\\nimport \\\"../../utils/StorageSlot.sol\\\";\\n\\n/**\\n * @dev This abstract contract provides getters and event emitting update functions for\\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\\n *\\n * _Available since v4.1._\\n *\\n * @custom:oz-upgrades-unsafe-allow delegatecall\\n */\\nabstract contract ERC1967Upgrade {\\n // This is the keccak-256 hash of \\\"eip1967.proxy.rollback\\\" subtracted by 1\\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\\n\\n /**\\n * @dev Storage slot with the address of the current implementation.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.implementation\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n\\n /**\\n * @dev Emitted when the implementation is upgraded.\\n */\\n event Upgraded(address indexed implementation);\\n\\n /**\\n * @dev Returns the current implementation address.\\n */\\n function _getImplementation() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 implementation slot.\\n */\\n function _setImplementation(address newImplementation) private {\\n require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n }\\n\\n /**\\n * @dev Perform implementation upgrade\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeTo(address newImplementation) internal {\\n _setImplementation(newImplementation);\\n emit Upgraded(newImplementation);\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCall(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _upgradeTo(newImplementation);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(newImplementation, data);\\n }\\n }\\n\\n /**\\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\\n *\\n * Emits an {Upgraded} event.\\n */\\n function _upgradeToAndCallUUPS(\\n address newImplementation,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n // Upgrades from old implementations will perform a rollback test. This test requires the new\\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\\n // this special case will break upgrade paths from old UUPS implementation to new ones.\\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\\n _setImplementation(newImplementation);\\n } else {\\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\\n require(slot == _IMPLEMENTATION_SLOT, \\\"ERC1967Upgrade: unsupported proxiableUUID\\\");\\n } catch {\\n revert(\\\"ERC1967Upgrade: new implementation is not UUPS\\\");\\n }\\n _upgradeToAndCall(newImplementation, data, forceCall);\\n }\\n }\\n\\n /**\\n * @dev Storage slot with the admin of the contract.\\n * This is the keccak-256 hash of \\\"eip1967.proxy.admin\\\" subtracted by 1, and is\\n * validated in the constructor.\\n */\\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\\n\\n /**\\n * @dev Emitted when the admin account has changed.\\n */\\n event AdminChanged(address previousAdmin, address newAdmin);\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _getAdmin() internal view virtual returns (address) {\\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new address in the EIP1967 admin slot.\\n */\\n function _setAdmin(address newAdmin) private {\\n require(newAdmin != address(0), \\\"ERC1967: new admin is the zero address\\\");\\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n */\\n function _changeAdmin(address newAdmin) internal {\\n emit AdminChanged(_getAdmin(), newAdmin);\\n _setAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\\n */\\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\\n\\n /**\\n * @dev Emitted when the beacon is upgraded.\\n */\\n event BeaconUpgraded(address indexed beacon);\\n\\n /**\\n * @dev Returns the current beacon.\\n */\\n function _getBeacon() internal view returns (address) {\\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\\n }\\n\\n /**\\n * @dev Stores a new beacon in the EIP1967 beacon slot.\\n */\\n function _setBeacon(address newBeacon) private {\\n require(Address.isContract(newBeacon), \\\"ERC1967: new beacon is not a contract\\\");\\n require(Address.isContract(IBeacon(newBeacon).implementation()), \\\"ERC1967: beacon implementation is not a contract\\\");\\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\\n }\\n\\n /**\\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\\n *\\n * Emits a {BeaconUpgraded} event.\\n */\\n function _upgradeBeaconToAndCall(\\n address newBeacon,\\n bytes memory data,\\n bool forceCall\\n ) internal {\\n _setBeacon(newBeacon);\\n emit BeaconUpgraded(newBeacon);\\n if (data.length > 0 || forceCall) {\\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\\n }\\n }\\n}\\n\",\"keccak256\":\"0x17668652127feebed0ce8d9431ef95ccc8c4292f03e3b8cf06c6ca16af396633\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/Proxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (proxy/Proxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\\n * be specified by overriding the virtual {_implementation} function.\\n *\\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\\n * different contract through the {_delegate} function.\\n *\\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\\n */\\nabstract contract Proxy {\\n /**\\n * @dev Delegates the current call to `implementation`.\\n *\\n * This function does not return to its internal call site, it will return directly to the external caller.\\n */\\n function _delegate(address implementation) internal virtual {\\n assembly {\\n // Copy msg.data. We take full control of memory in this inline assembly\\n // block because it will not return to Solidity code. We overwrite the\\n // Solidity scratch pad at memory position 0.\\n calldatacopy(0, 0, calldatasize())\\n\\n // Call the implementation.\\n // out and outsize are 0 because we don't know the size yet.\\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\\n\\n // Copy the returned data.\\n returndatacopy(0, 0, returndatasize())\\n\\n switch result\\n // delegatecall returns 0 on error.\\n case 0 {\\n revert(0, returndatasize())\\n }\\n default {\\n return(0, returndatasize())\\n }\\n }\\n }\\n\\n /**\\n * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function\\n * and {_fallback} should delegate.\\n */\\n function _implementation() internal view virtual returns (address);\\n\\n /**\\n * @dev Delegates the current call to the address returned by `_implementation()`.\\n *\\n * This function does not return to its internall call site, it will return directly to the external caller.\\n */\\n function _fallback() internal virtual {\\n _beforeFallback();\\n _delegate(_implementation());\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\\n * function in the contract matches the call data.\\n */\\n fallback() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\\n * is empty.\\n */\\n receive() external payable virtual {\\n _fallback();\\n }\\n\\n /**\\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\\n * call, or as part of the Solidity `fallback` or `receive` functions.\\n *\\n * If overriden should call `super._beforeFallback()`.\\n */\\n function _beforeFallback() internal virtual {}\\n}\\n\",\"keccak256\":\"0xd5d1fd16e9faff7fcb3a52e02a8d49156f42a38a03f07b5f1810c21c2149a8ab\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/beacon/IBeacon.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\\n */\\ninterface IBeacon {\\n /**\\n * @dev Must return an address that can be used as a delegate call target.\\n *\\n * {BeaconProxy} will check that this address is a contract.\\n */\\n function implementation() external view returns (address);\\n}\\n\",\"keccak256\":\"0xd50a3421ac379ccb1be435fa646d66a65c986b4924f0849839f08692f39dde61\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/proxy/transparent/TransparentUpgradeableProxy.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)\\n\\npragma solidity ^0.8.0;\\n\\nimport \\\"../ERC1967/ERC1967Proxy.sol\\\";\\n\\n/**\\n * @dev This contract implements a proxy that is upgradeable by an admin.\\n *\\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\\n * clashing], which can potentially be used in an attack, this contract uses the\\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\\n * things that go hand in hand:\\n *\\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\\n * that call matches one of the admin functions exposed by the proxy itself.\\n * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the\\n * implementation. If the admin tries to call a function on the implementation it will fail with an error that says\\n * \\\"admin cannot fallback to proxy target\\\".\\n *\\n * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing\\n * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due\\n * to sudden errors when trying to call a function from the proxy implementation.\\n *\\n * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,\\n * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\\n */\\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\\n /**\\n * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and\\n * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\\n */\\n constructor(\\n address _logic,\\n address admin_,\\n bytes memory _data\\n ) payable ERC1967Proxy(_logic, _data) {\\n assert(_ADMIN_SLOT == bytes32(uint256(keccak256(\\\"eip1967.proxy.admin\\\")) - 1));\\n _changeAdmin(admin_);\\n }\\n\\n /**\\n * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.\\n */\\n modifier ifAdmin() {\\n if (msg.sender == _getAdmin()) {\\n _;\\n } else {\\n _fallback();\\n }\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\\n */\\n function admin() external ifAdmin returns (address admin_) {\\n admin_ = _getAdmin();\\n }\\n\\n /**\\n * @dev Returns the current implementation.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.\\n *\\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\\n */\\n function implementation() external ifAdmin returns (address implementation_) {\\n implementation_ = _implementation();\\n }\\n\\n /**\\n * @dev Changes the admin of the proxy.\\n *\\n * Emits an {AdminChanged} event.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\\n */\\n function changeAdmin(address newAdmin) external virtual ifAdmin {\\n _changeAdmin(newAdmin);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\\n */\\n function upgradeTo(address newImplementation) external ifAdmin {\\n _upgradeToAndCall(newImplementation, bytes(\\\"\\\"), false);\\n }\\n\\n /**\\n * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified\\n * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the\\n * proxied contract.\\n *\\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\\n */\\n function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {\\n _upgradeToAndCall(newImplementation, data, true);\\n }\\n\\n /**\\n * @dev Returns the current admin.\\n */\\n function _admin() internal view virtual returns (address) {\\n return _getAdmin();\\n }\\n\\n /**\\n * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.\\n */\\n function _beforeFallback() internal virtual override {\\n require(msg.sender != _getAdmin(), \\\"TransparentUpgradeableProxy: admin cannot fallback to proxy target\\\");\\n super._beforeFallback();\\n }\\n}\\n\",\"keccak256\":\"0x140055a64cf579d622e04f5a198595832bf2cb193cd0005f4f2d4d61ca906253\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/utils/Address.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v4.5.0-rc.0) (utils/Address.sol)\\n\\npragma solidity ^0.8.1;\\n\\n/**\\n * @dev Collection of functions related to the address type\\n */\\nlibrary Address {\\n /**\\n * @dev Returns true if `account` is a contract.\\n *\\n * [IMPORTANT]\\n * ====\\n * It is unsafe to assume that an address for which this function returns\\n * false is an externally-owned account (EOA) and not a contract.\\n *\\n * Among others, `isContract` will return false for the following\\n * types of addresses:\\n *\\n * - an externally-owned account\\n * - a contract in construction\\n * - an address where a contract will be created\\n * - an address where a contract lived, but was destroyed\\n * ====\\n *\\n * [IMPORTANT]\\n * ====\\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\\n *\\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\\n * constructor.\\n * ====\\n */\\n function isContract(address account) internal view returns (bool) {\\n // This method relies on extcodesize/address.code.length, which returns 0\\n // for contracts in construction, since the code is only stored at the end\\n // of the constructor execution.\\n\\n return account.code.length > 0;\\n }\\n\\n /**\\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\\n * `recipient`, forwarding all available gas and reverting on errors.\\n *\\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\\n * imposed by `transfer`, making them unable to receive funds via\\n * `transfer`. {sendValue} removes this limitation.\\n *\\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\\n *\\n * IMPORTANT: because control is transferred to `recipient`, care must be\\n * taken to not create reentrancy vulnerabilities. Consider using\\n * {ReentrancyGuard} or the\\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\\n */\\n function sendValue(address payable recipient, uint256 amount) internal {\\n require(address(this).balance >= amount, \\\"Address: insufficient balance\\\");\\n\\n (bool success, ) = recipient.call{value: amount}(\\\"\\\");\\n require(success, \\\"Address: unable to send value, recipient may have reverted\\\");\\n }\\n\\n /**\\n * @dev Performs a Solidity function call using a low level `call`. A\\n * plain `call` is an unsafe replacement for a function call: use this\\n * function instead.\\n *\\n * If `target` reverts with a revert reason, it is bubbled up by this\\n * function (like regular Solidity function calls).\\n *\\n * Returns the raw returned data. To convert to the expected return value,\\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\\n *\\n * Requirements:\\n *\\n * - `target` must be a contract.\\n * - calling `target` with `data` must not revert.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionCall(target, data, \\\"Address: low-level call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\\n * `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, 0, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but also transferring `value` wei to `target`.\\n *\\n * Requirements:\\n *\\n * - the calling contract must have an ETH balance of at least `value`.\\n * - the called Solidity function must be `payable`.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value\\n ) internal returns (bytes memory) {\\n return functionCallWithValue(target, data, value, \\\"Address: low-level call with value failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\\n * with `errorMessage` as a fallback revert reason when `target` reverts.\\n *\\n * _Available since v3.1._\\n */\\n function functionCallWithValue(\\n address target,\\n bytes memory data,\\n uint256 value,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(address(this).balance >= value, \\\"Address: insufficient balance for call\\\");\\n require(isContract(target), \\\"Address: call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.call{value: value}(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\\n return functionStaticCall(target, data, \\\"Address: low-level static call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a static call.\\n *\\n * _Available since v3.3._\\n */\\n function functionStaticCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal view returns (bytes memory) {\\n require(isContract(target), \\\"Address: static call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.staticcall(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\\n return functionDelegateCall(target, data, \\\"Address: low-level delegate call failed\\\");\\n }\\n\\n /**\\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\\n * but performing a delegate call.\\n *\\n * _Available since v3.4._\\n */\\n function functionDelegateCall(\\n address target,\\n bytes memory data,\\n string memory errorMessage\\n ) internal returns (bytes memory) {\\n require(isContract(target), \\\"Address: delegate call to non-contract\\\");\\n\\n (bool success, bytes memory returndata) = target.delegatecall(data);\\n return verifyCallResult(success, returndata, errorMessage);\\n }\\n\\n /**\\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\\n * revert reason using the provided one.\\n *\\n * _Available since v4.3._\\n */\\n function verifyCallResult(\\n bool success,\\n bytes memory returndata,\\n string memory errorMessage\\n ) internal pure returns (bytes memory) {\\n if (success) {\\n return returndata;\\n } else {\\n // Look for revert reason and bubble it up if present\\n if (returndata.length > 0) {\\n // The easiest way to bubble the revert reason is using memory via assembly\\n\\n assembly {\\n let returndata_size := mload(returndata)\\n revert(add(32, returndata), returndata_size)\\n }\\n } else {\\n revert(errorMessage);\\n }\\n }\\n }\\n}\\n\",\"keccak256\":\"0x3777e696b62134e6177440dbe6e6601c0c156a443f57167194b67e75527439de\",\"license\":\"MIT\"},\"solc_0.8/openzeppelin/utils/StorageSlot.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)\\n\\npragma solidity ^0.8.0;\\n\\n/**\\n * @dev Library for reading and writing primitive types to specific storage slots.\\n *\\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\\n * This library helps with reading and writing to such slots without the need for inline assembly.\\n *\\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\\n *\\n * Example usage to set ERC1967 implementation slot:\\n * ```\\n * contract ERC1967 {\\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\\n *\\n * function _getImplementation() internal view returns (address) {\\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\\n * }\\n *\\n * function _setImplementation(address newImplementation) internal {\\n * require(Address.isContract(newImplementation), \\\"ERC1967: new implementation is not a contract\\\");\\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\\n * }\\n * }\\n * ```\\n *\\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\\n */\\nlibrary StorageSlot {\\n struct AddressSlot {\\n address value;\\n }\\n\\n struct BooleanSlot {\\n bool value;\\n }\\n\\n struct Bytes32Slot {\\n bytes32 value;\\n }\\n\\n struct Uint256Slot {\\n uint256 value;\\n }\\n\\n /**\\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\\n */\\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\\n */\\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\\n */\\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n\\n /**\\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\\n */\\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\\n assembly {\\n r.slot := slot\\n }\\n }\\n}\\n\",\"keccak256\":\"0xfe1b7a9aa2a530a9e705b220e26cd584e2fbdc9602a3a1066032b12816b46aca\",\"license\":\"MIT\"}},\"version\":1}", + "bytecode": "0x6080604052604051620011b2380380620011b2833981016040819052620000269162000519565b82816200005560017f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbd620005f9565b6000805160206200116b833981519152146200007557620000756200061f565b6200008382826000620000e7565b50620000b3905060017fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6104620005f9565b6000805160206200114b83398151915214620000d357620000d36200061f565b620000de8262000124565b50505062000688565b620000f2836200017f565b600082511180620001005750805b156200011f576200011d8383620001c160201b620002ff1760201c565b505b505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6200014f620001f0565b604080516001600160a01b03928316815291841660208301520160405180910390a16200017c8162000229565b50565b6200018a81620002de565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b6060620001e983836040518060600160405280602781526020016200118b6027913962000381565b9392505050565b60006200021a6000805160206200114b83398151915260001b6200046760201b620002731760201c565b546001600160a01b0316919050565b6001600160a01b038116620002945760405162461bcd60e51b815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201526564647265737360d01b60648201526084015b60405180910390fd5b80620002bd6000805160206200114b83398151915260001b6200046760201b620002731760201c565b80546001600160a01b0319166001600160a01b039290921691909117905550565b620002f4816200046a60201b6200032b1760201c565b620003585760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084016200028b565b80620002bd6000805160206200116b83398151915260001b6200046760201b620002731760201c565b60606001600160a01b0384163b620003eb5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f6044820152651b9d1c9858dd60d21b60648201526084016200028b565b600080856001600160a01b03168560405162000408919062000635565b600060405180830381855af49150503d806000811462000445576040519150601f19603f3d011682016040523d82523d6000602084013e6200044a565b606091505b5090925090506200045d82828662000479565b9695505050505050565b90565b6001600160a01b03163b151590565b606083156200048a575081620001e9565b8251156200049b5782518084602001fd5b8160405162461bcd60e51b81526004016200028b919062000653565b80516001600160a01b0381168114620004cf57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101562000507578181015183820152602001620004ed565b838111156200011d5750506000910152565b6000806000606084860312156200052f57600080fd5b6200053a84620004b7565b92506200054a60208501620004b7565b60408501519092506001600160401b03808211156200056857600080fd5b818601915086601f8301126200057d57600080fd5b815181811115620005925762000592620004d4565b604051601f8201601f19908116603f01168101908382118183101715620005bd57620005bd620004d4565b81604052828152896020848701011115620005d757600080fd5b620005ea836020830160208801620004ea565b80955050505050509250925092565b6000828210156200061a57634e487b7160e01b600052601160045260246000fd5b500390565b634e487b7160e01b600052600160045260246000fd5b6000825162000649818460208701620004ea565b9190910192915050565b602081526000825180602084015262000674816040850160208701620004ea565b601f01601f19169190910160400192915050565b610ab380620006986000396000f3fe60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100a85780638f283970146100e6578063f851a440146101065761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61011b565b005b61006b61011b565b34801561008157600080fd5b5061006b61009036600461091f565b610135565b61006b6100a336600461093a565b610196565b3480156100b457600080fd5b506100bd610221565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b3480156100f257600080fd5b5061006b61010136600461091f565b610276565b34801561011257600080fd5b506100bd6102ba565b610123610347565b61013361012e610435565b61043f565b565b61013d610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816040518060200160405280600081525060006104a3565b50565b61018b61011b565b61019e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610219576102148383838080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250600192506104a3915050565b505050565b61021461011b565b600061022b610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610435565b905090565b61027361011b565b90565b61027e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816104ce565b60006102c4610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610463565b60606103248383604051806060016040528060278152602001610a576027913961052f565b9392505050565b73ffffffffffffffffffffffffffffffffffffffff163b151590565b61034f610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152604260248201527f5472616e73706172656e745570677261646561626c6550726f78793a2061646d60448201527f696e2063616e6e6f742066616c6c6261636b20746f2070726f7879207461726760648201527f6574000000000000000000000000000000000000000000000000000000000000608482015260a4015b60405180910390fd5b6000610266610657565b3660008037600080366000845af43d6000803e80801561045e573d6000f35b3d6000fd5b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b5473ffffffffffffffffffffffffffffffffffffffff16919050565b6104ac8361067f565b6000825111806104b95750805b15610214576104c883836102ff565b50505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6104f7610463565b6040805173ffffffffffffffffffffffffffffffffffffffff928316815291841660208301520160405180910390a161018b816106cc565b606073ffffffffffffffffffffffffffffffffffffffff84163b6105d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f60448201527f6e74726163740000000000000000000000000000000000000000000000000000606482015260840161042c565b6000808573ffffffffffffffffffffffffffffffffffffffff16856040516105fd91906109e9565b600060405180830381855af49150503d8060008114610638576040519150601f19603f3d011682016040523d82523d6000602084013e61063d565b606091505b509150915061064d8282866107d8565b9695505050505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610487565b6106888161082b565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b73ffffffffffffffffffffffffffffffffffffffff811661076f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201527f6464726573730000000000000000000000000000000000000000000000000000606482015260840161042c565b807fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff9290921691909117905550565b606083156107e7575081610324565b8251156107f75782518084602001fd5b816040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042c9190610a05565b73ffffffffffffffffffffffffffffffffffffffff81163b6108cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e747261637400000000000000000000000000000000000000606482015260840161042c565b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610792565b803573ffffffffffffffffffffffffffffffffffffffff8116811461091a57600080fd5b919050565b60006020828403121561093157600080fd5b610324826108f6565b60008060006040848603121561094f57600080fd5b610958846108f6565b9250602084013567ffffffffffffffff8082111561097557600080fd5b818601915086601f83011261098957600080fd5b81358181111561099857600080fd5b8760208285010111156109aa57600080fd5b6020830194508093505050509250925092565b60005b838110156109d85781810151838201526020016109c0565b838111156104c85750506000910152565b600082516109fb8184602087016109bd565b9190910192915050565b6020815260008251806020840152610a248160408501602087016109bd565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016919091016040019291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220b29caa54336b3ee836679675e9732ec5e526fb3f803cca2fe336cc3555aba62264736f6c634300080a0033b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564", + "deployedBytecode": "0x60806040526004361061005e5760003560e01c80635c60da1b116100435780635c60da1b146100a85780638f283970146100e6578063f851a440146101065761006d565b80633659cfe6146100755780634f1ef286146100955761006d565b3661006d5761006b61011b565b005b61006b61011b565b34801561008157600080fd5b5061006b61009036600461091f565b610135565b61006b6100a336600461093a565b610196565b3480156100b457600080fd5b506100bd610221565b60405173ffffffffffffffffffffffffffffffffffffffff909116815260200160405180910390f35b3480156100f257600080fd5b5061006b61010136600461091f565b610276565b34801561011257600080fd5b506100bd6102ba565b610123610347565b61013361012e610435565b61043f565b565b61013d610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816040518060200160405280600081525060006104a3565b50565b61018b61011b565b61019e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610219576102148383838080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250600192506104a3915050565b505050565b61021461011b565b600061022b610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610435565b905090565b61027361011b565b90565b61027e610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561018e5761018b816104ce565b60006102c4610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141561026b57610266610463565b60606103248383604051806060016040528060278152602001610a576027913961052f565b9392505050565b73ffffffffffffffffffffffffffffffffffffffff163b151590565b61034f610463565b73ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415610133576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152604260248201527f5472616e73706172656e745570677261646561626c6550726f78793a2061646d60448201527f696e2063616e6e6f742066616c6c6261636b20746f2070726f7879207461726760648201527f6574000000000000000000000000000000000000000000000000000000000000608482015260a4015b60405180910390fd5b6000610266610657565b3660008037600080366000845af43d6000803e80801561045e573d6000f35b3d6000fd5b60007fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b5473ffffffffffffffffffffffffffffffffffffffff16919050565b6104ac8361067f565b6000825111806104b95750805b15610214576104c883836102ff565b50505050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6104f7610463565b6040805173ffffffffffffffffffffffffffffffffffffffff928316815291841660208301520160405180910390a161018b816106cc565b606073ffffffffffffffffffffffffffffffffffffffff84163b6105d5576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f60448201527f6e74726163740000000000000000000000000000000000000000000000000000606482015260840161042c565b6000808573ffffffffffffffffffffffffffffffffffffffff16856040516105fd91906109e9565b600060405180830381855af49150503d8060008114610638576040519150601f19603f3d011682016040523d82523d6000602084013e61063d565b606091505b509150915061064d8282866107d8565b9695505050505050565b60007f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610487565b6106888161082b565b60405173ffffffffffffffffffffffffffffffffffffffff8216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b73ffffffffffffffffffffffffffffffffffffffff811661076f576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f455243313936373a206e65772061646d696e20697320746865207a65726f206160448201527f6464726573730000000000000000000000000000000000000000000000000000606482015260840161042c565b807fb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d61035b80547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff9290921691909117905550565b606083156107e7575081610324565b8251156107f75782518084602001fd5b816040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161042c9190610a05565b73ffffffffffffffffffffffffffffffffffffffff81163b6108cf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201527f6f74206120636f6e747261637400000000000000000000000000000000000000606482015260840161042c565b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc610792565b803573ffffffffffffffffffffffffffffffffffffffff8116811461091a57600080fd5b919050565b60006020828403121561093157600080fd5b610324826108f6565b60008060006040848603121561094f57600080fd5b610958846108f6565b9250602084013567ffffffffffffffff8082111561097557600080fd5b818601915086601f83011261098957600080fd5b81358181111561099857600080fd5b8760208285010111156109aa57600080fd5b6020830194508093505050509250925092565b60005b838110156109d85781810151838201526020016109c0565b838111156104c85750506000910152565b600082516109fb8184602087016109bd565b9190910192915050565b6020815260008251806020840152610a248160408501602087016109bd565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016919091016040019291505056fe416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a2646970667358221220b29caa54336b3ee836679675e9732ec5e526fb3f803cca2fe336cc3555aba62264736f6c634300080a0033", + "devdoc": { + "details": "This contract implements a proxy that is upgradeable by an admin. To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector clashing], which can potentially be used in an attack, this contract uses the https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two things that go hand in hand: 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if that call matches one of the admin functions exposed by the proxy itself. 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the implementation. If the admin tries to call a function on the implementation it will fail with an error that says \"admin cannot fallback to proxy target\". These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to call a function from the proxy implementation. Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.", + "kind": "dev", + "methods": { + "admin()": { + "details": "Returns the current admin. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`" + }, + "changeAdmin(address)": { + "details": "Changes the admin of the proxy. Emits an {AdminChanged} event. NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}." + }, + "constructor": { + "details": "Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}." + }, + "implementation()": { + "details": "Returns the current implementation. NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`" + }, + "upgradeTo(address)": { + "details": "Upgrade the implementation of the proxy. NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}." + }, + "upgradeToAndCall(address,bytes)": { + "details": "Upgrade the implementation of the proxy, and then call a function from the new implementation as specified by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the proxied contract. NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}." + } + }, + "version": 1 + }, + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 + }, + "storageLayout": { + "storage": [], + "types": null + } +} \ No newline at end of file diff --git a/packages/contracts/deployments/base/solcInputs/34a0d1556aea7d4f3124b66dedee8846.json b/packages/contracts/deployments/base/solcInputs/34a0d1556aea7d4f3124b66dedee8846.json new file mode 100644 index 0000000000..41c379f7b5 --- /dev/null +++ b/packages/contracts/deployments/base/solcInputs/34a0d1556aea7d4f3124b66dedee8846.json @@ -0,0 +1,957 @@ +{ + "language": "Solidity", + "sources": { + "@layerzerolabs/lz-evm-messagelib-v2/contracts/libs/ExecutorOptions.sol": { + "content": "// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nimport \"@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol\";\n\nlibrary ExecutorOptions {\n using CalldataBytesLib for bytes;\n\n uint8 internal constant WORKER_ID = 1;\n\n uint8 internal constant OPTION_TYPE_LZRECEIVE = 1;\n uint8 internal constant OPTION_TYPE_NATIVE_DROP = 2;\n uint8 internal constant OPTION_TYPE_LZCOMPOSE = 3;\n uint8 internal constant OPTION_TYPE_ORDERED_EXECUTION = 4;\n uint8 internal constant OPTION_TYPE_LZREAD = 5;\n\n error Executor_InvalidLzReceiveOption();\n error Executor_InvalidNativeDropOption();\n error Executor_InvalidLzComposeOption();\n error Executor_InvalidLzReadOption();\n\n /// @dev decode the next executor option from the options starting from the specified cursor\n /// @param _options [executor_id][executor_option][executor_id][executor_option]...\n /// executor_option = [option_size][option_type][option]\n /// option_size = len(option_type) + len(option)\n /// executor_id: uint8, option_size: uint16, option_type: uint8, option: bytes\n /// @param _cursor the cursor to start decoding from\n /// @return optionType the type of the option\n /// @return option the option of the executor\n /// @return cursor the cursor to start decoding the next executor option\n function nextExecutorOption(\n bytes calldata _options,\n uint256 _cursor\n ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) {\n unchecked {\n // skip worker id\n cursor = _cursor + 1;\n\n // read option size\n uint16 size = _options.toU16(cursor);\n cursor += 2;\n\n // read option type\n optionType = _options.toU8(cursor);\n\n // startCursor and endCursor are used to slice the option from _options\n uint256 startCursor = cursor + 1; // skip option type\n uint256 endCursor = cursor + size;\n option = _options[startCursor:endCursor];\n cursor += size;\n }\n }\n\n function decodeLzReceiveOption(bytes calldata _option) internal pure returns (uint128 gas, uint128 value) {\n if (_option.length != 16 && _option.length != 32) revert Executor_InvalidLzReceiveOption();\n gas = _option.toU128(0);\n value = _option.length == 32 ? _option.toU128(16) : 0;\n }\n\n function decodeNativeDropOption(bytes calldata _option) internal pure returns (uint128 amount, bytes32 receiver) {\n if (_option.length != 48) revert Executor_InvalidNativeDropOption();\n amount = _option.toU128(0);\n receiver = _option.toB32(16);\n }\n\n function decodeLzComposeOption(\n bytes calldata _option\n ) internal pure returns (uint16 index, uint128 gas, uint128 value) {\n if (_option.length != 18 && _option.length != 34) revert Executor_InvalidLzComposeOption();\n index = _option.toU16(0);\n gas = _option.toU128(2);\n value = _option.length == 34 ? _option.toU128(18) : 0;\n }\n\n function decodeLzReadOption(\n bytes calldata _option\n ) internal pure returns (uint128 gas, uint32 calldataSize, uint128 value) {\n if (_option.length != 20 && _option.length != 36) revert Executor_InvalidLzReadOption();\n gas = _option.toU128(0);\n calldataSize = _option.toU32(16);\n value = _option.length == 36 ? _option.toU128(20) : 0;\n }\n\n function encodeLzReceiveOption(uint128 _gas, uint128 _value) internal pure returns (bytes memory) {\n return _value == 0 ? abi.encodePacked(_gas) : abi.encodePacked(_gas, _value);\n }\n\n function encodeNativeDropOption(uint128 _amount, bytes32 _receiver) internal pure returns (bytes memory) {\n return abi.encodePacked(_amount, _receiver);\n }\n\n function encodeLzComposeOption(uint16 _index, uint128 _gas, uint128 _value) internal pure returns (bytes memory) {\n return _value == 0 ? abi.encodePacked(_index, _gas) : abi.encodePacked(_index, _gas, _value);\n }\n\n function encodeLzReadOption(\n uint128 _gas,\n uint32 _calldataSize,\n uint128 _value\n ) internal pure returns (bytes memory) {\n return _value == 0 ? abi.encodePacked(_gas, _calldataSize) : abi.encodePacked(_gas, _calldataSize, _value);\n }\n}\n" + }, + "@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/libs/DVNOptions.sol": { + "content": "// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nimport { BytesLib } from \"solidity-bytes-utils/contracts/BytesLib.sol\";\n\nimport { BitMap256 } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol\";\nimport { CalldataBytesLib } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol\";\n\nlibrary DVNOptions {\n using CalldataBytesLib for bytes;\n using BytesLib for bytes;\n\n uint8 internal constant WORKER_ID = 2;\n uint8 internal constant OPTION_TYPE_PRECRIME = 1;\n\n error DVN_InvalidDVNIdx();\n error DVN_InvalidDVNOptions(uint256 cursor);\n\n /// @dev group dvn options by its idx\n /// @param _options [dvn_id][dvn_option][dvn_id][dvn_option]...\n /// dvn_option = [option_size][dvn_idx][option_type][option]\n /// option_size = len(dvn_idx) + len(option_type) + len(option)\n /// dvn_id: uint8, dvn_idx: uint8, option_size: uint16, option_type: uint8, option: bytes\n /// @return dvnOptions the grouped options, still share the same format of _options\n /// @return dvnIndices the dvn indices\n function groupDVNOptionsByIdx(\n bytes memory _options\n ) internal pure returns (bytes[] memory dvnOptions, uint8[] memory dvnIndices) {\n if (_options.length == 0) return (dvnOptions, dvnIndices);\n\n uint8 numDVNs = getNumDVNs(_options);\n\n // if there is only 1 dvn, we can just return the whole options\n if (numDVNs == 1) {\n dvnOptions = new bytes[](1);\n dvnOptions[0] = _options;\n\n dvnIndices = new uint8[](1);\n dvnIndices[0] = _options.toUint8(3); // dvn idx\n return (dvnOptions, dvnIndices);\n }\n\n // otherwise, we need to group the options by dvn_idx\n dvnIndices = new uint8[](numDVNs);\n dvnOptions = new bytes[](numDVNs);\n unchecked {\n uint256 cursor = 0;\n uint256 start = 0;\n uint8 lastDVNIdx = 255; // 255 is an invalid dvn_idx\n\n while (cursor < _options.length) {\n ++cursor; // skip worker_id\n\n // optionLength asserted in getNumDVNs (skip check)\n uint16 optionLength = _options.toUint16(cursor);\n cursor += 2;\n\n // dvnIdx asserted in getNumDVNs (skip check)\n uint8 dvnIdx = _options.toUint8(cursor);\n\n // dvnIdx must equal to the lastDVNIdx for the first option\n // so it is always skipped in the first option\n // this operation slices out options whenever the scan finds a different lastDVNIdx\n if (lastDVNIdx == 255) {\n lastDVNIdx = dvnIdx;\n } else if (dvnIdx != lastDVNIdx) {\n uint256 len = cursor - start - 3; // 3 is for worker_id and option_length\n bytes memory opt = _options.slice(start, len);\n _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, opt);\n\n // reset the start and lastDVNIdx\n start += len;\n lastDVNIdx = dvnIdx;\n }\n\n cursor += optionLength;\n }\n\n // skip check the cursor here because the cursor is asserted in getNumDVNs\n // if we have reached the end of the options, we need to process the last dvn\n uint256 size = cursor - start;\n bytes memory op = _options.slice(start, size);\n _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, op);\n\n // revert dvnIndices to start from 0\n for (uint8 i = 0; i < numDVNs; ++i) {\n --dvnIndices[i];\n }\n }\n }\n\n function _insertDVNOptions(\n bytes[] memory _dvnOptions,\n uint8[] memory _dvnIndices,\n uint8 _dvnIdx,\n bytes memory _newOptions\n ) internal pure {\n // dvnIdx starts from 0 but default value of dvnIndices is 0,\n // so we tell if the slot is empty by adding 1 to dvnIdx\n if (_dvnIdx == 255) revert DVN_InvalidDVNIdx();\n uint8 dvnIdxAdj = _dvnIdx + 1;\n\n for (uint256 j = 0; j < _dvnIndices.length; ++j) {\n uint8 index = _dvnIndices[j];\n if (dvnIdxAdj == index) {\n _dvnOptions[j] = abi.encodePacked(_dvnOptions[j], _newOptions);\n break;\n } else if (index == 0) {\n // empty slot, that means it is the first time we see this dvn\n _dvnIndices[j] = dvnIdxAdj;\n _dvnOptions[j] = _newOptions;\n break;\n }\n }\n }\n\n /// @dev get the number of unique dvns\n /// @param _options the format is the same as groupDVNOptionsByIdx\n function getNumDVNs(bytes memory _options) internal pure returns (uint8 numDVNs) {\n uint256 cursor = 0;\n BitMap256 bitmap;\n\n // find number of unique dvn_idx\n unchecked {\n while (cursor < _options.length) {\n ++cursor; // skip worker_id\n\n uint16 optionLength = _options.toUint16(cursor);\n cursor += 2;\n if (optionLength < 2) revert DVN_InvalidDVNOptions(cursor); // at least 1 byte for dvn_idx and 1 byte for option_type\n\n uint8 dvnIdx = _options.toUint8(cursor);\n\n // if dvnIdx is not set, increment numDVNs\n // max num of dvns is 255, 255 is an invalid dvn_idx\n // The order of the dvnIdx is not required to be sequential, as enforcing the order may weaken\n // the composability of the options. e.g. if we refrain from enforcing the order, an OApp that has\n // already enforced certain options can append additional options to the end of the enforced\n // ones without restrictions.\n if (dvnIdx == 255) revert DVN_InvalidDVNIdx();\n if (!bitmap.get(dvnIdx)) {\n ++numDVNs;\n bitmap = bitmap.set(dvnIdx);\n }\n\n cursor += optionLength;\n }\n }\n if (cursor != _options.length) revert DVN_InvalidDVNOptions(cursor);\n }\n\n /// @dev decode the next dvn option from _options starting from the specified cursor\n /// @param _options the format is the same as groupDVNOptionsByIdx\n /// @param _cursor the cursor to start decoding\n /// @return optionType the type of the option\n /// @return option the option\n /// @return cursor the cursor to start decoding the next option\n function nextDVNOption(\n bytes calldata _options,\n uint256 _cursor\n ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) {\n unchecked {\n // skip worker id\n cursor = _cursor + 1;\n\n // read option size\n uint16 size = _options.toU16(cursor);\n cursor += 2;\n\n // read option type\n optionType = _options.toU8(cursor + 1); // skip dvn_idx\n\n // startCursor and endCursor are used to slice the option from _options\n uint256 startCursor = cursor + 2; // skip option type and dvn_idx\n uint256 endCursor = cursor + size;\n option = _options[startCursor:endCursor];\n cursor += size;\n }\n }\n}\n" + }, + "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { IMessageLibManager } from \"./IMessageLibManager.sol\";\nimport { IMessagingComposer } from \"./IMessagingComposer.sol\";\nimport { IMessagingChannel } from \"./IMessagingChannel.sol\";\nimport { IMessagingContext } from \"./IMessagingContext.sol\";\n\nstruct MessagingParams {\n uint32 dstEid;\n bytes32 receiver;\n bytes message;\n bytes options;\n bool payInLzToken;\n}\n\nstruct MessagingReceipt {\n bytes32 guid;\n uint64 nonce;\n MessagingFee fee;\n}\n\nstruct MessagingFee {\n uint256 nativeFee;\n uint256 lzTokenFee;\n}\n\nstruct Origin {\n uint32 srcEid;\n bytes32 sender;\n uint64 nonce;\n}\n\ninterface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {\n event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);\n\n event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);\n\n event PacketDelivered(Origin origin, address receiver);\n\n event LzReceiveAlert(\n address indexed receiver,\n address indexed executor,\n Origin origin,\n bytes32 guid,\n uint256 gas,\n uint256 value,\n bytes message,\n bytes extraData,\n bytes reason\n );\n\n event LzTokenSet(address token);\n\n event DelegateSet(address sender, address delegate);\n\n function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);\n\n function send(\n MessagingParams calldata _params,\n address _refundAddress\n ) external payable returns (MessagingReceipt memory);\n\n function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;\n\n function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);\n\n function initializable(Origin calldata _origin, address _receiver) external view returns (bool);\n\n function lzReceive(\n Origin calldata _origin,\n address _receiver,\n bytes32 _guid,\n bytes calldata _message,\n bytes calldata _extraData\n ) external payable;\n\n // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order\n function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;\n\n function setLzToken(address _lzToken) external;\n\n function lzToken() external view returns (address);\n\n function nativeToken() external view returns (address);\n\n function setDelegate(address _delegate) external;\n}\n" + }, + "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nimport { Origin } from \"./ILayerZeroEndpointV2.sol\";\n\ninterface ILayerZeroReceiver {\n function allowInitializePath(Origin calldata _origin) external view returns (bool);\n\n function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);\n\n function lzReceive(\n Origin calldata _origin,\n bytes32 _guid,\n bytes calldata _message,\n address _executor,\n bytes calldata _extraData\n ) external payable;\n}\n" + }, + "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLibManager.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\nstruct SetConfigParam {\n uint32 eid;\n uint32 configType;\n bytes config;\n}\n\ninterface IMessageLibManager {\n struct Timeout {\n address lib;\n uint256 expiry;\n }\n\n event LibraryRegistered(address newLib);\n event DefaultSendLibrarySet(uint32 eid, address newLib);\n event DefaultReceiveLibrarySet(uint32 eid, address newLib);\n event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);\n event SendLibrarySet(address sender, uint32 eid, address newLib);\n event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);\n event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);\n\n function registerLibrary(address _lib) external;\n\n function isRegisteredLibrary(address _lib) external view returns (bool);\n\n function getRegisteredLibraries() external view returns (address[] memory);\n\n function setDefaultSendLibrary(uint32 _eid, address _newLib) external;\n\n function defaultSendLibrary(uint32 _eid) external view returns (address);\n\n function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _timeout) external;\n\n function defaultReceiveLibrary(uint32 _eid) external view returns (address);\n\n function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;\n\n function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);\n\n function isSupportedEid(uint32 _eid) external view returns (bool);\n\n function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);\n\n /// ------------------- OApp interfaces -------------------\n function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;\n\n function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);\n\n function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);\n\n function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;\n\n function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);\n\n function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _gracePeriod) external;\n\n function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);\n\n function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;\n\n function getConfig(\n address _oapp,\n address _lib,\n uint32 _eid,\n uint32 _configType\n ) external view returns (bytes memory config);\n}\n" + }, + "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessagingChannel.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface IMessagingChannel {\n event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);\n event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);\n event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);\n\n function eid() external view returns (uint32);\n\n // this is an emergency function if a message cannot be verified for some reasons\n // required to provide _nextNonce to avoid race condition\n function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;\n\n function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;\n\n function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;\n\n function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);\n\n function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);\n\n function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);\n\n function inboundPayloadHash(\n address _receiver,\n uint32 _srcEid,\n bytes32 _sender,\n uint64 _nonce\n ) external view returns (bytes32);\n\n function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);\n}\n" + }, + "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessagingComposer.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface IMessagingComposer {\n event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);\n event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);\n event LzComposeAlert(\n address indexed from,\n address indexed to,\n address indexed executor,\n bytes32 guid,\n uint16 index,\n uint256 gas,\n uint256 value,\n bytes message,\n bytes extraData,\n bytes reason\n );\n\n function composeQueue(\n address _from,\n address _to,\n bytes32 _guid,\n uint16 _index\n ) external view returns (bytes32 messageHash);\n\n function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;\n\n function lzCompose(\n address _from,\n address _to,\n bytes32 _guid,\n uint16 _index,\n bytes calldata _message,\n bytes calldata _extraData\n ) external payable;\n}\n" + }, + "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessagingContext.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface IMessagingContext {\n function isSendingMessage() external view returns (bool);\n\n function getSendContext() external view returns (uint32 dstEid, address sender);\n}\n" + }, + "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol": { + "content": "// SPDX-License-Identifier: LZBL-1.2\n\npragma solidity ^0.8.20;\n\nlibrary CalldataBytesLib {\n function toU8(bytes calldata _bytes, uint256 _start) internal pure returns (uint8) {\n return uint8(_bytes[_start]);\n }\n\n function toU16(bytes calldata _bytes, uint256 _start) internal pure returns (uint16) {\n unchecked {\n uint256 end = _start + 2;\n return uint16(bytes2(_bytes[_start:end]));\n }\n }\n\n function toU32(bytes calldata _bytes, uint256 _start) internal pure returns (uint32) {\n unchecked {\n uint256 end = _start + 4;\n return uint32(bytes4(_bytes[_start:end]));\n }\n }\n\n function toU64(bytes calldata _bytes, uint256 _start) internal pure returns (uint64) {\n unchecked {\n uint256 end = _start + 8;\n return uint64(bytes8(_bytes[_start:end]));\n }\n }\n\n function toU128(bytes calldata _bytes, uint256 _start) internal pure returns (uint128) {\n unchecked {\n uint256 end = _start + 16;\n return uint128(bytes16(_bytes[_start:end]));\n }\n }\n\n function toU256(bytes calldata _bytes, uint256 _start) internal pure returns (uint256) {\n unchecked {\n uint256 end = _start + 32;\n return uint256(bytes32(_bytes[_start:end]));\n }\n }\n\n function toAddr(bytes calldata _bytes, uint256 _start) internal pure returns (address) {\n unchecked {\n uint256 end = _start + 20;\n return address(bytes20(_bytes[_start:end]));\n }\n }\n\n function toB32(bytes calldata _bytes, uint256 _start) internal pure returns (bytes32) {\n unchecked {\n uint256 end = _start + 32;\n return bytes32(_bytes[_start:end]);\n }\n }\n}\n" + }, + "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol": { + "content": "// SPDX-License-Identifier: MIT\n\n// modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/BitMaps.sol\npragma solidity ^0.8.20;\n\ntype BitMap256 is uint256;\n\nusing BitMaps for BitMap256 global;\n\nlibrary BitMaps {\n /**\n * @dev Returns whether the bit at `index` is set.\n */\n function get(BitMap256 bitmap, uint8 index) internal pure returns (bool) {\n uint256 mask = 1 << index;\n return BitMap256.unwrap(bitmap) & mask != 0;\n }\n\n /**\n * @dev Sets the bit at `index`.\n */\n function set(BitMap256 bitmap, uint8 index) internal pure returns (BitMap256) {\n uint256 mask = 1 << index;\n return BitMap256.wrap(BitMap256.unwrap(bitmap) | mask);\n }\n}\n" + }, + "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppCore.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { ILayerZeroEndpointV2 } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol\";\n\n/**\n * @title IOAppCore\n */\ninterface IOAppCore {\n // Custom error messages\n error OnlyPeer(uint32 eid, bytes32 sender);\n error NoPeer(uint32 eid);\n error InvalidEndpointCall();\n error InvalidDelegate();\n\n // Event emitted when a peer (OApp) is set for a corresponding endpoint\n event PeerSet(uint32 eid, bytes32 peer);\n\n /**\n * @notice Retrieves the OApp version information.\n * @return senderVersion The version of the OAppSender.sol contract.\n * @return receiverVersion The version of the OAppReceiver.sol contract.\n */\n function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion);\n\n /**\n * @notice Retrieves the LayerZero endpoint associated with the OApp.\n * @return iEndpoint The LayerZero endpoint as an interface.\n */\n function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint);\n\n /**\n * @notice Retrieves the peer (OApp) associated with a corresponding endpoint.\n * @param _eid The endpoint ID.\n * @return peer The peer address (OApp instance) associated with the corresponding endpoint.\n */\n function peers(uint32 _eid) external view returns (bytes32 peer);\n\n /**\n * @notice Sets the peer address (OApp instance) for a corresponding endpoint.\n * @param _eid The endpoint ID.\n * @param _peer The address of the peer to be associated with the corresponding endpoint.\n */\n function setPeer(uint32 _eid, bytes32 _peer) external;\n\n /**\n * @notice Sets the delegate address for the OApp Core.\n * @param _delegate The address of the delegate to be set.\n */\n function setDelegate(address _delegate) external;\n}\n" + }, + "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppReceiver.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.20;\n\nimport { ILayerZeroReceiver, Origin } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol\";\n\ninterface IOAppReceiver is ILayerZeroReceiver {\n /**\n * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.\n * @param _origin The origin information containing the source endpoint and sender address.\n * - srcEid: The source chain endpoint ID.\n * - sender: The sender address on the src chain.\n * - nonce: The nonce of the message.\n * @param _message The lzReceive payload.\n * @param _sender The sender address.\n * @return isSender Is a valid sender.\n *\n * @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer.\n * @dev The default sender IS the OAppReceiver implementer.\n */\n function isComposeMsgSender(\n Origin calldata _origin,\n bytes calldata _message,\n address _sender\n ) external view returns (bool isSender);\n}\n" + }, + "@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { BytesLib } from \"solidity-bytes-utils/contracts/BytesLib.sol\";\nimport { SafeCast } from \"@openzeppelin/contracts/utils/math/SafeCast.sol\";\n\nimport { ExecutorOptions } from \"@layerzerolabs/lz-evm-messagelib-v2/contracts/libs/ExecutorOptions.sol\";\nimport { DVNOptions } from \"@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/libs/DVNOptions.sol\";\n\n/**\n * @title OptionsBuilder\n * @dev Library for building and encoding various message options.\n */\nlibrary OptionsBuilder {\n using SafeCast for uint256;\n using BytesLib for bytes;\n\n // Constants for options types\n uint16 internal constant TYPE_1 = 1; // legacy options type 1\n uint16 internal constant TYPE_2 = 2; // legacy options type 2\n uint16 internal constant TYPE_3 = 3;\n\n // Custom error message\n error InvalidSize(uint256 max, uint256 actual);\n error InvalidOptionType(uint16 optionType);\n\n // Modifier to ensure only options of type 3 are used\n modifier onlyType3(bytes memory _options) {\n if (_options.toUint16(0) != TYPE_3) revert InvalidOptionType(_options.toUint16(0));\n _;\n }\n\n /**\n * @dev Creates a new options container with type 3.\n * @return options The newly created options container.\n */\n function newOptions() internal pure returns (bytes memory) {\n return abi.encodePacked(TYPE_3);\n }\n\n /**\n * @dev Adds an executor LZ receive option to the existing options.\n * @param _options The existing options container.\n * @param _gas The gasLimit used on the lzReceive() function in the OApp.\n * @param _value The msg.value passed to the lzReceive() function in the OApp.\n * @return options The updated options container.\n *\n * @dev When multiples of this option are added, they are summed by the executor\n * eg. if (_gas: 200k, and _value: 1 ether) AND (_gas: 100k, _value: 0.5 ether) are sent in an option to the LayerZeroEndpoint,\n * that becomes (300k, 1.5 ether) when the message is executed on the remote lzReceive() function.\n */\n function addExecutorLzReceiveOption(\n bytes memory _options,\n uint128 _gas,\n uint128 _value\n ) internal pure onlyType3(_options) returns (bytes memory) {\n bytes memory option = ExecutorOptions.encodeLzReceiveOption(_gas, _value);\n return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZRECEIVE, option);\n }\n\n /**\n * @dev Adds an executor native drop option to the existing options.\n * @param _options The existing options container.\n * @param _amount The amount for the native value that is airdropped to the 'receiver'.\n * @param _receiver The receiver address for the native drop option.\n * @return options The updated options container.\n *\n * @dev When multiples of this option are added, they are summed by the executor on the remote chain.\n */\n function addExecutorNativeDropOption(\n bytes memory _options,\n uint128 _amount,\n bytes32 _receiver\n ) internal pure onlyType3(_options) returns (bytes memory) {\n bytes memory option = ExecutorOptions.encodeNativeDropOption(_amount, _receiver);\n return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_NATIVE_DROP, option);\n }\n\n // /**\n // * @dev Adds an executor native drop option to the existing options.\n // * @param _options The existing options container.\n // * @param _amount The amount for the native value that is airdropped to the 'receiver'.\n // * @param _receiver The receiver address for the native drop option.\n // * @return options The updated options container.\n // *\n // * @dev When multiples of this option are added, they are summed by the executor on the remote chain.\n // */\n function addExecutorLzReadOption(\n bytes memory _options,\n uint128 _gas,\n uint32 _size,\n uint128 _value\n ) internal pure onlyType3(_options) returns (bytes memory) {\n bytes memory option = ExecutorOptions.encodeLzReadOption(_gas, _size, _value);\n return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZREAD, option);\n }\n\n /**\n * @dev Adds an executor LZ compose option to the existing options.\n * @param _options The existing options container.\n * @param _index The index for the lzCompose() function call.\n * @param _gas The gasLimit for the lzCompose() function call.\n * @param _value The msg.value for the lzCompose() function call.\n * @return options The updated options container.\n *\n * @dev When multiples of this option are added, they are summed PER index by the executor on the remote chain.\n * @dev If the OApp sends N lzCompose calls on the remote, you must provide N incremented indexes starting with 0.\n * ie. When your remote OApp composes (N = 3) messages, you must set this option for index 0,1,2\n */\n function addExecutorLzComposeOption(\n bytes memory _options,\n uint16 _index,\n uint128 _gas,\n uint128 _value\n ) internal pure onlyType3(_options) returns (bytes memory) {\n bytes memory option = ExecutorOptions.encodeLzComposeOption(_index, _gas, _value);\n return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZCOMPOSE, option);\n }\n\n /**\n * @dev Adds an executor ordered execution option to the existing options.\n * @param _options The existing options container.\n * @return options The updated options container.\n */\n function addExecutorOrderedExecutionOption(\n bytes memory _options\n ) internal pure onlyType3(_options) returns (bytes memory) {\n return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_ORDERED_EXECUTION, bytes(\"\"));\n }\n\n /**\n * @dev Adds a DVN pre-crime option to the existing options.\n * @param _options The existing options container.\n * @param _dvnIdx The DVN index for the pre-crime option.\n * @return options The updated options container.\n */\n function addDVNPreCrimeOption(\n bytes memory _options,\n uint8 _dvnIdx\n ) internal pure onlyType3(_options) returns (bytes memory) {\n return addDVNOption(_options, _dvnIdx, DVNOptions.OPTION_TYPE_PRECRIME, bytes(\"\"));\n }\n\n /**\n * @dev Adds an executor option to the existing options.\n * @param _options The existing options container.\n * @param _optionType The type of the executor option.\n * @param _option The encoded data for the executor option.\n * @return options The updated options container.\n */\n function addExecutorOption(\n bytes memory _options,\n uint8 _optionType,\n bytes memory _option\n ) internal pure onlyType3(_options) returns (bytes memory) {\n return\n abi.encodePacked(\n _options,\n ExecutorOptions.WORKER_ID,\n _option.length.toUint16() + 1, // +1 for optionType\n _optionType,\n _option\n );\n }\n\n /**\n * @dev Adds a DVN option to the existing options.\n * @param _options The existing options container.\n * @param _dvnIdx The DVN index for the DVN option.\n * @param _optionType The type of the DVN option.\n * @param _option The encoded data for the DVN option.\n * @return options The updated options container.\n */\n function addDVNOption(\n bytes memory _options,\n uint8 _dvnIdx,\n uint8 _optionType,\n bytes memory _option\n ) internal pure onlyType3(_options) returns (bytes memory) {\n return\n abi.encodePacked(\n _options,\n DVNOptions.WORKER_ID,\n _option.length.toUint16() + 2, // +2 for optionType and dvnIdx\n _dvnIdx,\n _optionType,\n _option\n );\n }\n\n /**\n * @dev Encodes legacy options of type 1.\n * @param _executionGas The gasLimit value passed to lzReceive().\n * @return legacyOptions The encoded legacy options.\n */\n function encodeLegacyOptionsType1(uint256 _executionGas) internal pure returns (bytes memory) {\n if (_executionGas > type(uint128).max) revert InvalidSize(type(uint128).max, _executionGas);\n return abi.encodePacked(TYPE_1, _executionGas);\n }\n\n /**\n * @dev Encodes legacy options of type 2.\n * @param _executionGas The gasLimit value passed to lzReceive().\n * @param _nativeForDst The amount of native air dropped to the receiver.\n * @param _receiver The _nativeForDst receiver address.\n * @return legacyOptions The encoded legacy options of type 2.\n */\n function encodeLegacyOptionsType2(\n uint256 _executionGas,\n uint256 _nativeForDst,\n bytes memory _receiver // @dev Use bytes instead of bytes32 in legacy type 2 for _receiver.\n ) internal pure returns (bytes memory) {\n if (_executionGas > type(uint128).max) revert InvalidSize(type(uint128).max, _executionGas);\n if (_nativeForDst > type(uint128).max) revert InvalidSize(type(uint128).max, _nativeForDst);\n if (_receiver.length > 32) revert InvalidSize(32, _receiver.length);\n return abi.encodePacked(TYPE_2, _executionGas, _nativeForDst, _receiver);\n }\n}\n" + }, + "@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\n// @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers\n// solhint-disable-next-line no-unused-import\nimport { OAppSender, MessagingFee, MessagingReceipt } from \"./OAppSender.sol\";\n// @dev Import the 'Origin' so it's exposed to OApp implementers\n// solhint-disable-next-line no-unused-import\nimport { OAppReceiver, Origin } from \"./OAppReceiver.sol\";\nimport { OAppCore } from \"./OAppCore.sol\";\n\n/**\n * @title OApp\n * @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality.\n */\nabstract contract OApp is OAppSender, OAppReceiver {\n /**\n * @dev Constructor to initialize the OApp with the provided endpoint and owner.\n * @param _endpoint The address of the LOCAL LayerZero endpoint.\n * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n */\n constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {}\n\n /**\n * @notice Retrieves the OApp version information.\n * @return senderVersion The version of the OAppSender.sol implementation.\n * @return receiverVersion The version of the OAppReceiver.sol implementation.\n */\n function oAppVersion()\n public\n pure\n virtual\n override(OAppSender, OAppReceiver)\n returns (uint64 senderVersion, uint64 receiverVersion)\n {\n return (SENDER_VERSION, RECEIVER_VERSION);\n }\n}\n" + }, + "@layerzerolabs/oapp-evm/contracts/oapp/OAppCore.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IOAppCore, ILayerZeroEndpointV2 } from \"./interfaces/IOAppCore.sol\";\n\n/**\n * @title OAppCore\n * @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.\n */\nabstract contract OAppCore is IOAppCore, Ownable {\n // The LayerZero endpoint associated with the given OApp\n ILayerZeroEndpointV2 public immutable endpoint;\n\n // Mapping to store peers associated with corresponding endpoints\n mapping(uint32 eid => bytes32 peer) public peers;\n\n /**\n * @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.\n * @param _endpoint The address of the LOCAL Layer Zero endpoint.\n * @param _delegate The delegate capable of making OApp configurations inside of the endpoint.\n *\n * @dev The delegate typically should be set as the owner of the contract.\n */\n constructor(address _endpoint, address _delegate) {\n endpoint = ILayerZeroEndpointV2(_endpoint);\n\n if (_delegate == address(0)) revert InvalidDelegate();\n endpoint.setDelegate(_delegate);\n }\n\n /**\n * @notice Sets the peer address (OApp instance) for a corresponding endpoint.\n * @param _eid The endpoint ID.\n * @param _peer The address of the peer to be associated with the corresponding endpoint.\n *\n * @dev Only the owner/admin of the OApp can call this function.\n * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.\n * @dev Set this to bytes32(0) to remove the peer address.\n * @dev Peer is a bytes32 to accommodate non-evm chains.\n */\n function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner {\n _setPeer(_eid, _peer);\n }\n\n /**\n * @notice Sets the peer address (OApp instance) for a corresponding endpoint.\n * @param _eid The endpoint ID.\n * @param _peer The address of the peer to be associated with the corresponding endpoint.\n *\n * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.\n * @dev Set this to bytes32(0) to remove the peer address.\n * @dev Peer is a bytes32 to accommodate non-evm chains.\n */\n function _setPeer(uint32 _eid, bytes32 _peer) internal virtual {\n peers[_eid] = _peer;\n emit PeerSet(_eid, _peer);\n }\n\n /**\n * @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.\n * ie. the peer is set to bytes32(0).\n * @param _eid The endpoint ID.\n * @return peer The address of the peer associated with the specified endpoint.\n */\n function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) {\n bytes32 peer = peers[_eid];\n if (peer == bytes32(0)) revert NoPeer(_eid);\n return peer;\n }\n\n /**\n * @notice Sets the delegate address for the OApp.\n * @param _delegate The address of the delegate to be set.\n *\n * @dev Only the owner/admin of the OApp can call this function.\n * @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.\n */\n function setDelegate(address _delegate) public onlyOwner {\n endpoint.setDelegate(_delegate);\n }\n}\n" + }, + "@layerzerolabs/oapp-evm/contracts/oapp/OAppReceiver.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { IOAppReceiver, Origin } from \"./interfaces/IOAppReceiver.sol\";\nimport { OAppCore } from \"./OAppCore.sol\";\n\n/**\n * @title OAppReceiver\n * @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.\n */\nabstract contract OAppReceiver is IOAppReceiver, OAppCore {\n // Custom error message for when the caller is not the registered endpoint/\n error OnlyEndpoint(address addr);\n\n // @dev The version of the OAppReceiver implementation.\n // @dev Version is bumped when changes are made to this contract.\n uint64 internal constant RECEIVER_VERSION = 2;\n\n /**\n * @notice Retrieves the OApp version information.\n * @return senderVersion The version of the OAppSender.sol contract.\n * @return receiverVersion The version of the OAppReceiver.sol contract.\n *\n * @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented.\n * ie. this is a RECEIVE only OApp.\n * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions.\n */\n function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {\n return (0, RECEIVER_VERSION);\n }\n\n /**\n * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.\n * @dev _origin The origin information containing the source endpoint and sender address.\n * - srcEid: The source chain endpoint ID.\n * - sender: The sender address on the src chain.\n * - nonce: The nonce of the message.\n * @dev _message The lzReceive payload.\n * @param _sender The sender address.\n * @return isSender Is a valid sender.\n *\n * @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer.\n * @dev The default sender IS the OAppReceiver implementer.\n */\n function isComposeMsgSender(\n Origin calldata /*_origin*/,\n bytes calldata /*_message*/,\n address _sender\n ) public view virtual returns (bool) {\n return _sender == address(this);\n }\n\n /**\n * @notice Checks if the path initialization is allowed based on the provided origin.\n * @param origin The origin information containing the source endpoint and sender address.\n * @return Whether the path has been initialized.\n *\n * @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received.\n * @dev This defaults to assuming if a peer has been set, its initialized.\n * Can be overridden by the OApp if there is other logic to determine this.\n */\n function allowInitializePath(Origin calldata origin) public view virtual returns (bool) {\n return peers[origin.srcEid] == origin.sender;\n }\n\n /**\n * @notice Retrieves the next nonce for a given source endpoint and sender address.\n * @dev _srcEid The source endpoint ID.\n * @dev _sender The sender address.\n * @return nonce The next nonce.\n *\n * @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.\n * @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.\n * @dev This is also enforced by the OApp.\n * @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.\n */\n function nextNonce(uint32 /*_srcEid*/, bytes32 /*_sender*/) public view virtual returns (uint64 nonce) {\n return 0;\n }\n\n /**\n * @dev Entry point for receiving messages or packets from the endpoint.\n * @param _origin The origin information containing the source endpoint and sender address.\n * - srcEid: The source chain endpoint ID.\n * - sender: The sender address on the src chain.\n * - nonce: The nonce of the message.\n * @param _guid The unique identifier for the received LayerZero message.\n * @param _message The payload of the received message.\n * @param _executor The address of the executor for the received message.\n * @param _extraData Additional arbitrary data provided by the corresponding executor.\n *\n * @dev Entry point for receiving msg/packet from the LayerZero endpoint.\n */\n function lzReceive(\n Origin calldata _origin,\n bytes32 _guid,\n bytes calldata _message,\n address _executor,\n bytes calldata _extraData\n ) public payable virtual {\n // Ensures that only the endpoint can attempt to lzReceive() messages to this OApp.\n if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender);\n\n // Ensure that the sender matches the expected peer for the source endpoint.\n if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender);\n\n // Call the internal OApp implementation of lzReceive.\n _lzReceive(_origin, _guid, _message, _executor, _extraData);\n }\n\n /**\n * @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation.\n */\n function _lzReceive(\n Origin calldata _origin,\n bytes32 _guid,\n bytes calldata _message,\n address _executor,\n bytes calldata _extraData\n ) internal virtual;\n}\n" + }, + "@layerzerolabs/oapp-evm/contracts/oapp/OAppSender.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.20;\n\nimport { SafeERC20, IERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { MessagingParams, MessagingFee, MessagingReceipt } from \"@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol\";\nimport { OAppCore } from \"./OAppCore.sol\";\n\n/**\n * @title OAppSender\n * @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.\n */\nabstract contract OAppSender is OAppCore {\n using SafeERC20 for IERC20;\n\n // Custom error messages\n error NotEnoughNative(uint256 msgValue);\n error LzTokenUnavailable();\n\n // @dev The version of the OAppSender implementation.\n // @dev Version is bumped when changes are made to this contract.\n uint64 internal constant SENDER_VERSION = 1;\n\n /**\n * @notice Retrieves the OApp version information.\n * @return senderVersion The version of the OAppSender.sol contract.\n * @return receiverVersion The version of the OAppReceiver.sol contract.\n *\n * @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.\n * ie. this is a SEND only OApp.\n * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions\n */\n function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {\n return (SENDER_VERSION, 0);\n }\n\n /**\n * @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.\n * @param _dstEid The destination endpoint ID.\n * @param _message The message payload.\n * @param _options Additional options for the message.\n * @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.\n * @return fee The calculated MessagingFee for the message.\n * - nativeFee: The native fee for the message.\n * - lzTokenFee: The LZ token fee for the message.\n */\n function _quote(\n uint32 _dstEid,\n bytes memory _message,\n bytes memory _options,\n bool _payInLzToken\n ) internal view virtual returns (MessagingFee memory fee) {\n return\n endpoint.quote(\n MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),\n address(this)\n );\n }\n\n /**\n * @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.\n * @param _dstEid The destination endpoint ID.\n * @param _message The message payload.\n * @param _options Additional options for the message.\n * @param _fee The calculated LayerZero fee for the message.\n * - nativeFee: The native fee.\n * - lzTokenFee: The lzToken fee.\n * @param _refundAddress The address to receive any excess fee values sent to the endpoint.\n * @return receipt The receipt for the sent message.\n * - guid: The unique identifier for the sent message.\n * - nonce: The nonce of the sent message.\n * - fee: The LayerZero fee incurred for the message.\n */\n function _lzSend(\n uint32 _dstEid,\n bytes memory _message,\n bytes memory _options,\n MessagingFee memory _fee,\n address _refundAddress\n ) internal virtual returns (MessagingReceipt memory receipt) {\n // @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.\n uint256 messageValue = _payNative(_fee.nativeFee);\n if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);\n\n return\n // solhint-disable-next-line check-send-result\n endpoint.send{ value: messageValue }(\n MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),\n _refundAddress\n );\n }\n\n /**\n * @dev Internal function to pay the native fee associated with the message.\n * @param _nativeFee The native fee to be paid.\n * @return nativeFee The amount of native currency paid.\n *\n * @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,\n * this will need to be overridden because msg.value would contain multiple lzFees.\n * @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.\n * @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.\n * @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.\n */\n function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) {\n if (msg.value != _nativeFee) revert NotEnoughNative(msg.value);\n return _nativeFee;\n }\n\n /**\n * @dev Internal function to pay the LZ token fee associated with the message.\n * @param _lzTokenFee The LZ token fee to be paid.\n *\n * @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.\n * @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().\n */\n function _payLzToken(uint256 _lzTokenFee) internal virtual {\n // @dev Cannot cache the token because it is not immutable in the endpoint.\n address lzToken = endpoint.lzToken();\n if (lzToken == address(0)) revert LzTokenUnavailable();\n\n // Pay LZ token fee by sending tokens to the endpoint.\n IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);\n }\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./OwnableUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable {\n function __Ownable2Step_init() internal onlyInitializing {\n __Ownable_init_unchained();\n }\n\n function __Ownable2Step_init_unchained() internal onlyInitializing {\n }\n address private _pendingOwner;\n\n event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Returns the address of the pending owner.\n */\n function pendingOwner() public view virtual returns (address) {\n return _pendingOwner;\n }\n\n /**\n * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual override onlyOwner {\n _pendingOwner = newOwner;\n emit OwnershipTransferStarted(owner(), newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual override {\n delete _pendingOwner;\n super._transferOwnership(newOwner);\n }\n\n /**\n * @dev The new owner accepts the ownership transfer.\n */\n function acceptOwnership() external {\n address sender = _msgSender();\n require(pendingOwner() == sender, \"Ownable2Step: caller is not the new owner\");\n _transferOwnership(sender);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal onlyInitializing {\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal onlyInitializing {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/interfaces/IERC4626Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC4626.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC20/IERC20Upgradeable.sol\";\nimport \"../token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\n/**\n * @dev Interface of the ERC4626 \"Tokenized Vault Standard\", as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].\n *\n * _Available since v4.7._\n */\ninterface IERC4626Upgradeable is IERC20Upgradeable, IERC20MetadataUpgradeable {\n event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed sender,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /**\n * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n *\n * - MUST be an ERC-20 token contract.\n * - MUST NOT revert.\n */\n function asset() external view returns (address assetTokenAddress);\n\n /**\n * @dev Returns the total amount of the underlying asset that is “managed” by Vault.\n *\n * - SHOULD include any compounding that occurs from yield.\n * - MUST be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT revert.\n */\n function totalAssets() external view returns (uint256 totalManagedAssets);\n\n /**\n * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal\n * scenario where all the conditions are met.\n *\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT show any variations depending on the caller.\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n * - MUST NOT revert.\n *\n * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n * from.\n */\n function convertToShares(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal\n * scenario where all the conditions are met.\n *\n * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.\n * - MUST NOT show any variations depending on the caller.\n * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.\n * - MUST NOT revert.\n *\n * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the\n * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and\n * from.\n */\n function convertToAssets(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,\n * through a deposit call.\n *\n * - MUST return a limited value if receiver is subject to some deposit limit.\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.\n * - MUST NOT revert.\n */\n function maxDeposit(address receiver) external view returns (uint256 maxAssets);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given\n * current on-chain conditions.\n *\n * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit\n * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called\n * in the same transaction.\n * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the\n * deposit would be accepted, regardless if the user has enough tokens approved, etc.\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n */\n function previewDeposit(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.\n *\n * - MUST emit the Deposit event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * deposit execution, and are accounted for during deposit.\n * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not\n * approving enough underlying tokens to the Vault contract, etc).\n *\n * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n */\n function deposit(uint256 assets, address receiver) external returns (uint256 shares);\n\n /**\n * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.\n * - MUST return a limited value if receiver is subject to some mint limit.\n * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.\n * - MUST NOT revert.\n */\n function maxMint(address receiver) external view returns (uint256 maxShares);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given\n * current on-chain conditions.\n *\n * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call\n * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the\n * same transaction.\n * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint\n * would be accepted, regardless if the user has enough tokens approved, etc.\n * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by minting.\n */\n function previewMint(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.\n *\n * - MUST emit the Deposit event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint\n * execution, and are accounted for during mint.\n * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not\n * approving enough underlying tokens to the Vault contract, etc).\n *\n * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.\n */\n function mint(uint256 shares, address receiver) external returns (uint256 assets);\n\n /**\n * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the\n * Vault, through a withdraw call.\n *\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n * - MUST NOT revert.\n */\n function maxWithdraw(address owner) external view returns (uint256 maxAssets);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,\n * given current on-chain conditions.\n *\n * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw\n * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if\n * called\n * in the same transaction.\n * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though\n * the withdrawal would be accepted, regardless if the user has enough shares, etc.\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by depositing.\n */\n function previewWithdraw(uint256 assets) external view returns (uint256 shares);\n\n /**\n * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.\n *\n * - MUST emit the Withdraw event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * withdraw execution, and are accounted for during withdraw.\n * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner\n * not having enough shares, etc).\n *\n * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n * Those methods should be performed separately.\n */\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) external returns (uint256 shares);\n\n /**\n * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,\n * through a redeem call.\n *\n * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.\n * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.\n * - MUST NOT revert.\n */\n function maxRedeem(address owner) external view returns (uint256 maxShares);\n\n /**\n * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,\n * given current on-chain conditions.\n *\n * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call\n * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the\n * same transaction.\n * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the\n * redemption would be accepted, regardless if the user has enough shares, etc.\n * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.\n * - MUST NOT revert.\n *\n * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in\n * share price or some other type of condition, meaning the depositor will lose assets by redeeming.\n */\n function previewRedeem(uint256 shares) external view returns (uint256 assets);\n\n /**\n * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.\n *\n * - MUST emit the Withdraw event.\n * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the\n * redeem execution, and are accounted for during redeem.\n * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner\n * not having enough shares, etc).\n *\n * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.\n * Those methods should be performed separately.\n */\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) external returns (uint256 assets);\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/proxy/ClonesUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/Clones.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for\n * deploying minimal proxy contracts, also known as \"clones\".\n *\n * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies\n * > a minimal bytecode implementation that delegates all calls to a known, fixed address.\n *\n * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`\n * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the\n * deterministic method.\n *\n * _Available since v3.4._\n */\nlibrary ClonesUpgradeable {\n /**\n * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n *\n * This function uses the create opcode, which should never revert.\n */\n function clone(address implementation) internal returns (address instance) {\n /// @solidity memory-safe-assembly\n assembly {\n // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n // of the `implementation` address with the bytecode before the address.\n mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n instance := create(0, 0x09, 0x37)\n }\n require(instance != address(0), \"ERC1167: create failed\");\n }\n\n /**\n * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.\n *\n * This function uses the create2 opcode and a `salt` to deterministically deploy\n * the clone. Using the same `implementation` and `salt` multiple time will revert, since\n * the clones cannot be deployed twice at the same address.\n */\n function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {\n /// @solidity memory-safe-assembly\n assembly {\n // Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes\n // of the `implementation` address with the bytecode before the address.\n mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))\n // Packs the remaining 17 bytes of `implementation` with the bytecode after the address.\n mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))\n instance := create2(0, 0x09, 0x37, salt)\n }\n require(instance != address(0), \"ERC1167: create2 failed\");\n }\n\n /**\n * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n */\n function predictDeterministicAddress(\n address implementation,\n bytes32 salt,\n address deployer\n ) internal pure returns (address predicted) {\n /// @solidity memory-safe-assembly\n assembly {\n let ptr := mload(0x40)\n mstore(add(ptr, 0x38), deployer)\n mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)\n mstore(add(ptr, 0x14), implementation)\n mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)\n mstore(add(ptr, 0x58), salt)\n mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))\n predicted := keccak256(add(ptr, 0x43), 0x55)\n }\n }\n\n /**\n * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.\n */\n function predictDeterministicAddress(address implementation, bytes32 salt)\n internal\n view\n returns (address predicted)\n {\n return predictDeterministicAddress(implementation, salt, address(this));\n }\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts.\n *\n * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {Initialized} event.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * A reinitializer may be used after the original initialization step. This is essential to configure modules that\n * are added through upgrades and that require initialization.\n *\n * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`\n * cannot be nested. If one is invoked in the context of another, execution will revert.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n *\n * WARNING: setting the version to 255 will prevent any future reinitialization.\n *\n * Emits an {Initialized} event.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {Initialized} event the first time it is successfully executed.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized < type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n\n /**\n * @dev Internal function that returns the initialized version. Returns `_initialized`\n */\n function _getInitializedVersion() internal view returns (uint8) {\n return _initialized;\n }\n\n /**\n * @dev Internal function that returns the initialized version. Returns `_initializing`\n */\n function _isInitializing() internal view returns (bool) {\n return _initializing;\n }\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/security/PausableUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which allows children to implement an emergency stop\n * mechanism that can be triggered by an authorized account.\n *\n * This module is used through inheritance. It will make available the\n * modifiers `whenNotPaused` and `whenPaused`, which can be applied to\n * the functions of your contract. Note that they will not be pausable by\n * simply including this module, only once the modifiers are put in place.\n */\nabstract contract PausableUpgradeable is Initializable, ContextUpgradeable {\n /**\n * @dev Emitted when the pause is triggered by `account`.\n */\n event Paused(address account);\n\n /**\n * @dev Emitted when the pause is lifted by `account`.\n */\n event Unpaused(address account);\n\n bool private _paused;\n\n /**\n * @dev Initializes the contract in unpaused state.\n */\n function __Pausable_init() internal onlyInitializing {\n __Pausable_init_unchained();\n }\n\n function __Pausable_init_unchained() internal onlyInitializing {\n _paused = false;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is not paused.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n modifier whenNotPaused() {\n _requireNotPaused();\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only when the contract is paused.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n modifier whenPaused() {\n _requirePaused();\n _;\n }\n\n /**\n * @dev Returns true if the contract is paused, and false otherwise.\n */\n function paused() public view virtual returns (bool) {\n return _paused;\n }\n\n /**\n * @dev Throws if the contract is paused.\n */\n function _requireNotPaused() internal view virtual {\n require(!paused(), \"Pausable: paused\");\n }\n\n /**\n * @dev Throws if the contract is not paused.\n */\n function _requirePaused() internal view virtual {\n require(paused(), \"Pausable: not paused\");\n }\n\n /**\n * @dev Triggers stopped state.\n *\n * Requirements:\n *\n * - The contract must not be paused.\n */\n function _pause() internal virtual whenNotPaused {\n _paused = true;\n emit Paused(_msgSender());\n }\n\n /**\n * @dev Returns to normal state.\n *\n * Requirements:\n *\n * - The contract must be paused.\n */\n function _unpause() internal virtual whenPaused {\n _paused = false;\n emit Unpaused(_msgSender());\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuardUpgradeable is Initializable {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n function __ReentrancyGuard_init() internal onlyInitializing {\n __ReentrancyGuard_init_unchained();\n }\n\n function __ReentrancyGuard_init_unchained() internal onlyInitializing {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and making it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n _nonReentrantBefore();\n _;\n _nonReentrantAfter();\n }\n\n function _nonReentrantBefore() private {\n // On the first call to nonReentrant, _status will be _NOT_ENTERED\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n }\n\n function _nonReentrantAfter() private {\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n // decrementing then incrementing.\n _balances[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n unchecked {\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n _balances[account] += amount;\n }\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n // Overflow not possible: amount <= accountBalance <= totalSupply.\n _totalSupply -= amount;\n }\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[45] private __gap;\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20PermitUpgradeable {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/extensions/ERC4626.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20Upgradeable.sol\";\nimport \"../utils/SafeERC20Upgradeable.sol\";\nimport \"../../../interfaces/IERC4626Upgradeable.sol\";\nimport \"../../../utils/math/MathUpgradeable.sol\";\nimport \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the ERC4626 \"Tokenized Vault Standard\" as defined in\n * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].\n *\n * This extension allows the minting and burning of \"shares\" (represented using the ERC20 inheritance) in exchange for\n * underlying \"assets\" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends\n * the ERC20 standard. Any additional extensions included along it would affect the \"shares\" token represented by this\n * contract and not the \"assets\" token which is an independent contract.\n *\n * CAUTION: Deposits and withdrawals may incur unexpected slippage. Users should verify that the amount received of\n * shares or assets is as expected. EOAs should operate through a wrapper that performs these checks such as\n * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].\n *\n * _Available since v4.7._\n */\nabstract contract ERC4626Upgradeable is Initializable, ERC20Upgradeable, IERC4626Upgradeable {\n using MathUpgradeable for uint256;\n\n IERC20Upgradeable private _asset;\n uint8 private _decimals;\n\n /**\n * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).\n */\n function __ERC4626_init(IERC20Upgradeable asset_) internal onlyInitializing {\n __ERC4626_init_unchained(asset_);\n }\n\n function __ERC4626_init_unchained(IERC20Upgradeable asset_) internal onlyInitializing {\n (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);\n _decimals = success ? assetDecimals : super.decimals();\n _asset = asset_;\n }\n\n /**\n * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.\n */\n function _tryGetAssetDecimals(IERC20Upgradeable asset_) private returns (bool, uint8) {\n (bool success, bytes memory encodedDecimals) = address(asset_).call(\n abi.encodeWithSelector(IERC20MetadataUpgradeable.decimals.selector)\n );\n if (success && encodedDecimals.length >= 32) {\n uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));\n if (returnedDecimals <= type(uint8).max) {\n return (true, uint8(returnedDecimals));\n }\n }\n return (false, 0);\n }\n\n /**\n * @dev Decimals are read from the underlying asset in the constructor and cached. If this fails (e.g., the asset\n * has not been created yet), the cached value is set to a default obtained by `super.decimals()` (which depends on\n * inheritance but is most likely 18). Override this function in order to set a guaranteed hardcoded value.\n * See {IERC20Metadata-decimals}.\n */\n function decimals() public view virtual override(IERC20MetadataUpgradeable, ERC20Upgradeable) returns (uint8) {\n return _decimals;\n }\n\n /** @dev See {IERC4626-asset}. */\n function asset() public view virtual override returns (address) {\n return address(_asset);\n }\n\n /** @dev See {IERC4626-totalAssets}. */\n function totalAssets() public view virtual override returns (uint256) {\n return _asset.balanceOf(address(this));\n }\n\n /** @dev See {IERC4626-convertToShares}. */\n function convertToShares(uint256 assets) public view virtual override returns (uint256 shares) {\n return _convertToShares(assets, MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-convertToAssets}. */\n function convertToAssets(uint256 shares) public view virtual override returns (uint256 assets) {\n return _convertToAssets(shares, MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-maxDeposit}. */\n function maxDeposit(address) public view virtual override returns (uint256) {\n return _isVaultCollateralized() ? type(uint256).max : 0;\n }\n\n /** @dev See {IERC4626-maxMint}. */\n function maxMint(address) public view virtual override returns (uint256) {\n return type(uint256).max;\n }\n\n /** @dev See {IERC4626-maxWithdraw}. */\n function maxWithdraw(address owner) public view virtual override returns (uint256) {\n return _convertToAssets(balanceOf(owner), MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-maxRedeem}. */\n function maxRedeem(address owner) public view virtual override returns (uint256) {\n return balanceOf(owner);\n }\n\n /** @dev See {IERC4626-previewDeposit}. */\n function previewDeposit(uint256 assets) public view virtual override returns (uint256) {\n return _convertToShares(assets, MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-previewMint}. */\n function previewMint(uint256 shares) public view virtual override returns (uint256) {\n return _convertToAssets(shares, MathUpgradeable.Rounding.Up);\n }\n\n /** @dev See {IERC4626-previewWithdraw}. */\n function previewWithdraw(uint256 assets) public view virtual override returns (uint256) {\n return _convertToShares(assets, MathUpgradeable.Rounding.Up);\n }\n\n /** @dev See {IERC4626-previewRedeem}. */\n function previewRedeem(uint256 shares) public view virtual override returns (uint256) {\n return _convertToAssets(shares, MathUpgradeable.Rounding.Down);\n }\n\n /** @dev See {IERC4626-deposit}. */\n function deposit(uint256 assets, address receiver) public virtual override returns (uint256) {\n require(assets <= maxDeposit(receiver), \"ERC4626: deposit more than max\");\n\n uint256 shares = previewDeposit(assets);\n _deposit(_msgSender(), receiver, assets, shares);\n\n return shares;\n }\n\n /** @dev See {IERC4626-mint}. */\n function mint(uint256 shares, address receiver) public virtual override returns (uint256) {\n require(shares <= maxMint(receiver), \"ERC4626: mint more than max\");\n\n uint256 assets = previewMint(shares);\n _deposit(_msgSender(), receiver, assets, shares);\n\n return assets;\n }\n\n /** @dev See {IERC4626-withdraw}. */\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual override returns (uint256) {\n require(assets <= maxWithdraw(owner), \"ERC4626: withdraw more than max\");\n\n uint256 shares = previewWithdraw(assets);\n _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n return shares;\n }\n\n /** @dev See {IERC4626-redeem}. */\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual override returns (uint256) {\n require(shares <= maxRedeem(owner), \"ERC4626: redeem more than max\");\n\n uint256 assets = previewRedeem(shares);\n _withdraw(_msgSender(), receiver, owner, assets, shares);\n\n return assets;\n }\n\n /**\n * @dev Internal conversion function (from assets to shares) with support for rounding direction.\n *\n * Will revert if assets > 0, totalSupply > 0 and totalAssets = 0. That corresponds to a case where any asset\n * would represent an infinite amount of shares.\n */\n function _convertToShares(uint256 assets, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256 shares) {\n uint256 supply = totalSupply();\n return\n (assets == 0 || supply == 0)\n ? _initialConvertToShares(assets, rounding)\n : assets.mulDiv(supply, totalAssets(), rounding);\n }\n\n /**\n * @dev Internal conversion function (from assets to shares) to apply when the vault is empty.\n *\n * NOTE: Make sure to keep this function consistent with {_initialConvertToAssets} when overriding it.\n */\n function _initialConvertToShares(\n uint256 assets,\n MathUpgradeable.Rounding /*rounding*/\n ) internal view virtual returns (uint256 shares) {\n return assets;\n }\n\n /**\n * @dev Internal conversion function (from shares to assets) with support for rounding direction.\n */\n function _convertToAssets(uint256 shares, MathUpgradeable.Rounding rounding) internal view virtual returns (uint256 assets) {\n uint256 supply = totalSupply();\n return\n (supply == 0) ? _initialConvertToAssets(shares, rounding) : shares.mulDiv(totalAssets(), supply, rounding);\n }\n\n /**\n * @dev Internal conversion function (from shares to assets) to apply when the vault is empty.\n *\n * NOTE: Make sure to keep this function consistent with {_initialConvertToShares} when overriding it.\n */\n function _initialConvertToAssets(\n uint256 shares,\n MathUpgradeable.Rounding /*rounding*/\n ) internal view virtual returns (uint256 assets) {\n return shares;\n }\n\n /**\n * @dev Deposit/mint common workflow.\n */\n function _deposit(\n address caller,\n address receiver,\n uint256 assets,\n uint256 shares\n ) internal virtual {\n // If _asset is ERC777, `transferFrom` can trigger a reenterancy BEFORE the transfer happens through the\n // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,\n // calls the vault, which is assumed not malicious.\n //\n // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the\n // assets are transferred and before the shares are minted, which is a valid state.\n // slither-disable-next-line reentrancy-no-eth\n SafeERC20Upgradeable.safeTransferFrom(_asset, caller, address(this), assets);\n _mint(receiver, shares);\n\n emit Deposit(caller, receiver, assets, shares);\n }\n\n /**\n * @dev Withdraw/redeem common workflow.\n */\n function _withdraw(\n address caller,\n address receiver,\n address owner,\n uint256 assets,\n uint256 shares\n ) internal virtual {\n if (caller != owner) {\n _spendAllowance(owner, caller, shares);\n }\n\n // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the\n // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,\n // calls the vault, which is assumed not malicious.\n //\n // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the\n // shares are burned and after the assets are transferred, which is a valid state.\n _burn(owner, shares);\n SafeERC20Upgradeable.safeTransfer(_asset, receiver, assets);\n\n emit Withdraw(caller, receiver, owner, assets, shares);\n }\n\n function _isVaultCollateralized() private view returns (bool) {\n return totalAssets() > 0 || totalSupply() == 0;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20Upgradeable token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20Upgradeable token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20PermitUpgradeable token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/ERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC721Upgradeable.sol\";\nimport \"./IERC721ReceiverUpgradeable.sol\";\nimport \"./extensions/IERC721MetadataUpgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../utils/StringsUpgradeable.sol\";\nimport \"../../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including\n * the Metadata extension, but not including the Enumerable extension, which is available separately as\n * {ERC721Enumerable}.\n */\ncontract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {\n using AddressUpgradeable for address;\n using StringsUpgradeable for uint256;\n\n // Token name\n string private _name;\n\n // Token symbol\n string private _symbol;\n\n // Mapping from token ID to owner address\n mapping(uint256 => address) private _owners;\n\n // Mapping owner address to token count\n mapping(address => uint256) private _balances;\n\n // Mapping from token ID to approved address\n mapping(uint256 => address) private _tokenApprovals;\n\n // Mapping from owner to operator approvals\n mapping(address => mapping(address => bool)) private _operatorApprovals;\n\n /**\n * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.\n */\n function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC721_init_unchained(name_, symbol_);\n }\n\n function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {\n return\n interfaceId == type(IERC721Upgradeable).interfaceId ||\n interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||\n super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev See {IERC721-balanceOf}.\n */\n function balanceOf(address owner) public view virtual override returns (uint256) {\n require(owner != address(0), \"ERC721: address zero is not a valid owner\");\n return _balances[owner];\n }\n\n /**\n * @dev See {IERC721-ownerOf}.\n */\n function ownerOf(uint256 tokenId) public view virtual override returns (address) {\n address owner = _ownerOf(tokenId);\n require(owner != address(0), \"ERC721: invalid token ID\");\n return owner;\n }\n\n /**\n * @dev See {IERC721Metadata-name}.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev See {IERC721Metadata-symbol}.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev See {IERC721Metadata-tokenURI}.\n */\n function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {\n _requireMinted(tokenId);\n\n string memory baseURI = _baseURI();\n return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : \"\";\n }\n\n /**\n * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each\n * token will be the concatenation of the `baseURI` and the `tokenId`. Empty\n * by default, can be overridden in child contracts.\n */\n function _baseURI() internal view virtual returns (string memory) {\n return \"\";\n }\n\n /**\n * @dev See {IERC721-approve}.\n */\n function approve(address to, uint256 tokenId) public virtual override {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n require(to != owner, \"ERC721: approval to current owner\");\n\n require(\n _msgSender() == owner || isApprovedForAll(owner, _msgSender()),\n \"ERC721: approve caller is not token owner or approved for all\"\n );\n\n _approve(to, tokenId);\n }\n\n /**\n * @dev See {IERC721-getApproved}.\n */\n function getApproved(uint256 tokenId) public view virtual override returns (address) {\n _requireMinted(tokenId);\n\n return _tokenApprovals[tokenId];\n }\n\n /**\n * @dev See {IERC721-setApprovalForAll}.\n */\n function setApprovalForAll(address operator, bool approved) public virtual override {\n _setApprovalForAll(_msgSender(), operator, approved);\n }\n\n /**\n * @dev See {IERC721-isApprovedForAll}.\n */\n function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {\n return _operatorApprovals[owner][operator];\n }\n\n /**\n * @dev See {IERC721-transferFrom}.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n //solhint-disable-next-line max-line-length\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n\n _transfer(from, to, tokenId);\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) public virtual override {\n safeTransferFrom(from, to, tokenId, \"\");\n }\n\n /**\n * @dev See {IERC721-safeTransferFrom}.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) public virtual override {\n require(_isApprovedOrOwner(_msgSender(), tokenId), \"ERC721: caller is not token owner or approved\");\n _safeTransfer(from, to, tokenId, data);\n }\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * `data` is additional data, it has no specified format and it is sent in call to `to`.\n *\n * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.\n * implement alternative mechanisms to perform token transfer, such as signature-based.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeTransfer(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _transfer(from, to, tokenId);\n require(_checkOnERC721Received(from, to, tokenId, data), \"ERC721: transfer to non ERC721Receiver implementer\");\n }\n\n /**\n * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist\n */\n function _ownerOf(uint256 tokenId) internal view virtual returns (address) {\n return _owners[tokenId];\n }\n\n /**\n * @dev Returns whether `tokenId` exists.\n *\n * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.\n *\n * Tokens start existing when they are minted (`_mint`),\n * and stop existing when they are burned (`_burn`).\n */\n function _exists(uint256 tokenId) internal view virtual returns (bool) {\n return _ownerOf(tokenId) != address(0);\n }\n\n /**\n * @dev Returns whether `spender` is allowed to manage `tokenId`.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);\n }\n\n /**\n * @dev Safely mints `tokenId` and transfers it to `to`.\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function _safeMint(address to, uint256 tokenId) internal virtual {\n _safeMint(to, tokenId, \"\");\n }\n\n /**\n * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is\n * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.\n */\n function _safeMint(\n address to,\n uint256 tokenId,\n bytes memory data\n ) internal virtual {\n _mint(to, tokenId);\n require(\n _checkOnERC721Received(address(0), to, tokenId, data),\n \"ERC721: transfer to non ERC721Receiver implementer\"\n );\n }\n\n /**\n * @dev Mints `tokenId` and transfers it to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible\n *\n * Requirements:\n *\n * - `tokenId` must not exist.\n * - `to` cannot be the zero address.\n *\n * Emits a {Transfer} event.\n */\n function _mint(address to, uint256 tokenId) internal virtual {\n require(to != address(0), \"ERC721: mint to the zero address\");\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n _beforeTokenTransfer(address(0), to, tokenId);\n\n // Check that tokenId was not minted by `_beforeTokenTransfer` hook\n require(!_exists(tokenId), \"ERC721: token already minted\");\n\n unchecked {\n // Will not overflow unless all 2**256 token ids are minted to the same owner.\n // Given that tokens are minted one by one, it is impossible in practice that\n // this ever happens. Might change if we allow batch minting.\n // The ERC fails to describe this case.\n _balances[to] += 1;\n }\n\n _owners[tokenId] = to;\n\n emit Transfer(address(0), to, tokenId);\n\n _afterTokenTransfer(address(0), to, tokenId);\n }\n\n /**\n * @dev Destroys `tokenId`.\n * The approval is cleared when the token is burned.\n * This is an internal function that does not check if the sender is authorized to operate on the token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n *\n * Emits a {Transfer} event.\n */\n function _burn(uint256 tokenId) internal virtual {\n address owner = ERC721Upgradeable.ownerOf(tokenId);\n\n _beforeTokenTransfer(owner, address(0), tokenId);\n\n // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook\n owner = ERC721Upgradeable.ownerOf(tokenId);\n\n // Clear approvals\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // Cannot overflow, as that would require more tokens to be burned/transferred\n // out than the owner initially received through minting and transferring in.\n _balances[owner] -= 1;\n }\n delete _owners[tokenId];\n\n emit Transfer(owner, address(0), tokenId);\n\n _afterTokenTransfer(owner, address(0), tokenId);\n }\n\n /**\n * @dev Transfers `tokenId` from `from` to `to`.\n * As opposed to {transferFrom}, this imposes no restrictions on msg.sender.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n *\n * Emits a {Transfer} event.\n */\n function _transfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n require(to != address(0), \"ERC721: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, tokenId);\n\n // Check that tokenId was not transferred by `_beforeTokenTransfer` hook\n require(ERC721Upgradeable.ownerOf(tokenId) == from, \"ERC721: transfer from incorrect owner\");\n\n // Clear approvals from the previous owner\n delete _tokenApprovals[tokenId];\n\n unchecked {\n // `_balances[from]` cannot overflow for the same reason as described in `_burn`:\n // `from`'s balance is the number of token held, which is at least one before the current\n // transfer.\n // `_balances[to]` could overflow in the conditions described in `_mint`. That would require\n // all 2**256 token ids to be minted, which in practice is impossible.\n _balances[from] -= 1;\n _balances[to] += 1;\n }\n _owners[tokenId] = to;\n\n emit Transfer(from, to, tokenId);\n\n _afterTokenTransfer(from, to, tokenId);\n }\n\n /**\n * @dev Approve `to` to operate on `tokenId`\n *\n * Emits an {Approval} event.\n */\n function _approve(address to, uint256 tokenId) internal virtual {\n _tokenApprovals[tokenId] = to;\n emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);\n }\n\n /**\n * @dev Approve `operator` to operate on all of `owner` tokens\n *\n * Emits an {ApprovalForAll} event.\n */\n function _setApprovalForAll(\n address owner,\n address operator,\n bool approved\n ) internal virtual {\n require(owner != operator, \"ERC721: approve to caller\");\n _operatorApprovals[owner][operator] = approved;\n emit ApprovalForAll(owner, operator, approved);\n }\n\n /**\n * @dev Reverts if the `tokenId` has not been minted yet.\n */\n function _requireMinted(uint256 tokenId) internal view virtual {\n require(_exists(tokenId), \"ERC721: invalid token ID\");\n }\n\n /**\n * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.\n * The call is not executed if the target address is not a contract.\n *\n * @param from address representing the previous owner of the given token ID\n * @param to target address that will receive the tokens\n * @param tokenId uint256 ID of the token to be transferred\n * @param data bytes optional data to send along with the call\n * @return bool whether the call correctly returned the expected magic value\n */\n function _checkOnERC721Received(\n address from,\n address to,\n uint256 tokenId,\n bytes memory data\n ) private returns (bool) {\n if (to.isContract()) {\n try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {\n return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;\n } catch (bytes memory reason) {\n if (reason.length == 0) {\n revert(\"ERC721: transfer to non ERC721Receiver implementer\");\n } else {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, reason), mload(reason))\n }\n }\n }\n } else {\n return true;\n }\n }\n\n /**\n * @dev Hook that is called before any (single) token transfer. This includes minting and burning.\n * See {_beforeConsecutiveTokenTransfer}.\n *\n * Calling conditions:\n *\n * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be\n * transferred to `to`.\n * - When `from` is zero, `tokenId` will be minted for `to`.\n * - When `to` is zero, ``from``'s `tokenId` will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any (single) transfer of tokens. This includes minting and burning.\n * See {_afterConsecutiveTokenTransfer}.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 tokenId\n ) internal virtual {}\n\n /**\n * @dev Hook that is called before \"consecutive token transfers\" as defined in ERC2309 and implemented in\n * {ERC721Consecutive}.\n * Calling conditions are similar to {_beforeTokenTransfer}.\n */\n function _beforeConsecutiveTokenTransfer(\n address from,\n address to,\n uint256, /*first*/\n uint96 size\n ) internal virtual {\n if (from != address(0)) {\n _balances[from] -= size;\n }\n if (to != address(0)) {\n _balances[to] += size;\n }\n }\n\n /**\n * @dev Hook that is called after \"consecutive token transfers\" as defined in ERC2309 and implemented in\n * {ERC721Consecutive}.\n * Calling conditions are similar to {_afterTokenTransfer}.\n */\n function _afterConsecutiveTokenTransfer(\n address, /*from*/\n address, /*to*/\n uint256, /*first*/\n uint96 /*size*/\n ) internal virtual {}\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[44] private __gap;\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC721/IERC721ReceiverUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721ReceiverUpgradeable {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/token/ERC721/IERC721Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721\n * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must\n * understand this adds an external call which potentially creates a reentrancy vulnerability.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/utils/ContextUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/utils/Create2Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Create2.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2Upgradeable {\n /**\n * @dev Deploys a contract using `CREATE2`. The address where the contract\n * will be deployed can be known in advance via {computeAddress}.\n *\n * The bytecode for a contract can be obtained from Solidity with\n * `type(contractName).creationCode`.\n *\n * Requirements:\n *\n * - `bytecode` must not be empty.\n * - `salt` must have not been used for `bytecode` already.\n * - the factory must have a balance of at least `amount`.\n * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\n */\n function deploy(\n uint256 amount,\n bytes32 salt,\n bytes memory bytecode\n ) internal returns (address addr) {\n require(address(this).balance >= amount, \"Create2: insufficient balance\");\n require(bytecode.length != 0, \"Create2: bytecode length is zero\");\n /// @solidity memory-safe-assembly\n assembly {\n addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\n }\n require(addr != address(0), \"Create2: Failed on deploy\");\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the\n * `bytecodeHash` or `salt` will result in a new destination address.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {\n return computeAddress(salt, bytecodeHash, address(this));\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n */\n function computeAddress(\n bytes32 salt,\n bytes32 bytecodeHash,\n address deployer\n ) internal pure returns (address addr) {\n /// @solidity memory-safe-assembly\n assembly {\n let ptr := mload(0x40) // Get free memory pointer\n\n // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |\n // |-------------------|---------------------------------------------------------------------------|\n // | bytecodeHash | CCCCCCCCCCCCC...CC |\n // | salt | BBBBBBBBBBBBB...BB |\n // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |\n // | 0xFF | FF |\n // |-------------------|---------------------------------------------------------------------------|\n // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n mstore(add(ptr, 0x40), bytecodeHash)\n mstore(add(ptr, 0x20), salt)\n mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n mstore8(start, 0xff)\n addr := keccak256(start, 85)\n }\n }\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/utils/introspection/ERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/utils/introspection/IERC165Upgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/utils/math/MathUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary MathUpgradeable {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n" + }, + "@openzeppelin-contracts-upgradeable/contracts/utils/StringsUpgradeable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/MathUpgradeable.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n bytes16 private constant _SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n unchecked {\n uint256 length = MathUpgradeable.log10(value) + 1;\n string memory buffer = new string(length);\n uint256 ptr;\n /// @solidity memory-safe-assembly\n assembly {\n ptr := add(buffer, add(32, length))\n }\n while (true) {\n ptr--;\n /// @solidity memory-safe-assembly\n assembly {\n mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n }\n value /= 10;\n if (value == 0) break;\n }\n return buffer;\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n unchecked {\n return toHexString(value, MathUpgradeable.log256(value) + 1);\n }\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n" + }, + "@openzeppelin/contracts/access/Ownable.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/Context.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor() {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n}\n" + }, + "@openzeppelin/contracts/access/Ownable2Step.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./Ownable.sol\";\n\n/**\n * @dev Contract module which provides access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership} and {acceptOwnership}.\n *\n * This module is used through inheritance. It will make available all functions\n * from parent (Ownable).\n */\nabstract contract Ownable2Step is Ownable {\n address private _pendingOwner;\n\n event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Returns the address of the pending owner.\n */\n function pendingOwner() public view virtual returns (address) {\n return _pendingOwner;\n }\n\n /**\n * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual override onlyOwner {\n _pendingOwner = newOwner;\n emit OwnershipTransferStarted(owner(), newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual override {\n delete _pendingOwner;\n super._transferOwnership(newOwner);\n }\n\n /**\n * @dev The new owner accepts the ownership transfer.\n */\n function acceptOwnership() external {\n address sender = _msgSender();\n require(pendingOwner() == sender, \"Ownable2Step: caller is not the new owner\");\n _transferOwnership(sender);\n }\n}\n" + }, + "@openzeppelin/contracts/interfaces/draft-IERC1822.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822Proxiable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/beacon/BeaconProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../Proxy.sol\";\nimport \"../ERC1967/ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements a proxy that gets the implementation address for each call from an {UpgradeableBeacon}.\n *\n * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't\n * conflict with the storage layout of the implementation behind the proxy.\n *\n * _Available since v3.4._\n */\ncontract BeaconProxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the proxy with `beacon`.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This\n * will typically be an encoded function call, and allows initializing the storage of the proxy like a Solidity\n * constructor.\n *\n * Requirements:\n *\n * - `beacon` must be a contract with the interface {IBeacon}.\n */\n constructor(address beacon, bytes memory data) payable {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n\n /**\n * @dev Returns the current beacon address.\n */\n function _beacon() internal view virtual returns (address) {\n return _getBeacon();\n }\n\n /**\n * @dev Returns the current implementation address of the associated beacon.\n */\n function _implementation() internal view virtual override returns (address) {\n return IBeacon(_getBeacon()).implementation();\n }\n\n /**\n * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.\n *\n * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.\n *\n * Requirements:\n *\n * - `beacon` must be a contract.\n * - The implementation returned by `beacon` must be a contract.\n */\n function _setBeacon(address beacon, bytes memory data) internal virtual {\n _upgradeBeaconToAndCall(beacon, data, false);\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/IBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This is the interface that {BeaconProxy} expects of its beacon.\n */\ninterface IBeacon {\n /**\n * @dev Must return an address that can be used as a delegate call target.\n *\n * {BeaconProxy} will check that this address is a contract.\n */\n function implementation() external view returns (address);\n}\n" + }, + "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IBeacon.sol\";\nimport \"../../access/Ownable.sol\";\nimport \"../../utils/Address.sol\";\n\n/**\n * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their\n * implementation contract, which is where they will delegate all function calls.\n *\n * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.\n */\ncontract UpgradeableBeacon is IBeacon, Ownable {\n address private _implementation;\n\n /**\n * @dev Emitted when the implementation returned by the beacon is changed.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the\n * beacon.\n */\n constructor(address implementation_) {\n _setImplementation(implementation_);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function implementation() public view virtual override returns (address) {\n return _implementation;\n }\n\n /**\n * @dev Upgrades the beacon to a new implementation.\n *\n * Emits an {Upgraded} event.\n *\n * Requirements:\n *\n * - msg.sender must be the owner of the contract.\n * - `newImplementation` must be a contract.\n */\n function upgradeTo(address newImplementation) public virtual onlyOwner {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Sets the implementation contract address for this beacon\n *\n * Requirements:\n *\n * - `newImplementation` must be a contract.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"UpgradeableBeacon: implementation is not a contract\");\n _implementation = newImplementation;\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Proxy.sol\";\nimport \"./ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\n * function call, and allows initializing the storage of the proxy like a Solidity constructor.\n */\n constructor(address _logic, bytes memory _data) payable {\n _upgradeToAndCall(_logic, _data, false);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function _implementation() internal view virtual override returns (address impl) {\n return ERC1967Upgrade._getImplementation();\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n *\n * @custom:oz-upgrades-unsafe-allow delegatecall\n */\nabstract contract ERC1967Upgrade {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Emitted when the implementation is upgraded.\n */\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(\n address newImplementation,\n bytes memory data,\n bool forceCall\n ) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Emitted when the admin account has changed.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Emitted when the beacon is upgraded.\n */\n event BeaconUpgraded(address indexed beacon);\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(\n address newBeacon,\n bytes memory data,\n bool forceCall\n ) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/proxy/Proxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n" + }, + "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/transparent/TransparentUpgradeableProxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC1967/ERC1967Proxy.sol\";\n\n/**\n * @dev This contract implements a proxy that is upgradeable by an admin.\n *\n * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector\n * clashing], which can potentially be used in an attack, this contract uses the\n * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two\n * things that go hand in hand:\n *\n * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if\n * that call matches one of the admin functions exposed by the proxy itself.\n * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the\n * implementation. If the admin tries to call a function on the implementation it will fail with an error that says\n * \"admin cannot fallback to proxy target\".\n *\n * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing\n * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due\n * to sudden errors when trying to call a function from the proxy implementation.\n *\n * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,\n * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.\n */\ncontract TransparentUpgradeableProxy is ERC1967Proxy {\n /**\n * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and\n * optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.\n */\n constructor(\n address _logic,\n address admin_,\n bytes memory _data\n ) payable ERC1967Proxy(_logic, _data) {\n _changeAdmin(admin_);\n }\n\n /**\n * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.\n */\n modifier ifAdmin() {\n if (msg.sender == _getAdmin()) {\n _;\n } else {\n _fallback();\n }\n }\n\n /**\n * @dev Returns the current admin.\n *\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`\n */\n function admin() external ifAdmin returns (address admin_) {\n admin_ = _getAdmin();\n }\n\n /**\n * @dev Returns the current implementation.\n *\n * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.\n *\n * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the\n * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.\n * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`\n */\n function implementation() external ifAdmin returns (address implementation_) {\n implementation_ = _implementation();\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n *\n * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.\n */\n function changeAdmin(address newAdmin) external virtual ifAdmin {\n _changeAdmin(newAdmin);\n }\n\n /**\n * @dev Upgrade the implementation of the proxy.\n *\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.\n */\n function upgradeTo(address newImplementation) external ifAdmin {\n _upgradeToAndCall(newImplementation, bytes(\"\"), false);\n }\n\n /**\n * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified\n * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the\n * proxied contract.\n *\n * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.\n */\n function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {\n _upgradeToAndCall(newImplementation, data, true);\n }\n\n /**\n * @dev Returns the current admin.\n */\n function _admin() internal view virtual returns (address) {\n return _getAdmin();\n }\n\n /**\n * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.\n */\n function _beforeFallback() internal virtual override {\n require(msg.sender != _getAdmin(), \"TransparentUpgradeableProxy: admin cannot fallback to proxy target\");\n super._beforeFallback();\n }\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/IERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" + }, + "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" + }, + "@openzeppelin/contracts/utils/Address.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/utils/Context.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n}\n" + }, + "@openzeppelin/contracts/utils/math/Math.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n }\n }\n}\n" + }, + "@openzeppelin/contracts/utils/math/SafeCast.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)\n// This file was procedurally generated from scripts/generate/templates/SafeCast.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCast {\n /**\n * @dev Returns the downcasted uint248 from uint256, reverting on\n * overflow (when the input is greater than largest uint248).\n *\n * Counterpart to Solidity's `uint248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toUint248(uint256 value) internal pure returns (uint248) {\n require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return uint248(value);\n }\n\n /**\n * @dev Returns the downcasted uint240 from uint256, reverting on\n * overflow (when the input is greater than largest uint240).\n *\n * Counterpart to Solidity's `uint240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toUint240(uint256 value) internal pure returns (uint240) {\n require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return uint240(value);\n }\n\n /**\n * @dev Returns the downcasted uint232 from uint256, reverting on\n * overflow (when the input is greater than largest uint232).\n *\n * Counterpart to Solidity's `uint232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toUint232(uint256 value) internal pure returns (uint232) {\n require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return uint232(value);\n }\n\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.2._\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint216 from uint256, reverting on\n * overflow (when the input is greater than largest uint216).\n *\n * Counterpart to Solidity's `uint216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toUint216(uint256 value) internal pure returns (uint216) {\n require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return uint216(value);\n }\n\n /**\n * @dev Returns the downcasted uint208 from uint256, reverting on\n * overflow (when the input is greater than largest uint208).\n *\n * Counterpart to Solidity's `uint208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toUint208(uint256 value) internal pure returns (uint208) {\n require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return uint208(value);\n }\n\n /**\n * @dev Returns the downcasted uint200 from uint256, reverting on\n * overflow (when the input is greater than largest uint200).\n *\n * Counterpart to Solidity's `uint200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toUint200(uint256 value) internal pure returns (uint200) {\n require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return uint200(value);\n }\n\n /**\n * @dev Returns the downcasted uint192 from uint256, reverting on\n * overflow (when the input is greater than largest uint192).\n *\n * Counterpart to Solidity's `uint192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toUint192(uint256 value) internal pure returns (uint192) {\n require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return uint192(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint176 from uint256, reverting on\n * overflow (when the input is greater than largest uint176).\n *\n * Counterpart to Solidity's `uint176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toUint176(uint256 value) internal pure returns (uint176) {\n require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return uint176(value);\n }\n\n /**\n * @dev Returns the downcasted uint168 from uint256, reverting on\n * overflow (when the input is greater than largest uint168).\n *\n * Counterpart to Solidity's `uint168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toUint168(uint256 value) internal pure returns (uint168) {\n require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return uint168(value);\n }\n\n /**\n * @dev Returns the downcasted uint160 from uint256, reverting on\n * overflow (when the input is greater than largest uint160).\n *\n * Counterpart to Solidity's `uint160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toUint160(uint256 value) internal pure returns (uint160) {\n require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return uint160(value);\n }\n\n /**\n * @dev Returns the downcasted uint152 from uint256, reverting on\n * overflow (when the input is greater than largest uint152).\n *\n * Counterpart to Solidity's `uint152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toUint152(uint256 value) internal pure returns (uint152) {\n require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return uint152(value);\n }\n\n /**\n * @dev Returns the downcasted uint144 from uint256, reverting on\n * overflow (when the input is greater than largest uint144).\n *\n * Counterpart to Solidity's `uint144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toUint144(uint256 value) internal pure returns (uint144) {\n require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return uint144(value);\n }\n\n /**\n * @dev Returns the downcasted uint136 from uint256, reverting on\n * overflow (when the input is greater than largest uint136).\n *\n * Counterpart to Solidity's `uint136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toUint136(uint256 value) internal pure returns (uint136) {\n require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return uint136(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v2.5._\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint120 from uint256, reverting on\n * overflow (when the input is greater than largest uint120).\n *\n * Counterpart to Solidity's `uint120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toUint120(uint256 value) internal pure returns (uint120) {\n require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return uint120(value);\n }\n\n /**\n * @dev Returns the downcasted uint112 from uint256, reverting on\n * overflow (when the input is greater than largest uint112).\n *\n * Counterpart to Solidity's `uint112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toUint112(uint256 value) internal pure returns (uint112) {\n require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return uint112(value);\n }\n\n /**\n * @dev Returns the downcasted uint104 from uint256, reverting on\n * overflow (when the input is greater than largest uint104).\n *\n * Counterpart to Solidity's `uint104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toUint104(uint256 value) internal pure returns (uint104) {\n require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return uint104(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.2._\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint88 from uint256, reverting on\n * overflow (when the input is greater than largest uint88).\n *\n * Counterpart to Solidity's `uint88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toUint88(uint256 value) internal pure returns (uint88) {\n require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return uint88(value);\n }\n\n /**\n * @dev Returns the downcasted uint80 from uint256, reverting on\n * overflow (when the input is greater than largest uint80).\n *\n * Counterpart to Solidity's `uint80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toUint80(uint256 value) internal pure returns (uint80) {\n require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return uint80(value);\n }\n\n /**\n * @dev Returns the downcasted uint72 from uint256, reverting on\n * overflow (when the input is greater than largest uint72).\n *\n * Counterpart to Solidity's `uint72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toUint72(uint256 value) internal pure returns (uint72) {\n require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return uint72(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v2.5._\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint56 from uint256, reverting on\n * overflow (when the input is greater than largest uint56).\n *\n * Counterpart to Solidity's `uint56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toUint56(uint256 value) internal pure returns (uint56) {\n require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return uint56(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint40 from uint256, reverting on\n * overflow (when the input is greater than largest uint40).\n *\n * Counterpart to Solidity's `uint40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toUint40(uint256 value) internal pure returns (uint40) {\n require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return uint40(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v2.5._\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint24 from uint256, reverting on\n * overflow (when the input is greater than largest uint24).\n *\n * Counterpart to Solidity's `uint24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toUint24(uint256 value) internal pure returns (uint24) {\n require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return uint24(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v2.5._\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v2.5._\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n *\n * _Available since v3.0._\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int248 from int256, reverting on\n * overflow (when the input is less than smallest int248 or\n * greater than largest int248).\n *\n * Counterpart to Solidity's `int248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toInt248(int256 value) internal pure returns (int248 downcasted) {\n downcasted = int248(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 248 bits\");\n }\n\n /**\n * @dev Returns the downcasted int240 from int256, reverting on\n * overflow (when the input is less than smallest int240 or\n * greater than largest int240).\n *\n * Counterpart to Solidity's `int240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toInt240(int256 value) internal pure returns (int240 downcasted) {\n downcasted = int240(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 240 bits\");\n }\n\n /**\n * @dev Returns the downcasted int232 from int256, reverting on\n * overflow (when the input is less than smallest int232 or\n * greater than largest int232).\n *\n * Counterpart to Solidity's `int232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toInt232(int256 value) internal pure returns (int232 downcasted) {\n downcasted = int232(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 232 bits\");\n }\n\n /**\n * @dev Returns the downcasted int224 from int256, reverting on\n * overflow (when the input is less than smallest int224 or\n * greater than largest int224).\n *\n * Counterpart to Solidity's `int224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.7._\n */\n function toInt224(int256 value) internal pure returns (int224 downcasted) {\n downcasted = int224(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 224 bits\");\n }\n\n /**\n * @dev Returns the downcasted int216 from int256, reverting on\n * overflow (when the input is less than smallest int216 or\n * greater than largest int216).\n *\n * Counterpart to Solidity's `int216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toInt216(int256 value) internal pure returns (int216 downcasted) {\n downcasted = int216(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 216 bits\");\n }\n\n /**\n * @dev Returns the downcasted int208 from int256, reverting on\n * overflow (when the input is less than smallest int208 or\n * greater than largest int208).\n *\n * Counterpart to Solidity's `int208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toInt208(int256 value) internal pure returns (int208 downcasted) {\n downcasted = int208(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 208 bits\");\n }\n\n /**\n * @dev Returns the downcasted int200 from int256, reverting on\n * overflow (when the input is less than smallest int200 or\n * greater than largest int200).\n *\n * Counterpart to Solidity's `int200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toInt200(int256 value) internal pure returns (int200 downcasted) {\n downcasted = int200(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 200 bits\");\n }\n\n /**\n * @dev Returns the downcasted int192 from int256, reverting on\n * overflow (when the input is less than smallest int192 or\n * greater than largest int192).\n *\n * Counterpart to Solidity's `int192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toInt192(int256 value) internal pure returns (int192 downcasted) {\n downcasted = int192(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 192 bits\");\n }\n\n /**\n * @dev Returns the downcasted int184 from int256, reverting on\n * overflow (when the input is less than smallest int184 or\n * greater than largest int184).\n *\n * Counterpart to Solidity's `int184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toInt184(int256 value) internal pure returns (int184 downcasted) {\n downcasted = int184(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 184 bits\");\n }\n\n /**\n * @dev Returns the downcasted int176 from int256, reverting on\n * overflow (when the input is less than smallest int176 or\n * greater than largest int176).\n *\n * Counterpart to Solidity's `int176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toInt176(int256 value) internal pure returns (int176 downcasted) {\n downcasted = int176(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 176 bits\");\n }\n\n /**\n * @dev Returns the downcasted int168 from int256, reverting on\n * overflow (when the input is less than smallest int168 or\n * greater than largest int168).\n *\n * Counterpart to Solidity's `int168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toInt168(int256 value) internal pure returns (int168 downcasted) {\n downcasted = int168(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 168 bits\");\n }\n\n /**\n * @dev Returns the downcasted int160 from int256, reverting on\n * overflow (when the input is less than smallest int160 or\n * greater than largest int160).\n *\n * Counterpart to Solidity's `int160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toInt160(int256 value) internal pure returns (int160 downcasted) {\n downcasted = int160(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 160 bits\");\n }\n\n /**\n * @dev Returns the downcasted int152 from int256, reverting on\n * overflow (when the input is less than smallest int152 or\n * greater than largest int152).\n *\n * Counterpart to Solidity's `int152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toInt152(int256 value) internal pure returns (int152 downcasted) {\n downcasted = int152(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 152 bits\");\n }\n\n /**\n * @dev Returns the downcasted int144 from int256, reverting on\n * overflow (when the input is less than smallest int144 or\n * greater than largest int144).\n *\n * Counterpart to Solidity's `int144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toInt144(int256 value) internal pure returns (int144 downcasted) {\n downcasted = int144(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 144 bits\");\n }\n\n /**\n * @dev Returns the downcasted int136 from int256, reverting on\n * overflow (when the input is less than smallest int136 or\n * greater than largest int136).\n *\n * Counterpart to Solidity's `int136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toInt136(int256 value) internal pure returns (int136 downcasted) {\n downcasted = int136(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 136 bits\");\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128 downcasted) {\n downcasted = int128(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 128 bits\");\n }\n\n /**\n * @dev Returns the downcasted int120 from int256, reverting on\n * overflow (when the input is less than smallest int120 or\n * greater than largest int120).\n *\n * Counterpart to Solidity's `int120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toInt120(int256 value) internal pure returns (int120 downcasted) {\n downcasted = int120(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 120 bits\");\n }\n\n /**\n * @dev Returns the downcasted int112 from int256, reverting on\n * overflow (when the input is less than smallest int112 or\n * greater than largest int112).\n *\n * Counterpart to Solidity's `int112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toInt112(int256 value) internal pure returns (int112 downcasted) {\n downcasted = int112(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 112 bits\");\n }\n\n /**\n * @dev Returns the downcasted int104 from int256, reverting on\n * overflow (when the input is less than smallest int104 or\n * greater than largest int104).\n *\n * Counterpart to Solidity's `int104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toInt104(int256 value) internal pure returns (int104 downcasted) {\n downcasted = int104(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 104 bits\");\n }\n\n /**\n * @dev Returns the downcasted int96 from int256, reverting on\n * overflow (when the input is less than smallest int96 or\n * greater than largest int96).\n *\n * Counterpart to Solidity's `int96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.7._\n */\n function toInt96(int256 value) internal pure returns (int96 downcasted) {\n downcasted = int96(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 96 bits\");\n }\n\n /**\n * @dev Returns the downcasted int88 from int256, reverting on\n * overflow (when the input is less than smallest int88 or\n * greater than largest int88).\n *\n * Counterpart to Solidity's `int88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toInt88(int256 value) internal pure returns (int88 downcasted) {\n downcasted = int88(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 88 bits\");\n }\n\n /**\n * @dev Returns the downcasted int80 from int256, reverting on\n * overflow (when the input is less than smallest int80 or\n * greater than largest int80).\n *\n * Counterpart to Solidity's `int80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toInt80(int256 value) internal pure returns (int80 downcasted) {\n downcasted = int80(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 80 bits\");\n }\n\n /**\n * @dev Returns the downcasted int72 from int256, reverting on\n * overflow (when the input is less than smallest int72 or\n * greater than largest int72).\n *\n * Counterpart to Solidity's `int72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toInt72(int256 value) internal pure returns (int72 downcasted) {\n downcasted = int72(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 72 bits\");\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64 downcasted) {\n downcasted = int64(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 64 bits\");\n }\n\n /**\n * @dev Returns the downcasted int56 from int256, reverting on\n * overflow (when the input is less than smallest int56 or\n * greater than largest int56).\n *\n * Counterpart to Solidity's `int56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toInt56(int256 value) internal pure returns (int56 downcasted) {\n downcasted = int56(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 56 bits\");\n }\n\n /**\n * @dev Returns the downcasted int48 from int256, reverting on\n * overflow (when the input is less than smallest int48 or\n * greater than largest int48).\n *\n * Counterpart to Solidity's `int48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toInt48(int256 value) internal pure returns (int48 downcasted) {\n downcasted = int48(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 48 bits\");\n }\n\n /**\n * @dev Returns the downcasted int40 from int256, reverting on\n * overflow (when the input is less than smallest int40 or\n * greater than largest int40).\n *\n * Counterpart to Solidity's `int40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toInt40(int256 value) internal pure returns (int40 downcasted) {\n downcasted = int40(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 40 bits\");\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32 downcasted) {\n downcasted = int32(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 32 bits\");\n }\n\n /**\n * @dev Returns the downcasted int24 from int256, reverting on\n * overflow (when the input is less than smallest int24 or\n * greater than largest int24).\n *\n * Counterpart to Solidity's `int24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toInt24(int256 value) internal pure returns (int24 downcasted) {\n downcasted = int24(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 24 bits\");\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16 downcasted) {\n downcasted = int16(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 16 bits\");\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8 downcasted) {\n downcasted = int8(value);\n require(downcasted == value, \"SafeCast: value doesn't fit in 8 bits\");\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n *\n * _Available since v3.0._\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\n}\n" + }, + "@openzeppelin/contracts/utils/StorageSlot.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/StorageSlot.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for reading and writing primitive types to specific storage slots.\n *\n * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.\n * This library helps with reading and writing to such slots without the need for inline assembly.\n *\n * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.\n *\n * Example usage to set ERC1967 implementation slot:\n * ```\n * contract ERC1967 {\n * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n *\n * function _getImplementation() internal view returns (address) {\n * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n * }\n *\n * function _setImplementation(address newImplementation) internal {\n * require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n * }\n * }\n * ```\n *\n * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._\n */\nlibrary StorageSlot {\n struct AddressSlot {\n address value;\n }\n\n struct BooleanSlot {\n bool value;\n }\n\n struct Bytes32Slot {\n bytes32 value;\n }\n\n struct Uint256Slot {\n uint256 value;\n }\n\n /**\n * @dev Returns an `AddressSlot` with member `value` located at `slot`.\n */\n function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `BooleanSlot` with member `value` located at `slot`.\n */\n function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.\n */\n function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n\n /**\n * @dev Returns an `Uint256Slot` with member `value` located at `slot`.\n */\n function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {\n /// @solidity memory-safe-assembly\n assembly {\n r.slot := slot\n }\n }\n}\n" + }, + "@openzeppelin/contracts/utils/structs/EnumerableSet.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure\n * unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping(bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) {\n // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n if (lastIndex != toDeleteIndex) {\n bytes32 lastValue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastValue;\n // Update the index for the moved value\n set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n }\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n return set._values[index];\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function _values(Set storage set) private view returns (bytes32[] memory) {\n return set._values;\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n bytes32[] memory store = _values(set._inner);\n bytes32[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = _values(set._inner);\n address[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(UintSet storage set) internal view returns (uint256[] memory) {\n bytes32[] memory store = _values(set._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n}\n" + }, + "@pythnetwork/pyth-sdk-solidity/IPyth.sol": { + "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity ^0.8.0;\n\nimport \"./PythStructs.sol\";\nimport \"./IPythEvents.sol\";\n\n/// @title Consume prices from the Pyth Network (https://pyth.network/).\n/// @dev Please refer to the guidance at https://docs.pyth.network/consumers/best-practices for how to consume prices safely.\n/// @author Pyth Data Association\ninterface IPyth is IPythEvents {\n /// @notice Returns the period (in seconds) that a price feed is considered valid since its publish time\n function getValidTimePeriod() external view returns (uint validTimePeriod);\n\n /// @notice Returns the price and confidence interval.\n /// @dev Reverts if the price has not been updated within the last `getValidTimePeriod()` seconds.\n /// @param id The Pyth Price Feed ID of which to fetch the price and confidence interval.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getPrice(\n bytes32 id\n ) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponentially-weighted moving average price and confidence interval.\n /// @dev Reverts if the EMA price is not available.\n /// @param id The Pyth Price Feed ID of which to fetch the EMA price and confidence interval.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getEmaPrice(\n bytes32 id\n ) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the price of a price feed without any sanity checks.\n /// @dev This function returns the most recent price update in this contract without any recency checks.\n /// This function is unsafe as the returned price update may be arbitrarily far in the past.\n ///\n /// Users of this function should check the `publishTime` in the price to ensure that the returned price is\n /// sufficiently recent for their application. If you are considering using this function, it may be\n /// safer / easier to use either `getPrice` or `getPriceNoOlderThan`.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getPriceUnsafe(\n bytes32 id\n ) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the price that is no older than `age` seconds of the current time.\n /// @dev This function is a sanity-checked version of `getPriceUnsafe` which is useful in\n /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently\n /// recently.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getPriceNoOlderThan(\n bytes32 id,\n uint age\n ) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponentially-weighted moving average price of a price feed without any sanity checks.\n /// @dev This function returns the same price as `getEmaPrice` in the case where the price is available.\n /// However, if the price is not recent this function returns the latest available price.\n ///\n /// The returned price can be from arbitrarily far in the past; this function makes no guarantees that\n /// the returned price is recent or useful for any particular application.\n ///\n /// Users of this function should check the `publishTime` in the price to ensure that the returned price is\n /// sufficiently recent for their application. If you are considering using this function, it may be\n /// safer / easier to use either `getEmaPrice` or `getEmaPriceNoOlderThan`.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getEmaPriceUnsafe(\n bytes32 id\n ) external view returns (PythStructs.Price memory price);\n\n /// @notice Returns the exponentially-weighted moving average price that is no older than `age` seconds\n /// of the current time.\n /// @dev This function is a sanity-checked version of `getEmaPriceUnsafe` which is useful in\n /// applications that require a sufficiently-recent price. Reverts if the price wasn't updated sufficiently\n /// recently.\n /// @return price - please read the documentation of PythStructs.Price to understand how to use this safely.\n function getEmaPriceNoOlderThan(\n bytes32 id,\n uint age\n ) external view returns (PythStructs.Price memory price);\n\n /// @notice Update price feeds with given update messages.\n /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling\n /// `getUpdateFee` with the length of the `updateData` array.\n /// Prices will be updated if they are more recent than the current stored prices.\n /// The call will succeed even if the update is not the most recent.\n /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid.\n /// @param updateData Array of price update data.\n function updatePriceFeeds(bytes[] calldata updateData) external payable;\n\n /// @notice Wrapper around updatePriceFeeds that rejects fast if a price update is not necessary. A price update is\n /// necessary if the current on-chain publishTime is older than the given publishTime. It relies solely on the\n /// given `publishTimes` for the price feeds and does not read the actual price update publish time within `updateData`.\n ///\n /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling\n /// `getUpdateFee` with the length of the `updateData` array.\n ///\n /// `priceIds` and `publishTimes` are two arrays with the same size that correspond to senders known publishTime\n /// of each priceId when calling this method. If all of price feeds within `priceIds` have updated and have\n /// a newer or equal publish time than the given publish time, it will reject the transaction to save gas.\n /// Otherwise, it calls updatePriceFeeds method to update the prices.\n ///\n /// @dev Reverts if update is not needed or the transferred fee is not sufficient or the updateData is invalid.\n /// @param updateData Array of price update data.\n /// @param priceIds Array of price ids.\n /// @param publishTimes Array of publishTimes. `publishTimes[i]` corresponds to known `publishTime` of `priceIds[i]`\n function updatePriceFeedsIfNecessary(\n bytes[] calldata updateData,\n bytes32[] calldata priceIds,\n uint64[] calldata publishTimes\n ) external payable;\n\n /// @notice Returns the required fee to update an array of price updates.\n /// @param updateData Array of price update data.\n /// @return feeAmount The required fee in Wei.\n function getUpdateFee(\n bytes[] calldata updateData\n ) external view returns (uint feeAmount);\n\n /// @notice Parse `updateData` and return price feeds of the given `priceIds` if they are all published\n /// within `minPublishTime` and `maxPublishTime`.\n ///\n /// You can use this method if you want to use a Pyth price at a fixed time and not the most recent price;\n /// otherwise, please consider using `updatePriceFeeds`. This method does not store the price updates on-chain.\n ///\n /// This method requires the caller to pay a fee in wei; the required fee can be computed by calling\n /// `getUpdateFee` with the length of the `updateData` array.\n ///\n ///\n /// @dev Reverts if the transferred fee is not sufficient or the updateData is invalid or there is\n /// no update for any of the given `priceIds` within the given time range.\n /// @param updateData Array of price update data.\n /// @param priceIds Array of price ids.\n /// @param minPublishTime minimum acceptable publishTime for the given `priceIds`.\n /// @param maxPublishTime maximum acceptable publishTime for the given `priceIds`.\n /// @return priceFeeds Array of the price feeds corresponding to the given `priceIds` (with the same order).\n function parsePriceFeedUpdates(\n bytes[] calldata updateData,\n bytes32[] calldata priceIds,\n uint64 minPublishTime,\n uint64 maxPublishTime\n ) external payable returns (PythStructs.PriceFeed[] memory priceFeeds);\n}\n" + }, + "@pythnetwork/pyth-sdk-solidity/IPythEvents.sol": { + "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity ^0.8.0;\n\n/// @title IPythEvents contains the events that Pyth contract emits.\n/// @dev This interface can be used for listening to the updates for off-chain and testing purposes.\ninterface IPythEvents {\n /// @dev Emitted when the price feed with `id` has received a fresh update.\n /// @param id The Pyth Price Feed ID.\n /// @param publishTime Publish time of the given price update.\n /// @param price Price of the given price update.\n /// @param conf Confidence interval of the given price update.\n event PriceFeedUpdate(\n bytes32 indexed id,\n uint64 publishTime,\n int64 price,\n uint64 conf\n );\n\n /// @dev Emitted when a batch price update is processed successfully.\n /// @param chainId ID of the source chain that the batch price update comes from.\n /// @param sequenceNumber Sequence number of the batch price update.\n event BatchPriceFeedUpdate(uint16 chainId, uint64 sequenceNumber);\n}\n" + }, + "@pythnetwork/pyth-sdk-solidity/PythStructs.sol": { + "content": "// SPDX-License-Identifier: Apache-2.0\npragma solidity ^0.8.0;\n\ncontract PythStructs {\n // A price with a degree of uncertainty, represented as a price +- a confidence interval.\n //\n // The confidence interval roughly corresponds to the standard error of a normal distribution.\n // Both the price and confidence are stored in a fixed-point numeric representation,\n // `x * (10^expo)`, where `expo` is the exponent.\n //\n // Please refer to the documentation at https://docs.pyth.network/consumers/best-practices for how\n // to how this price safely.\n struct Price {\n // Price\n int64 price;\n // Confidence interval around the price\n uint64 conf;\n // Price exponent\n int32 expo;\n // Unix timestamp describing when the price was published\n uint publishTime;\n }\n\n // PriceFeed represents a current aggregate price from pyth publisher feeds.\n struct PriceFeed {\n // The price ID.\n bytes32 id;\n // Latest available price\n Price price;\n // Latest available exponentially-weighted moving average price\n Price emaPrice;\n }\n}\n" + }, + "adrastia-periphery/rates/IHistoricalRates.sol": { + "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.5.0 <0.9.0;\n\nimport \"./RateLibrary.sol\";\n\n/**\n * @title IHistoricalRates\n * @notice An interface that defines a contract that stores historical rates.\n */\ninterface IHistoricalRates {\n /// @notice Gets an rate for a token at a specific index.\n /// @param token The address of the token to get the rates for.\n /// @param index The index of the rate to get, where index 0 contains the latest rate, and the last\n /// index contains the oldest rate (uses reverse chronological ordering).\n /// @return rate The rate for the token at the specified index.\n function getRateAt(address token, uint256 index) external view returns (RateLibrary.Rate memory);\n\n /// @notice Gets the latest rates for a token.\n /// @param token The address of the token to get the rates for.\n /// @param amount The number of rates to get.\n /// @return rates The latest rates for the token, in reverse chronological order, from newest to oldest.\n function getRates(address token, uint256 amount) external view returns (RateLibrary.Rate[] memory);\n\n /// @notice Gets the latest rates for a token.\n /// @param token The address of the token to get the rates for.\n /// @param amount The number of rates to get.\n /// @param offset The index of the first rate to get (default: 0).\n /// @param increment The increment between rates to get (default: 1).\n /// @return rates The latest rates for the token, in reverse chronological order, from newest to oldest.\n function getRates(\n address token,\n uint256 amount,\n uint256 offset,\n uint256 increment\n ) external view returns (RateLibrary.Rate[] memory);\n\n /// @notice Gets the number of rates for a token.\n /// @param token The address of the token to get the number of rates for.\n /// @return count The number of rates for the token.\n function getRatesCount(address token) external view returns (uint256);\n\n /// @notice Gets the capacity of rates for a token.\n /// @param token The address of the token to get the capacity of rates for.\n /// @return capacity The capacity of rates for the token.\n function getRatesCapacity(address token) external view returns (uint256);\n\n /// @notice Sets the capacity of rates for a token.\n /// @param token The address of the token to set the capacity of rates for.\n /// @param amount The new capacity of rates for the token.\n function setRatesCapacity(address token, uint256 amount) external;\n}\n" + }, + "adrastia-periphery/rates/IRateComputer.sol": { + "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.5.0 <0.9.0;\n\n/**\n * @title IRateComputer\n * @notice An interface that defines a contract that computes rates.\n */\ninterface IRateComputer {\n /// @notice Computes the rate for a token.\n /// @param token The address of the token to compute the rate for.\n /// @return rate The rate for the token.\n function computeRate(address token) external view returns (uint64);\n}\n" + }, + "adrastia-periphery/rates/RateLibrary.sol": { + "content": "//SPDX-License-Identifier: MIT\npragma solidity >=0.5.0 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\nlibrary RateLibrary {\n struct Rate {\n uint64 target;\n uint64 current;\n uint32 timestamp;\n }\n}\n" + }, + "contracts/src/adrastia/PrudentiaLib.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nlibrary PrudentiaLib {\n struct PrudentiaConfig {\n address controller; // Adrastia Prudentia controller address\n uint8 offset; // Offset for delayed rate activation\n int8 decimalShift; // Positive values scale the rate up (in powers of 10), negative values scale the rate down\n }\n}\n" + }, + "contracts/src/bridge/hyperlane/interfaces/hooks/IPostDispatchHook.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\n/*@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@ HYPERLANE @@@@@@@\n @@@@@@@@@@@@@@@@@@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n @@@@@@@@@ @@@@@@@@@\n@@@@@@@@@ @@@@@@@@*/\n\ninterface IPostDispatchHook {\n enum Types {\n UNUSED,\n ROUTING,\n AGGREGATION,\n MERKLE_TREE,\n INTERCHAIN_GAS_PAYMASTER,\n FALLBACK_ROUTING,\n ID_AUTH_ISM,\n PAUSABLE,\n PROTOCOL_FEE,\n LAYER_ZERO_V1,\n RATE_LIMITED,\n ARB_L2_TO_L1,\n OP_L2_TO_L1\n }\n\n /**\n * @notice Returns an enum that represents the type of hook\n */\n function hookType() external view returns (uint8);\n\n /**\n * @notice Returns whether the hook supports metadata\n * @param metadata metadata\n * @return Whether the hook supports metadata\n */\n function supportsMetadata(\n bytes calldata metadata\n ) external view returns (bool);\n\n /**\n * @notice Post action after a message is dispatched via the Mailbox\n * @param metadata The metadata required for the hook\n * @param message The message passed from the Mailbox.dispatch() call\n */\n function postDispatch(\n bytes calldata metadata,\n bytes calldata message\n ) external payable;\n\n /**\n * @notice Compute the payment required by the postDispatch call\n * @param metadata The metadata required for the hook\n * @param message The message passed from the Mailbox.dispatch() call\n * @return Quoted payment for the postDispatch call\n */\n function quoteDispatch(\n bytes calldata metadata,\n bytes calldata message\n ) external view returns (uint256);\n}" + }, + "contracts/src/bridge/hyperlane/interfaces/IInterchainSecurityModule.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.6.11;\n\ninterface IInterchainSecurityModule {\n enum Types {\n UNUSED,\n ROUTING,\n AGGREGATION,\n LEGACY_MULTISIG,\n MERKLE_ROOT_MULTISIG,\n MESSAGE_ID_MULTISIG,\n NULL, // used with relayer carrying no metadata\n CCIP_READ,\n ARB_L2_TO_L1,\n WEIGHTED_MERKLE_ROOT_MULTISIG,\n WEIGHTED_MESSAGE_ID_MULTISIG,\n OP_L2_TO_L1\n }\n\n /**\n * @notice Returns an enum that represents the type of security model\n * encoded by this ISM.\n * @dev Relayers infer how to fetch and format metadata.\n */\n function moduleType() external view returns (uint8);\n\n /**\n * @notice Defines a security model responsible for verifying interchain\n * messages based on the provided metadata.\n * @param _metadata Off-chain metadata provided by a relayer, specific to\n * the security model encoded by the module (e.g. validator signatures)\n * @param _message Hyperlane encoded interchain message\n * @return True if the message was verified\n */\n function verify(\n bytes calldata _metadata,\n bytes calldata _message\n ) external returns (bool);\n}\n\ninterface ISpecifiesInterchainSecurityModule {\n function interchainSecurityModule()\n external\n view\n returns (IInterchainSecurityModule);\n}" + }, + "contracts/src/bridge/hyperlane/interfaces/IMailbox.sol": { + "content": "// SPDX-License-Identifier: MIT OR Apache-2.0\npragma solidity >=0.8.0;\n\nimport {IInterchainSecurityModule} from \"./IInterchainSecurityModule.sol\";\nimport {IPostDispatchHook} from \"./hooks/IPostDispatchHook.sol\";\n\ninterface IMailbox {\n // ============ Events ============\n /**\n * @notice Emitted when a new message is dispatched via Hyperlane\n * @param sender The address that dispatched the message\n * @param destination The destination domain of the message\n * @param recipient The message recipient address on `destination`\n * @param message Raw bytes of message\n */\n event Dispatch(\n address indexed sender,\n uint32 indexed destination,\n bytes32 indexed recipient,\n bytes message\n );\n\n /**\n * @notice Emitted when a new message is dispatched via Hyperlane\n * @param messageId The unique message identifier\n */\n event DispatchId(bytes32 indexed messageId);\n\n /**\n * @notice Emitted when a Hyperlane message is processed\n * @param messageId The unique message identifier\n */\n event ProcessId(bytes32 indexed messageId);\n\n /**\n * @notice Emitted when a Hyperlane message is delivered\n * @param origin The origin domain of the message\n * @param sender The message sender address on `origin`\n * @param recipient The address that handled the message\n */\n event Process(\n uint32 indexed origin,\n bytes32 indexed sender,\n address indexed recipient\n );\n\n function localDomain() external view returns (uint32);\n\n function delivered(bytes32 messageId) external view returns (bool);\n\n function defaultIsm() external view returns (IInterchainSecurityModule);\n\n function defaultHook() external view returns (IPostDispatchHook);\n\n function requiredHook() external view returns (IPostDispatchHook);\n\n function latestDispatchedId() external view returns (bytes32);\n\n function dispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody\n ) external payable returns (bytes32 messageId);\n\n function quoteDispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody\n ) external view returns (uint256 fee);\n\n function dispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata body,\n bytes calldata defaultHookMetadata\n ) external payable returns (bytes32 messageId);\n\n function quoteDispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody,\n bytes calldata defaultHookMetadata\n ) external view returns (uint256 fee);\n\n function dispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata body,\n bytes calldata customHookMetadata,\n IPostDispatchHook customHook\n ) external payable returns (bytes32 messageId);\n\n function quoteDispatch(\n uint32 destinationDomain,\n bytes32 recipientAddress,\n bytes calldata messageBody,\n bytes calldata customHookMetadata,\n IPostDispatchHook customHook\n ) external view returns (uint256 fee);\n\n function process(\n bytes calldata metadata,\n bytes calldata message\n ) external payable;\n\n function recipientIsm(\n address recipient\n ) external view returns (IInterchainSecurityModule module);\n}" + }, + "contracts/src/bridge/interface/IXERC20.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.4 <0.9.0;\n\ninterface IXERC20 {\n /**\n * @notice Emits when a lockbox is set\n *\n * @param _lockbox The address of the lockbox\n */\n event LockboxSet(address _lockbox);\n\n /**\n * @notice Emits when a limit is set\n *\n * @param _mintingLimit The updated minting limit we are setting to the bridge\n * @param _burningLimit The updated burning limit we are setting to the bridge\n * @param _bridge The address of the bridge we are setting the limit too\n */\n event BridgeLimitsSet(uint256 _mintingLimit, uint256 _burningLimit, address indexed _bridge);\n\n /**\n * @notice Reverts when a user with too low of a limit tries to call mint/burn\n */\n error IXERC20_NotHighEnoughLimits();\n\n /**\n * @notice Reverts when caller is not the factory\n */\n error IXERC20_NotFactory();\n\n /**\n * @notice Reverts when limits are too high\n */\n error IXERC20_LimitsTooHigh();\n\n /**\n * @notice Contains the full minting and burning data for a particular bridge\n *\n * @param minterParams The minting parameters for the bridge\n * @param burnerParams The burning parameters for the bridge\n */\n struct Bridge {\n BridgeParameters minterParams;\n BridgeParameters burnerParams;\n }\n\n /**\n * @notice Contains the mint or burn parameters for a bridge\n *\n * @param timestamp The timestamp of the last mint/burn\n * @param ratePerSecond The rate per second of the bridge\n * @param maxLimit The max limit of the bridge\n * @param currentLimit The current limit of the bridge\n */\n struct BridgeParameters {\n uint256 timestamp;\n uint256 ratePerSecond;\n uint256 maxLimit;\n uint256 currentLimit;\n }\n\n /**\n * @notice Sets the lockbox address\n *\n * @param _lockbox The address of the lockbox\n */\n function setLockbox(address _lockbox) external;\n\n /**\n * @notice Updates the limits of any bridge\n * @dev Can only be called by the owner\n * @param _mintingLimit The updated minting limit we are setting to the bridge\n * @param _burningLimit The updated burning limit we are setting to the bridge\n * @param _bridge The address of the bridge we are setting the limits too\n */\n function setLimits(address _bridge, uint256 _mintingLimit, uint256 _burningLimit) external;\n\n /**\n * @notice Returns the max limit of a minter\n *\n * @param _minter The minter we are viewing the limits of\n * @return _limit The limit the minter has\n */\n function mintingMaxLimitOf(address _minter) external view returns (uint256 _limit);\n\n /**\n * @notice Returns the max limit of a bridge\n *\n * @param _bridge the bridge we are viewing the limits of\n * @return _limit The limit the bridge has\n */\n function burningMaxLimitOf(address _bridge) external view returns (uint256 _limit);\n\n /**\n * @notice Returns the current limit of a minter\n *\n * @param _minter The minter we are viewing the limits of\n * @return _limit The limit the minter has\n */\n function mintingCurrentLimitOf(address _minter) external view returns (uint256 _limit);\n\n /**\n * @notice Returns the current limit of a bridge\n *\n * @param _bridge the bridge we are viewing the limits of\n * @return _limit The limit the bridge has\n */\n function burningCurrentLimitOf(address _bridge) external view returns (uint256 _limit);\n\n /**\n * @notice Mints tokens for a user\n * @dev Can only be called by a minter\n * @param _user The address of the user who needs tokens minted\n * @param _amount The amount of tokens being minted\n */\n function mint(address _user, uint256 _amount) external;\n\n /**\n * @notice Burns tokens for a user\n * @dev Can only be called by a minter\n * @param _user The address of the user who needs tokens burned\n * @param _amount The amount of tokens being burned\n */\n function burn(address _user, uint256 _amount) external;\n}" + }, + "contracts/src/bridge/xERC20Hyperlane.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.22;\n\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IXERC20 } from \"./interface/IXERC20.sol\";\nimport { IMailbox } from \"./hyperlane/interfaces/IMailbox.sol\";\n\nlibrary TypeCasts {\n // alignment preserving cast\n function addressToBytes32(address _addr) internal pure returns (bytes32) {\n return bytes32(uint256(uint160(_addr)));\n }\n\n // alignment preserving cast\n function bytes32ToAddress(bytes32 _buf) internal pure returns (address) {\n return address(uint160(uint256(_buf)));\n }\n}\n\ncontract xERC20Hyperlane is Ownable {\n using TypeCasts for address;\n using TypeCasts for bytes32;\n\n uint256 public feeBps;\n mapping(address => mapping(uint32 => address)) public mappedTokens;\n mapping(uint32 => address) public mappedBridges;\n IMailbox immutable mailbox;\n\n event TokenMapped(address indexed _token, uint32 indexed _chainId, address indexed _dstToken);\n event BridgeMapped(uint32 indexed _chainId, address indexed _bridge);\n event FeeBpsSet(uint256 indexed _feeBps);\n event TokenSent(\n address indexed _token,\n uint256 _amount,\n address indexed _to,\n uint32 indexed _dstChainId,\n bytes32 _guid\n );\n event TokenReceived(\n address indexed _token,\n uint256 _amount,\n address indexed _to,\n uint32 indexed _srcChainId,\n bytes32 _guid\n );\n\n error TokenNotSet();\n error ChainIdNotSet();\n error DestinationBridgeNotSet(uint32 _chainId);\n error OriginNotAllowed(uint32 _chainId, address _sender);\n\n /**\n * @notice Only accept messages from an Hyperlane Mailbox contract\n */\n modifier onlyMailbox() {\n require(msg.sender == address(mailbox), \"MailboxClient: sender not mailbox\");\n _;\n }\n\n constructor(uint256 _feeBps, address _mailbox) Ownable() {\n mailbox = IMailbox(_mailbox);\n feeBps = _feeBps;\n }\n\n // ADMIN FUNCTIONS\n function setFeeBps(uint256 _feeBps) public onlyOwner {\n feeBps = _feeBps;\n emit FeeBpsSet(_feeBps);\n }\n\n function setMappedToken(uint32 _chainId, address _srcToken, address _dstToken) public onlyOwner {\n mappedTokens[_srcToken][_chainId] = _dstToken;\n emit TokenMapped(_srcToken, _chainId, _dstToken);\n }\n\n function setMappedBridge(uint32 _chainId, address _bridge) public onlyOwner {\n mappedBridges[_chainId] = _bridge;\n emit BridgeMapped(_chainId, _bridge);\n }\n\n function withdrawFee(address _token) public onlyOwner {\n uint256 _amount = IERC20(_token).balanceOf(address(this));\n IERC20(_token).transfer(msg.sender, _amount);\n }\n\n function withdrawFee(address _token, uint256 _amount) public onlyOwner {\n IERC20(_token).transfer(msg.sender, _amount);\n }\n\n function withdrawEth() public onlyOwner {\n uint256 _amount = address(this).balance;\n payable(msg.sender).transfer(_amount);\n }\n\n function withdrawEth(uint256 _amount) public onlyOwner {\n payable(msg.sender).transfer(_amount);\n }\n\n // PUBLIC FUNCTIONS\n function quote(uint32 _dstChainId, address _token, uint256 _amount, address _to) external view returns (uint256 fee) {\n return _quoteInternal(_dstChainId, _token, _amount, _to);\n }\n\n function send(address _token, uint256 _amount, address _to, uint32 _dstChainId) external payable {\n _send(_dstChainId, _token, _amount, _to);\n }\n\n // INTERNAL FUNCTIONS\n function _quoteInternal(\n uint32 _dstChainId,\n address _token,\n uint256 _amount,\n address _to\n ) internal view returns (uint256 fee) {\n address _bridge = mappedBridges[_dstChainId];\n if (_bridge == address(0)) {\n revert DestinationBridgeNotSet(_dstChainId);\n }\n uint256 _amountAfterFee = (_amount * (10000 - feeBps)) / 10000;\n bytes memory _payload = abi.encode(_to, _token, _amountAfterFee);\n fee = mailbox.quoteDispatch(_dstChainId, _bridge.addressToBytes32(), _payload);\n return fee;\n }\n\n function _send(uint32 _dstChainId, address _token, uint256 _amount, address _to) internal {\n address _bridge = mappedBridges[_dstChainId];\n if (_bridge == address(0)) {\n revert DestinationBridgeNotSet(_dstChainId);\n }\n // transfer tokens to this contract\n IERC20(_token).transferFrom(msg.sender, address(this), _amount);\n\n // take fee and burn the tokens\n uint256 _amountAfterFee = (_amount * (10000 - feeBps)) / 10000;\n IXERC20(_token).burn(address(this), _amountAfterFee);\n\n bytes memory _payload = abi.encode(_to, _token, _amountAfterFee);\n bytes32 _guid = mailbox.dispatch{ value: msg.value }(_dstChainId, _bridge.addressToBytes32(), _payload);\n emit TokenSent(_token, _amountAfterFee, _to, _dstChainId, _guid);\n }\n\n function handle(uint32 _origin, bytes32 _sender, bytes calldata _data) external payable virtual onlyMailbox {\n if (mappedBridges[_origin] != _sender.bytes32ToAddress()) {\n revert OriginNotAllowed(_origin, _sender.bytes32ToAddress());\n }\n // Decode the payload to get the message\n (address _to, address _srcToken, uint256 _amount) = abi.decode(_data, (address, address, uint256));\n\n // get the mapped token using the current chain id and received source token\n address _dstToken = mappedTokens[_srcToken][_origin];\n if (_dstToken == address(0)) {\n revert TokenNotSet();\n }\n\n // mint the tokens to the destination address\n IXERC20(_dstToken).mint(_to, _amount);\n emit TokenReceived(_dstToken, _amount, _to, _origin, bytes32(0));\n }\n\n receive() external payable {}\n}\n" + }, + "contracts/src/bridge/xERC20LayerZero.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.22;\n\nimport { OApp, Origin, MessagingFee, MessagingReceipt } from \"@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol\";\nimport { OptionsBuilder } from \"@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol\";\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IXERC20 } from \"./interface/IXERC20.sol\";\n\ncontract xERC20LayerZero is Ownable, OApp {\n using OptionsBuilder for bytes;\n\n uint256 public feeBps;\n mapping(address => mapping(uint32 => address)) public mappedTokens;\n mapping(uint32 => uint32) public chainIdToEid;\n mapping(uint32 => uint32) public eidToChainId;\n\n event TokenMapped(address indexed _token, uint32 indexed _chainId, address indexed _dstToken);\n event ChainIdToEidSet(uint32 indexed _chainId, uint32 indexed _eid);\n event EidToChainIdSet(uint32 indexed _eid, uint32 indexed _chainId);\n event FeeBpsSet(uint256 indexed _feeBps);\n event TokenSent(\n address indexed _token,\n uint256 _amount,\n address indexed _to,\n uint32 indexed _dstChainId,\n bytes32 _guid\n );\n event TokenReceived(\n address indexed _token,\n uint256 _amount,\n address indexed _to,\n uint32 indexed _srcChainId,\n bytes32 _guid\n );\n\n error TokenNotSet();\n error ChainIdNotSet();\n error OriginNotMirrorAdapter();\n\n constructor(uint256 _feeBps, address _endpoint) OApp(_endpoint, msg.sender) Ownable() {\n feeBps = _feeBps;\n\n // known chain ids\n // Set initial chain ID to EID mappings\n setChainIdToEid(8453, 30184); // base\n setChainIdToEid(10, 30111); // optimism\n setChainIdToEid(252, 30255); // fraxtal\n setChainIdToEid(60808, 30279); // bob\n setChainIdToEid(34443, 30260); // mode\n\n // Set initial EID to chain ID mappings\n setEidToChainId(30184, 8453); // base\n setEidToChainId(30111, 10); // optimism\n setEidToChainId(30255, 252); // fraxtal\n setEidToChainId(30279, 60808); // bob\n setEidToChainId(30260, 34443); // mode\n }\n\n // ADMIN FUNCTIONS\n function setFeeBps(uint256 _feeBps) public onlyOwner {\n feeBps = _feeBps;\n emit FeeBpsSet(_feeBps);\n }\n\n function setMappedToken(uint32 _chainId, address _srcToken, address _dstToken) public onlyOwner {\n mappedTokens[_srcToken][_chainId] = _dstToken;\n emit TokenMapped(_srcToken, _chainId, _dstToken);\n }\n\n function setChainIdToEid(uint32 _chainId, uint32 _eid) public onlyOwner {\n chainIdToEid[_chainId] = _eid;\n emit ChainIdToEidSet(_chainId, _eid);\n }\n\n function setEidToChainId(uint32 _eid, uint32 _chainId) public onlyOwner {\n eidToChainId[_eid] = _chainId;\n emit EidToChainIdSet(_eid, _chainId);\n }\n\n function withdrawFee(address _token) public onlyOwner {\n uint256 _amount = IERC20(_token).balanceOf(address(this));\n IERC20(_token).transfer(msg.sender, _amount);\n }\n\n function withdrawFee(address _token, uint256 _amount) public onlyOwner {\n IERC20(_token).transfer(msg.sender, _amount);\n }\n\n function withdrawEth() public onlyOwner {\n uint256 _amount = address(this).balance;\n payable(msg.sender).transfer(_amount);\n }\n\n function withdrawEth(uint256 _amount) public onlyOwner {\n payable(msg.sender).transfer(_amount);\n }\n\n // PUBLIC FUNCTIONS\n function quote(\n uint32 _dstChainId,\n address _token,\n uint256 _amount,\n address _to\n ) external view returns (uint256 nativeFee, uint256 zroFee) {\n bytes memory options = OptionsBuilder.newOptions().addExecutorLzReceiveOption(50000, 0);\n return _quoteInternal(_dstChainId, _token, _amount, _to, options, false);\n }\n\n function quote(\n uint32 _dstChainId, // destination endpoint id\n address _token,\n uint256 _amount,\n address _to,\n bytes memory _options, // your message execution options\n bool _payInLzToken // boolean for which token to return fee in\n ) external view returns (uint256 nativeFee, uint256 zroFee) {\n return _quoteInternal(_dstChainId, _token, _amount, _to, _options, _payInLzToken);\n }\n\n function send(\n address _token,\n uint256 _amount,\n address _to,\n uint32 _dstChainId\n ) external payable {\n bytes memory options = OptionsBuilder.newOptions().addExecutorLzReceiveOption(50000, 0);\n _send(_dstChainId, _token, _amount, _to, options);\n }\n\n /**\n * @notice Sends tokens to a destination chain\n *\n * @param _token The token to send\n * @param _amount The amount of tokens to send\n * @param _to The address to send the tokens to\n * @param _dstChainId The destination chain id\n * @param _options The options to send the tokens with\n */\n function send(\n address _token,\n uint256 _amount,\n address _to,\n uint32 _dstChainId,\n bytes calldata _options\n ) external payable {\n _send(_dstChainId, _token, _amount, _to, _options);\n }\n\n // INTERNAL FUNCTIONS\n function _quoteInternal(\n uint32 _dstChainId,\n address _token,\n uint256 _amount,\n address _to,\n bytes memory _options,\n bool _payInLzToken\n ) internal view returns (uint256 nativeFee, uint256 zroFee) {\n uint32 _dstEid = chainIdToEid[_dstChainId];\n if (_dstEid == 0) {\n revert ChainIdNotSet();\n }\n uint256 _amountAfterFee = (_amount * (10000 - feeBps)) / 10000;\n bytes memory _payload = abi.encode(_to, _token, _amountAfterFee);\n MessagingFee memory fee = _quote(_dstEid, _payload, _options, _payInLzToken);\n return (fee.nativeFee, fee.lzTokenFee);\n }\n\n function _send(\n uint32 _dstChainId,\n address _token,\n uint256 _amount,\n address _to,\n bytes memory _options\n ) internal {\n uint32 _dstEid = chainIdToEid[_dstChainId];\n if (_dstEid == 0) {\n revert ChainIdNotSet();\n }\n\n // transfer tokens to this contract\n IERC20(_token).transferFrom(msg.sender, address(this), _amount);\n\n // take fee and burn the tokens\n uint256 _amountAfterFee = (_amount * (10000 - feeBps)) / 10000;\n IXERC20(_token).burn(address(this), _amountAfterFee);\n\n bytes memory _payload = abi.encode(_to, _token, _amountAfterFee);\n MessagingReceipt memory _receipt = _lzSend(\n _dstEid,\n _payload,\n _options,\n // Fee in native gas and ZRO token.\n MessagingFee(msg.value, 0),\n // Refund address in case of failed source message.\n payable(msg.sender)\n );\n emit TokenSent(_token, _amountAfterFee, _to, _dstChainId, _receipt.guid);\n }\n\n // LAYERZERO FUNCTIONS\n /**\n * @dev Called when data is received from the protocol. It overrides the equivalent function in the parent contract.\n * Protocol messages are defined as packets, comprised of the following parameters.\n * @param _origin A struct containing information about where the packet came from.\n * @param _guid A global unique identifier for tracking the packet.\n * @param payload Encoded message.\n */\n function _lzReceive(\n Origin calldata _origin,\n bytes32 _guid,\n bytes calldata payload,\n address, // Executor address as specified by the OApp.\n bytes calldata // Any extra data or options to trigger on receipt.\n ) internal override {\n // Decode the payload to get the message\n (address _to, address _srcToken, uint256 _amount) = abi.decode(payload, (address, address, uint256));\n\n uint32 _srcChainId = eidToChainId[_origin.srcEid];\n // get the mapped token using the current chain id and received source token\n address _dstToken = mappedTokens[_srcToken][_srcChainId];\n if (_dstToken == address(0)) {\n revert TokenNotSet();\n }\n\n // mint the tokens to the destination address\n IXERC20(_dstToken).mint(_to, _amount);\n emit TokenReceived(_dstToken, _amount, _to, _srcChainId, _guid);\n }\n\n receive() external payable {}\n}\n" + }, + "contracts/src/compound/CarefulMath.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\n/**\n * @title Careful Math\n * @author Compound\n * @notice Derived from OpenZeppelin's SafeMath library\n * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol\n */\ncontract CarefulMath {\n /**\n * @dev Possible error codes that we can return\n */\n enum MathError {\n NO_ERROR,\n DIVISION_BY_ZERO,\n INTEGER_OVERFLOW,\n INTEGER_UNDERFLOW\n }\n\n /**\n * @dev Multiplies two numbers, returns an error on overflow.\n */\n function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {\n if (a == 0) {\n return (MathError.NO_ERROR, 0);\n }\n\n uint256 c;\n unchecked {\n c = a * b;\n }\n\n if (c / a != b) {\n return (MathError.INTEGER_OVERFLOW, 0);\n } else {\n return (MathError.NO_ERROR, c);\n }\n }\n\n /**\n * @dev Integer division of two numbers, truncating the quotient.\n */\n function divUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {\n if (b == 0) {\n return (MathError.DIVISION_BY_ZERO, 0);\n }\n\n return (MathError.NO_ERROR, a / b);\n }\n\n /**\n * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).\n */\n function subUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {\n if (b <= a) {\n return (MathError.NO_ERROR, a - b);\n } else {\n return (MathError.INTEGER_UNDERFLOW, 0);\n }\n }\n\n /**\n * @dev Adds two numbers, returns an error on overflow.\n */\n function addUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {\n uint256 c;\n unchecked {\n c = a + b;\n }\n\n if (c >= a) {\n return (MathError.NO_ERROR, c);\n } else {\n return (MathError.INTEGER_OVERFLOW, 0);\n }\n }\n\n /**\n * @dev add a and b and then subtract c\n */\n function addThenSubUInt(\n uint256 a,\n uint256 b,\n uint256 c\n ) internal pure returns (MathError, uint256) {\n (MathError err0, uint256 sum) = addUInt(a, b);\n\n if (err0 != MathError.NO_ERROR) {\n return (err0, 0);\n }\n\n return subUInt(sum, c);\n }\n}\n" + }, + "contracts/src/compound/CErc20Delegate.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./CToken.sol\";\n\n/**\n * @title Compound's CErc20Delegate Contract\n * @notice CTokens which wrap an EIP-20 underlying and are delegated to\n * @author Compound\n */\ncontract CErc20Delegate is CErc20 {\n function _getExtensionFunctions() public pure virtual override returns (bytes4[] memory functionSelectors) {\n uint8 fnsCount = 3;\n\n bytes4[] memory superFunctionSelectors = super._getExtensionFunctions();\n functionSelectors = new bytes4[](superFunctionSelectors.length + fnsCount);\n\n for (uint256 i = 0; i < superFunctionSelectors.length; i++) {\n functionSelectors[i] = superFunctionSelectors[i];\n }\n\n functionSelectors[--fnsCount + superFunctionSelectors.length] = this.contractType.selector;\n functionSelectors[--fnsCount + superFunctionSelectors.length] = this.delegateType.selector;\n functionSelectors[--fnsCount + superFunctionSelectors.length] = this._becomeImplementation.selector;\n\n require(fnsCount == 0, \"use the correct array length\");\n }\n\n /**\n * @notice Called by the delegator on a delegate to initialize it for duty\n */\n function _becomeImplementation(bytes memory) public virtual override {\n require(msg.sender == address(this) || hasAdminRights(), \"!self || !admin\");\n }\n\n function delegateType() public pure virtual override returns (uint8) {\n return 1;\n }\n\n function contractType() external pure virtual override returns (string memory) {\n return \"CErc20Delegate\";\n }\n}\n" + }, + "contracts/src/compound/CErc20Delegator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./ComptrollerInterface.sol\";\nimport \"./InterestRateModel.sol\";\nimport \"../ionic/DiamondExtension.sol\";\nimport { CErc20DelegatorBase, CDelegateInterface } from \"./CTokenInterfaces.sol\";\nimport { IFeeDistributor } from \"./IFeeDistributor.sol\";\nimport { EIP20Interface } from \"./EIP20Interface.sol\";\n\n/**\n * @title Compound's CErc20Delegator Contract\n * @notice CTokens which wrap an EIP-20 underlying and delegate to an implementation\n * @author Compound\n */\ncontract CErc20Delegator is CErc20DelegatorBase, DiamondBase {\n /**\n * @notice Emitted when implementation is changed\n */\n event NewImplementation(address oldImplementation, address newImplementation);\n\n /**\n * @notice Initialize the new money market\n * @param underlying_ The address of the underlying asset\n * @param comptroller_ The address of the Comptroller\n * @param ionicAdmin_ The FeeDistributor contract address.\n * @param interestRateModel_ The address of the interest rate model\n * @param name_ ERC-20 name of this token\n * @param symbol_ ERC-20 symbol of this token\n */\n constructor(\n address underlying_,\n IonicComptroller comptroller_,\n address payable ionicAdmin_,\n InterestRateModel interestRateModel_,\n string memory name_,\n string memory symbol_,\n uint256 reserveFactorMantissa_,\n uint256 adminFeeMantissa_\n ) {\n require(msg.sender == ionicAdmin_, \"!admin\");\n uint8 decimals_ = EIP20Interface(underlying_).decimals();\n {\n ionicAdmin = ionicAdmin_;\n\n // Set initial exchange rate\n initialExchangeRateMantissa = 0.2e18;\n\n // Set the comptroller\n comptroller = comptroller_;\n\n // Initialize block number and borrow index (block number mocks depend on comptroller being set)\n accrualBlockNumber = block.number;\n borrowIndex = 1e18;\n\n // Set the interest rate model (depends on block number / borrow index)\n require(interestRateModel_.isInterestRateModel(), \"!notIrm\");\n interestRateModel = interestRateModel_;\n emit NewMarketInterestRateModel(InterestRateModel(address(0)), interestRateModel_);\n\n name = name_;\n symbol = symbol_;\n decimals = decimals_;\n\n // Set reserve factor\n // Check newReserveFactor ≤ maxReserveFactor\n require(\n reserveFactorMantissa_ + adminFeeMantissa + ionicFeeMantissa <= reserveFactorPlusFeesMaxMantissa,\n \"!rf:set\"\n );\n reserveFactorMantissa = reserveFactorMantissa_;\n emit NewReserveFactor(0, reserveFactorMantissa_);\n\n // Set admin fee\n // Sanitize adminFeeMantissa_\n if (adminFeeMantissa_ == type(uint256).max) adminFeeMantissa_ = adminFeeMantissa;\n // Get latest Ionic fee\n uint256 newIonicFeeMantissa = IFeeDistributor(ionicAdmin).interestFeeRate();\n require(\n reserveFactorMantissa + adminFeeMantissa_ + newIonicFeeMantissa <= reserveFactorPlusFeesMaxMantissa,\n \"!adminFee:set\"\n );\n adminFeeMantissa = adminFeeMantissa_;\n emit NewAdminFee(0, adminFeeMantissa_);\n ionicFeeMantissa = newIonicFeeMantissa;\n emit NewIonicFee(0, newIonicFeeMantissa);\n\n // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)\n _notEntered = true;\n }\n\n // Set underlying and sanity check it\n underlying = underlying_;\n EIP20Interface(underlying).totalSupply();\n }\n\n function implementation() public view returns (address) {\n return LibDiamond.getExtensionForFunction(bytes4(keccak256(bytes(\"delegateType()\"))));\n }\n\n /**\n * @notice Called by the admin to update the implementation of the delegator\n * @param implementation_ The address of the new implementation for delegation\n * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n */\n function _setImplementationSafe(address implementation_, bytes calldata becomeImplementationData) external override {\n // Check admin rights\n require(hasAdminRights(), \"!admin\");\n\n // Set implementation\n _setImplementationInternal(implementation_, becomeImplementationData);\n }\n\n /**\n * @dev upgrades the implementation if necessary\n */\n function _upgrade() external override {\n require(msg.sender == address(this) || hasAdminRights(), \"!self or admin\");\n\n (bool success, bytes memory data) = address(this).staticcall(abi.encodeWithSignature(\"delegateType()\"));\n require(success, \"no delegate type\");\n\n uint8 currentDelegateType = abi.decode(data, (uint8));\n (address latestCErc20Delegate, bytes memory becomeImplementationData) = IFeeDistributor(ionicAdmin)\n .latestCErc20Delegate(currentDelegateType);\n\n address currentDelegate = implementation();\n if (currentDelegate != latestCErc20Delegate) {\n _setImplementationInternal(latestCErc20Delegate, becomeImplementationData);\n } else {\n // only update the extensions without reinitializing with becomeImplementationData\n _updateExtensions(currentDelegate);\n }\n }\n\n /**\n * @dev register a logic extension\n * @param extensionToAdd the extension whose functions are to be added\n * @param extensionToReplace the extension whose functions are to be removed/replaced\n */\n function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) external override {\n require(msg.sender == address(ionicAdmin), \"!unauthorized\");\n LibDiamond.registerExtension(extensionToAdd, extensionToReplace);\n }\n\n /**\n * @dev Internal function to update the implementation of the delegator\n * @param implementation_ The address of the new implementation for delegation\n * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n */\n function _setImplementationInternal(address implementation_, bytes memory becomeImplementationData) internal {\n address delegateBefore = implementation();\n _updateExtensions(implementation_);\n\n _functionCall(\n address(this),\n abi.encodeWithSelector(CDelegateInterface._becomeImplementation.selector, becomeImplementationData),\n \"!become impl\"\n );\n\n emit NewImplementation(delegateBefore, implementation_);\n }\n\n function _updateExtensions(address newDelegate) internal {\n address[] memory latestExtensions = IFeeDistributor(ionicAdmin).getCErc20DelegateExtensions(newDelegate);\n address[] memory currentExtensions = LibDiamond.listExtensions();\n\n // removed the current (old) extensions\n for (uint256 i = 0; i < currentExtensions.length; i++) {\n LibDiamond.removeExtension(DiamondExtension(currentExtensions[i]));\n }\n // add the new extensions\n for (uint256 i = 0; i < latestExtensions.length; i++) {\n LibDiamond.addExtension(DiamondExtension(latestExtensions[i]));\n }\n }\n\n function _functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.call(data);\n\n if (!success) {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n\n return returndata;\n }\n}\n" + }, + "contracts/src/compound/CErc20PluginDelegate.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./CErc20Delegate.sol\";\nimport \"./EIP20Interface.sol\";\nimport \"./IERC4626.sol\";\nimport \"../external/uniswap/IUniswapV2Pair.sol\";\n\n/**\n * @title Rari's CErc20Plugin's Contract\n * @notice CToken which outsources token logic to a plugin\n * @author Joey Santoro\n *\n * CErc20PluginDelegate deposits and withdraws from a plugin contract\n * It is also capable of delegating reward functionality to a PluginRewardsDistributor\n */\ncontract CErc20PluginDelegate is CErc20Delegate {\n event NewPluginImplementation(address oldImpl, address newImpl);\n\n /**\n * @notice Plugin address\n */\n IERC4626 public plugin;\n\n function _getExtensionFunctions() public pure virtual override returns (bytes4[] memory functionSelectors) {\n uint8 fnsCount = 2;\n\n bytes4[] memory superFunctionSelectors = super._getExtensionFunctions();\n functionSelectors = new bytes4[](superFunctionSelectors.length + fnsCount);\n\n for (uint256 i = 0; i < superFunctionSelectors.length; i++) {\n functionSelectors[i] = superFunctionSelectors[i];\n }\n\n functionSelectors[--fnsCount + superFunctionSelectors.length] = this.plugin.selector;\n functionSelectors[--fnsCount + superFunctionSelectors.length] = this._updatePlugin.selector;\n\n require(fnsCount == 0, \"use the correct array length\");\n }\n\n /**\n * @notice Delegate interface to become the implementation\n * @param data The encoded arguments for becoming\n */\n function _becomeImplementation(bytes memory data) public virtual override {\n require(msg.sender == address(this) || hasAdminRights(), \"only self and admins can call _becomeImplementation\");\n\n address _plugin = abi.decode(data, (address));\n\n if (_plugin == address(0) && address(plugin) != address(0)) {\n // if no new plugin address is given, use the latest implementation\n _plugin = IFeeDistributor(ionicAdmin).latestPluginImplementation(address(plugin));\n }\n\n if (_plugin != address(0) && _plugin != address(plugin)) {\n _updatePlugin(_plugin);\n }\n }\n\n /**\n * @notice Update the plugin implementation to a whitelisted implementation\n * @param _plugin The address of the plugin implementation to use\n */\n function _updatePlugin(address _plugin) public {\n require(msg.sender == address(this) || hasAdminRights(), \"only self and admins can call _updatePlugin\");\n\n address oldImplementation = address(plugin) != address(0) ? address(plugin) : _plugin;\n\n if (address(plugin) != address(0) && plugin.balanceOf(address(this)) != 0) {\n plugin.redeem(plugin.balanceOf(address(this)), address(this), address(this));\n }\n\n plugin = IERC4626(_plugin);\n\n EIP20Interface(underlying).approve(_plugin, type(uint256).max);\n\n uint256 amount = EIP20Interface(underlying).balanceOf(address(this));\n if (amount != 0) {\n deposit(amount);\n }\n\n emit NewPluginImplementation(oldImplementation, _plugin);\n }\n\n /*** CToken Overrides ***/\n\n /*** Safe Token ***/\n\n /**\n * @notice Gets balance of the plugin in terms of the underlying\n * @return The quantity of underlying tokens owned by this contract\n */\n function getCashInternal() internal view override returns (uint256) {\n return plugin.previewRedeem(plugin.balanceOf(address(this)));\n }\n\n /**\n * @notice Transfer the underlying to the cToken and trigger a deposit\n * @param from Address to transfer funds from\n * @param amount Amount of underlying to transfer\n * @return The actual amount that is transferred\n */\n function doTransferIn(address from, uint256 amount) internal override returns (uint256) {\n // Perform the EIP-20 transfer in\n require(EIP20Interface(underlying).transferFrom(from, address(this), amount), \"send\");\n\n deposit(amount);\n return amount;\n }\n\n function deposit(uint256 amount) internal {\n plugin.deposit(amount, address(this));\n }\n\n /**\n * @notice Transfer the underlying from plugin to destination\n * @param to Address to transfer funds to\n * @param amount Amount of underlying to transfer\n */\n function doTransferOut(address to, uint256 amount) internal override {\n plugin.withdraw(amount, to, address(this));\n }\n\n function delegateType() public pure virtual override returns (uint8) {\n return 2;\n }\n\n function contractType() external pure virtual override returns (string memory) {\n return \"CErc20PluginDelegate\";\n }\n}\n" + }, + "contracts/src/compound/CErc20PluginRewardsDelegate.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./CErc20PluginDelegate.sol\";\n\ncontract CErc20PluginRewardsDelegate is CErc20PluginDelegate {\n function _getExtensionFunctions() public pure virtual override returns (bytes4[] memory functionSelectors) {\n uint8 fnsCount = 2;\n\n bytes4[] memory superFunctionSelectors = super._getExtensionFunctions();\n functionSelectors = new bytes4[](superFunctionSelectors.length + fnsCount);\n\n for (uint256 i = 0; i < superFunctionSelectors.length; i++) {\n functionSelectors[i] = superFunctionSelectors[i];\n }\n\n functionSelectors[--fnsCount + superFunctionSelectors.length] = this.claim.selector;\n functionSelectors[--fnsCount + superFunctionSelectors.length] = this.approve.selector;\n\n require(fnsCount == 0, \"use the correct array length\");\n }\n\n /// @notice A reward token claim function\n /// to be overridden for use cases where rewardToken needs to be pulled in\n function claim() external {}\n\n /// @notice token approval function\n function approve(address _token, address _spender) external {\n require(hasAdminRights(), \"!admin\");\n require(_token != underlying && _token != address(plugin), \"!token\");\n\n EIP20Interface(_token).approve(_spender, type(uint256).max);\n }\n\n function delegateType() public pure virtual override returns (uint8) {\n return 4;\n }\n\n function contractType() external pure override returns (string memory) {\n return \"CErc20PluginRewardsDelegate\";\n }\n}\n" + }, + "contracts/src/compound/CErc20RewardsDelegate.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./CErc20Delegate.sol\";\nimport \"./EIP20Interface.sol\";\n\ncontract CErc20RewardsDelegate is CErc20Delegate {\n function _getExtensionFunctions() public pure virtual override returns (bytes4[] memory functionSelectors) {\n uint8 fnsCount = 2;\n\n bytes4[] memory superFunctionSelectors = super._getExtensionFunctions();\n functionSelectors = new bytes4[](superFunctionSelectors.length + fnsCount);\n\n for (uint256 i = 0; i < superFunctionSelectors.length; i++) {\n functionSelectors[i] = superFunctionSelectors[i];\n }\n\n functionSelectors[--fnsCount + superFunctionSelectors.length] = this.claim.selector;\n functionSelectors[--fnsCount + superFunctionSelectors.length] = this.approve.selector;\n\n require(fnsCount == 0, \"use the correct array length\");\n }\n \n /// @notice A reward token claim function\n /// to be overridden for use cases where rewardToken needs to be pulled in\n function claim() external {}\n\n /// @notice token approval function\n function approve(address _token, address _spender) external {\n require(hasAdminRights(), \"!admin\");\n require(_token != underlying, \"!underlying\");\n\n EIP20Interface(_token).approve(_spender, type(uint256).max);\n }\n\n function delegateType() public pure virtual override returns (uint8) {\n return 3;\n }\n\n function contractType() external pure override returns (string memory) {\n return \"CErc20RewardsDelegate\";\n }\n}\n" + }, + "contracts/src/compound/Comptroller.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { ICErc20 } from \"./CTokenInterfaces.sol\";\nimport { ComptrollerErrorReporter } from \"./ErrorReporter.sol\";\nimport { Exponential } from \"./Exponential.sol\";\nimport { BasePriceOracle } from \"../oracles/BasePriceOracle.sol\";\nimport { Unitroller } from \"./Unitroller.sol\";\nimport { IFeeDistributor } from \"./IFeeDistributor.sol\";\nimport { IIonicFlywheel } from \"../ionic/strategies/flywheel/IIonicFlywheel.sol\";\nimport { DiamondExtension, DiamondBase, LibDiamond } from \"../ionic/DiamondExtension.sol\";\nimport { ComptrollerExtensionInterface, ComptrollerBase, ComptrollerInterface } from \"./ComptrollerInterface.sol\";\n\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\n/**\n * @title Compound's Comptroller Contract\n * @author Compound\n * @dev This contract should not to be deployed alone; instead, deploy `Unitroller` (proxy contract) on top of this `Comptroller` (logic/implementation contract).\n */\ncontract Comptroller is ComptrollerBase, ComptrollerInterface, ComptrollerErrorReporter, Exponential, DiamondExtension {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /// @notice Emitted when an admin supports a market\n event MarketListed(ICErc20 cToken);\n\n /// @notice Emitted when an account enters a market\n event MarketEntered(ICErc20 cToken, address account);\n\n /// @notice Emitted when an account exits a market\n event MarketExited(ICErc20 cToken, address account);\n\n /// @notice Emitted when close factor is changed by admin\n event NewCloseFactor(uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa);\n\n /// @notice Emitted when a collateral factor is changed by admin\n event NewCollateralFactor(ICErc20 cToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa);\n\n /// @notice Emitted when liquidation incentive is changed by admin\n event NewLiquidationIncentive(uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa);\n\n /// @notice Emitted when price oracle is changed\n event NewPriceOracle(BasePriceOracle oldPriceOracle, BasePriceOracle newPriceOracle);\n\n /// @notice Emitted when the whitelist enforcement is changed\n event WhitelistEnforcementChanged(bool enforce);\n\n /// @notice Emitted when a new RewardsDistributor contract is added to hooks\n event AddedRewardsDistributor(address rewardsDistributor);\n\n // closeFactorMantissa must be strictly greater than this value\n uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05\n\n // closeFactorMantissa must not exceed this value\n uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9\n\n // No collateralFactorMantissa may exceed this value\n uint256 internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9\n\n // liquidationIncentiveMantissa must be no less than this value\n uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0\n\n // liquidationIncentiveMantissa must be no greater than this value\n uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5\n\n modifier isAuthorized() {\n require(IFeeDistributor(ionicAdmin).canCall(address(this), msg.sender, address(this), msg.sig), \"not authorized\");\n _;\n }\n\n /**\n * @notice Gets the supply cap of a cToken in the units of the underlying asset.\n * @param cToken The address of the cToken.\n */\n function effectiveSupplyCaps(\n address cToken\n ) public view override(ComptrollerBase, ComptrollerInterface) returns (uint256 supplyCap) {\n return ComptrollerBase.effectiveSupplyCaps(cToken);\n }\n\n /**\n * @notice Gets the borrow cap of a cToken in the units of the underlying asset.\n * @param cToken The address of the cToken.\n */\n function effectiveBorrowCaps(\n address cToken\n ) public view override(ComptrollerBase, ComptrollerInterface) returns (uint256 borrowCap) {\n return ComptrollerBase.effectiveBorrowCaps(cToken);\n }\n\n /*** Assets You Are In ***/\n\n /**\n * @notice Returns the assets an account has entered\n * @param account The address of the account to pull assets for\n * @return A dynamic list with the assets the account has entered\n */\n function getAssetsIn(address account) external view returns (ICErc20[] memory) {\n ICErc20[] memory assetsIn = accountAssets[account];\n\n return assetsIn;\n }\n\n /**\n * @notice Returns whether the given account is entered in the given asset\n * @param account The address of the account to check\n * @param cToken The cToken to check\n * @return True if the account is in the asset, otherwise false.\n */\n function checkMembership(address account, ICErc20 cToken) external view returns (bool) {\n return markets[address(cToken)].accountMembership[account];\n }\n\n /**\n * @notice Add assets to be included in account liquidity calculation\n * @param cTokens The list of addresses of the cToken markets to be enabled\n * @return Success indicator for whether each corresponding market was entered\n */\n function enterMarkets(address[] memory cTokens) public override isAuthorized returns (uint256[] memory) {\n uint256 len = cTokens.length;\n\n uint256[] memory results = new uint256[](len);\n for (uint256 i = 0; i < len; i++) {\n ICErc20 cToken = ICErc20(cTokens[i]);\n\n results[i] = uint256(addToMarketInternal(cToken, msg.sender));\n }\n\n return results;\n }\n\n /**\n * @notice Add the market to the borrower's \"assets in\" for liquidity calculations\n * @param cToken The market to enter\n * @param borrower The address of the account to modify\n * @return Success indicator for whether the market was entered\n */\n function addToMarketInternal(ICErc20 cToken, address borrower) internal returns (Error) {\n Market storage marketToJoin = markets[address(cToken)];\n\n if (!marketToJoin.isListed) {\n // market is not listed, cannot join\n return Error.MARKET_NOT_LISTED;\n }\n\n if (marketToJoin.accountMembership[borrower] == true) {\n // already joined\n return Error.NO_ERROR;\n }\n\n // survived the gauntlet, add to list\n // NOTE: we store these somewhat redundantly as a significant optimization\n // this avoids having to iterate through the list for the most common use cases\n // that is, only when we need to perform liquidity checks\n // and not whenever we want to check if an account is in a particular market\n marketToJoin.accountMembership[borrower] = true;\n accountAssets[borrower].push(cToken);\n\n // Add to allBorrowers\n if (!borrowers[borrower]) {\n allBorrowers.push(borrower);\n borrowers[borrower] = true;\n borrowerIndexes[borrower] = allBorrowers.length - 1;\n }\n\n emit MarketEntered(cToken, borrower);\n\n return Error.NO_ERROR;\n }\n\n /**\n * @notice Removes asset from sender's account liquidity calculation\n * @dev Sender must not have an outstanding borrow balance in the asset,\n * or be providing necessary collateral for an outstanding borrow.\n * @param cTokenAddress The address of the asset to be removed\n * @return Whether or not the account successfully exited the market\n */\n function exitMarket(address cTokenAddress) external override isAuthorized returns (uint256) {\n // TODO\n require(markets[cTokenAddress].isListed, \"!Comptroller:exitMarket\");\n\n ICErc20 cToken = ICErc20(cTokenAddress);\n /* Get sender tokensHeld and amountOwed underlying from the cToken */\n (uint256 oErr, uint256 tokensHeld, uint256 amountOwed, ) = cToken.getAccountSnapshot(msg.sender);\n require(oErr == 0, \"!exitMarket\"); // semi-opaque error code\n\n /* Fail if the sender has a borrow balance */\n if (amountOwed != 0) {\n return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);\n }\n\n /* Fail if the sender is not permitted to redeem all of their tokens */\n uint256 allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);\n if (allowed != 0) {\n return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);\n }\n\n Market storage marketToExit = markets[cTokenAddress];\n\n /* Return true if the sender is not already ‘in’ the market */\n if (!marketToExit.accountMembership[msg.sender]) {\n return uint256(Error.NO_ERROR);\n }\n\n /* Set cToken account membership to false */\n delete marketToExit.accountMembership[msg.sender];\n\n /* Delete cToken from the account’s list of assets */\n // load into memory for faster iteration\n ICErc20[] memory userAssetList = accountAssets[msg.sender];\n uint256 len = userAssetList.length;\n uint256 assetIndex = len;\n for (uint256 i = 0; i < len; i++) {\n if (userAssetList[i] == ICErc20(cTokenAddress)) {\n assetIndex = i;\n break;\n }\n }\n\n // We *must* have found the asset in the list or our redundant data structure is broken\n assert(assetIndex < len);\n\n // copy last item in list to location of item to be removed, reduce length by 1\n ICErc20[] storage storedList = accountAssets[msg.sender];\n storedList[assetIndex] = storedList[storedList.length - 1];\n storedList.pop();\n\n // If the user has exited all markets, remove them from the `allBorrowers` array\n if (storedList.length == 0) {\n allBorrowers[borrowerIndexes[msg.sender]] = allBorrowers[allBorrowers.length - 1]; // Copy last item in list to location of item to be removed\n allBorrowers.pop(); // Reduce length by 1\n borrowerIndexes[allBorrowers[borrowerIndexes[msg.sender]]] = borrowerIndexes[msg.sender]; // Set borrower index of moved item to correct index\n borrowerIndexes[msg.sender] = 0; // Reset sender borrower index to 0 for a gas refund\n borrowers[msg.sender] = false; // Tell the contract that the sender is no longer a borrower (so it knows to add the borrower back if they enter a market in the future)\n }\n\n emit MarketExited(ICErc20(cTokenAddress), msg.sender);\n\n return uint256(Error.NO_ERROR);\n }\n\n /*** Policy Hooks ***/\n\n /**\n * @notice Checks if the account should be allowed to mint tokens in the given market\n * @param cTokenAddress The market to verify the mint against\n * @param minter The account which would get the minted tokens\n * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens\n * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n */\n function mintAllowed(address cTokenAddress, address minter, uint256 mintAmount) external override returns (uint256) {\n // Pausing is a very serious situation - we revert to sound the alarms\n require(!mintGuardianPaused[cTokenAddress], \"!mint:paused\");\n\n // Make sure market is listed\n if (!markets[cTokenAddress].isListed) {\n return uint256(Error.MARKET_NOT_LISTED);\n }\n\n // Make sure minter is whitelisted\n if (enforceWhitelist && !whitelist[minter]) {\n return uint256(Error.SUPPLIER_NOT_WHITELISTED);\n }\n\n uint256 supplyCap = effectiveSupplyCaps(cTokenAddress);\n\n // Supply cap of 0 corresponds to unlimited supplying\n if (supplyCap != 0 && !supplyCapWhitelist[cTokenAddress].contains(minter)) {\n uint256 totalUnderlyingSupply = ICErc20(cTokenAddress).getTotalUnderlyingSupplied();\n uint256 whitelistedSuppliersSupply = asComptrollerExtension().getWhitelistedSuppliersSupply(cTokenAddress);\n uint256 nonWhitelistedTotalSupply;\n if (whitelistedSuppliersSupply >= totalUnderlyingSupply) nonWhitelistedTotalSupply = 0;\n else nonWhitelistedTotalSupply = totalUnderlyingSupply - whitelistedSuppliersSupply;\n\n require(nonWhitelistedTotalSupply + mintAmount < supplyCap, \"!supply cap\");\n }\n\n // Keep the flywheel moving\n flywheelPreSupplierAction(cTokenAddress, minter);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Checks if the account should be allowed to redeem tokens in the given market\n * @param cToken The market to verify the redeem against\n * @param redeemer The account which would redeem the tokens\n * @param redeemTokens The number of cTokens to exchange for the underlying asset in the market\n * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n */\n function redeemAllowed(address cToken, address redeemer, uint256 redeemTokens) external override returns (uint256) {\n uint256 allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);\n if (allowed != uint256(Error.NO_ERROR)) {\n return allowed;\n }\n\n // Keep the flywheel moving\n flywheelPreSupplierAction(cToken, redeemer);\n\n return uint256(Error.NO_ERROR);\n }\n\n function redeemAllowedInternal(\n address cToken,\n address redeemer,\n uint256 redeemTokens\n ) internal view returns (uint256) {\n if (!markets[cToken].isListed) {\n return uint256(Error.MARKET_NOT_LISTED);\n }\n\n /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */\n if (!markets[cToken].accountMembership[redeemer]) {\n return uint256(Error.NO_ERROR);\n }\n\n /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */\n (Error err, , , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(\n redeemer,\n ICErc20(cToken),\n redeemTokens,\n 0,\n 0\n );\n if (err != Error.NO_ERROR) {\n return uint256(err);\n }\n if (shortfall > 0) {\n return uint256(Error.INSUFFICIENT_LIQUIDITY);\n }\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Validates mint and reverts on rejection. May emit logs.\n * @param cToken Asset being minted\n * @param minter The address minting the tokens\n * @param actualMintAmount The amount of the underlying asset being minted\n * @param mintTokens The number of tokens being minted\n */\n function mintVerify(address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens) external {\n // Add minter to suppliers mapping\n suppliers[minter] = true;\n\n // Keep the flywheel moving\n flywheelPostSupplierAction(cToken, minter);\n }\n\n /**\n * @notice Validates redeem and reverts on rejection. May emit logs.\n * @param cToken Asset being redeemed\n * @param redeemer The address redeeming the tokens\n * @param redeemAmount The amount of the underlying asset being redeemed\n * @param redeemTokens The number of tokens being redeemed\n */\n function redeemVerify(\n address cToken,\n address redeemer,\n uint256 redeemAmount,\n uint256 redeemTokens\n ) external override {\n require(markets[msg.sender].isListed, \"!market\");\n\n // Require tokens is zero or amount is also zero\n if (redeemTokens == 0 && redeemAmount > 0) {\n revert(\"!zero\");\n }\n\n // Keep the flywheel moving\n flywheelPostSupplierAction(cToken, redeemer);\n }\n\n function getMaxRedeemOrBorrow(\n address account,\n ICErc20 cTokenModify,\n bool isBorrow\n ) external view override returns (uint256) {\n address cToken = address(cTokenModify);\n // Accrue interest\n uint256 balanceOfUnderlying = cTokenModify.balanceOfUnderlying(account);\n\n // Get account liquidity\n (Error err, , uint256 liquidity, uint256 shortfall) = getHypotheticalAccountLiquidityInternal(\n account,\n isBorrow ? cTokenModify : ICErc20(address(0)),\n 0,\n 0,\n 0\n );\n require(err == Error.NO_ERROR, \"!liquidity\");\n if (shortfall > 0) return 0; // Shortfall, so no more borrow/redeem\n\n // Get max borrow/redeem\n uint256 maxBorrowOrRedeemAmount;\n\n if (!isBorrow && !markets[cToken].accountMembership[account]) {\n // Max redeem = balance of underlying if not used as collateral\n maxBorrowOrRedeemAmount = balanceOfUnderlying;\n } else {\n // Avoid \"stack too deep\" error by separating this logic\n maxBorrowOrRedeemAmount = _getMaxRedeemOrBorrow(liquidity, cTokenModify, isBorrow);\n\n // Redeem only: max out at underlying balance\n if (!isBorrow && balanceOfUnderlying < maxBorrowOrRedeemAmount) maxBorrowOrRedeemAmount = balanceOfUnderlying;\n }\n\n // Get max borrow or redeem considering cToken liquidity\n uint256 cTokenLiquidity = cTokenModify.getCash();\n\n // Return the minimum of the two maximums\n return maxBorrowOrRedeemAmount <= cTokenLiquidity ? maxBorrowOrRedeemAmount : cTokenLiquidity;\n }\n\n /**\n * @dev Portion of the logic in `getMaxRedeemOrBorrow` above separated to avoid \"stack too deep\" errors.\n */\n function _getMaxRedeemOrBorrow(\n uint256 liquidity,\n ICErc20 cTokenModify,\n bool isBorrow\n ) internal view returns (uint256) {\n if (liquidity == 0) return 0; // No available account liquidity, so no more borrow/redeem\n\n // Get the normalized price of the asset\n uint256 conversionFactor = oracle.getUnderlyingPrice(cTokenModify);\n require(conversionFactor > 0, \"!oracle\");\n\n // Pre-compute a conversion factor from tokens -> ether (normalized price value)\n if (!isBorrow) {\n uint256 collateralFactorMantissa = markets[address(cTokenModify)].collateralFactorMantissa;\n conversionFactor = (collateralFactorMantissa * conversionFactor) / 1e18;\n }\n\n // Get max borrow or redeem considering excess account liquidity\n return (liquidity * 1e18) / conversionFactor;\n }\n\n /**\n * @notice Checks if the account should be allowed to borrow the underlying asset of the given market\n * @param cToken The market to verify the borrow against\n * @param borrower The account which would borrow the asset\n * @param borrowAmount The amount of underlying the account would borrow\n * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n */\n function borrowAllowed(address cToken, address borrower, uint256 borrowAmount) external override returns (uint256) {\n // Pausing is a very serious situation - we revert to sound the alarms\n require(!borrowGuardianPaused[cToken], \"!borrow:paused\");\n\n // Make sure market is listed\n if (!markets[cToken].isListed) {\n return uint256(Error.MARKET_NOT_LISTED);\n }\n\n if (!markets[cToken].accountMembership[borrower]) {\n // only cTokens may call borrowAllowed if borrower not in market\n require(msg.sender == cToken, \"!ctoken\");\n\n // attempt to add borrower to the market\n Error err = addToMarketInternal(ICErc20(msg.sender), borrower);\n if (err != Error.NO_ERROR) {\n return uint256(err);\n }\n\n // it should be impossible to break the important invariant\n assert(markets[cToken].accountMembership[borrower]);\n }\n\n // Make sure oracle price is available\n if (oracle.getUnderlyingPrice(ICErc20(cToken)) == 0) {\n return uint256(Error.PRICE_ERROR);\n }\n\n // Make sure borrower is whitelisted\n if (enforceWhitelist && !whitelist[borrower]) {\n return uint256(Error.SUPPLIER_NOT_WHITELISTED);\n }\n\n uint256 borrowCap = effectiveBorrowCaps(cToken);\n\n // Borrow cap of 0 corresponds to unlimited borrowing\n if (borrowCap != 0 && !borrowCapWhitelist[cToken].contains(borrower)) {\n uint256 totalBorrows = ICErc20(cToken).totalBorrowsCurrent();\n uint256 whitelistedBorrowersBorrows = asComptrollerExtension().getWhitelistedBorrowersBorrows(cToken);\n uint256 nonWhitelistedTotalBorrows;\n if (whitelistedBorrowersBorrows >= totalBorrows) nonWhitelistedTotalBorrows = 0;\n else nonWhitelistedTotalBorrows = totalBorrows - whitelistedBorrowersBorrows;\n\n require(nonWhitelistedTotalBorrows + borrowAmount < borrowCap, \"!borrow:cap\");\n }\n\n // Keep the flywheel moving\n flywheelPreBorrowerAction(cToken, borrower);\n\n // Perform a hypothetical liquidity check to guard against shortfall\n (uint256 err, , , uint256 shortfall) = this.getHypotheticalAccountLiquidity(borrower, cToken, 0, borrowAmount, 0);\n if (err != uint256(Error.NO_ERROR)) {\n return err;\n }\n if (shortfall > 0) {\n return uint256(Error.INSUFFICIENT_LIQUIDITY);\n }\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Validates borrow the underlying asset of the given market\n * @param cToken The market to verify the borrow against\n * @param borrower The account which borrowed the asset\n */\n function borrowVerify(address cToken, address borrower) external override {\n // Keep the flywheel moving\n flywheelPostBorrowerAction(cToken, borrower);\n }\n\n /**\n * @notice Checks if the account should be allowed to borrow the underlying asset of the given market\n * @param cToken Asset whose underlying is being borrowed\n * @param accountBorrowsNew The user's new borrow balance of the underlying asset\n */\n function borrowWithinLimits(address cToken, uint256 accountBorrowsNew) external view override returns (uint256) {\n // Check if min borrow exists\n uint256 minBorrowEth = IFeeDistributor(ionicAdmin).minBorrowEth();\n\n if (minBorrowEth > 0) {\n // Get new underlying borrow balance of account for this cToken\n uint256 oraclePriceMantissa = oracle.getUnderlyingPrice(ICErc20(cToken));\n if (oraclePriceMantissa == 0) return uint256(Error.PRICE_ERROR);\n (MathError mathErr, uint256 borrowBalanceEth) = mulScalarTruncate(\n Exp({ mantissa: oraclePriceMantissa }),\n accountBorrowsNew\n );\n if (mathErr != MathError.NO_ERROR) return uint256(Error.MATH_ERROR);\n\n // Check against min borrow\n if (borrowBalanceEth < minBorrowEth) return uint256(Error.BORROW_BELOW_MIN);\n }\n\n // Return no error\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Checks if the account should be allowed to repay a borrow in the given market\n * @param cToken The market to verify the repay against\n * @param payer The account which would repay the asset\n * @param borrower The account which would borrowed the asset\n * @param repayAmount The amount of the underlying asset the account would repay\n * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n */\n function repayBorrowAllowed(\n address cToken,\n address payer,\n address borrower,\n uint256 repayAmount\n ) external override returns (uint256) {\n // Make sure market is listed\n if (!markets[cToken].isListed) {\n return uint256(Error.MARKET_NOT_LISTED);\n }\n\n // Keep the flywheel moving\n flywheelPreBorrowerAction(cToken, borrower);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Validates that blacklisted balances are updated after borrow repayment\n * @param cToken The market to verify the repay against\n * @param payer The account which repayed the asset\n * @param borrower The account which borrowed the asset\n * @param repayAmount The amount of the underlying asset the account repayed\n */\n function repayBorrowVerify(\n address cToken,\n address payer,\n address borrower,\n uint256 repayAmount\n ) external override {\n // Keep the flywheel moving\n flywheelPostBorrowerAction(cToken, borrower);\n }\n\n /**\n * @notice Checks if the liquidation should be allowed to occur\n * @param cTokenBorrowed Asset which was borrowed by the borrower\n * @param cTokenCollateral Asset which was used as collateral and will be seized\n * @param liquidator The address repaying the borrow and seizing the collateral\n * @param borrower The address of the borrower\n * @param repayAmount The amount of underlying being repaid\n */\n function liquidateBorrowAllowed(\n address cTokenBorrowed,\n address cTokenCollateral,\n address liquidator,\n address borrower,\n uint256 repayAmount\n ) external override returns (uint256) {\n // Make sure markets are listed\n if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {\n return uint256(Error.MARKET_NOT_LISTED);\n }\n\n // Get borrowers' underlying borrow balance\n uint256 borrowBalance = ICErc20(cTokenBorrowed).borrowBalanceCurrent(borrower);\n\n /* allow accounts to be liquidated if the market is deprecated */\n if (isDeprecated(ICErc20(cTokenBorrowed))) {\n require(borrowBalance >= repayAmount, \"!borrow>repay\");\n } else {\n /* The borrower must have shortfall in order to be liquidateable */\n (Error err, , , uint256 shortfall) = getHypotheticalAccountLiquidityInternal(\n borrower,\n ICErc20(address(0)),\n 0,\n 0,\n 0\n );\n if (err != Error.NO_ERROR) {\n return uint256(err);\n }\n\n if (shortfall == 0) {\n return uint256(Error.INSUFFICIENT_SHORTFALL);\n }\n\n /* The liquidator may not repay more than what is allowed by the closeFactor */\n uint256 maxClose = mul_ScalarTruncate(Exp({ mantissa: closeFactorMantissa }), borrowBalance);\n if (repayAmount > maxClose) {\n return uint256(Error.TOO_MUCH_REPAY);\n }\n }\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Checks if the seizing of assets should be allowed to occur\n * @param cTokenCollateral Asset which was used as collateral and will be seized\n * @param cTokenBorrowed Asset which was borrowed by the borrower\n * @param liquidator The address repaying the borrow and seizing the collateral\n * @param borrower The address of the borrower\n * @param seizeTokens The number of collateral tokens to seize\n */\n function seizeAllowed(\n address cTokenCollateral,\n address cTokenBorrowed,\n address liquidator,\n address borrower,\n uint256 seizeTokens\n ) external override returns (uint256) {\n // Pausing is a very serious situation - we revert to sound the alarms\n require(!seizeGuardianPaused, \"!seize:paused\");\n\n // Make sure markets are listed\n if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {\n return uint256(Error.MARKET_NOT_LISTED);\n }\n\n // Make sure cToken Comptrollers are identical\n if (ICErc20(cTokenCollateral).comptroller() != ICErc20(cTokenBorrowed).comptroller()) {\n return uint256(Error.COMPTROLLER_MISMATCH);\n }\n\n // Keep the flywheel moving\n flywheelPreTransferAction(cTokenCollateral, borrower, liquidator);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Validates that blacklisted balances are updated after seizing of assets\n * @param cTokenCollateral Asset which was used as collateral and will be seized\n * @param cTokenBorrowed Asset which was borrowed by the borrower\n * @param liquidator The address repaying the borrow and seizing the collateral\n * @param borrower The address of the borrower\n * @param seizeTokens The number of collateral tokens to seize\n */\n function seizeVerify(\n address cTokenCollateral,\n address cTokenBorrowed,\n address liquidator,\n address borrower,\n uint256 seizeTokens\n ) external override {\n // Keep the flywheel moving\n flywheelPostTransferAction(cTokenCollateral, borrower, liquidator);\n }\n\n /**\n * @notice Checks if the account should be allowed to transfer tokens in the given market\n * @param cToken The market to verify the transfer against\n * @param src The account which sources the tokens\n * @param dst The account which receives the tokens\n * @param transferTokens The number of cTokens to transfer\n * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\n */\n function transferAllowed(\n address cToken,\n address src,\n address dst,\n uint256 transferTokens\n ) external override returns (uint256) {\n // Pausing is a very serious situation - we revert to sound the alarms\n require(!transferGuardianPaused, \"!transfer:paused\");\n\n // Currently the only consideration is whether or not\n // the src is allowed to redeem this many tokens\n uint256 allowed = redeemAllowedInternal(cToken, src, transferTokens);\n if (allowed != uint256(Error.NO_ERROR)) {\n return allowed;\n }\n\n // Keep the flywheel moving\n flywheelPreTransferAction(cToken, src, dst);\n\n return uint256(Error.NO_ERROR);\n }\n\n\n /**\n * @notice Validates that blacklisted balances are updated after transfering assets\n * @param cToken The market to verify the transfer against\n * @param src The account which sources the tokens\n * @param dst The account which receives the tokens\n * @param transferTokens The number of cTokens to transfer\n */\n function transferVerify(\n address cToken,\n address src,\n address dst,\n uint256 transferTokens\n ) external override {\n\n // Keep the flywheel moving\n flywheelPostTransferAction(cToken, src, dst);\n }\n\n /*** Flywheel Hooks ***/\n\n /**\n * @notice Keeps the flywheel moving pre-mint and pre-redeem\n * @param cToken The relevant market\n * @param supplier The minter/redeemer\n */\n function flywheelPreSupplierAction(address cToken, address supplier) internal {\n for (uint256 i = 0; i < rewardsDistributors.length; i++)\n IIonicFlywheel(rewardsDistributors[i]).flywheelPreSupplierAction(cToken, supplier);\n }\n\n /**\n * @notice Keeps the flywheel moving post-mint and post-redeem\n * @param cToken The relevant market\n * @param supplier The minter/redeemer\n */\n function flywheelPostSupplierAction(address cToken, address supplier) internal {\n for (uint256 i = 0; i < rewardsDistributors.length; i++)\n IIonicFlywheel(rewardsDistributors[i]).flywheelPostSupplierAction(cToken, supplier);\n }\n\n /**\n * @notice Keeps the flywheel moving pre-borrow and pre-repay\n * @param cToken The relevant market\n * @param borrower The borrower\n */\n function flywheelPreBorrowerAction(address cToken, address borrower) internal {\n for (uint256 i = 0; i < rewardsDistributors.length; i++)\n IIonicFlywheel(rewardsDistributors[i]).flywheelPreBorrowerAction(cToken, borrower);\n }\n\n /**\n * @notice Keeps the flywheel moving post-borrow and post-repay\n * @param cToken The relevant market\n * @param borrower The borrower\n */\n function flywheelPostBorrowerAction(address cToken, address borrower) internal {\n for (uint256 i = 0; i < rewardsDistributors.length; i++)\n IIonicFlywheel(rewardsDistributors[i]).flywheelPostBorrowerAction(cToken, borrower);\n }\n\n /**\n * @notice Keeps the flywheel moving pre-transfer and pre-seize\n * @param cToken The relevant market\n * @param src The account which sources the tokens\n * @param dst The account which receives the tokens\n */\n function flywheelPreTransferAction(address cToken, address src, address dst) internal {\n for (uint256 i = 0; i < rewardsDistributors.length; i++)\n IIonicFlywheel(rewardsDistributors[i]).flywheelPreTransferAction(cToken, src, dst);\n }\n\n /**\n * @notice Keeps the flywheel moving post-transfer and post-seize\n * @param cToken The relevant market\n * @param src The account which sources the tokens\n * @param dst The account which receives the tokens\n */\n function flywheelPostTransferAction(address cToken, address src, address dst) internal {\n for (uint256 i = 0; i < rewardsDistributors.length; i++)\n IIonicFlywheel(rewardsDistributors[i]).flywheelPostTransferAction(cToken, src, dst);\n }\n\n /*** Liquidity/Liquidation Calculations ***/\n\n /**\n * @dev Local vars for avoiding stack-depth limits in calculating account liquidity.\n * Note that `cTokenBalance` is the number of cTokens the account owns in the market,\n * whereas `borrowBalance` is the amount of underlying that the account has borrowed.\n */\n struct AccountLiquidityLocalVars {\n ICErc20 asset;\n uint256 sumCollateral;\n uint256 sumBorrowPlusEffects;\n uint256 cTokenBalance;\n uint256 borrowBalance;\n uint256 exchangeRateMantissa;\n uint256 oraclePriceMantissa;\n Exp collateralFactor;\n Exp exchangeRate;\n Exp oraclePrice;\n Exp tokensToDenom;\n uint256 borrowCapForCollateral;\n uint256 borrowedAssetPrice;\n uint256 assetAsCollateralValueCap;\n }\n\n function getAccountLiquidity(address account) public view override returns (uint256, uint256, uint256, uint256) {\n (\n Error err,\n uint256 collateralValue,\n uint256 liquidity,\n uint256 shortfall\n ) = getHypotheticalAccountLiquidityInternal(account, ICErc20(address(0)), 0, 0, 0);\n return (uint256(err), collateralValue, liquidity, shortfall);\n }\n\n /**\n * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\n * @param cTokenModify The market to hypothetically redeem/borrow in\n * @param account The account to determine liquidity for\n * @param redeemTokens The number of tokens to hypothetically redeem\n * @param borrowAmount The amount of underlying to hypothetically borrow\n * @return (possible error code (semi-opaque),\n hypothetical account liquidity in excess of collateral requirements,\n * hypothetical account shortfall below collateral requirements)\n */\n function getHypotheticalAccountLiquidity(\n address account,\n address cTokenModify,\n uint256 redeemTokens,\n uint256 borrowAmount,\n uint256 repayAmount\n ) public view returns (uint256, uint256, uint256, uint256) {\n (\n Error err,\n uint256 collateralValue,\n uint256 liquidity,\n uint256 shortfall\n ) = getHypotheticalAccountLiquidityInternal(\n account,\n ICErc20(cTokenModify),\n redeemTokens,\n borrowAmount,\n repayAmount\n );\n return (uint256(err), collateralValue, liquidity, shortfall);\n }\n\n /**\n * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\n * @param cTokenModify The market to hypothetically redeem/borrow in\n * @param account The account to determine liquidity for\n * @param redeemTokens The number of tokens to hypothetically redeem\n * @param borrowAmount The amount of underlying to hypothetically borrow\n * @return (possible error code,\n hypothetical account collateral value,\n hypothetical account liquidity in excess of collateral requirements,\n * hypothetical account shortfall below collateral requirements)\n */\n function getHypotheticalAccountLiquidityInternal(\n address account,\n ICErc20 cTokenModify,\n uint256 redeemTokens,\n uint256 borrowAmount,\n uint256 repayAmount\n ) internal view returns (Error, uint256, uint256, uint256) {\n AccountLiquidityLocalVars memory vars; // Holds all our calculation results\n\n if (address(cTokenModify) != address(0)) {\n vars.borrowedAssetPrice = oracle.getUnderlyingPrice(cTokenModify);\n }\n\n // For each asset the account is in\n for (uint256 i = 0; i < accountAssets[account].length; i++) {\n vars.asset = accountAssets[account][i];\n\n {\n // Read the balances and exchange rate from the cToken\n uint256 oErr;\n (oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = vars.asset.getAccountSnapshot(\n account\n );\n if (oErr != 0) {\n // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades\n return (Error.SNAPSHOT_ERROR, 0, 0, 0);\n }\n }\n {\n vars.collateralFactor = Exp({ mantissa: markets[address(vars.asset)].collateralFactorMantissa });\n vars.exchangeRate = Exp({ mantissa: vars.exchangeRateMantissa });\n\n // Get the normalized price of the asset\n vars.oraclePriceMantissa = oracle.getUnderlyingPrice(vars.asset);\n if (vars.oraclePriceMantissa == 0) {\n return (Error.PRICE_ERROR, 0, 0, 0);\n }\n vars.oraclePrice = Exp({ mantissa: vars.oraclePriceMantissa });\n\n // Pre-compute a conversion factor from tokens -> ether (normalized price value)\n vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice);\n }\n {\n // Exclude the asset-to-be-borrowed from the liquidity, except for when redeeming\n vars.assetAsCollateralValueCap = asComptrollerExtension().getAssetAsCollateralValueCap(\n vars.asset,\n cTokenModify,\n redeemTokens > 0,\n account\n );\n\n // accumulate the collateral value to sumCollateral\n uint256 assetCollateralValue = mul_ScalarTruncate(vars.tokensToDenom, vars.cTokenBalance);\n if (assetCollateralValue > vars.assetAsCollateralValueCap)\n assetCollateralValue = vars.assetAsCollateralValueCap;\n vars.sumCollateral += assetCollateralValue;\n }\n\n // sumBorrowPlusEffects += oraclePrice * borrowBalance\n vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(\n vars.oraclePrice,\n vars.borrowBalance,\n vars.sumBorrowPlusEffects\n );\n\n // Calculate effects of interacting with cTokenModify\n if (vars.asset == cTokenModify) {\n // redeem effect\n // sumBorrowPlusEffects += tokensToDenom * redeemTokens\n vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(\n vars.tokensToDenom,\n redeemTokens,\n vars.sumBorrowPlusEffects\n );\n\n // borrow effect\n // sumBorrowPlusEffects += oraclePrice * borrowAmount\n vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(\n vars.oraclePrice,\n borrowAmount,\n vars.sumBorrowPlusEffects\n );\n\n uint256 repayEffect = mul_ScalarTruncate(vars.oraclePrice, repayAmount);\n if (repayEffect >= vars.sumBorrowPlusEffects) {\n vars.sumBorrowPlusEffects = 0;\n } else {\n vars.sumBorrowPlusEffects -= repayEffect;\n }\n }\n }\n\n // These are safe, as the underflow condition is checked first\n if (vars.sumCollateral > vars.sumBorrowPlusEffects) {\n return (Error.NO_ERROR, vars.sumCollateral, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);\n } else {\n return (Error.NO_ERROR, vars.sumCollateral, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);\n }\n }\n\n /**\n * @notice Calculate number of tokens of collateral asset to seize given an underlying amount\n * @dev Used in liquidation (called in cToken.liquidateBorrowFresh)\n * @param cTokenBorrowed The address of the borrowed cToken\n * @param cTokenCollateral The address of the collateral cToken\n * @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens\n * @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)\n */\n function liquidateCalculateSeizeTokens(\n address cTokenBorrowed,\n address cTokenCollateral,\n uint256 actualRepayAmount\n ) external view override returns (uint256, uint256) {\n /* Read oracle prices for borrowed and collateral markets */\n uint256 priceBorrowedMantissa = oracle.getUnderlyingPrice(ICErc20(cTokenBorrowed));\n uint256 priceCollateralMantissa = oracle.getUnderlyingPrice(ICErc20(cTokenCollateral));\n if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {\n return (uint256(Error.PRICE_ERROR), 0);\n }\n\n /*\n * Get the exchange rate and calculate the number of collateral tokens to seize:\n * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral\n * seizeTokens = seizeAmount / exchangeRate\n * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)\n */\n ICErc20 collateralCToken = ICErc20(cTokenCollateral);\n uint256 exchangeRateMantissa = collateralCToken.exchangeRateCurrent();\n uint256 seizeTokens;\n Exp memory numerator;\n Exp memory denominator;\n Exp memory ratio;\n\n uint256 protocolSeizeShareMantissa = collateralCToken.protocolSeizeShareMantissa();\n uint256 feeSeizeShareMantissa = collateralCToken.feeSeizeShareMantissa();\n\n /*\n * The liquidation penalty includes\n * - the liquidator incentive\n * - the protocol fees (Ionic admin fees)\n * - the market fee\n */\n Exp memory totalPenaltyMantissa = add_(\n add_(Exp({ mantissa: liquidationIncentiveMantissa }), Exp({ mantissa: protocolSeizeShareMantissa })),\n Exp({ mantissa: feeSeizeShareMantissa })\n );\n\n numerator = mul_(totalPenaltyMantissa, Exp({ mantissa: priceBorrowedMantissa }));\n denominator = mul_(Exp({ mantissa: priceCollateralMantissa }), Exp({ mantissa: exchangeRateMantissa }));\n ratio = div_(numerator, denominator);\n\n seizeTokens = mul_ScalarTruncate(ratio, actualRepayAmount);\n return (uint256(Error.NO_ERROR), seizeTokens);\n }\n\n /*** Admin Functions ***/\n\n /**\n * @notice Add a RewardsDistributor contracts.\n * @dev Admin function to add a RewardsDistributor contract\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _addRewardsDistributor(address distributor) external returns (uint256) {\n require(hasAdminRights(), \"!admin\");\n\n // Check marker method\n require(IIonicFlywheel(distributor).isRewardsDistributor(), \"!isRewardsDistributor\");\n\n // Check for existing RewardsDistributor\n for (uint256 i = 0; i < rewardsDistributors.length; i++) require(distributor != rewardsDistributors[i], \"!added\");\n\n // Add RewardsDistributor to array\n rewardsDistributors.push(distributor);\n emit AddedRewardsDistributor(distributor);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Sets the whitelist enforcement for the comptroller\n * @dev Admin function to set a new whitelist enforcement boolean\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _setWhitelistEnforcement(bool enforce) external returns (uint256) {\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_WHITELIST_ENFORCEMENT_OWNER_CHECK);\n }\n\n // Check if `enforceWhitelist` already equals `enforce`\n if (enforceWhitelist == enforce) {\n return uint256(Error.NO_ERROR);\n }\n\n // Set comptroller's `enforceWhitelist` to `enforce`\n enforceWhitelist = enforce;\n\n // Emit WhitelistEnforcementChanged(bool enforce);\n emit WhitelistEnforcementChanged(enforce);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Sets the whitelist `statuses` for `suppliers`\n * @dev Admin function to set the whitelist `statuses` for `suppliers`\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _setWhitelistStatuses(address[] calldata suppliers, bool[] calldata statuses) external returns (uint256) {\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_WHITELIST_STATUS_OWNER_CHECK);\n }\n\n // Set whitelist statuses for suppliers\n for (uint256 i = 0; i < suppliers.length; i++) {\n address supplier = suppliers[i];\n\n if (statuses[i]) {\n // If not already whitelisted, add to whitelist\n if (!whitelist[supplier]) {\n whitelist[supplier] = true;\n whitelistArray.push(supplier);\n whitelistIndexes[supplier] = whitelistArray.length - 1;\n }\n } else {\n // If whitelisted, remove from whitelist\n if (whitelist[supplier]) {\n whitelistArray[whitelistIndexes[supplier]] = whitelistArray[whitelistArray.length - 1]; // Copy last item in list to location of item to be removed\n whitelistArray.pop(); // Reduce length by 1\n whitelistIndexes[whitelistArray[whitelistIndexes[supplier]]] = whitelistIndexes[supplier]; // Set whitelist index of moved item to correct index\n whitelistIndexes[supplier] = 0; // Reset supplier whitelist index to 0 for a gas refund\n whitelist[supplier] = false; // Tell the contract that the supplier is no longer whitelisted\n }\n }\n }\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Sets a new price oracle for the comptroller\n * @dev Admin function to set a new price oracle\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _setPriceOracle(BasePriceOracle newOracle) public returns (uint256) {\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);\n }\n\n // Track the old oracle for the comptroller\n BasePriceOracle oldOracle = oracle;\n\n // Set comptroller's oracle to newOracle\n oracle = newOracle;\n\n // Emit NewPriceOracle(oldOracle, newOracle)\n emit NewPriceOracle(oldOracle, newOracle);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Sets the closeFactor used when liquidating borrows\n * @dev Admin function to set closeFactor\n * @param newCloseFactorMantissa New close factor, scaled by 1e18\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\n */\n function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256) {\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);\n }\n\n // Check limits\n Exp memory newCloseFactorExp = Exp({ mantissa: newCloseFactorMantissa });\n Exp memory lowLimit = Exp({ mantissa: closeFactorMinMantissa });\n if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {\n return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);\n }\n\n Exp memory highLimit = Exp({ mantissa: closeFactorMaxMantissa });\n if (lessThanExp(highLimit, newCloseFactorExp)) {\n return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);\n }\n\n // Set pool close factor to new close factor, remember old value\n uint256 oldCloseFactorMantissa = closeFactorMantissa;\n closeFactorMantissa = newCloseFactorMantissa;\n\n // Emit event\n emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Sets the collateralFactor for a market\n * @dev Admin function to set per-market collateralFactor\n * @param cToken The market to set the factor on\n * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\n */\n function _setCollateralFactor(ICErc20 cToken, uint256 newCollateralFactorMantissa) public returns (uint256) {\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);\n }\n\n // Verify market is listed\n Market storage market = markets[address(cToken)];\n if (!market.isListed) {\n return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);\n }\n\n Exp memory newCollateralFactorExp = Exp({ mantissa: newCollateralFactorMantissa });\n\n // Check collateral factor <= 0.9\n Exp memory highLimit = Exp({ mantissa: collateralFactorMaxMantissa });\n if (lessThanExp(highLimit, newCollateralFactorExp)) {\n return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);\n }\n\n // If collateral factor != 0, fail if price == 0\n if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {\n return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);\n }\n\n // Set market's collateral factor to new collateral factor, remember old value\n uint256 oldCollateralFactorMantissa = market.collateralFactorMantissa;\n market.collateralFactorMantissa = newCollateralFactorMantissa;\n\n // Emit event with asset, old collateral factor, and new collateral factor\n emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Sets liquidationIncentive\n * @dev Admin function to set liquidationIncentive\n * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\n */\n function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256) {\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);\n }\n\n // Check de-scaled min <= newLiquidationIncentive <= max\n Exp memory newLiquidationIncentive = Exp({ mantissa: newLiquidationIncentiveMantissa });\n Exp memory minLiquidationIncentive = Exp({ mantissa: liquidationIncentiveMinMantissa });\n if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {\n return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);\n }\n\n Exp memory maxLiquidationIncentive = Exp({ mantissa: liquidationIncentiveMaxMantissa });\n if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {\n return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);\n }\n\n // Save current value for use in log\n uint256 oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;\n\n // Set liquidation incentive to new incentive\n liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;\n\n // Emit event with old incentive, new incentive\n emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Add the market to the markets mapping and set it as listed\n * @dev Admin function to set isListed and add support for the market\n * @param cToken The address of the market (token) to list\n * @return uint 0=success, otherwise a failure. (See enum Error for details)\n */\n function _supportMarket(ICErc20 cToken) internal returns (uint256) {\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);\n }\n\n // Is market already listed?\n if (markets[address(cToken)].isListed) {\n return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);\n }\n\n // Check cToken.comptroller == this\n require(address(cToken.comptroller()) == address(this), \"!comptroller\");\n\n // Make sure market is not already listed\n address underlying = ICErc20(address(cToken)).underlying();\n\n if (address(cTokensByUnderlying[underlying]) != address(0)) {\n return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);\n }\n\n // List market and emit event\n Market storage market = markets[address(cToken)];\n market.isListed = true;\n market.collateralFactorMantissa = 0;\n allMarkets.push(cToken);\n cTokensByUnderlying[underlying] = cToken;\n emit MarketListed(cToken);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Deploy cToken, add the market to the markets mapping, and set it as listed and set the collateral factor\n * @dev Admin function to deploy cToken, set isListed, and add support for the market and set the collateral factor\n * @return uint 0=success, otherwise a failure. (See enum Error for details)\n */\n function _deployMarket(\n uint8 delegateType,\n bytes calldata constructorData,\n bytes calldata becomeImplData,\n uint256 collateralFactorMantissa\n ) external returns (uint256) {\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);\n }\n\n // Temporarily enable Ionic admin rights for asset deployment (storing the original value)\n bool oldIonicAdminHasRights = ionicAdminHasRights;\n ionicAdminHasRights = true;\n\n // Deploy via Ionic admin\n ICErc20 cToken = ICErc20(IFeeDistributor(ionicAdmin).deployCErc20(delegateType, constructorData, becomeImplData));\n // Reset Ionic admin rights to the original value\n ionicAdminHasRights = oldIonicAdminHasRights;\n // Support market here in the Comptroller\n uint256 err = _supportMarket(cToken);\n\n IFeeDistributor(ionicAdmin).authoritiesRegistry().reconfigureAuthority(address(this));\n\n // Set collateral factor\n return err == uint256(Error.NO_ERROR) ? _setCollateralFactor(cToken, collateralFactorMantissa) : err;\n }\n\n function _becomeImplementation() external {\n require(msg.sender == address(this), \"!self call\");\n\n if (!_notEnteredInitialized) {\n _notEntered = true;\n _notEnteredInitialized = true;\n }\n }\n\n /*** Helper Functions ***/\n\n /**\n * @notice Returns true if the given cToken market has been deprecated\n * @dev All borrows in a deprecated cToken market can be immediately liquidated\n * @param cToken The market to check if deprecated\n */\n function isDeprecated(ICErc20 cToken) public view returns (bool) {\n return\n markets[address(cToken)].collateralFactorMantissa == 0 &&\n borrowGuardianPaused[address(cToken)] == true &&\n add_(add_(cToken.reserveFactorMantissa(), cToken.adminFeeMantissa()), cToken.ionicFeeMantissa()) == 1e18;\n }\n\n function asComptrollerExtension() internal view returns (ComptrollerExtensionInterface) {\n return ComptrollerExtensionInterface(address(this));\n }\n\n function _getExtensionFunctions() external pure virtual override returns (bytes4[] memory functionSelectors) {\n uint8 fnsCount = 32;\n\n functionSelectors = new bytes4[](fnsCount);\n\n functionSelectors[--fnsCount] = this.isDeprecated.selector;\n functionSelectors[--fnsCount] = this._deployMarket.selector;\n functionSelectors[--fnsCount] = this.getAssetsIn.selector;\n functionSelectors[--fnsCount] = this.checkMembership.selector;\n functionSelectors[--fnsCount] = this._setPriceOracle.selector;\n functionSelectors[--fnsCount] = this._setCloseFactor.selector;\n functionSelectors[--fnsCount] = this._setCollateralFactor.selector;\n functionSelectors[--fnsCount] = this._setLiquidationIncentive.selector;\n functionSelectors[--fnsCount] = this._setWhitelistEnforcement.selector;\n functionSelectors[--fnsCount] = this._setWhitelistStatuses.selector;\n functionSelectors[--fnsCount] = this._addRewardsDistributor.selector;\n functionSelectors[--fnsCount] = this.getHypotheticalAccountLiquidity.selector;\n functionSelectors[--fnsCount] = this.getMaxRedeemOrBorrow.selector;\n functionSelectors[--fnsCount] = this.enterMarkets.selector;\n functionSelectors[--fnsCount] = this.exitMarket.selector;\n functionSelectors[--fnsCount] = this.mintAllowed.selector;\n functionSelectors[--fnsCount] = this.redeemAllowed.selector;\n functionSelectors[--fnsCount] = this.redeemVerify.selector;\n functionSelectors[--fnsCount] = this.borrowAllowed.selector;\n functionSelectors[--fnsCount] = this.borrowWithinLimits.selector;\n functionSelectors[--fnsCount] = this.repayBorrowAllowed.selector;\n functionSelectors[--fnsCount] = this.liquidateBorrowAllowed.selector;\n functionSelectors[--fnsCount] = this.seizeAllowed.selector;\n functionSelectors[--fnsCount] = this.transferAllowed.selector;\n functionSelectors[--fnsCount] = this.mintVerify.selector;\n functionSelectors[--fnsCount] = this.getAccountLiquidity.selector;\n functionSelectors[--fnsCount] = this.liquidateCalculateSeizeTokens.selector;\n functionSelectors[--fnsCount] = this._beforeNonReentrant.selector;\n functionSelectors[--fnsCount] = this._afterNonReentrant.selector;\n functionSelectors[--fnsCount] = this._becomeImplementation.selector;\n functionSelectors[--fnsCount] = this.effectiveSupplyCaps.selector;\n functionSelectors[--fnsCount] = this.effectiveBorrowCaps.selector;\n\n require(fnsCount == 0, \"use the correct array length\");\n }\n\n /*** Pool-Wide/Cross-Asset Reentrancy Prevention ***/\n\n /**\n * @dev Called by cTokens before a non-reentrant function for pool-wide reentrancy prevention.\n * Prevents pool-wide/cross-asset reentrancy exploits like AMP on Cream.\n */\n function _beforeNonReentrant() external override {\n require(markets[msg.sender].isListed, \"!Comptroller:_beforeNonReentrant\");\n require(_notEntered, \"!reentered\");\n _notEntered = false;\n }\n\n /**\n * @dev Called by cTokens after a non-reentrant function for pool-wide reentrancy prevention.\n * Prevents pool-wide/cross-asset reentrancy exploits like AMP on Cream.\n */\n function _afterNonReentrant() external override {\n require(markets[msg.sender].isListed, \"!Comptroller:_afterNonReentrant\");\n _notEntered = true; // get a gas-refund post-Istanbul\n }\n}\n" + }, + "contracts/src/compound/ComptrollerFirstExtension.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { DiamondExtension } from \"../ionic/DiamondExtension.sol\";\nimport { ComptrollerErrorReporter } from \"../compound/ErrorReporter.sol\";\nimport { ICErc20 } from \"./CTokenInterfaces.sol\";\nimport { ComptrollerExtensionInterface, ComptrollerBase, SFSRegister } from \"./ComptrollerInterface.sol\";\n\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract ComptrollerFirstExtension is\n DiamondExtension,\n ComptrollerBase,\n ComptrollerExtensionInterface,\n ComptrollerErrorReporter\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /// @notice Emitted when supply cap for a cToken is changed\n event NewSupplyCap(ICErc20 indexed cToken, uint256 newSupplyCap);\n\n /// @notice Emitted when borrow cap for a cToken is changed\n event NewBorrowCap(ICErc20 indexed cToken, uint256 newBorrowCap);\n\n /// @notice Emitted when borrow cap guardian is changed\n event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);\n\n /// @notice Emitted when pause guardian is changed\n event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);\n\n /// @notice Emitted when an action is paused globally\n event ActionPaused(string action, bool pauseState);\n\n /// @notice Emitted when an action is paused on a market\n event MarketActionPaused(ICErc20 cToken, string action, bool pauseState);\n\n /// @notice Emitted when an admin unsupports a market\n event MarketUnlisted(ICErc20 cToken);\n\n function _getExtensionFunctions() external pure virtual override returns (bytes4[] memory) {\n uint8 fnsCount = 33;\n bytes4[] memory functionSelectors = new bytes4[](fnsCount);\n functionSelectors[--fnsCount] = this.addNonAccruingFlywheel.selector;\n functionSelectors[--fnsCount] = this._setMarketSupplyCaps.selector;\n functionSelectors[--fnsCount] = this._setMarketBorrowCaps.selector;\n functionSelectors[--fnsCount] = this._setBorrowCapForCollateralWhitelist.selector;\n functionSelectors[--fnsCount] = this._blacklistBorrowingAgainstCollateralWhitelist.selector;\n functionSelectors[--fnsCount] = this._supplyCapWhitelist.selector;\n functionSelectors[--fnsCount] = this._borrowCapWhitelist.selector;\n functionSelectors[--fnsCount] = this._setBorrowCapGuardian.selector;\n functionSelectors[--fnsCount] = this._setPauseGuardian.selector;\n functionSelectors[--fnsCount] = this._setMintPaused.selector;\n functionSelectors[--fnsCount] = this._setBorrowPaused.selector;\n functionSelectors[--fnsCount] = this._setTransferPaused.selector;\n functionSelectors[--fnsCount] = this._setSeizePaused.selector;\n functionSelectors[--fnsCount] = this._unsupportMarket.selector;\n functionSelectors[--fnsCount] = this.getAllMarkets.selector;\n functionSelectors[--fnsCount] = this.getAllBorrowers.selector;\n functionSelectors[--fnsCount] = this.getAllBorrowersCount.selector;\n functionSelectors[--fnsCount] = this.getPaginatedBorrowers.selector;\n functionSelectors[--fnsCount] = this.getWhitelist.selector;\n functionSelectors[--fnsCount] = this.getRewardsDistributors.selector;\n functionSelectors[--fnsCount] = this.isUserOfPool.selector;\n functionSelectors[--fnsCount] = this.getAccruingFlywheels.selector;\n functionSelectors[--fnsCount] = this._removeFlywheel.selector;\n functionSelectors[--fnsCount] = this._setBorrowCapForCollateral.selector;\n functionSelectors[--fnsCount] = this._blacklistBorrowingAgainstCollateral.selector;\n functionSelectors[--fnsCount] = this.isBorrowCapForCollateralWhitelisted.selector;\n functionSelectors[--fnsCount] = this.isBlacklistBorrowingAgainstCollateralWhitelisted.selector;\n functionSelectors[--fnsCount] = this.isSupplyCapWhitelisted.selector;\n functionSelectors[--fnsCount] = this.isBorrowCapWhitelisted.selector;\n functionSelectors[--fnsCount] = this.getWhitelistedSuppliersSupply.selector;\n functionSelectors[--fnsCount] = this.getWhitelistedBorrowersBorrows.selector;\n functionSelectors[--fnsCount] = this.getAssetAsCollateralValueCap.selector;\n functionSelectors[--fnsCount] = this.registerInSFS.selector;\n require(fnsCount == 0, \"use the correct array length\");\n return functionSelectors;\n }\n\n /**\n * @notice Returns true if the accruing flyhwheel was found and replaced\n * @dev Adds a flywheel to the non-accruing list and if already in the accruing, removes it from that list\n * @param flywheelAddress The address of the flywheel to add to the non-accruing\n */\n function addNonAccruingFlywheel(address flywheelAddress) external returns (bool) {\n require(hasAdminRights(), \"!admin\");\n require(flywheelAddress != address(0), \"!flywheel\");\n\n for (uint256 i = 0; i < nonAccruingRewardsDistributors.length; i++) {\n require(flywheelAddress != nonAccruingRewardsDistributors[i], \"!alreadyadded\");\n }\n\n // add it to the non-accruing\n nonAccruingRewardsDistributors.push(flywheelAddress);\n\n // remove it from the accruing\n for (uint256 i = 0; i < rewardsDistributors.length; i++) {\n if (flywheelAddress == rewardsDistributors[i]) {\n rewardsDistributors[i] = rewardsDistributors[rewardsDistributors.length - 1];\n rewardsDistributors.pop();\n return true;\n }\n }\n\n return false;\n }\n\n function getAssetAsCollateralValueCap(\n ICErc20 collateral,\n ICErc20 cTokenModify,\n bool redeeming,\n address account\n ) external view returns (uint256) {\n if (address(collateral) == address(cTokenModify) && !redeeming) {\n // the collateral asset counts as 0 liquidity when borrowed\n return 0;\n }\n\n uint256 assetAsCollateralValueCap = type(uint256).max;\n if (address(cTokenModify) != address(0)) {\n // if the borrowed asset is blacklisted against this collateral & account is not whitelisted\n if (\n borrowingAgainstCollateralBlacklist[address(cTokenModify)][address(collateral)] &&\n !borrowingAgainstCollateralBlacklistWhitelist[address(cTokenModify)][address(collateral)].contains(account)\n ) {\n assetAsCollateralValueCap = 0;\n } else {\n // for each user the value of this kind of collateral is capped regardless of the amount borrowed\n // denominated in the borrowed asset\n uint256 borrowCapForCollateral = borrowCapForCollateral[address(cTokenModify)][address(collateral)];\n // check if set to any value & account is not whitelisted\n if (\n borrowCapForCollateral != 0 &&\n !borrowCapForCollateralWhitelist[address(cTokenModify)][address(collateral)].contains(account)\n ) {\n uint256 borrowedAssetPrice = oracle.getUnderlyingPrice(cTokenModify);\n // this asset usage as collateral is capped at the native value of the borrow cap\n assetAsCollateralValueCap = (borrowCapForCollateral * borrowedAssetPrice) / 1e18;\n }\n }\n }\n\n uint256 supplyCap = effectiveSupplyCaps(address(collateral));\n\n // if there is any supply cap, don't allow donations to the market/plugin to go around it\n if (supplyCap > 0 && !supplyCapWhitelist[address(collateral)].contains(account)) {\n uint256 collateralAssetPrice = oracle.getUnderlyingPrice(collateral);\n uint256 supplyCapValue = (supplyCap * collateralAssetPrice) / 1e18;\n supplyCapValue = (supplyCapValue * markets[address(collateral)].collateralFactorMantissa) / 1e18;\n if (supplyCapValue < assetAsCollateralValueCap) assetAsCollateralValueCap = supplyCapValue;\n }\n\n return assetAsCollateralValueCap;\n }\n\n /**\n * @notice Set the given supply caps for the given cToken markets. Supplying that brings total underlying supply to or above supply cap will revert.\n * @dev Admin or borrowCapGuardian function to set the supply caps. A supply cap of 0 corresponds to unlimited supplying.\n * @param cTokens The addresses of the markets (tokens) to change the supply caps for\n * @param newSupplyCaps The new supply cap values in underlying to be set. A value of 0 corresponds to unlimited supplying.\n */\n function _setMarketSupplyCaps(ICErc20[] calldata cTokens, uint256[] calldata newSupplyCaps) external {\n require(msg.sender == admin || msg.sender == borrowCapGuardian, \"!admin\");\n\n uint256 numMarkets = cTokens.length;\n uint256 numSupplyCaps = newSupplyCaps.length;\n\n require(numMarkets != 0 && numMarkets == numSupplyCaps, \"!input\");\n\n for (uint256 i = 0; i < numMarkets; i++) {\n supplyCaps[address(cTokens[i])] = newSupplyCaps[i];\n emit NewSupplyCap(cTokens[i], newSupplyCaps[i]);\n }\n }\n\n /**\n * @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.\n * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.\n * @param cTokens The addresses of the markets (tokens) to change the borrow caps for\n * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.\n */\n function _setMarketBorrowCaps(ICErc20[] calldata cTokens, uint256[] calldata newBorrowCaps) external {\n require(msg.sender == admin || msg.sender == borrowCapGuardian, \"!admin\");\n\n uint256 numMarkets = cTokens.length;\n uint256 numBorrowCaps = newBorrowCaps.length;\n\n require(numMarkets != 0 && numMarkets == numBorrowCaps, \"!input\");\n\n for (uint256 i = 0; i < numMarkets; i++) {\n borrowCaps[address(cTokens[i])] = newBorrowCaps[i];\n emit NewBorrowCap(cTokens[i], newBorrowCaps[i]);\n }\n }\n\n /**\n * @notice Admin function to change the Borrow Cap Guardian\n * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian\n */\n function _setBorrowCapGuardian(address newBorrowCapGuardian) external {\n require(msg.sender == admin, \"!admin\");\n\n // Save current value for inclusion in log\n address oldBorrowCapGuardian = borrowCapGuardian;\n\n // Store borrowCapGuardian with value newBorrowCapGuardian\n borrowCapGuardian = newBorrowCapGuardian;\n\n // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)\n emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);\n }\n\n /**\n * @notice Admin function to change the Pause Guardian\n * @param newPauseGuardian The address of the new Pause Guardian\n * @return uint 0=success, otherwise a failure. (See enum Error for details)\n */\n function _setPauseGuardian(address newPauseGuardian) public returns (uint256) {\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);\n }\n\n // Save current value for inclusion in log\n address oldPauseGuardian = pauseGuardian;\n\n // Store pauseGuardian with value newPauseGuardian\n pauseGuardian = newPauseGuardian;\n\n // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)\n emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);\n\n return uint256(Error.NO_ERROR);\n }\n\n function _setMintPaused(ICErc20 cToken, bool state) public returns (bool) {\n require(markets[address(cToken)].isListed, \"!market\");\n require(msg.sender == pauseGuardian || hasAdminRights(), \"!guardian\");\n require(hasAdminRights() || state == true, \"!admin\");\n\n mintGuardianPaused[address(cToken)] = state;\n emit MarketActionPaused(cToken, \"Mint\", state);\n return state;\n }\n\n function _setBorrowPaused(ICErc20 cToken, bool state) public returns (bool) {\n require(markets[address(cToken)].isListed, \"!market\");\n require(msg.sender == pauseGuardian || hasAdminRights(), \"!guardian\");\n require(hasAdminRights() || state == true, \"!admin\");\n\n borrowGuardianPaused[address(cToken)] = state;\n emit MarketActionPaused(cToken, \"Borrow\", state);\n return state;\n }\n\n function _setTransferPaused(bool state) public returns (bool) {\n require(msg.sender == pauseGuardian || hasAdminRights(), \"!guardian\");\n require(hasAdminRights() || state == true, \"!admin\");\n\n transferGuardianPaused = state;\n emit ActionPaused(\"Transfer\", state);\n return state;\n }\n\n function _setSeizePaused(bool state) public returns (bool) {\n require(msg.sender == pauseGuardian || hasAdminRights(), \"!guardian\");\n require(hasAdminRights() || state == true, \"!admin\");\n\n seizeGuardianPaused = state;\n emit ActionPaused(\"Seize\", state);\n return state;\n }\n\n /**\n * @notice Removed a market from the markets mapping and sets it as unlisted\n * @dev Admin function unset isListed and collateralFactorMantissa and unadd support for the market\n * @param cToken The address of the market (token) to unlist\n * @return uint 0=success, otherwise a failure. (See enum Error for details)\n */\n function _unsupportMarket(ICErc20 cToken) external returns (uint256) {\n // Check admin rights\n if (!hasAdminRights()) return fail(Error.UNAUTHORIZED, FailureInfo.UNSUPPORT_MARKET_OWNER_CHECK);\n\n // Check if market is already unlisted\n if (!markets[address(cToken)].isListed)\n return fail(Error.MARKET_NOT_LISTED, FailureInfo.UNSUPPORT_MARKET_DOES_NOT_EXIST);\n\n // Check if market is in use\n if (cToken.totalSupply() > 0) return fail(Error.NONZERO_TOTAL_SUPPLY, FailureInfo.UNSUPPORT_MARKET_IN_USE);\n\n // Unlist market\n delete markets[address(cToken)];\n\n /* Delete cToken from allMarkets */\n // load into memory for faster iteration\n ICErc20[] memory _allMarkets = allMarkets;\n uint256 len = _allMarkets.length;\n uint256 assetIndex = len;\n for (uint256 i = 0; i < len; i++) {\n if (_allMarkets[i] == cToken) {\n assetIndex = i;\n break;\n }\n }\n\n // We *must* have found the asset in the list or our redundant data structure is broken\n assert(assetIndex < len);\n\n // copy last item in list to location of item to be removed, reduce length by 1\n allMarkets[assetIndex] = allMarkets[allMarkets.length - 1];\n allMarkets.pop();\n\n cTokensByUnderlying[ICErc20(address(cToken)).underlying()] = ICErc20(address(0));\n emit MarketUnlisted(cToken);\n\n return uint256(Error.NO_ERROR);\n }\n\n function _setBorrowCapForCollateral(address cTokenBorrow, address cTokenCollateral, uint256 borrowCap) public {\n require(hasAdminRights(), \"!admin\");\n borrowCapForCollateral[cTokenBorrow][cTokenCollateral] = borrowCap;\n }\n\n function _setBorrowCapForCollateralWhitelist(\n address cTokenBorrow,\n address cTokenCollateral,\n address account,\n bool whitelisted\n ) public {\n require(hasAdminRights(), \"!admin\");\n\n if (whitelisted) borrowCapForCollateralWhitelist[cTokenBorrow][cTokenCollateral].add(account);\n else borrowCapForCollateralWhitelist[cTokenBorrow][cTokenCollateral].remove(account);\n }\n\n function isBorrowCapForCollateralWhitelisted(\n address cTokenBorrow,\n address cTokenCollateral,\n address account\n ) public view returns (bool) {\n return borrowCapForCollateralWhitelist[cTokenBorrow][cTokenCollateral].contains(account);\n }\n\n function _blacklistBorrowingAgainstCollateral(\n address cTokenBorrow,\n address cTokenCollateral,\n bool blacklisted\n ) public {\n require(hasAdminRights(), \"!admin\");\n borrowingAgainstCollateralBlacklist[cTokenBorrow][cTokenCollateral] = blacklisted;\n }\n\n function _blacklistBorrowingAgainstCollateralWhitelist(\n address cTokenBorrow,\n address cTokenCollateral,\n address account,\n bool whitelisted\n ) public {\n require(hasAdminRights(), \"!admin\");\n\n if (whitelisted) borrowingAgainstCollateralBlacklistWhitelist[cTokenBorrow][cTokenCollateral].add(account);\n else borrowingAgainstCollateralBlacklistWhitelist[cTokenBorrow][cTokenCollateral].remove(account);\n }\n\n function isBlacklistBorrowingAgainstCollateralWhitelisted(\n address cTokenBorrow,\n address cTokenCollateral,\n address account\n ) public view returns (bool) {\n return borrowingAgainstCollateralBlacklistWhitelist[cTokenBorrow][cTokenCollateral].contains(account);\n }\n\n function _supplyCapWhitelist(address cToken, address account, bool whitelisted) public {\n require(hasAdminRights(), \"!admin\");\n\n if (whitelisted) supplyCapWhitelist[cToken].add(account);\n else supplyCapWhitelist[cToken].remove(account);\n }\n\n function isSupplyCapWhitelisted(address cToken, address account) public view returns (bool) {\n return supplyCapWhitelist[cToken].contains(account);\n }\n\n function getWhitelistedSuppliersSupply(address cToken) public view returns (uint256 supplied) {\n address[] memory whitelistedSuppliers = supplyCapWhitelist[cToken].values();\n for (uint256 i = 0; i < whitelistedSuppliers.length; i++) {\n supplied += ICErc20(cToken).balanceOfUnderlying(whitelistedSuppliers[i]);\n }\n }\n\n function _borrowCapWhitelist(address cToken, address account, bool whitelisted) public {\n require(hasAdminRights(), \"!admin\");\n\n if (whitelisted) borrowCapWhitelist[cToken].add(account);\n else borrowCapWhitelist[cToken].remove(account);\n }\n\n function isBorrowCapWhitelisted(address cToken, address account) public view returns (bool) {\n return borrowCapWhitelist[cToken].contains(account);\n }\n\n function getWhitelistedBorrowersBorrows(address cToken) public view returns (uint256 borrowed) {\n address[] memory whitelistedBorrowers = borrowCapWhitelist[cToken].values();\n for (uint256 i = 0; i < whitelistedBorrowers.length; i++) {\n borrowed += ICErc20(cToken).borrowBalanceCurrent(whitelistedBorrowers[i]);\n }\n }\n\n /**\n * @notice Return all of the markets\n * @dev The automatic getter may be used to access an individual market.\n * @return The list of market addresses\n */\n function getAllMarkets() public view returns (ICErc20[] memory) {\n return allMarkets;\n }\n\n /**\n * @notice Return all of the borrowers\n * @dev The automatic getter may be used to access an individual borrower.\n * @return The list of borrower account addresses\n */\n function getAllBorrowers() public view returns (address[] memory) {\n return allBorrowers;\n }\n\n function getAllBorrowersCount() public view returns (uint256) {\n return allBorrowers.length;\n }\n\n function getPaginatedBorrowers(\n uint256 page,\n uint256 pageSize\n ) public view returns (uint256 _totalPages, address[] memory _pageOfBorrowers) {\n uint256 allBorrowersCount = allBorrowers.length;\n if (allBorrowersCount == 0) {\n return (0, new address[](0));\n }\n\n if (pageSize == 0) pageSize = 300;\n uint256 currentPageSize = pageSize;\n uint256 sizeOfPageFromRemainder = allBorrowersCount % pageSize;\n\n _totalPages = allBorrowersCount / pageSize;\n if (sizeOfPageFromRemainder > 0) {\n _totalPages++;\n if (page + 1 == _totalPages) {\n currentPageSize = sizeOfPageFromRemainder;\n }\n }\n\n if (page + 1 > _totalPages) {\n return (_totalPages, new address[](0));\n }\n\n uint256 offset = page * pageSize;\n _pageOfBorrowers = new address[](currentPageSize);\n for (uint256 i = 0; i < currentPageSize; i++) {\n _pageOfBorrowers[i] = allBorrowers[i + offset];\n }\n }\n\n /**\n * @notice Return all of the whitelist\n * @dev The automatic getter may be used to access an individual whitelist status.\n * @return The list of borrower account addresses\n */\n function getWhitelist() external view returns (address[] memory) {\n return whitelistArray;\n }\n\n /**\n * @notice Returns an array of all accruing and non-accruing flywheels\n */\n function getRewardsDistributors() external view returns (address[] memory) {\n address[] memory allFlywheels = new address[](rewardsDistributors.length + nonAccruingRewardsDistributors.length);\n\n uint8 i = 0;\n while (i < rewardsDistributors.length) {\n allFlywheels[i] = rewardsDistributors[i];\n i++;\n }\n uint8 j = 0;\n while (j < nonAccruingRewardsDistributors.length) {\n allFlywheels[i + j] = nonAccruingRewardsDistributors[j];\n j++;\n }\n\n return allFlywheels;\n }\n\n function getAccruingFlywheels() external view returns (address[] memory) {\n return rewardsDistributors;\n }\n\n /**\n * @dev Removes a flywheel from the accruing or non-accruing array\n * @param flywheelAddress The address of the flywheel to remove from the accruing or non-accruing array\n * @return true if the flywheel was found and removed\n */\n function _removeFlywheel(address flywheelAddress) external returns (bool) {\n require(hasAdminRights(), \"!admin\");\n require(flywheelAddress != address(0), \"!flywheel\");\n\n // remove it from the accruing\n for (uint256 i = 0; i < rewardsDistributors.length; i++) {\n if (flywheelAddress == rewardsDistributors[i]) {\n rewardsDistributors[i] = rewardsDistributors[rewardsDistributors.length - 1];\n rewardsDistributors.pop();\n return true;\n }\n }\n\n // or remove it from the non-accruing\n for (uint256 i = 0; i < nonAccruingRewardsDistributors.length; i++) {\n if (flywheelAddress == nonAccruingRewardsDistributors[i]) {\n nonAccruingRewardsDistributors[i] = nonAccruingRewardsDistributors[nonAccruingRewardsDistributors.length - 1];\n nonAccruingRewardsDistributors.pop();\n return true;\n }\n }\n\n return false;\n }\n\n function isUserOfPool(address user) external view returns (bool) {\n for (uint256 i = 0; i < allMarkets.length; i++) {\n address marketAddress = address(allMarkets[i]);\n if (markets[marketAddress].accountMembership[user]) {\n return true;\n }\n }\n\n return false;\n }\n\n function registerInSFS() external returns (uint256) {\n require(hasAdminRights(), \"!admin\");\n SFSRegister sfsContract = SFSRegister(0x8680CEaBcb9b56913c519c069Add6Bc3494B7020);\n\n for (uint256 i = 0; i < allMarkets.length; i++) {\n allMarkets[i].registerInSFS();\n }\n\n return sfsContract.register(0x8Fba84867Ba458E7c6E2c024D2DE3d0b5C3ea1C2);\n }\n}\n" + }, + "contracts/src/compound/ComptrollerInterface.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { BasePriceOracle } from \"../oracles/BasePriceOracle.sol\";\nimport { ICErc20 } from \"./CTokenInterfaces.sol\";\nimport { DiamondExtension } from \"../ionic/DiamondExtension.sol\";\nimport { ComptrollerV4Storage } from \"../compound/ComptrollerStorage.sol\";\nimport { PrudentiaLib } from \"../adrastia/PrudentiaLib.sol\";\nimport { IHistoricalRates } from \"adrastia-periphery/rates/IHistoricalRates.sol\";\n\ninterface ComptrollerInterface {\n function isDeprecated(ICErc20 cToken) external view returns (bool);\n\n function _becomeImplementation() external;\n\n function _deployMarket(\n uint8 delegateType,\n bytes memory constructorData,\n bytes calldata becomeImplData,\n uint256 collateralFactorMantissa\n ) external returns (uint256);\n\n function getAssetsIn(address account) external view returns (ICErc20[] memory);\n\n function checkMembership(address account, ICErc20 cToken) external view returns (bool);\n\n function _setPriceOracle(BasePriceOracle newOracle) external returns (uint256);\n\n function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256);\n\n function _setCollateralFactor(ICErc20 market, uint256 newCollateralFactorMantissa) external returns (uint256);\n\n function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256);\n\n function _setWhitelistEnforcement(bool enforce) external returns (uint256);\n\n function _setWhitelistStatuses(address[] calldata _suppliers, bool[] calldata statuses) external returns (uint256);\n\n function _addRewardsDistributor(address distributor) external returns (uint256);\n\n function getHypotheticalAccountLiquidity(\n address account,\n address cTokenModify,\n uint256 redeemTokens,\n uint256 borrowAmount,\n uint256 repayAmount\n ) external view returns (uint256, uint256, uint256, uint256);\n\n function getMaxRedeemOrBorrow(address account, ICErc20 cToken, bool isBorrow) external view returns (uint256);\n\n /*** Assets You Are In ***/\n\n function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);\n\n function exitMarket(address cToken) external returns (uint256);\n\n /*** Policy Hooks ***/\n\n function mintAllowed(address cToken, address minter, uint256 mintAmount) external returns (uint256);\n\n function redeemAllowed(address cToken, address redeemer, uint256 redeemTokens) external returns (uint256);\n\n function redeemVerify(address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens) external;\n\n function borrowAllowed(address cToken, address borrower, uint256 borrowAmount) external returns (uint256);\n\n function borrowVerify(address cToken, address borrower) external;\n\n function borrowWithinLimits(address cToken, uint256 accountBorrowsNew) external view returns (uint256);\n\n function repayBorrowAllowed(\n address cToken,\n address payer,\n address borrower,\n uint256 repayAmount\n ) external returns (uint256);\n\n function repayBorrowVerify(\n address cToken,\n address payer,\n address borrower,\n uint256 repayAmount\n ) external;\n\n function liquidateBorrowAllowed(\n address cTokenBorrowed,\n address cTokenCollateral,\n address liquidator,\n address borrower,\n uint256 repayAmount\n ) external returns (uint256);\n\n function seizeAllowed(\n address cTokenCollateral,\n address cTokenBorrowed,\n address liquidator,\n address borrower,\n uint256 seizeTokens\n ) external returns (uint256);\n \n function seizeVerify(\n address cTokenCollateral,\n address cTokenBorrowed,\n address liquidator,\n address borrower,\n uint256 seizeTokens\n ) external;\n\n function transferAllowed(address cToken, address src, address dst, uint256 transferTokens) external returns (uint256);\n \n function transferVerify(address cToken, address src, address dst, uint256 transferTokens) external;\n\n function mintVerify(address cToken, address minter, uint256 actualMintAmount, uint256 mintTokens) external;\n\n /*** Liquidity/Liquidation Calculations ***/\n\n function getAccountLiquidity(\n address account\n ) external view returns (uint256 error, uint256 collateralValue, uint256 liquidity, uint256 shortfall);\n\n function liquidateCalculateSeizeTokens(\n address cTokenBorrowed,\n address cTokenCollateral,\n uint256 repayAmount\n ) external view returns (uint256, uint256);\n\n /*** Pool-Wide/Cross-Asset Reentrancy Prevention ***/\n\n function _beforeNonReentrant() external;\n\n function _afterNonReentrant() external;\n\n /*** New supply and borrow cap view functions ***/\n\n /**\n * @notice Gets the supply cap of a cToken in the units of the underlying asset.\n * @param cToken The address of the cToken.\n */\n function effectiveSupplyCaps(address cToken) external view returns (uint256 supplyCap);\n\n /**\n * @notice Gets the borrow cap of a cToken in the units of the underlying asset.\n * @param cToken The address of the cToken.\n */\n function effectiveBorrowCaps(address cToken) external view returns (uint256 borrowCap);\n}\n\ninterface ComptrollerStorageInterface {\n function admin() external view returns (address);\n\n function adminHasRights() external view returns (bool);\n\n function ionicAdmin() external view returns (address);\n\n function ionicAdminHasRights() external view returns (bool);\n\n function pendingAdmin() external view returns (address);\n\n function oracle() external view returns (BasePriceOracle);\n\n function pauseGuardian() external view returns (address);\n\n function closeFactorMantissa() external view returns (uint256);\n\n function liquidationIncentiveMantissa() external view returns (uint256);\n\n function isUserOfPool(address user) external view returns (bool);\n\n function whitelist(address account) external view returns (bool);\n\n function enforceWhitelist() external view returns (bool);\n\n function borrowCapForCollateral(address borrowed, address collateral) external view returns (uint256);\n\n function borrowingAgainstCollateralBlacklist(address borrowed, address collateral) external view returns (bool);\n\n function suppliers(address account) external view returns (bool);\n\n function cTokensByUnderlying(address) external view returns (address);\n\n /**\n * Gets the supply cap of a cToken in the units of the underlying asset.\n * @dev WARNING: This function is misleading if Adrastia Prudentia is being used for the supply cap. Instead, use\n * `effectiveSupplyCaps` to get the correct supply cap.\n * @param cToken The address of the cToken.\n * @return The supply cap in the units of the underlying asset.\n */\n function supplyCaps(address cToken) external view returns (uint256);\n\n /**\n * Gets the borrow cap of a cToken in the units of the underlying asset.\n * @dev WARNING: This function is misleading if Adrastia Prudentia is being used for the borrow cap. Instead, use\n * `effectiveBorrowCaps` to get the correct borrow cap.\n * @param cToken The address of the cToken.\n * @return The borrow cap in the units of the underlying asset.\n */\n function borrowCaps(address cToken) external view returns (uint256);\n\n function markets(address cToken) external view returns (bool, uint256);\n\n function accountAssets(address, uint256) external view returns (address);\n\n function borrowGuardianPaused(address cToken) external view returns (bool);\n\n function mintGuardianPaused(address cToken) external view returns (bool);\n\n function rewardsDistributors(uint256) external view returns (address);\n}\n\ninterface SFSRegister {\n function register(address _recipient) external returns (uint256 tokenId);\n}\n\ninterface ComptrollerExtensionInterface {\n function getWhitelistedSuppliersSupply(address cToken) external view returns (uint256 supplied);\n\n function getWhitelistedBorrowersBorrows(address cToken) external view returns (uint256 borrowed);\n\n function getAllMarkets() external view returns (ICErc20[] memory);\n\n function getAllBorrowers() external view returns (address[] memory);\n\n function getAllBorrowersCount() external view returns (uint256);\n\n function getPaginatedBorrowers(\n uint256 page,\n uint256 pageSize\n ) external view returns (uint256 _totalPages, address[] memory _pageOfBorrowers);\n\n function getRewardsDistributors() external view returns (address[] memory);\n\n function getAccruingFlywheels() external view returns (address[] memory);\n\n function _supplyCapWhitelist(address cToken, address account, bool whitelisted) external;\n\n function _setBorrowCapForCollateral(address cTokenBorrow, address cTokenCollateral, uint256 borrowCap) external;\n\n function _setBorrowCapForCollateralWhitelist(\n address cTokenBorrow,\n address cTokenCollateral,\n address account,\n bool whitelisted\n ) external;\n\n function isBorrowCapForCollateralWhitelisted(\n address cTokenBorrow,\n address cTokenCollateral,\n address account\n ) external view returns (bool);\n\n function _blacklistBorrowingAgainstCollateral(\n address cTokenBorrow,\n address cTokenCollateral,\n bool blacklisted\n ) external;\n\n function _blacklistBorrowingAgainstCollateralWhitelist(\n address cTokenBorrow,\n address cTokenCollateral,\n address account,\n bool whitelisted\n ) external;\n\n function isBlacklistBorrowingAgainstCollateralWhitelisted(\n address cTokenBorrow,\n address cTokenCollateral,\n address account\n ) external view returns (bool);\n\n function isSupplyCapWhitelisted(address cToken, address account) external view returns (bool);\n\n function _borrowCapWhitelist(address cToken, address account, bool whitelisted) external;\n\n function isBorrowCapWhitelisted(address cToken, address account) external view returns (bool);\n\n function _removeFlywheel(address flywheelAddress) external returns (bool);\n\n function getWhitelist() external view returns (address[] memory);\n\n function addNonAccruingFlywheel(address flywheelAddress) external returns (bool);\n\n function _setMarketSupplyCaps(ICErc20[] calldata cTokens, uint256[] calldata newSupplyCaps) external;\n\n function _setMarketBorrowCaps(ICErc20[] calldata cTokens, uint256[] calldata newBorrowCaps) external;\n\n function _setBorrowCapGuardian(address newBorrowCapGuardian) external;\n\n function _setPauseGuardian(address newPauseGuardian) external returns (uint256);\n\n function _setMintPaused(ICErc20 cToken, bool state) external returns (bool);\n\n function _setBorrowPaused(ICErc20 cToken, bool state) external returns (bool);\n\n function _setTransferPaused(bool state) external returns (bool);\n\n function _setSeizePaused(bool state) external returns (bool);\n\n function _unsupportMarket(ICErc20 cToken) external returns (uint256);\n\n function getAssetAsCollateralValueCap(\n ICErc20 collateral,\n ICErc20 cTokenModify,\n bool redeeming,\n address account\n ) external view returns (uint256);\n\n function registerInSFS() external returns (uint256);\n}\n\ninterface ComptrollerPrudentiaCapsExtInterface {\n /**\n * @notice Retrieves Adrastia Prudentia borrow cap config from storage.\n * @return The config.\n */\n function getBorrowCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory);\n\n /**\n * @notice Retrieves Adrastia Prudentia supply cap config from storage.\n * @return The config.\n */\n function getSupplyCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory);\n\n /**\n * @notice Sets the Adrastia Prudentia supply cap config.\n * @dev Specifying a zero address for the `controller` parameter will make the Comptroller use the native supply caps.\n * @param newConfig The new config.\n */\n function _setSupplyCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external;\n\n /**\n * @notice Sets the Adrastia Prudentia supply cap config.\n * @dev Specifying a zero address for the `controller` parameter will make the Comptroller use the native borrow caps.\n * @param newConfig The new config.\n */\n function _setBorrowCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external;\n}\n\ninterface UnitrollerInterface {\n function comptrollerImplementation() external view returns (address);\n\n function _upgrade() external;\n\n function _acceptAdmin() external returns (uint256);\n\n function _setPendingAdmin(address newPendingAdmin) external returns (uint256);\n\n function _toggleAdminRights(bool hasRights) external returns (uint256);\n}\n\ninterface IComptrollerExtension is ComptrollerExtensionInterface, ComptrollerStorageInterface {}\n\n//interface IComptrollerBase is ComptrollerInterface, ComptrollerStorageInterface {}\n\ninterface IonicComptroller is\n ComptrollerInterface,\n ComptrollerExtensionInterface,\n UnitrollerInterface,\n ComptrollerStorageInterface\n{\n\n}\n\nabstract contract ComptrollerBase is ComptrollerV4Storage {\n /// @notice Indicator that this is a Comptroller contract (for inspection)\n bool public constant isComptroller = true;\n\n /**\n * @notice Gets the supply cap of a cToken in the units of the underlying asset.\n * @param cToken The address of the cToken.\n */\n function effectiveSupplyCaps(address cToken) public view virtual returns (uint256 supplyCap) {\n PrudentiaLib.PrudentiaConfig memory capConfig = supplyCapConfig;\n\n // Check if we're using Adrastia Prudentia for the supply cap\n if (capConfig.controller != address(0)) {\n // We have a controller, so we're using Adrastia Prudentia\n\n address underlyingToken = ICErc20(cToken).underlying();\n\n // Get the supply cap from Adrastia Prudentia\n supplyCap = IHistoricalRates(capConfig.controller).getRateAt(underlyingToken, capConfig.offset).current;\n\n // Prudentia trims decimal points from amounts while our code requires the mantissa amount, so we\n // must scale the supply cap to get the correct amount\n\n int256 scaleByDecimals = 18;\n // Not all ERC20s implement decimals(), so we use a staticcall and check the return data\n (bool success, bytes memory data) = underlyingToken.staticcall(abi.encodeWithSignature(\"decimals()\"));\n if (success && data.length == 32) {\n scaleByDecimals = int256(uint256(abi.decode(data, (uint8))));\n }\n\n scaleByDecimals += capConfig.decimalShift;\n\n if (scaleByDecimals >= 0) {\n // We're scaling up, so we need to multiply\n supplyCap *= 10 ** uint256(scaleByDecimals);\n } else {\n // We're scaling down, so we need to divide\n supplyCap /= 10 ** uint256(-scaleByDecimals);\n }\n } else {\n // We don't have a controller, so we're using the local supply cap\n\n // Get the supply cap from the local supply cap\n supplyCap = supplyCaps[cToken];\n }\n }\n\n /**\n * @notice Gets the borrow cap of a cToken in the units of the underlying asset.\n * @param cToken The address of the cToken.\n */\n function effectiveBorrowCaps(address cToken) public view virtual returns (uint256 borrowCap) {\n PrudentiaLib.PrudentiaConfig memory capConfig = borrowCapConfig;\n\n // Check if we're using Adrastia Prudentia for the borrow cap\n if (capConfig.controller != address(0)) {\n // We have a controller, so we're using Adrastia Prudentia\n\n address underlyingToken = ICErc20(cToken).underlying();\n\n // Get the borrow cap from Adrastia Prudentia\n borrowCap = IHistoricalRates(capConfig.controller).getRateAt(underlyingToken, capConfig.offset).current;\n\n // Prudentia trims decimal points from amounts while our code requires the mantissa amount, so we\n // must scale the supply cap to get the correct amount\n\n int256 scaleByDecimals = 18;\n // Not all ERC20s implement decimals(), so we use a staticcall and check the return data\n (bool success, bytes memory data) = underlyingToken.staticcall(abi.encodeWithSignature(\"decimals()\"));\n if (success && data.length == 32) {\n scaleByDecimals = int256(uint256(abi.decode(data, (uint8))));\n }\n\n scaleByDecimals += capConfig.decimalShift;\n\n if (scaleByDecimals >= 0) {\n // We're scaling up, so we need to multiply\n borrowCap *= 10 ** uint256(scaleByDecimals);\n } else {\n // We're scaling down, so we need to divide\n borrowCap /= 10 ** uint256(-scaleByDecimals);\n }\n } else {\n // We don't have a controller, so we're using the local borrow cap\n borrowCap = borrowCaps[cToken];\n }\n }\n}\n" + }, + "contracts/src/compound/ComptrollerPrudentiaCapsExt.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { DiamondExtension } from \"../ionic/DiamondExtension.sol\";\nimport { ICErc20 } from \"./CTokenInterfaces.sol\";\nimport { ComptrollerPrudentiaCapsExtInterface, ComptrollerBase } from \"./ComptrollerInterface.sol\";\nimport { PrudentiaLib } from \"../adrastia/PrudentiaLib.sol\";\n\n/**\n * @title ComptrollerPrudentiaCapsExt\n * @author Tyler Loewen (TRILEZ SOFTWARE INC. dba. Adrastia)\n * @notice A diamond extension that allows the Comptroller to use Adrastia Prudentia to control supply and borrow caps.\n */\ncontract ComptrollerPrudentiaCapsExt is DiamondExtension, ComptrollerBase, ComptrollerPrudentiaCapsExtInterface {\n /**\n * @notice Emitted when the Adrastia Prudentia supply cap config is changed.\n * @param oldConfig The old config.\n * @param newConfig The new config.\n */\n event NewSupplyCapConfig(PrudentiaLib.PrudentiaConfig oldConfig, PrudentiaLib.PrudentiaConfig newConfig);\n\n /**\n * @notice Emitted when the Adrastia Prudentia borrow cap config is changed.\n * @param oldConfig The old config.\n * @param newConfig The new config.\n */\n event NewBorrowCapConfig(PrudentiaLib.PrudentiaConfig oldConfig, PrudentiaLib.PrudentiaConfig newConfig);\n\n /// @inheritdoc ComptrollerPrudentiaCapsExtInterface\n function _setSupplyCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external {\n require(msg.sender == admin || msg.sender == borrowCapGuardian, \"!admin\");\n\n PrudentiaLib.PrudentiaConfig memory oldConfig = supplyCapConfig;\n supplyCapConfig = newConfig;\n\n emit NewSupplyCapConfig(oldConfig, newConfig);\n }\n\n /// @inheritdoc ComptrollerPrudentiaCapsExtInterface\n function _setBorrowCapConfig(PrudentiaLib.PrudentiaConfig calldata newConfig) external {\n require(msg.sender == admin || msg.sender == borrowCapGuardian, \"!admin\");\n\n PrudentiaLib.PrudentiaConfig memory oldConfig = borrowCapConfig;\n borrowCapConfig = newConfig;\n\n emit NewBorrowCapConfig(oldConfig, newConfig);\n }\n\n /// @inheritdoc ComptrollerPrudentiaCapsExtInterface\n function getBorrowCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory) {\n return borrowCapConfig;\n }\n\n /// @inheritdoc ComptrollerPrudentiaCapsExtInterface\n function getSupplyCapConfig() external view returns (PrudentiaLib.PrudentiaConfig memory) {\n return supplyCapConfig;\n }\n\n function _getExtensionFunctions() external pure virtual override returns (bytes4[] memory) {\n uint8 fnsCount = 4;\n bytes4[] memory functionSelectors = new bytes4[](fnsCount);\n functionSelectors[--fnsCount] = this._setSupplyCapConfig.selector;\n functionSelectors[--fnsCount] = this._setBorrowCapConfig.selector;\n functionSelectors[--fnsCount] = this.getBorrowCapConfig.selector;\n functionSelectors[--fnsCount] = this.getSupplyCapConfig.selector;\n require(fnsCount == 0, \"use the correct array length\");\n return functionSelectors;\n }\n}\n" + }, + "contracts/src/compound/ComptrollerStorage.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./IFeeDistributor.sol\";\nimport \"../oracles/BasePriceOracle.sol\";\nimport { ICErc20 } from \"./CTokenInterfaces.sol\";\nimport { PrudentiaLib } from \"../adrastia/PrudentiaLib.sol\";\n\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract UnitrollerAdminStorage {\n /*\n * Administrator for Ionic\n */\n address payable public ionicAdmin;\n\n /**\n * @notice Administrator for this contract\n */\n address public admin;\n\n /**\n * @notice Pending administrator for this contract\n */\n address public pendingAdmin;\n\n /**\n * @notice Whether or not the Ionic admin has admin rights\n */\n bool public ionicAdminHasRights = true;\n\n /**\n * @notice Whether or not the admin has admin rights\n */\n bool public adminHasRights = true;\n\n /**\n * @notice Returns a boolean indicating if the sender has admin rights\n */\n function hasAdminRights() internal view returns (bool) {\n return (msg.sender == admin && adminHasRights) || (msg.sender == address(ionicAdmin) && ionicAdminHasRights);\n }\n}\n\ncontract ComptrollerV1Storage is UnitrollerAdminStorage {\n /**\n * @notice Oracle which gives the price of any given asset\n */\n BasePriceOracle public oracle;\n\n /**\n * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow\n */\n uint256 public closeFactorMantissa;\n\n /**\n * @notice Multiplier representing the discount on collateral that a liquidator receives\n */\n uint256 public liquidationIncentiveMantissa;\n\n /*\n * UNUSED AFTER UPGRADE: Max number of assets a single account can participate in (borrow or use as collateral)\n */\n uint256 internal maxAssets;\n\n /**\n * @notice Per-account mapping of \"assets you are in\", capped by maxAssets\n */\n mapping(address => ICErc20[]) public accountAssets;\n}\n\ncontract ComptrollerV2Storage is ComptrollerV1Storage {\n struct Market {\n // Whether or not this market is listed\n bool isListed;\n // Multiplier representing the most one can borrow against their collateral in this market.\n // For instance, 0.9 to allow borrowing 90% of collateral value.\n // Must be between 0 and 1, and stored as a mantissa.\n uint256 collateralFactorMantissa;\n // Per-market mapping of \"accounts in this asset\"\n mapping(address => bool) accountMembership;\n }\n\n /**\n * @notice Official mapping of cTokens -> Market metadata\n * @dev Used e.g. to determine if a market is supported\n */\n mapping(address => Market) public markets;\n\n /// @notice A list of all markets\n ICErc20[] public allMarkets;\n\n /**\n * @dev Maps borrowers to booleans indicating if they have entered any markets\n */\n mapping(address => bool) internal borrowers;\n\n /// @notice A list of all borrowers who have entered markets\n address[] public allBorrowers;\n\n // Indexes of borrower account addresses in the `allBorrowers` array\n mapping(address => uint256) internal borrowerIndexes;\n\n /**\n * @dev Maps suppliers to booleans indicating if they have ever supplied to any markets\n */\n mapping(address => bool) public suppliers;\n\n /// @notice All cTokens addresses mapped by their underlying token addresses\n mapping(address => ICErc20) public cTokensByUnderlying;\n\n /// @notice Whether or not the supplier whitelist is enforced\n bool public enforceWhitelist;\n\n /// @notice Maps addresses to booleans indicating if they are allowed to supply assets (i.e., mint cTokens)\n mapping(address => bool) public whitelist;\n\n /// @notice An array of all whitelisted accounts\n address[] public whitelistArray;\n\n // Indexes of account addresses in the `whitelistArray` array\n mapping(address => uint256) internal whitelistIndexes;\n\n /**\n * @notice The Pause Guardian can pause certain actions as a safety mechanism.\n * Actions which allow users to remove their own assets cannot be paused.\n * Liquidation / seizing / transfer can only be paused globally, not by market.\n */\n address public pauseGuardian;\n bool public _mintGuardianPaused;\n bool public _borrowGuardianPaused;\n bool public transferGuardianPaused;\n bool public seizeGuardianPaused;\n mapping(address => bool) public mintGuardianPaused;\n mapping(address => bool) public borrowGuardianPaused;\n}\n\ncontract ComptrollerV3Storage is ComptrollerV2Storage {\n /// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.\n /// @dev If Adrastia Prudentia is enabled, the values the borrow cap guardian sets are ignored.\n address public borrowCapGuardian;\n\n /// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing.\n /// @dev If Adrastia Prudentia is enabled, this value is ignored. Use `effectiveBorrowCaps` instead.\n mapping(address => uint256) public borrowCaps;\n\n /// @notice Supply caps enforced by mintAllowed for each cToken address. Defaults to zero which corresponds to unlimited supplying.\n /// @dev If Adrastia Prudentia is enabled, this value is ignored. Use `effectiveSupplyCaps` instead.\n mapping(address => uint256) public supplyCaps;\n\n /// @notice RewardsDistributor contracts to notify of flywheel changes.\n address[] public rewardsDistributors;\n\n /// @dev Guard variable for pool-wide/cross-asset re-entrancy checks\n bool internal _notEntered;\n\n /// @dev Whether or not _notEntered has been initialized\n bool internal _notEnteredInitialized;\n\n /// @notice RewardsDistributor to list for claiming, but not to notify of flywheel changes.\n address[] public nonAccruingRewardsDistributors;\n\n /// @dev cap for each user's borrows against specific assets - denominated in the borrowed asset\n mapping(address => mapping(address => uint256)) public borrowCapForCollateral;\n\n /// @dev blacklist to disallow the borrowing of an asset against specific collateral\n mapping(address => mapping(address => bool)) public borrowingAgainstCollateralBlacklist;\n\n /// @dev set of whitelisted accounts that are allowed to bypass the borrowing against specific collateral cap\n mapping(address => mapping(address => EnumerableSet.AddressSet)) internal borrowCapForCollateralWhitelist;\n\n /// @dev set of whitelisted accounts that are allowed to bypass the borrow cap\n mapping(address => mapping(address => EnumerableSet.AddressSet))\n internal borrowingAgainstCollateralBlacklistWhitelist;\n\n /// @dev set of whitelisted accounts that are allowed to bypass the supply cap\n mapping(address => EnumerableSet.AddressSet) internal supplyCapWhitelist;\n\n /// @dev set of whitelisted accounts that are allowed to bypass the borrow cap\n mapping(address => EnumerableSet.AddressSet) internal borrowCapWhitelist;\n}\n\ncontract ComptrollerV4Storage is ComptrollerV3Storage {\n /// @dev Adrastia Prudentia config for controlling borrow caps.\n PrudentiaLib.PrudentiaConfig internal borrowCapConfig;\n\n /// @dev Adrastia Prudentia config for controlling supply caps.\n PrudentiaLib.PrudentiaConfig internal supplyCapConfig;\n}\n" + }, + "contracts/src/compound/CToken.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IonicComptroller } from \"./ComptrollerInterface.sol\";\nimport { CTokenSecondExtensionBase, ICErc20 } from \"./CTokenInterfaces.sol\";\nimport { TokenErrorReporter } from \"./ErrorReporter.sol\";\nimport { Exponential } from \"./Exponential.sol\";\nimport { EIP20Interface } from \"./EIP20Interface.sol\";\nimport { InterestRateModel } from \"./InterestRateModel.sol\";\nimport { ComptrollerV3Storage } from \"./ComptrollerStorage.sol\";\nimport { IFeeDistributor } from \"./IFeeDistributor.sol\";\nimport { CTokenOracleProtected } from \"./CTokenOracleProtected.sol\";\n\nimport { DiamondExtension, LibDiamond } from \"../ionic/DiamondExtension.sol\";\nimport { PoolLens } from \"../PoolLens.sol\";\nimport { IonicUniV3Liquidator } from \"../IonicUniV3Liquidator.sol\";\nimport { IHypernativeOracle } from \"../external/hypernative/interfaces/IHypernativeOracle.sol\";\n\n/**\n * @title Compound's CErc20 Contract\n * @notice CTokens which wrap an EIP-20 underlying\n * @dev This contract should not to be deployed on its own; instead, deploy `CErc20Delegator` (proxy contract) and `CErc20Delegate` (logic/implementation contract).\n * @author Compound\n */\nabstract contract CErc20 is CTokenOracleProtected, CTokenSecondExtensionBase, TokenErrorReporter, Exponential, DiamondExtension {\n modifier isAuthorized() {\n require(\n IFeeDistributor(ionicAdmin).canCall(address(comptroller), msg.sender, address(this), msg.sig),\n \"not authorized\"\n );\n _;\n }\n\n modifier isMinHFThresholdExceeded(address borrower) {\n PoolLens lens = PoolLens(ap.getAddress(\"PoolLens\"));\n IonicUniV3Liquidator liquidator = IonicUniV3Liquidator(payable(ap.getAddress(\"IonicUniV3Liquidator\")));\n\n if (lens.getHealthFactor(borrower, comptroller) > liquidator.healthFactorThreshold()) {\n require(msg.sender == address(liquidator), \"Health factor not low enough for non-permissioned liquidations\");\n _;\n } else {\n _;\n }\n }\n\n function _getExtensionFunctions() public pure virtual override returns (bytes4[] memory) {\n uint8 fnsCount = 13;\n bytes4[] memory functionSelectors = new bytes4[](fnsCount);\n functionSelectors[--fnsCount] = this.mint.selector;\n functionSelectors[--fnsCount] = this.redeem.selector;\n functionSelectors[--fnsCount] = this.redeemUnderlying.selector;\n functionSelectors[--fnsCount] = this.borrow.selector;\n functionSelectors[--fnsCount] = this.repayBorrow.selector;\n functionSelectors[--fnsCount] = this.repayBorrowBehalf.selector;\n functionSelectors[--fnsCount] = this.liquidateBorrow.selector;\n functionSelectors[--fnsCount] = this.getCash.selector;\n functionSelectors[--fnsCount] = this.seize.selector;\n functionSelectors[--fnsCount] = this.selfTransferOut.selector;\n functionSelectors[--fnsCount] = this.selfTransferIn.selector;\n functionSelectors[--fnsCount] = this._withdrawIonicFees.selector;\n functionSelectors[--fnsCount] = this._withdrawAdminFees.selector;\n\n require(fnsCount == 0, \"use the correct array length\");\n return functionSelectors;\n }\n\n /*** User Interface ***/\n\n /**\n * @notice Sender supplies assets into the market and receives cTokens in exchange\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param mintAmount The amount of the underlying asset to supply\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function mint(uint256 mintAmount) external override isAuthorized onlyOracleApprovedAllowEOA returns (uint256) {\n (uint256 err, ) = mintInternal(mintAmount);\n return err;\n }\n\n /**\n * @notice Sender redeems cTokens in exchange for the underlying asset\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param redeemTokens The number of cTokens to redeem into underlying\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function redeem(uint256 redeemTokens) external override isAuthorized onlyOracleApprovedAllowEOA returns (uint256) {\n return redeemInternal(redeemTokens);\n }\n\n /**\n * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param redeemAmount The amount of underlying to redeem\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function redeemUnderlying(uint256 redeemAmount) external override isAuthorized onlyOracleApprovedAllowEOA returns (uint256) {\n return redeemUnderlyingInternal(redeemAmount);\n }\n\n /**\n * @notice Sender borrows assets from the protocol to their own address\n * @param borrowAmount The amount of the underlying asset to borrow\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function borrow(uint256 borrowAmount) external override isAuthorized onlyOracleApprovedAllowEOA returns (uint256) {\n return borrowInternal(borrowAmount);\n }\n\n /**\n * @notice Sender repays their own borrow\n * @param repayAmount The amount to repay\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function repayBorrow(uint256 repayAmount) external override isAuthorized onlyOracleApprovedAllowEOA returns (uint256) {\n (uint256 err, ) = repayBorrowInternal(repayAmount);\n return err;\n }\n\n /**\n * @notice Sender repays a borrow belonging to borrower\n * @param borrower the account with the debt being payed off\n * @param repayAmount The amount to repay\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function repayBorrowBehalf(address borrower, uint256 repayAmount) external override isAuthorized onlyOracleApprovedAllowEOA returns (uint256) {\n (uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount);\n return err;\n }\n\n /**\n * @notice The sender liquidates the borrowers collateral.\n * The collateral seized is transferred to the liquidator.\n * @param borrower The borrower of this cToken to be liquidated\n * @param repayAmount The amount of the underlying borrowed asset to repay\n * @param cTokenCollateral The market in which to seize collateral from the borrower\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function liquidateBorrow(\n address borrower,\n uint256 repayAmount,\n address cTokenCollateral\n ) external override isAuthorized onlyOracleApprovedAllowEOA isMinHFThresholdExceeded(borrower) returns (uint256) {\n (uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);\n return err;\n }\n\n /**\n * @notice Get cash balance of this cToken in the underlying asset\n * @return The quantity of underlying asset owned by this contract\n */\n function getCash() external view override returns (uint256) {\n return getCashInternal();\n }\n\n /**\n * @notice Transfers collateral tokens (this market) to the liquidator.\n * @dev Will fail unless called by another cToken during the process of liquidation.\n * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.\n * @param liquidator The account receiving seized collateral\n * @param borrower The account having collateral seized\n * @param seizeTokens The number of cTokens to seize\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function seize(\n address liquidator,\n address borrower,\n uint256 seizeTokens\n ) external override nonReentrant(true) onlyOracleApprovedAllowEOA returns (uint256) {\n return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);\n }\n\n function selfTransferOut(address to, uint256 amount) external override {\n require(msg.sender == address(this), \"!self\");\n doTransferOut(to, amount);\n }\n\n function selfTransferIn(address from, uint256 amount) external override returns (uint256) {\n require(msg.sender == address(this), \"!self\");\n return doTransferIn(from, amount);\n }\n\n /**\n * @notice Accrues interest and reduces Ionic fees by transferring to Ionic\n * @param withdrawAmount Amount of fees to withdraw\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _withdrawIonicFees(uint256 withdrawAmount) external override nonReentrant(false) onlyOracleApproved returns (uint256) {\n asCTokenExtension().accrueInterest();\n\n if (accrualBlockNumber != block.number) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.WITHDRAW_IONIC_FEES_FRESH_CHECK);\n }\n\n if (getCashInternal() < withdrawAmount) {\n return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_IONIC_FEES_CASH_NOT_AVAILABLE);\n }\n\n if (withdrawAmount > totalIonicFees) {\n return fail(Error.BAD_INPUT, FailureInfo.WITHDRAW_IONIC_FEES_VALIDATION);\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n uint256 totalIonicFeesNew = totalIonicFees - withdrawAmount;\n totalIonicFees = totalIonicFeesNew;\n\n // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n doTransferOut(address(ionicAdmin), withdrawAmount);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Accrues interest and reduces admin fees by transferring to admin\n * @param withdrawAmount Amount of fees to withdraw\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _withdrawAdminFees(uint256 withdrawAmount) external override nonReentrant(false) onlyOracleApproved returns (uint256) {\n asCTokenExtension().accrueInterest();\n\n if (accrualBlockNumber != block.number) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.WITHDRAW_ADMIN_FEES_FRESH_CHECK);\n }\n\n // Fail gracefully if protocol has insufficient underlying cash\n if (getCashInternal() < withdrawAmount) {\n return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.WITHDRAW_ADMIN_FEES_CASH_NOT_AVAILABLE);\n }\n\n if (withdrawAmount > totalAdminFees) {\n return fail(Error.BAD_INPUT, FailureInfo.WITHDRAW_ADMIN_FEES_VALIDATION);\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n totalAdminFees = totalAdminFees - withdrawAmount;\n\n // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n doTransferOut(ComptrollerV3Storage(address(comptroller)).admin(), withdrawAmount);\n\n return uint256(Error.NO_ERROR);\n }\n\n /*** Safe Token ***/\n\n /**\n * @notice Gets balance of this contract in terms of the underlying\n * @dev This excludes the value of the current message, if any\n * @return The quantity of underlying tokens owned by this contract\n */\n function getCashInternal() internal view virtual returns (uint256) {\n return EIP20Interface(underlying).balanceOf(address(this));\n }\n\n /**\n * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.\n * This will revert due to insufficient balance or insufficient allowance.\n * This function returns the actual amount received,\n * which may be less than `amount` if there is a fee attached to the transfer.\n *\n * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n */\n function doTransferIn(address from, uint256 amount) internal virtual returns (uint256) {\n uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this));\n _callOptionalReturn(\n abi.encodeWithSelector(EIP20Interface.transferFrom.selector, from, address(this), amount),\n \"TOKEN_TRANSFER_IN_FAILED\"\n );\n\n // Calculate the amount that was *actually* transferred\n uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this));\n require(balanceAfter >= balanceBefore, \"TOKEN_TRANSFER_IN_OVERFLOW\");\n return balanceAfter - balanceBefore; // underflow already checked above, just subtract\n }\n\n /**\n * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory\n * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to\n * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified\n * it is >= amount, this should not revert in normal conditions.\n *\n * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.\n * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n */\n function doTransferOut(address to, uint256 amount) internal virtual {\n _callOptionalReturn(\n abi.encodeWithSelector(EIP20Interface.transfer.selector, to, amount),\n \"TOKEN_TRANSFER_OUT_FAILED\"\n );\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param data The call data (encoded using abi.encode or one of its variants).\n * @param errorMessage The revert string to return on failure.\n */\n function _callOptionalReturn(bytes memory data, string memory errorMessage) internal {\n bytes memory returndata = _functionCall(underlying, data, errorMessage);\n if (returndata.length > 0) require(abi.decode(returndata, (bool)), errorMessage);\n }\n\n /**\n * @notice Sender supplies assets into the market and receives cTokens in exchange\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param mintAmount The amount of the underlying asset to supply\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n */\n function mintInternal(uint256 mintAmount) internal nonReentrant(false) returns (uint256, uint256) {\n asCTokenExtension().accrueInterest();\n // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to\n return mintFresh(msg.sender, mintAmount);\n }\n\n struct MintLocalVars {\n Error err;\n MathError mathErr;\n uint256 exchangeRateMantissa;\n uint256 mintTokens;\n uint256 totalSupplyNew;\n uint256 accountTokensNew;\n uint256 actualMintAmount;\n }\n\n /**\n * @notice User supplies assets into the market and receives cTokens in exchange\n * @dev Assumes interest has already been accrued up to the current block\n * @param minter The address of the account which is supplying the assets\n * @param mintAmount The amount of the underlying asset to supply\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.\n */\n function mintFresh(address minter, uint256 mintAmount) internal returns (uint256, uint256) {\n /* Fail if mint not allowed */\n uint256 allowed = comptroller.mintAllowed(address(this), minter, mintAmount);\n if (allowed != 0) {\n return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);\n }\n\n /* Verify market's block number equals current block number */\n if (accrualBlockNumber != block.number) {\n return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);\n }\n\n MintLocalVars memory vars;\n\n vars.exchangeRateMantissa = asCTokenExtension().exchangeRateCurrent();\n\n // Check max supply\n // unused function\n /* allowed = comptroller.mintWithinLimits(address(this), vars.exchangeRateMantissa, accountTokens[minter], mintAmount);\n if (allowed != 0) {\n return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);\n } */\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n /*\n * We call `doTransferIn` for the minter and the mintAmount.\n * Note: The cToken must handle variations between ERC-20 and ETH underlying.\n * `doTransferIn` reverts if anything goes wrong, since we can't be sure if\n * side-effects occurred. The function returns the amount actually transferred,\n * in case of a fee. On success, the cToken holds an additional `actualMintAmount`\n * of cash.\n */\n vars.actualMintAmount = doTransferIn(minter, mintAmount);\n\n /*\n * We get the current exchange rate and calculate the number of cTokens to be minted:\n * mintTokens = actualMintAmount / exchangeRate\n */\n\n // mintTokens is rounded down here - correct\n (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(\n vars.actualMintAmount,\n Exp({ mantissa: vars.exchangeRateMantissa })\n );\n require(vars.mathErr == MathError.NO_ERROR, \"MINT_EXCHANGE_CALCULATION_FAILED\");\n require(vars.mintTokens > 0, \"MINT_ZERO_CTOKENS_REJECTED\");\n\n /*\n * We calculate the new total supply of cTokens and minter token balance, checking for overflow:\n * totalSupplyNew = totalSupply + mintTokens\n * accountTokensNew = accountTokens[minter] + mintTokens\n */\n vars.totalSupplyNew = totalSupply + vars.mintTokens;\n\n vars.accountTokensNew = accountTokens[minter] + vars.mintTokens;\n\n /* We write previously calculated values into storage */\n totalSupply = vars.totalSupplyNew;\n accountTokens[minter] = vars.accountTokensNew;\n\n /* We emit a Mint event, and a Transfer event */\n emit Mint(minter, vars.actualMintAmount, vars.mintTokens);\n emit Transfer(address(this), minter, vars.mintTokens);\n\n /* We call the defense hook */\n comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);\n\n return (uint256(Error.NO_ERROR), vars.actualMintAmount);\n }\n\n /**\n * @notice Sender redeems cTokens in exchange for the underlying asset\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param redeemTokens The number of cTokens to redeem into underlying\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function redeemInternal(uint256 redeemTokens) internal nonReentrant(false) returns (uint256) {\n asCTokenExtension().accrueInterest();\n // redeemFresh emits redeem-specific logs on errors, so we don't need to\n return redeemFresh(msg.sender, redeemTokens, 0);\n }\n\n /**\n * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset\n * @dev Accrues interest whether or not the operation succeeds, unless reverted\n * @param redeemAmount The amount of underlying to receive from redeeming cTokens\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function redeemUnderlyingInternal(uint256 redeemAmount) internal nonReentrant(false) returns (uint256) {\n asCTokenExtension().accrueInterest();\n // redeemFresh emits redeem-specific logs on errors, so we don't need to\n return redeemFresh(msg.sender, 0, redeemAmount);\n }\n\n struct RedeemLocalVars {\n Error err;\n MathError mathErr;\n uint256 exchangeRateMantissa;\n uint256 redeemTokens;\n uint256 redeemAmount;\n uint256 totalSupplyNew;\n uint256 accountTokensNew;\n }\n\n function divRoundUp(uint256 x, uint256 y) internal pure returns (uint256 res) {\n res = (x * 1e18) / y;\n if (x % y != 0) res += 1;\n }\n\n /**\n * @notice User redeems cTokens in exchange for the underlying asset\n * @dev Assumes interest has already been accrued up to the current block\n * @param redeemer The address of the account which is redeeming the tokens\n * @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)\n * @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function redeemFresh(\n address redeemer,\n uint256 redeemTokensIn,\n uint256 redeemAmountIn\n ) internal returns (uint256) {\n require(redeemTokensIn == 0 || redeemAmountIn == 0, \"!redeem tokens or amount\");\n\n RedeemLocalVars memory vars;\n\n vars.exchangeRateMantissa = asCTokenExtension().exchangeRateCurrent();\n\n if (redeemTokensIn > 0) {\n // don't allow dust tokens/assets to be left after\n if (totalSupply - redeemTokensIn < 5000) redeemTokensIn = totalSupply;\n\n /*\n * We calculate the exchange rate and the amount of underlying to be redeemed:\n * redeemTokens = redeemTokensIn\n * redeemAmount = redeemTokensIn x exchangeRateCurrent\n */\n vars.redeemTokens = redeemTokensIn;\n\n (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(\n Exp({ mantissa: vars.exchangeRateMantissa }),\n redeemTokensIn\n );\n if (vars.mathErr != MathError.NO_ERROR) {\n return\n failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint256(vars.mathErr));\n }\n } else {\n if (redeemAmountIn == type(uint256).max) {\n redeemAmountIn = comptroller.getMaxRedeemOrBorrow(redeemer, ICErc20(address(this)), false);\n }\n\n // don't allow dust tokens/assets to be left after\n uint256 totalUnderlyingSupplied = asCTokenExtension().getTotalUnderlyingSupplied();\n if (totalUnderlyingSupplied - redeemAmountIn < 1000) redeemAmountIn = totalUnderlyingSupplied;\n\n /*\n * We get the current exchange rate and calculate the amount to be redeemed:\n * redeemTokens = redeemAmountIn / exchangeRate\n * redeemAmount = redeemAmountIn\n */\n\n vars.redeemTokens = divRoundUp(redeemAmountIn, vars.exchangeRateMantissa);\n\n // don't allow dust tokens/assets to be left after\n if (totalSupply - vars.redeemTokens < 1000) vars.redeemTokens = totalSupply;\n\n vars.redeemAmount = redeemAmountIn;\n }\n\n /* Fail if redeem not allowed */\n uint256 allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);\n if (allowed != 0) {\n return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);\n }\n\n /* Verify market's block number equals current block number */\n if (accrualBlockNumber != block.number) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);\n }\n\n /*\n * We calculate the new total supply and redeemer balance, checking for underflow:\n * totalSupplyNew = totalSupply - redeemTokens\n * accountTokensNew = accountTokens[redeemer] - redeemTokens\n */\n (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);\n if (vars.mathErr != MathError.NO_ERROR) {\n return\n failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint256(vars.mathErr));\n }\n\n (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);\n if (vars.mathErr != MathError.NO_ERROR) {\n return\n failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr));\n }\n\n /* Fail gracefully if protocol has insufficient cash */\n if (getCashInternal() < vars.redeemAmount) {\n return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n /* We write previously calculated values into storage */\n totalSupply = vars.totalSupplyNew;\n accountTokens[redeemer] = vars.accountTokensNew;\n\n /*\n * We invoke doTransferOut for the redeemer and the redeemAmount.\n * Note: The cToken must handle variations between ERC-20 and ETH underlying.\n * On success, the cToken has redeemAmount less of cash.\n * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n */\n doTransferOut(redeemer, vars.redeemAmount);\n\n /* We emit a Transfer event, and a Redeem event */\n emit Transfer(redeemer, address(this), vars.redeemTokens);\n emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);\n\n /* We call the defense hook */\n comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Sender borrows assets from the protocol to their own address\n * @param borrowAmount The amount of the underlying asset to borrow\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function borrowInternal(uint256 borrowAmount) internal nonReentrant(false) returns (uint256) {\n asCTokenExtension().accrueInterest();\n // borrowFresh emits borrow-specific logs on errors, so we don't need to\n return borrowFresh(msg.sender, borrowAmount);\n }\n\n struct BorrowLocalVars {\n MathError mathErr;\n uint256 accountBorrows;\n uint256 accountBorrowsNew;\n uint256 totalBorrowsNew;\n }\n\n /**\n * @notice Users borrow assets from the protocol to their own address\n * @param borrowAmount The amount of the underlying asset to borrow\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function borrowFresh(address borrower, uint256 borrowAmount) internal returns (uint256) {\n /* Fail if borrow not allowed */\n uint256 allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);\n if (allowed != 0) {\n return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);\n }\n\n /* Verify market's block number equals current block number */\n if (accrualBlockNumber != block.number) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);\n }\n\n /* Fail gracefully if protocol has insufficient underlying cash */\n uint256 cashPrior = getCashInternal();\n\n if (cashPrior < borrowAmount) {\n return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);\n }\n\n BorrowLocalVars memory vars;\n\n /*\n * We calculate the new borrower and total borrow balances, failing on overflow:\n * accountBorrowsNew = accountBorrows + borrowAmount\n * totalBorrowsNew = totalBorrows + borrowAmount\n */\n vars.accountBorrows = asCTokenExtension().borrowBalanceCurrent(borrower);\n\n (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);\n if (vars.mathErr != MathError.NO_ERROR) {\n return\n failOpaque(\n Error.MATH_ERROR,\n FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\n uint256(vars.mathErr)\n );\n }\n\n // Check min borrow for this user for this asset\n allowed = comptroller.borrowWithinLimits(address(this), vars.accountBorrowsNew);\n if (allowed != 0) {\n return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);\n }\n\n (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);\n if (vars.mathErr != MathError.NO_ERROR) {\n return\n failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint256(vars.mathErr));\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n /* We write the previously calculated values into storage */\n accountBorrows[borrower].principal = vars.accountBorrowsNew;\n accountBorrows[borrower].interestIndex = borrowIndex;\n totalBorrows = vars.totalBorrowsNew;\n\n /*\n * We invoke doTransferOut for the borrower and the borrowAmount.\n * Note: The cToken must handle variations between ERC-20 and ETH underlying.\n * On success, the cToken borrowAmount less of cash.\n * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.\n */\n doTransferOut(borrower, borrowAmount);\n\n /* We emit a Borrow event */\n emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);\n\n /* We call the defense hook */\n comptroller.borrowVerify(address(this), borrower);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Sender repays their own borrow\n * @param repayAmount The amount to repay\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */\n function repayBorrowInternal(uint256 repayAmount) internal nonReentrant(false) returns (uint256, uint256) {\n asCTokenExtension().accrueInterest();\n // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to\n return repayBorrowFresh(msg.sender, msg.sender, repayAmount);\n }\n\n /**\n * @notice Sender repays a borrow belonging to borrower\n * @param borrower the account with the debt being payed off\n * @param repayAmount The amount to repay\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */\n function repayBorrowBehalfInternal(address borrower, uint256 repayAmount)\n internal\n nonReentrant(false)\n returns (uint256, uint256)\n {\n asCTokenExtension().accrueInterest();\n // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to\n return repayBorrowFresh(msg.sender, borrower, repayAmount);\n }\n\n struct RepayBorrowLocalVars {\n Error err;\n MathError mathErr;\n uint256 repayAmount;\n uint256 borrowerIndex;\n uint256 accountBorrows;\n uint256 accountBorrowsNew;\n uint256 totalBorrowsNew;\n uint256 actualRepayAmount;\n }\n\n /**\n * @notice Borrows are repaid by another user (possibly the borrower).\n * @param payer the account paying off the borrow\n * @param borrower the account with the debt being payed off\n * @param repayAmount the amount of undelrying tokens being returned\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */\n function repayBorrowFresh(\n address payer,\n address borrower,\n uint256 repayAmount\n ) internal returns (uint256, uint256) {\n /* Fail if repayBorrow not allowed */\n uint256 allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);\n if (allowed != 0) {\n return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);\n }\n\n /* Verify market's block number equals current block number */\n if (accrualBlockNumber != block.number) {\n return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);\n }\n\n RepayBorrowLocalVars memory vars;\n\n /* We remember the original borrowerIndex for verification purposes */\n vars.borrowerIndex = accountBorrows[borrower].interestIndex;\n\n /* We fetch the amount the borrower owes, with accumulated interest */\n vars.accountBorrows = asCTokenExtension().borrowBalanceCurrent(borrower);\n\n /* If repayAmount == -1, repayAmount = accountBorrows */\n if (repayAmount == type(uint256).max) {\n vars.repayAmount = vars.accountBorrows;\n } else {\n vars.repayAmount = repayAmount;\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n /*\n * We call doTransferIn for the payer and the repayAmount\n * Note: The cToken must handle variations between ERC-20 and ETH underlying.\n * On success, the cToken holds an additional repayAmount of cash.\n * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.\n * it returns the amount actually transferred, in case of a fee.\n */\n vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);\n\n /*\n * We calculate the new borrower and total borrow balances, failing on underflow:\n * accountBorrowsNew = accountBorrows - actualRepayAmount\n * totalBorrowsNew = totalBorrows - actualRepayAmount\n */\n (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);\n require(vars.mathErr == MathError.NO_ERROR, \"REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED\");\n\n (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);\n require(vars.mathErr == MathError.NO_ERROR, \"REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED\");\n\n /* We write the previously calculated values into storage */\n accountBorrows[borrower].principal = vars.accountBorrowsNew;\n accountBorrows[borrower].interestIndex = borrowIndex;\n totalBorrows = vars.totalBorrowsNew;\n\n /* We emit a RepayBorrow event */\n emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);\n\n /* We call the defense hook */\n comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount);\n\n return (uint256(Error.NO_ERROR), vars.actualRepayAmount);\n }\n\n /**\n * @notice The sender liquidates the borrowers collateral.\n * The collateral seized is transferred to the liquidator.\n * @param borrower The borrower of this cToken to be liquidated\n * @param cTokenCollateral The market in which to seize collateral from the borrower\n * @param repayAmount The amount of the underlying borrowed asset to repay\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */\n function liquidateBorrowInternal(\n address borrower,\n uint256 repayAmount,\n address cTokenCollateral\n ) internal nonReentrant(false) returns (uint256, uint256) {\n asCTokenExtension().accrueInterest();\n ICErc20(cTokenCollateral).accrueInterest();\n // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to\n return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);\n }\n\n /**\n * @notice The liquidator liquidates the borrowers collateral.\n * The collateral seized is transferred to the liquidator.\n * @param borrower The borrower of this cToken to be liquidated\n * @param liquidator The address repaying the borrow and seizing collateral\n * @param cTokenCollateral The market in which to seize collateral from the borrower\n * @param repayAmount The amount of the underlying borrowed asset to repay\n * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.\n */\n function liquidateBorrowFresh(\n address liquidator,\n address borrower,\n uint256 repayAmount,\n address cTokenCollateral\n ) internal returns (uint256, uint256) {\n /* Fail if liquidate not allowed */\n uint256 allowed = comptroller.liquidateBorrowAllowed(\n address(this),\n cTokenCollateral,\n liquidator,\n borrower,\n repayAmount\n );\n if (allowed != 0) {\n return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);\n }\n\n /* Verify market's block number equals current block number */\n if (accrualBlockNumber != block.number) {\n return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);\n }\n\n /* Verify cTokenCollateral market's block number equals current block number */\n if (CErc20(cTokenCollateral).accrualBlockNumber() != block.number) {\n return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);\n }\n\n /* Fail if borrower = liquidator */\n if (borrower == liquidator) {\n return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);\n }\n\n /* Fail if repayAmount = 0 */\n if (repayAmount == 0) {\n return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);\n }\n\n /* Fail if repayAmount = -1 */\n if (repayAmount == type(uint256).max) {\n return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);\n }\n\n /* Fail if repayBorrow fails */\n (uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);\n if (repayBorrowError != uint256(Error.NO_ERROR)) {\n return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n /* We calculate the number of collateral tokens that will be seized */\n (uint256 amountSeizeError, uint256 seizeTokens) = comptroller.liquidateCalculateSeizeTokens(\n address(this),\n cTokenCollateral,\n actualRepayAmount\n );\n require(amountSeizeError == uint256(Error.NO_ERROR), \"LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED\");\n\n /* Revert if borrower collateral token balance < seizeTokens */\n require(ICErc20(cTokenCollateral).balanceOf(borrower) >= seizeTokens, \"LIQUIDATE_SEIZE_TOO_MUCH\");\n\n // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call\n uint256 seizeError;\n if (cTokenCollateral == address(this)) {\n seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);\n } else {\n seizeError = CErc20(cTokenCollateral).seize(liquidator, borrower, seizeTokens);\n }\n\n /* Revert if seize tokens fails (since we cannot be sure of side effects) */\n require(seizeError == uint256(Error.NO_ERROR), \"!seize\");\n\n /* We emit a LiquidateBorrow event */\n emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, cTokenCollateral, seizeTokens);\n\n /* We call the defense hook */\n // unused function\n // comptroller.liquidateBorrowVerify(address(this), cTokenCollateral, liquidator, borrower, actualRepayAmount, seizeTokens);\n\n return (uint256(Error.NO_ERROR), actualRepayAmount);\n }\n\n struct SeizeInternalLocalVars {\n MathError mathErr;\n uint256 borrowerTokensNew;\n uint256 liquidatorTokensNew;\n uint256 liquidatorSeizeTokens;\n uint256 protocolSeizeTokens;\n uint256 protocolSeizeAmount;\n uint256 exchangeRateMantissa;\n uint256 totalReservesNew;\n uint256 totalIonicFeeNew;\n uint256 totalSupplyNew;\n uint256 feeSeizeTokens;\n uint256 feeSeizeAmount;\n }\n\n /**\n * @notice Transfers collateral tokens (this market) to the liquidator.\n * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.\n * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.\n * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)\n * @param liquidator The account receiving seized collateral\n * @param borrower The account having collateral seized\n * @param seizeTokens The number of cTokens to seize\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function seizeInternal(\n address seizerToken,\n address liquidator,\n address borrower,\n uint256 seizeTokens\n ) internal returns (uint256) {\n /* Fail if seize not allowed */\n uint256 allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);\n if (allowed != 0) {\n return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);\n }\n\n /* Fail if borrower = liquidator */\n if (borrower == liquidator) {\n return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);\n }\n\n SeizeInternalLocalVars memory vars;\n\n /*\n * We calculate the new borrower and liquidator token balances, failing on underflow/overflow:\n * borrowerTokensNew = accountTokens[borrower] - seizeTokens\n * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens\n */\n (vars.mathErr, vars.borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);\n if (vars.mathErr != MathError.NO_ERROR) {\n return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint256(vars.mathErr));\n }\n\n vars.protocolSeizeTokens = mul_(seizeTokens, Exp({ mantissa: protocolSeizeShareMantissa }));\n vars.feeSeizeTokens = mul_(seizeTokens, Exp({ mantissa: feeSeizeShareMantissa }));\n vars.liquidatorSeizeTokens = seizeTokens - vars.protocolSeizeTokens - vars.feeSeizeTokens;\n\n vars.exchangeRateMantissa = asCTokenExtension().exchangeRateCurrent();\n\n vars.protocolSeizeAmount = mul_ScalarTruncate(\n Exp({ mantissa: vars.exchangeRateMantissa }),\n vars.protocolSeizeTokens\n );\n vars.feeSeizeAmount = mul_ScalarTruncate(Exp({ mantissa: vars.exchangeRateMantissa }), vars.feeSeizeTokens);\n\n vars.totalReservesNew = totalReserves + vars.protocolSeizeAmount;\n vars.totalSupplyNew = totalSupply - vars.protocolSeizeTokens - vars.feeSeizeTokens;\n vars.totalIonicFeeNew = totalIonicFees + vars.feeSeizeAmount;\n\n (vars.mathErr, vars.liquidatorTokensNew) = addUInt(accountTokens[liquidator], vars.liquidatorSeizeTokens);\n if (vars.mathErr != MathError.NO_ERROR) {\n return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint256(vars.mathErr));\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n /* We write the previously calculated values into storage */\n totalReserves = vars.totalReservesNew;\n totalSupply = vars.totalSupplyNew;\n totalIonicFees = vars.totalIonicFeeNew;\n\n accountTokens[borrower] = vars.borrowerTokensNew;\n accountTokens[liquidator] = vars.liquidatorTokensNew;\n\n /* Emit a Transfer event */\n emit Transfer(borrower, liquidator, vars.liquidatorSeizeTokens);\n emit Transfer(borrower, address(this), vars.protocolSeizeTokens);\n emit ReservesAdded(address(this), vars.protocolSeizeAmount, vars.totalReservesNew);\n\n /* We call the defense hook */\n comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);\n\n return uint256(Error.NO_ERROR);\n }\n\n function asCTokenExtension() internal view returns (ICErc20) {\n return ICErc20(address(this));\n }\n\n /*** Reentrancy Guard ***/\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n */\n modifier nonReentrant(bool localOnly) {\n _beforeNonReentrant(localOnly);\n _;\n _afterNonReentrant(localOnly);\n }\n\n /**\n * @dev Split off from `nonReentrant` to keep contract below the 24 KB size limit.\n * Saves space because function modifier code is \"inlined\" into every function with the modifier).\n * In this specific case, the optimization saves around 1500 bytes of that valuable 24 KB limit.\n */\n function _beforeNonReentrant(bool localOnly) private {\n require(_notEntered, \"re-entered\");\n if (!localOnly) comptroller._beforeNonReentrant();\n _notEntered = false;\n }\n\n /**\n * @dev Split off from `nonReentrant` to keep contract below the 24 KB size limit.\n * Saves space because function modifier code is \"inlined\" into every function with the modifier).\n * In this specific case, the optimization saves around 150 bytes of that valuable 24 KB limit.\n */\n function _afterNonReentrant(bool localOnly) private {\n _notEntered = true; // get a gas-refund post-Istanbul\n if (!localOnly) comptroller._afterNonReentrant();\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n * @param data The call data (encoded using abi.encode or one of its variants).\n * @param errorMessage The revert string to return on failure.\n */\n function _functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.call(data);\n\n if (!success) {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n\n return returndata;\n }\n}\n" + }, + "contracts/src/compound/CTokenFirstExtension.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { DiamondExtension } from \"../ionic/DiamondExtension.sol\";\nimport { IFlashLoanReceiver } from \"../ionic/IFlashLoanReceiver.sol\";\nimport { CErc20FirstExtensionBase, CTokenFirstExtensionInterface, ICErc20 } from \"./CTokenInterfaces.sol\";\nimport { SFSRegister } from \"./ComptrollerInterface.sol\";\nimport { TokenErrorReporter } from \"./ErrorReporter.sol\";\nimport { Exponential } from \"./Exponential.sol\";\nimport { InterestRateModel } from \"./InterestRateModel.sol\";\nimport { IFeeDistributor } from \"./IFeeDistributor.sol\";\nimport { CTokenOracleProtected } from \"./CTokenOracleProtected.sol\";\n\nimport { IERC20, SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport { Multicall } from \"../utils/Multicall.sol\";\nimport { AddressesProvider } from \"../ionic/AddressesProvider.sol\";\nimport { IHypernativeOracle } from \"../external/hypernative/interfaces/IHypernativeOracle.sol\";\n\ncontract CTokenFirstExtension is\n CTokenOracleProtected,\n CErc20FirstExtensionBase,\n TokenErrorReporter,\n Exponential,\n DiamondExtension,\n Multicall\n{\n modifier isAuthorized() {\n require(\n IFeeDistributor(ionicAdmin).canCall(address(comptroller), msg.sender, address(this), msg.sig),\n \"not authorized\"\n );\n _;\n }\n\n function _getExtensionFunctions() external pure virtual override returns (bytes4[] memory) {\n uint8 fnsCount = 25;\n bytes4[] memory functionSelectors = new bytes4[](fnsCount);\n functionSelectors[--fnsCount] = this.transfer.selector;\n functionSelectors[--fnsCount] = this.transferFrom.selector;\n functionSelectors[--fnsCount] = this.allowance.selector;\n functionSelectors[--fnsCount] = this.approve.selector;\n functionSelectors[--fnsCount] = this.balanceOf.selector;\n functionSelectors[--fnsCount] = this._setAdminFee.selector;\n functionSelectors[--fnsCount] = this._setInterestRateModel.selector;\n functionSelectors[--fnsCount] = this._setNameAndSymbol.selector;\n functionSelectors[--fnsCount] = this._setAddressesProvider.selector;\n functionSelectors[--fnsCount] = this._setReserveFactor.selector;\n functionSelectors[--fnsCount] = this.supplyRatePerBlock.selector;\n functionSelectors[--fnsCount] = this.borrowRatePerBlock.selector;\n functionSelectors[--fnsCount] = this.exchangeRateCurrent.selector;\n functionSelectors[--fnsCount] = this.accrueInterest.selector;\n functionSelectors[--fnsCount] = this.totalBorrowsCurrent.selector;\n functionSelectors[--fnsCount] = this.balanceOfUnderlying.selector;\n functionSelectors[--fnsCount] = this.multicall.selector;\n functionSelectors[--fnsCount] = this.supplyRatePerBlockAfterDeposit.selector;\n functionSelectors[--fnsCount] = this.supplyRatePerBlockAfterWithdraw.selector;\n functionSelectors[--fnsCount] = this.borrowRatePerBlockAfterBorrow.selector;\n functionSelectors[--fnsCount] = this.getTotalUnderlyingSupplied.selector;\n functionSelectors[--fnsCount] = this.flash.selector;\n functionSelectors[--fnsCount] = this.getAccountSnapshot.selector;\n functionSelectors[--fnsCount] = this.borrowBalanceCurrent.selector;\n functionSelectors[--fnsCount] = this.registerInSFS.selector;\n\n require(fnsCount == 0, \"use the correct array length\");\n return functionSelectors;\n }\n\n function getTotalUnderlyingSupplied() public view override returns (uint256) {\n // (totalCash + totalBorrows - (totalReserves + totalIonicFees + totalAdminFees))\n return asCToken().getCash() + totalBorrows - (totalReserves + totalIonicFees + totalAdminFees);\n }\n\n /* ERC20 fns */\n /**\n * @notice Transfer `tokens` tokens from `src` to `dst` by `spender`\n * @dev Called by both `transfer` and `transferFrom` internally\n * @param spender The address of the account performing the transfer\n * @param src The address of the source account\n * @param dst The address of the destination account\n * @param tokens The number of tokens to transfer\n * @return Whether or not the transfer succeeded\n */\n function transferTokens(address spender, address src, address dst, uint256 tokens) internal returns (uint256) {\n /* Fail if transfer not allowed */\n uint256 allowed = comptroller.transferAllowed(address(this), src, dst, tokens);\n if (allowed != 0) {\n return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);\n }\n\n /* Do not allow self-transfers */\n if (src == dst) {\n return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);\n }\n\n /* Get the allowance, infinite for the account owner */\n uint256 startingAllowance = 0;\n if (spender == src) {\n startingAllowance = type(uint256).max;\n } else {\n startingAllowance = transferAllowances[src][spender];\n }\n\n /* Do the calculations, checking for {under,over}flow */\n MathError mathErr;\n uint256 allowanceNew;\n uint256 srcTokensNew;\n uint256 dstTokensNew;\n\n (mathErr, allowanceNew) = subUInt(startingAllowance, tokens);\n if (mathErr != MathError.NO_ERROR) {\n return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);\n }\n\n (mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);\n if (mathErr != MathError.NO_ERROR) {\n return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);\n }\n\n (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);\n if (mathErr != MathError.NO_ERROR) {\n return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);\n }\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n\n accountTokens[src] = srcTokensNew;\n accountTokens[dst] = dstTokensNew;\n\n /* Eat some of the allowance (if necessary) */\n if (startingAllowance != type(uint256).max) {\n transferAllowances[src][spender] = allowanceNew;\n }\n\n /* We emit a Transfer event */\n emit Transfer(src, dst, tokens);\n\n /* We call the defense hook */\n comptroller.transferVerify(address(this), src, dst, tokens);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n * @return Whether or not the transfer succeeded\n */\n function transfer(\n address dst,\n uint256 amount\n ) public override nonReentrant(false) isAuthorized onlyOracleApprovedAllowEOA returns (bool) {\n return transferTokens(msg.sender, msg.sender, dst, amount) == uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Transfer `amount` tokens from `src` to `dst`\n * @param src The address of the source account\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n * @return Whether or not the transfer succeeded\n */\n function transferFrom(\n address src,\n address dst,\n uint256 amount\n ) public override nonReentrant(false) isAuthorized onlyOracleApprovedAllowEOA returns (bool) {\n return transferTokens(msg.sender, src, dst, amount) == uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Approve `spender` to transfer up to `amount` from `src`\n * @dev This will overwrite the approval amount for `spender`\n * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n * @param spender The address of the account which may transfer tokens\n * @param amount The number of tokens that are approved (-1 means infinite)\n * @return Whether or not the approval succeeded\n */\n function approve(\n address spender,\n uint256 amount\n ) public override isAuthorized onlyOracleApprovedAllowEOA returns (bool) {\n address src = msg.sender;\n transferAllowances[src][spender] = amount;\n emit Approval(src, spender, amount);\n return true;\n }\n\n /**\n * @notice Get the current allowance from `owner` for `spender`\n * @param owner The address of the account which owns the tokens to be spent\n * @param spender The address of the account which may transfer tokens\n * @return The number of tokens allowed to be spent (-1 means infinite)\n */\n function allowance(address owner, address spender) public view override returns (uint256) {\n return transferAllowances[owner][spender];\n }\n\n /**\n * @notice Get the token balance of the `owner`\n * @param owner The address of the account to query\n * @return The number of tokens owned by `owner`\n */\n function balanceOf(address owner) public view override returns (uint256) {\n return accountTokens[owner];\n }\n\n /*** Admin Functions ***/\n\n /**\n * @notice updates the cToken ERC20 name and symbol\n * @dev Admin function to update the cToken ERC20 name and symbol\n * @param _name the new ERC20 token name to use\n * @param _symbol the new ERC20 token symbol to use\n */\n function _setNameAndSymbol(string calldata _name, string calldata _symbol) external {\n // Check caller is admin\n require(hasAdminRights(), \"!admin\");\n\n // Set ERC20 name and symbol\n name = _name;\n symbol = _symbol;\n }\n\n function _setAddressesProvider(address _ap) external {\n // Check caller is admin\n require(hasAdminRights(), \"!admin\");\n\n ap = AddressesProvider(_ap);\n }\n\n /**\n * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh\n * @dev Admin function to accrue interest and set a new reserve factor\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _setReserveFactor(\n uint256 newReserveFactorMantissa\n ) public override nonReentrant(false) returns (uint256) {\n accrueInterest();\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);\n }\n\n // Verify market's block number equals current block number\n if (accrualBlockNumber != block.number) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);\n }\n\n // Check newReserveFactor ≤ maxReserveFactor\n if (newReserveFactorMantissa + adminFeeMantissa + ionicFeeMantissa > reserveFactorPlusFeesMaxMantissa) {\n return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);\n }\n\n uint256 oldReserveFactorMantissa = reserveFactorMantissa;\n reserveFactorMantissa = newReserveFactorMantissa;\n\n emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice accrues interest and sets a new admin fee for the protocol using _setAdminFeeFresh\n * @dev Admin function to accrue interest and set a new admin fee\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _setAdminFee(\n uint256 newAdminFeeMantissa\n ) public override nonReentrant(false) returns (uint256) {\n accrueInterest();\n // Verify market's block number equals current block number\n if (accrualBlockNumber != block.number) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_ADMIN_FEE_FRESH_CHECK);\n }\n\n // Sanitize newAdminFeeMantissa\n if (newAdminFeeMantissa == type(uint256).max) newAdminFeeMantissa = adminFeeMantissa;\n\n // Get latest Ionic fee\n uint256 newIonicFeeMantissa = IFeeDistributor(ionicAdmin).interestFeeRate();\n\n // Check reserveFactorMantissa + newAdminFeeMantissa + newIonicFeeMantissa ≤ reserveFactorPlusFeesMaxMantissa\n if (reserveFactorMantissa + newAdminFeeMantissa + newIonicFeeMantissa > reserveFactorPlusFeesMaxMantissa) {\n return fail(Error.BAD_INPUT, FailureInfo.SET_ADMIN_FEE_BOUNDS_CHECK);\n }\n\n // If setting admin fee\n if (adminFeeMantissa != newAdminFeeMantissa) {\n // Check caller is admin\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_ADMIN_FEE_ADMIN_CHECK);\n }\n\n // Set admin fee\n uint256 oldAdminFeeMantissa = adminFeeMantissa;\n adminFeeMantissa = newAdminFeeMantissa;\n\n // Emit event\n emit NewAdminFee(oldAdminFeeMantissa, newAdminFeeMantissa);\n }\n\n // If setting Ionic fee\n if (ionicFeeMantissa != newIonicFeeMantissa) {\n // Set Ionic fee\n uint256 oldIonicFeeMantissa = ionicFeeMantissa;\n ionicFeeMantissa = newIonicFeeMantissa;\n\n // Emit event\n emit NewIonicFee(oldIonicFeeMantissa, newIonicFeeMantissa);\n }\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh\n * @dev Admin function to accrue interest and update the interest rate model\n * @param newInterestRateModel the new interest rate model to use\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _setInterestRateModel(\n InterestRateModel newInterestRateModel\n ) public override nonReentrant(false) returns (uint256) {\n accrueInterest();\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);\n }\n\n if (accrualBlockNumber != block.number) {\n return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);\n }\n\n require(newInterestRateModel.isInterestRateModel(), \"!notIrm\");\n\n InterestRateModel oldInterestRateModel = interestRateModel;\n interestRateModel = newInterestRateModel;\n emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Returns the current per-block borrow interest rate for this cToken\n * @return The borrow interest rate per block, scaled by 1e18\n */\n function borrowRatePerBlock() public view override returns (uint256) {\n return\n interestRateModel.getBorrowRate(\n asCToken().getCash(),\n totalBorrows,\n totalReserves + totalAdminFees + totalIonicFees\n );\n }\n\n function borrowRatePerBlockAfterBorrow(uint256 borrowAmount) public view returns (uint256) {\n uint256 cash = asCToken().getCash();\n require(cash >= borrowAmount, \"market cash not enough\");\n\n return\n interestRateModel.getBorrowRate(\n cash - borrowAmount,\n totalBorrows + borrowAmount,\n totalReserves + totalAdminFees + totalIonicFees\n );\n }\n\n /**\n * @notice Returns the current per-block supply interest rate for this cToken\n * @return The supply interest rate per block, scaled by 1e18\n */\n function supplyRatePerBlock() public view override returns (uint256) {\n return\n interestRateModel.getSupplyRate(\n asCToken().getCash(),\n totalBorrows,\n totalReserves + totalAdminFees + totalIonicFees,\n reserveFactorMantissa + ionicFeeMantissa + adminFeeMantissa\n );\n }\n\n function supplyRatePerBlockAfterDeposit(uint256 mintAmount) external view returns (uint256) {\n return\n interestRateModel.getSupplyRate(\n asCToken().getCash() + mintAmount,\n totalBorrows,\n totalReserves + totalAdminFees + totalIonicFees,\n reserveFactorMantissa + ionicFeeMantissa + adminFeeMantissa\n );\n }\n\n function supplyRatePerBlockAfterWithdraw(uint256 withdrawAmount) external view returns (uint256) {\n uint256 cash = asCToken().getCash();\n require(cash >= withdrawAmount, \"market cash not enough\");\n return\n interestRateModel.getSupplyRate(\n cash - withdrawAmount,\n totalBorrows,\n totalReserves + totalAdminFees + totalIonicFees,\n reserveFactorMantissa + ionicFeeMantissa + adminFeeMantissa\n );\n }\n\n /**\n * @notice Accrue interest then return the up-to-date exchange rate\n * @return Calculated exchange rate scaled by 1e18\n */\n function exchangeRateCurrent() public view override returns (uint256) {\n if (block.number == accrualBlockNumber) {\n return\n _exchangeRateHypothetical(\n totalSupply,\n initialExchangeRateMantissa,\n asCToken().getCash(),\n totalBorrows,\n totalReserves,\n totalAdminFees,\n totalIonicFees\n );\n } else {\n uint256 cashPrior = asCToken().getCash();\n InterestAccrual memory accrual = _accrueInterestHypothetical(block.number, cashPrior);\n\n return\n _exchangeRateHypothetical(\n accrual.totalSupply,\n initialExchangeRateMantissa,\n cashPrior,\n accrual.totalBorrows,\n accrual.totalReserves,\n accrual.totalAdminFees,\n accrual.totalIonicFees\n );\n }\n }\n\n function _exchangeRateHypothetical(\n uint256 _totalSupply,\n uint256 _initialExchangeRateMantissa,\n uint256 _totalCash,\n uint256 _totalBorrows,\n uint256 _totalReserves,\n uint256 _totalAdminFees,\n uint256 _totalIonicFees\n ) internal pure returns (uint256) {\n if (_totalSupply == 0) {\n /*\n * If there are no tokens minted:\n * exchangeRate = initialExchangeRate\n */\n return _initialExchangeRateMantissa;\n } else {\n /*\n * Otherwise:\n * exchangeRate = (totalCash + totalBorrows - (totalReserves + totalIonicFees + totalAdminFees)) / totalSupply\n */\n uint256 cashPlusBorrowsMinusReserves;\n Exp memory exchangeRate;\n MathError mathErr;\n\n (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(\n _totalCash,\n _totalBorrows,\n _totalReserves + _totalAdminFees + _totalIonicFees\n );\n require(mathErr == MathError.NO_ERROR, \"!addThenSubUInt overflow check failed\");\n\n (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);\n require(mathErr == MathError.NO_ERROR, \"!getExp overflow check failed\");\n\n return exchangeRate.mantissa;\n }\n }\n\n struct InterestAccrual {\n uint256 accrualBlockNumber;\n uint256 borrowIndex;\n uint256 totalSupply;\n uint256 totalBorrows;\n uint256 totalReserves;\n uint256 totalIonicFees;\n uint256 totalAdminFees;\n uint256 interestAccumulated;\n }\n\n function _accrueInterestHypothetical(\n uint256 blockNumber,\n uint256 cashPrior\n ) internal view returns (InterestAccrual memory accrual) {\n uint256 totalFees = totalAdminFees + totalIonicFees;\n uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, totalBorrows, totalReserves + totalFees);\n if (borrowRateMantissa > borrowRateMaxMantissa) {\n if (cashPrior > totalFees) revert(\"!borrowRate\");\n else borrowRateMantissa = borrowRateMaxMantissa;\n }\n (MathError mathErr, uint256 blockDelta) = subUInt(blockNumber, accrualBlockNumber);\n require(mathErr == MathError.NO_ERROR, \"!blockDelta\");\n\n /*\n * Calculate the interest accumulated into borrows and reserves and the new index:\n * simpleInterestFactor = borrowRate * blockDelta\n * interestAccumulated = simpleInterestFactor * totalBorrows\n * totalBorrowsNew = interestAccumulated + totalBorrows\n * totalReservesNew = interestAccumulated * reserveFactor + totalReserves\n * totalIonicFeesNew = interestAccumulated * ionicFee + totalIonicFees\n * totalAdminFeesNew = interestAccumulated * adminFee + totalAdminFees\n * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex\n */\n\n accrual.accrualBlockNumber = blockNumber;\n accrual.totalSupply = totalSupply;\n Exp memory simpleInterestFactor = mul_(Exp({ mantissa: borrowRateMantissa }), blockDelta);\n accrual.interestAccumulated = mul_ScalarTruncate(simpleInterestFactor, totalBorrows);\n accrual.totalBorrows = accrual.interestAccumulated + totalBorrows;\n accrual.totalReserves = mul_ScalarTruncateAddUInt(\n Exp({ mantissa: reserveFactorMantissa }),\n accrual.interestAccumulated,\n totalReserves\n );\n accrual.totalIonicFees = mul_ScalarTruncateAddUInt(\n Exp({ mantissa: ionicFeeMantissa }),\n accrual.interestAccumulated,\n totalIonicFees\n );\n accrual.totalAdminFees = mul_ScalarTruncateAddUInt(\n Exp({ mantissa: adminFeeMantissa }),\n accrual.interestAccumulated,\n totalAdminFees\n );\n accrual.borrowIndex = mul_ScalarTruncateAddUInt(simpleInterestFactor, borrowIndex, borrowIndex);\n }\n\n /**\n * @notice Applies accrued interest to total borrows and reserves\n * @dev This calculates interest accrued from the last checkpointed block\n * up to the current block and writes new checkpoint to storage.\n */\n function accrueInterest() public override returns (uint256) {\n /* Remember the initial block number */\n uint256 currentBlockNumber = block.number;\n\n /* Short-circuit accumulating 0 interest */\n if (accrualBlockNumber == currentBlockNumber) {\n return uint256(Error.NO_ERROR);\n }\n\n uint256 cashPrior = asCToken().getCash();\n InterestAccrual memory accrual = _accrueInterestHypothetical(currentBlockNumber, cashPrior);\n\n /////////////////////////\n // EFFECTS & INTERACTIONS\n // (No safe failures beyond this point)\n accrualBlockNumber = currentBlockNumber;\n borrowIndex = accrual.borrowIndex;\n totalBorrows = accrual.totalBorrows;\n totalReserves = accrual.totalReserves;\n totalIonicFees = accrual.totalIonicFees;\n totalAdminFees = accrual.totalAdminFees;\n emit AccrueInterest(cashPrior, accrual.interestAccumulated, borrowIndex, totalBorrows);\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Returns the current total borrows plus accrued interest\n * @return The total borrows with interest\n */\n function totalBorrowsCurrent() external view override returns (uint256) {\n if (accrualBlockNumber == block.number) {\n return totalBorrows;\n } else {\n uint256 cashPrior = asCToken().getCash();\n InterestAccrual memory accrual = _accrueInterestHypothetical(block.number, cashPrior);\n return accrual.totalBorrows;\n }\n }\n\n /**\n * @notice Get a snapshot of the account's balances, and the cached exchange rate\n * @dev This is used by comptroller to more efficiently perform liquidity checks.\n * @param account Address of the account to snapshot\n * @return (possible error, token balance, borrow balance, exchange rate mantissa)\n */\n function getAccountSnapshot(address account) external view override returns (uint256, uint256, uint256, uint256) {\n uint256 cTokenBalance = accountTokens[account];\n uint256 borrowBalance;\n uint256 exchangeRateMantissa;\n\n borrowBalance = borrowBalanceCurrent(account);\n\n exchangeRateMantissa = exchangeRateCurrent();\n\n return (uint256(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);\n }\n\n /**\n * @notice calculate the borrowIndex and the account's borrow balance using the fresh borrowIndex\n * @param account The address whose balance should be calculated after recalculating the borrowIndex\n * @return The calculated balance\n */\n function borrowBalanceCurrent(address account) public view override returns (uint256) {\n uint256 _borrowIndex;\n if (accrualBlockNumber == block.number) {\n _borrowIndex = borrowIndex;\n } else {\n uint256 cashPrior = asCToken().getCash();\n InterestAccrual memory accrual = _accrueInterestHypothetical(block.number, cashPrior);\n _borrowIndex = accrual.borrowIndex;\n }\n\n /* Note: we do not assert that the market is up to date */\n MathError mathErr;\n uint256 principalTimesIndex;\n uint256 result;\n\n /* Get borrowBalance and borrowIndex */\n BorrowSnapshot storage borrowSnapshot = accountBorrows[account];\n\n /* If borrowBalance = 0 then borrowIndex is likely also 0.\n * Rather than failing the calculation with a division by 0, we immediately return 0 in this case.\n */\n if (borrowSnapshot.principal == 0) {\n return 0;\n }\n\n /* Calculate new borrow balance using the interest index:\n * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex\n */\n (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, _borrowIndex);\n require(mathErr == MathError.NO_ERROR, \"!mulUInt overflow check failed\");\n\n (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);\n require(mathErr == MathError.NO_ERROR, \"!divUInt overflow check failed\");\n\n return result;\n }\n\n /**\n * @notice Get the underlying balance of the `owner`\n * @param owner The address of the account to query\n * @return The amount of underlying owned by `owner`\n */\n function balanceOfUnderlying(address owner) external view override returns (uint256) {\n Exp memory exchangeRate = Exp({ mantissa: exchangeRateCurrent() });\n (MathError mErr, uint256 balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);\n require(mErr == MathError.NO_ERROR, \"!balance\");\n return balance;\n }\n\n function flash(uint256 amount, bytes calldata data) public override isAuthorized onlyOracleApprovedAllowEOA {\n accrueInterest();\n\n totalBorrows += amount;\n asCToken().selfTransferOut(msg.sender, amount);\n\n IFlashLoanReceiver(msg.sender).receiveFlashLoan(underlying, amount, data);\n\n asCToken().selfTransferIn(msg.sender, amount);\n totalBorrows -= amount;\n\n emit Flash(msg.sender, amount);\n }\n\n /*** Reentrancy Guard ***/\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n */\n modifier nonReentrant(bool localOnly) {\n _beforeNonReentrant(localOnly);\n _;\n _afterNonReentrant(localOnly);\n }\n\n /**\n * @dev Split off from `nonReentrant` to keep contract below the 24 KB size limit.\n * Saves space because function modifier code is \"inlined\" into every function with the modifier).\n * In this specific case, the optimization saves around 1500 bytes of that valuable 24 KB limit.\n */\n function _beforeNonReentrant(bool localOnly) private {\n require(_notEntered, \"re-entered\");\n if (!localOnly) comptroller._beforeNonReentrant();\n _notEntered = false;\n }\n\n /**\n * @dev Split off from `nonReentrant` to keep contract below the 24 KB size limit.\n * Saves space because function modifier code is \"inlined\" into every function with the modifier).\n * In this specific case, the optimization saves around 150 bytes of that valuable 24 KB limit.\n */\n function _afterNonReentrant(bool localOnly) private {\n _notEntered = true; // get a gas-refund post-Istanbul\n if (!localOnly) comptroller._afterNonReentrant();\n }\n\n function asCToken() internal view returns (ICErc20) {\n return ICErc20(address(this));\n }\n\n function multicall(\n bytes[] calldata data\n ) public payable override(CTokenFirstExtensionInterface, Multicall) returns (bytes[] memory results) {\n return Multicall.multicall(data);\n }\n\n function registerInSFS() external returns (uint256) {\n require(hasAdminRights() || msg.sender == address(comptroller), \"!admin\");\n SFSRegister sfsContract = SFSRegister(0x8680CEaBcb9b56913c519c069Add6Bc3494B7020);\n return sfsContract.register(0x8Fba84867Ba458E7c6E2c024D2DE3d0b5C3ea1C2);\n }\n}\n" + }, + "contracts/src/compound/CTokenInterfaces.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IonicComptroller } from \"./ComptrollerInterface.sol\";\nimport { InterestRateModel } from \"./InterestRateModel.sol\";\nimport { ComptrollerV3Storage } from \"./ComptrollerStorage.sol\";\nimport { AddressesProvider } from \"../ionic/AddressesProvider.sol\";\n\nabstract contract CTokenAdminStorage {\n /*\n * Administrator for Ionic\n */\n address payable public ionicAdmin;\n}\n\nabstract contract CErc20Storage is CTokenAdminStorage {\n /**\n * @dev Guard variable for re-entrancy checks\n */\n bool internal _notEntered;\n\n /**\n * @notice EIP-20 token name for this token\n */\n string public name;\n\n /**\n * @notice EIP-20 token symbol for this token\n */\n string public symbol;\n\n /**\n * @notice EIP-20 token decimals for this token\n */\n uint8 public decimals;\n\n /*\n * Maximum borrow rate that can ever be applied (.0005% / block)\n */\n uint256 internal constant borrowRateMaxMantissa = 0.0005e16;\n\n /*\n * Maximum fraction of interest that can be set aside for reserves + fees\n */\n uint256 internal constant reserveFactorPlusFeesMaxMantissa = 1e18;\n\n /**\n * @notice Contract which oversees inter-cToken operations\n */\n IonicComptroller public comptroller;\n\n /**\n * @notice Model which tells what the current interest rate should be\n */\n InterestRateModel public interestRateModel;\n\n /*\n * Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)\n */\n uint256 internal initialExchangeRateMantissa;\n\n /**\n * @notice Fraction of interest currently set aside for admin fees\n */\n uint256 public adminFeeMantissa;\n\n /**\n * @notice Fraction of interest currently set aside for Ionic fees\n */\n uint256 public ionicFeeMantissa;\n\n /**\n * @notice Fraction of interest currently set aside for reserves\n */\n uint256 public reserveFactorMantissa;\n\n /**\n * @notice Block number that interest was last accrued at\n */\n uint256 public accrualBlockNumber;\n\n /**\n * @notice Accumulator of the total earned interest rate since the opening of the market\n */\n uint256 public borrowIndex;\n\n /**\n * @notice Total amount of outstanding borrows of the underlying in this market\n */\n uint256 public totalBorrows;\n\n /**\n * @notice Total amount of reserves of the underlying held in this market\n */\n uint256 public totalReserves;\n\n /**\n * @notice Total amount of admin fees of the underlying held in this market\n */\n uint256 public totalAdminFees;\n\n /**\n * @notice Total amount of Ionic fees of the underlying held in this market\n */\n uint256 public totalIonicFees;\n\n /**\n * @notice Total number of tokens in circulation\n */\n uint256 public totalSupply;\n\n /*\n * Official record of token balances for each account\n */\n mapping(address => uint256) internal accountTokens;\n\n /*\n * Approved token transfer amounts on behalf of others\n */\n mapping(address => mapping(address => uint256)) internal transferAllowances;\n\n /**\n * @notice Container for borrow balance information\n * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action\n * @member interestIndex Global borrowIndex as of the most recent balance-changing action\n */\n struct BorrowSnapshot {\n uint256 principal;\n uint256 interestIndex;\n }\n\n /*\n * Mapping of account addresses to outstanding borrow balances\n */\n mapping(address => BorrowSnapshot) internal accountBorrows;\n\n /*\n * Share of seized collateral that is added to reserves\n */\n uint256 public constant protocolSeizeShareMantissa = 2.8e16; //2.8%\n\n /*\n * Share of seized collateral taken as fees\n */\n uint256 public constant feeSeizeShareMantissa = 1e17; //10%\n\n /**\n * @notice Underlying asset for this CToken\n */\n address public underlying;\n\n /**\n * @notice Addresses Provider\n */\n AddressesProvider public ap;\n}\n\nabstract contract CTokenBaseEvents {\n /* ERC20 */\n\n /**\n * @notice EIP20 Transfer event\n */\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n /*** Admin Events ***/\n\n /**\n * @notice Event emitted when interestRateModel is changed\n */\n event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);\n\n /**\n * @notice Event emitted when the reserve factor is changed\n */\n event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);\n\n /**\n * @notice Event emitted when the admin fee is changed\n */\n event NewAdminFee(uint256 oldAdminFeeMantissa, uint256 newAdminFeeMantissa);\n\n /**\n * @notice Event emitted when the Ionic fee is changed\n */\n event NewIonicFee(uint256 oldIonicFeeMantissa, uint256 newIonicFeeMantissa);\n\n /**\n * @notice EIP20 Approval event\n */\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /**\n * @notice Event emitted when interest is accrued\n */\n event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);\n}\n\nabstract contract CTokenFirstExtensionEvents is CTokenBaseEvents {\n event Flash(address receiver, uint256 amount);\n}\n\nabstract contract CTokenSecondExtensionEvents is CTokenBaseEvents {\n /*** Market Events ***/\n\n /**\n * @notice Event emitted when tokens are minted\n */\n event Mint(address minter, uint256 mintAmount, uint256 mintTokens);\n\n /**\n * @notice Event emitted when tokens are redeemed\n */\n event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);\n\n /**\n * @notice Event emitted when underlying is borrowed\n */\n event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);\n\n /**\n * @notice Event emitted when a borrow is repaid\n */\n event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows);\n\n /**\n * @notice Event emitted when a borrow is liquidated\n */\n event LiquidateBorrow(\n address liquidator,\n address borrower,\n uint256 repayAmount,\n address cTokenCollateral,\n uint256 seizeTokens\n );\n\n /**\n * @notice Event emitted when the reserves are added\n */\n event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);\n\n /**\n * @notice Event emitted when the reserves are reduced\n */\n event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);\n}\n\ninterface CTokenFirstExtensionInterface {\n /*** User Interface ***/\n\n function transfer(address dst, uint256 amount) external returns (bool);\n\n function transferFrom(\n address src,\n address dst,\n uint256 amount\n ) external returns (bool);\n\n function approve(address spender, uint256 amount) external returns (bool);\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function balanceOf(address owner) external view returns (uint256);\n\n /*** Admin Functions ***/\n\n function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);\n\n function _setAdminFee(uint256 newAdminFeeMantissa) external returns (uint256);\n\n function _setInterestRateModel(InterestRateModel newInterestRateModel) external returns (uint256);\n\n function getAccountSnapshot(address account)\n external\n view\n returns (\n uint256,\n uint256,\n uint256,\n uint256\n );\n\n function borrowRatePerBlock() external view returns (uint256);\n\n function supplyRatePerBlock() external view returns (uint256);\n\n function exchangeRateCurrent() external view returns (uint256);\n\n function accrueInterest() external returns (uint256);\n\n function totalBorrowsCurrent() external view returns (uint256);\n\n function borrowBalanceCurrent(address account) external view returns (uint256);\n\n function getTotalUnderlyingSupplied() external view returns (uint256);\n\n function balanceOfUnderlying(address owner) external view returns (uint256);\n\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\n\n function flash(uint256 amount, bytes calldata data) external;\n\n function supplyRatePerBlockAfterDeposit(uint256 mintAmount) external view returns (uint256);\n\n function supplyRatePerBlockAfterWithdraw(uint256 withdrawAmount) external view returns (uint256);\n\n function borrowRatePerBlockAfterBorrow(uint256 borrowAmount) external view returns (uint256);\n\n function registerInSFS() external returns (uint256);\n}\n\ninterface CTokenSecondExtensionInterface {\n function mint(uint256 mintAmount) external returns (uint256);\n\n function redeem(uint256 redeemTokens) external returns (uint256);\n\n function redeemUnderlying(uint256 redeemAmount) external returns (uint256);\n\n function borrow(uint256 borrowAmount) external returns (uint256);\n\n function repayBorrow(uint256 repayAmount) external returns (uint256);\n\n function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);\n\n function liquidateBorrow(\n address borrower,\n uint256 repayAmount,\n address cTokenCollateral\n ) external returns (uint256);\n\n function getCash() external view returns (uint256);\n\n function seize(\n address liquidator,\n address borrower,\n uint256 seizeTokens\n ) external returns (uint256);\n\n /*** Admin Functions ***/\n\n function _withdrawAdminFees(uint256 withdrawAmount) external returns (uint256);\n\n function _withdrawIonicFees(uint256 withdrawAmount) external returns (uint256);\n\n function selfTransferOut(address to, uint256 amount) external;\n\n function selfTransferIn(address from, uint256 amount) external returns (uint256);\n}\n\ninterface CDelegatorInterface {\n function implementation() external view returns (address);\n\n /**\n * @notice Called by the admin to update the implementation of the delegator\n * @param implementation_ The address of the new implementation for delegation\n * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation\n */\n function _setImplementationSafe(address implementation_, bytes calldata becomeImplementationData) external;\n\n /**\n * @dev upgrades the implementation if necessary\n */\n function _upgrade() external;\n}\n\ninterface CDelegateInterface {\n /**\n * @notice Called by the delegator on a delegate to initialize it for duty\n * @dev Should revert if any issues arise which make it unfit for delegation\n * @param data The encoded bytes data for any initialization\n */\n function _becomeImplementation(bytes calldata data) external;\n\n function delegateType() external pure returns (uint8);\n\n function contractType() external pure returns (string memory);\n}\n\nabstract contract CErc20AdminBase is CErc20Storage {\n /**\n * @notice Returns a boolean indicating if the sender has admin rights\n */\n function hasAdminRights() internal view returns (bool) {\n ComptrollerV3Storage comptrollerStorage = ComptrollerV3Storage(address(comptroller));\n return\n (msg.sender == comptrollerStorage.admin() && comptrollerStorage.adminHasRights()) ||\n (msg.sender == address(ionicAdmin) && comptrollerStorage.ionicAdminHasRights());\n }\n}\n\nabstract contract CErc20FirstExtensionBase is\n CErc20AdminBase,\n CTokenFirstExtensionEvents,\n CTokenFirstExtensionInterface\n{}\n\nabstract contract CTokenSecondExtensionBase is\n CErc20AdminBase,\n CTokenSecondExtensionEvents,\n CTokenSecondExtensionInterface,\n CDelegateInterface\n{}\n\nabstract contract CErc20DelegatorBase is CErc20AdminBase, CTokenSecondExtensionEvents, CDelegatorInterface {}\n\ninterface CErc20StorageInterface {\n function admin() external view returns (address);\n\n function adminHasRights() external view returns (bool);\n\n function ionicAdmin() external view returns (address);\n\n function ionicAdminHasRights() external view returns (bool);\n\n function comptroller() external view returns (IonicComptroller);\n\n function name() external view returns (string memory);\n\n function symbol() external view returns (string memory);\n\n function decimals() external view returns (uint8);\n\n function totalSupply() external view returns (uint256);\n\n function adminFeeMantissa() external view returns (uint256);\n\n function ionicFeeMantissa() external view returns (uint256);\n\n function reserveFactorMantissa() external view returns (uint256);\n\n function protocolSeizeShareMantissa() external view returns (uint256);\n\n function feeSeizeShareMantissa() external view returns (uint256);\n\n function totalReserves() external view returns (uint256);\n\n function totalAdminFees() external view returns (uint256);\n\n function totalIonicFees() external view returns (uint256);\n\n function totalBorrows() external view returns (uint256);\n\n function accrualBlockNumber() external view returns (uint256);\n\n function underlying() external view returns (address);\n\n function borrowIndex() external view returns (uint256);\n\n function interestRateModel() external view returns (address);\n}\n\ninterface CErc20PluginStorageInterface is CErc20StorageInterface {\n function plugin() external view returns (address);\n}\n\ninterface CErc20PluginRewardsInterface is CErc20PluginStorageInterface {\n function approve(address, address) external;\n}\n\ninterface ICErc20 is\n CErc20StorageInterface,\n CTokenSecondExtensionInterface,\n CTokenFirstExtensionInterface,\n CDelegatorInterface,\n CDelegateInterface\n{}\n\ninterface ICErc20Plugin is CErc20PluginStorageInterface, ICErc20 {\n function _updatePlugin(address _plugin) external;\n}\n\ninterface ICErc20PluginRewards is CErc20PluginRewardsInterface, ICErc20 {}\n" + }, + "contracts/src/compound/CTokenOracleProtected.sol": { + "content": "// SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.22;\n\nimport { CErc20Storage } from \"./CTokenInterfaces.sol\";\nimport { IHypernativeOracle } from \"../external/hypernative/interfaces/IHypernativeOracle.sol\";\n\ncontract CTokenOracleProtected is CErc20Storage {\n error InteractionNotAllowed();\n error CallerIsNotEOA();\n\n modifier onlyOracleApproved() {\n address oracleAddress = ap.getAddress(\"HYPERNATIVE_ORACLE\");\n\n if (oracleAddress == address(0)) {\n _;\n return;\n }\n\n IHypernativeOracle oracle = IHypernativeOracle(oracleAddress);\n oracle.validateForbiddenContextInteraction(tx.origin, msg.sender);\n _;\n }\n\n modifier onlyOracleApprovedAllowEOA() {\n address oracleAddress = ap.getAddress(\"HYPERNATIVE_ORACLE\");\n\n if (oracleAddress == address(0)) {\n _;\n return;\n }\n\n IHypernativeOracle oracle = IHypernativeOracle(oracleAddress);\n oracle.validateBlacklistedAccountInteraction(msg.sender);\n if (tx.origin == msg.sender) {\n _;\n return;\n }\n\n oracle.validateForbiddenContextInteraction(tx.origin, msg.sender);\n _;\n }\n\n modifier onlyNotBlacklistedEOA() {\n address oracleAddress = ap.getAddress(\"HYPERNATIVE_ORACLE\");\n\n if (oracleAddress == address(0)) {\n _;\n return;\n }\n\n IHypernativeOracle oracle = IHypernativeOracle(oracleAddress);\n if (msg.sender != tx.origin) {\n revert CallerIsNotEOA();\n }\n oracle.validateBlacklistedAccountInteraction(msg.sender);\n _;\n }\n}\n" + }, + "contracts/src/compound/EIP20Interface.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\n/**\n * @title ERC 20 Token Standard Interface\n * https://eips.ethereum.org/EIPS/eip-20\n */\ninterface EIP20Interface {\n function name() external view returns (string memory);\n\n function symbol() external view returns (string memory);\n\n function decimals() external view returns (uint8);\n\n /**\n * @notice Get the total number of tokens in circulation\n * @return uint256 The supply of tokens\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @notice Gets the balance of the specified address\n * @param owner The address from which the balance will be retrieved\n * @return balance uint256 The balance\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n * @return success bool Whether or not the transfer succeeded\n */\n function transfer(address dst, uint256 amount) external returns (bool success);\n\n /**\n * @notice Transfer `amount` tokens from `src` to `dst`\n * @param src The address of the source account\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n * @return success bool Whether or not the transfer succeeded\n */\n function transferFrom(\n address src,\n address dst,\n uint256 amount\n ) external returns (bool success);\n\n /**\n * @notice Approve `spender` to transfer up to `amount` from `src`\n * @dev This will overwrite the approval amount for `spender`\n * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n * @param spender The address of the account which may transfer tokens\n * @param amount The number of tokens that are approved (-1 means infinite)\n * @return success bool Whether or not the approval succeeded\n */\n function approve(address spender, uint256 amount) external returns (bool success);\n\n /**\n * @notice Get the current allowance from `owner` for `spender`\n * @param owner The address of the account which owns the tokens to be spent\n * @param spender The address of the account which may transfer tokens\n * @return remaining uint256 The number of tokens allowed to be spent (-1 means infinite)\n */\n function allowance(address owner, address spender) external view returns (uint256 remaining);\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n}\n" + }, + "contracts/src/compound/EIP20NonStandardInterface.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\n/**\n * @title EIP20NonStandardInterface\n * @dev Version of ERC20 with no return values for `transfer` and `transferFrom`\n * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca\n */\ninterface EIP20NonStandardInterface {\n /**\n * @notice Get the total number of tokens in circulation\n * @return The supply of tokens\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @notice Gets the balance of the specified address\n * @param owner The address from which the balance will be retrieved\n * @return balance uint256 The balance\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n ///\n /// !!!!!!!!!!!!!!\n /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification\n /// !!!!!!!!!!!!!!\n ///\n\n /**\n * @notice Transfer `amount` tokens from `msg.sender` to `dst`\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n */\n function transfer(address dst, uint256 amount) external;\n\n ///\n /// !!!!!!!!!!!!!!\n /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification\n /// !!!!!!!!!!!!!!\n ///\n\n /**\n * @notice Transfer `amount` tokens from `src` to `dst`\n * @param src The address of the source account\n * @param dst The address of the destination account\n * @param amount The number of tokens to transfer\n */\n function transferFrom(\n address src,\n address dst,\n uint256 amount\n ) external;\n\n /**\n * @notice Approve `spender` to transfer up to `amount` from `src`\n * @dev This will overwrite the approval amount for `spender`\n * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\n * @param spender The address of the account which may transfer tokens\n * @param amount The number of tokens that are approved\n * @return success bool Whether or not the approval succeeded\n */\n function approve(address spender, uint256 amount) external returns (bool success);\n\n /**\n * @notice Get the current allowance from `owner` for `spender`\n * @param owner The address of the account which owns the tokens to be spent\n * @param spender The address of the account which may transfer tokens\n * @return remaining uint256 The number of tokens allowed to be spent\n */\n function allowance(address owner, address spender) external view returns (uint256 remaining);\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n}\n" + }, + "contracts/src/compound/ErrorReporter.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\ncontract ComptrollerErrorReporter {\n enum Error {\n NO_ERROR,\n UNAUTHORIZED,\n COMPTROLLER_MISMATCH,\n INSUFFICIENT_SHORTFALL,\n INSUFFICIENT_LIQUIDITY,\n INVALID_CLOSE_FACTOR,\n INVALID_COLLATERAL_FACTOR,\n INVALID_LIQUIDATION_INCENTIVE,\n MARKET_NOT_LISTED,\n MARKET_ALREADY_LISTED,\n MATH_ERROR,\n NONZERO_BORROW_BALANCE,\n PRICE_ERROR,\n REJECTION,\n SNAPSHOT_ERROR,\n TOO_MANY_ASSETS,\n TOO_MUCH_REPAY,\n SUPPLIER_NOT_WHITELISTED,\n BORROW_BELOW_MIN,\n SUPPLY_ABOVE_MAX,\n NONZERO_TOTAL_SUPPLY\n }\n\n enum FailureInfo {\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\n ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,\n ADD_REWARDS_DISTRIBUTOR_OWNER_CHECK,\n EXIT_MARKET_BALANCE_OWED,\n EXIT_MARKET_REJECTION,\n TOGGLE_ADMIN_RIGHTS_OWNER_CHECK,\n TOGGLE_AUTO_IMPLEMENTATIONS_ENABLED_OWNER_CHECK,\n SET_CLOSE_FACTOR_OWNER_CHECK,\n SET_CLOSE_FACTOR_VALIDATION,\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\n SET_COLLATERAL_FACTOR_NO_EXISTS,\n SET_COLLATERAL_FACTOR_VALIDATION,\n SET_COLLATERAL_FACTOR_WITHOUT_PRICE,\n SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,\n SET_LIQUIDATION_INCENTIVE_VALIDATION,\n SET_PENDING_ADMIN_OWNER_CHECK,\n SET_PENDING_IMPLEMENTATION_CONTRACT_CHECK,\n SET_PENDING_IMPLEMENTATION_OWNER_CHECK,\n SET_PRICE_ORACLE_OWNER_CHECK,\n SET_WHITELIST_ENFORCEMENT_OWNER_CHECK,\n SET_WHITELIST_STATUS_OWNER_CHECK,\n SUPPORT_MARKET_EXISTS,\n SUPPORT_MARKET_OWNER_CHECK,\n SET_PAUSE_GUARDIAN_OWNER_CHECK,\n UNSUPPORT_MARKET_OWNER_CHECK,\n UNSUPPORT_MARKET_DOES_NOT_EXIST,\n UNSUPPORT_MARKET_IN_USE\n }\n\n /**\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\n **/\n event Failure(uint256 error, uint256 info, uint256 detail);\n\n /**\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\n */\n function fail(Error err, FailureInfo info) internal returns (uint256) {\n emit Failure(uint256(err), uint256(info), 0);\n\n return uint256(err);\n }\n\n /**\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\n */\n function failOpaque(\n Error err,\n FailureInfo info,\n uint256 opaqueError\n ) internal returns (uint256) {\n emit Failure(uint256(err), uint256(info), opaqueError);\n\n return uint256(err);\n }\n}\n\ncontract TokenErrorReporter {\n enum Error {\n NO_ERROR,\n UNAUTHORIZED,\n BAD_INPUT,\n COMPTROLLER_REJECTION,\n COMPTROLLER_CALCULATION_ERROR,\n INTEREST_RATE_MODEL_ERROR,\n INVALID_ACCOUNT_PAIR,\n INVALID_CLOSE_AMOUNT_REQUESTED,\n INVALID_COLLATERAL_FACTOR,\n MATH_ERROR,\n MARKET_NOT_FRESH,\n MARKET_NOT_LISTED,\n TOKEN_INSUFFICIENT_ALLOWANCE,\n TOKEN_INSUFFICIENT_BALANCE,\n TOKEN_INSUFFICIENT_CASH,\n TOKEN_TRANSFER_IN_FAILED,\n TOKEN_TRANSFER_OUT_FAILED,\n UTILIZATION_ABOVE_MAX\n }\n\n /*\n * Note: FailureInfo (but not Error) is kept in alphabetical order\n * This is because FailureInfo grows significantly faster, and\n * the order of Error has some meaning, while the order of FailureInfo\n * is entirely arbitrary.\n */\n enum FailureInfo {\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\n ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,\n ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,\n ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,\n ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,\n ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,\n ACCRUE_INTEREST_NEW_TOTAL_IONIC_FEES_CALCULATION_FAILED,\n ACCRUE_INTEREST_NEW_TOTAL_ADMIN_FEES_CALCULATION_FAILED,\n ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,\n BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\n BORROW_ACCRUE_INTEREST_FAILED,\n BORROW_CASH_NOT_AVAILABLE,\n BORROW_FRESHNESS_CHECK,\n BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\n BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\n BORROW_MARKET_NOT_LISTED,\n BORROW_COMPTROLLER_REJECTION,\n LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,\n LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,\n LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,\n LIQUIDATE_COMPTROLLER_REJECTION,\n LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,\n LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,\n LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,\n LIQUIDATE_FRESHNESS_CHECK,\n LIQUIDATE_LIQUIDATOR_IS_BORROWER,\n LIQUIDATE_REPAY_BORROW_FRESH_FAILED,\n LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,\n LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,\n LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,\n LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,\n LIQUIDATE_SEIZE_TOO_MUCH,\n MINT_ACCRUE_INTEREST_FAILED,\n MINT_COMPTROLLER_REJECTION,\n MINT_EXCHANGE_CALCULATION_FAILED,\n MINT_EXCHANGE_RATE_READ_FAILED,\n MINT_FRESHNESS_CHECK,\n MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\n MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\n MINT_TRANSFER_IN_FAILED,\n MINT_TRANSFER_IN_NOT_POSSIBLE,\n NEW_UTILIZATION_RATE_ABOVE_MAX,\n REDEEM_ACCRUE_INTEREST_FAILED,\n REDEEM_COMPTROLLER_REJECTION,\n REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,\n REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,\n REDEEM_EXCHANGE_RATE_READ_FAILED,\n REDEEM_FRESHNESS_CHECK,\n REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\n REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\n REDEEM_TRANSFER_OUT_NOT_POSSIBLE,\n WITHDRAW_IONIC_FEES_ACCRUE_INTEREST_FAILED,\n WITHDRAW_IONIC_FEES_CASH_NOT_AVAILABLE,\n WITHDRAW_IONIC_FEES_FRESH_CHECK,\n WITHDRAW_IONIC_FEES_VALIDATION,\n WITHDRAW_ADMIN_FEES_ACCRUE_INTEREST_FAILED,\n WITHDRAW_ADMIN_FEES_CASH_NOT_AVAILABLE,\n WITHDRAW_ADMIN_FEES_FRESH_CHECK,\n WITHDRAW_ADMIN_FEES_VALIDATION,\n REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,\n REDUCE_RESERVES_ADMIN_CHECK,\n REDUCE_RESERVES_CASH_NOT_AVAILABLE,\n REDUCE_RESERVES_FRESH_CHECK,\n REDUCE_RESERVES_VALIDATION,\n REPAY_BEHALF_ACCRUE_INTEREST_FAILED,\n REPAY_BORROW_ACCRUE_INTEREST_FAILED,\n REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\n REPAY_BORROW_COMPTROLLER_REJECTION,\n REPAY_BORROW_FRESHNESS_CHECK,\n REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\n REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\n REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\n SET_COLLATERAL_FACTOR_VALIDATION,\n SET_COMPTROLLER_OWNER_CHECK,\n SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,\n SET_INTEREST_RATE_MODEL_FRESH_CHECK,\n SET_INTEREST_RATE_MODEL_OWNER_CHECK,\n TOGGLE_ADMIN_RIGHTS_OWNER_CHECK,\n SET_PENDING_ADMIN_OWNER_CHECK,\n SET_ADMIN_FEE_ACCRUE_INTEREST_FAILED,\n SET_ADMIN_FEE_ADMIN_CHECK,\n SET_ADMIN_FEE_FRESH_CHECK,\n SET_ADMIN_FEE_BOUNDS_CHECK,\n SET_IONIC_FEE_ACCRUE_INTEREST_FAILED,\n SET_IONIC_FEE_FRESH_CHECK,\n SET_IONIC_FEE_BOUNDS_CHECK,\n SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,\n SET_RESERVE_FACTOR_ADMIN_CHECK,\n SET_RESERVE_FACTOR_FRESH_CHECK,\n SET_RESERVE_FACTOR_BOUNDS_CHECK,\n TRANSFER_COMPTROLLER_REJECTION,\n TRANSFER_NOT_ALLOWED,\n TRANSFER_NOT_ENOUGH,\n TRANSFER_TOO_MUCH,\n ADD_RESERVES_ACCRUE_INTEREST_FAILED,\n ADD_RESERVES_FRESH_CHECK,\n ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE\n }\n\n /**\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\n **/\n event Failure(uint256 error, uint256 info, uint256 detail);\n\n /**\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\n */\n function fail(Error err, FailureInfo info) internal returns (uint256) {\n emit Failure(uint256(err), uint256(info), 0);\n\n return uint256(err);\n }\n\n /**\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\n */\n function failOpaque(\n Error err,\n FailureInfo info,\n uint256 opaqueError\n ) internal returns (uint256) {\n emit Failure(uint256(err), uint256(info), opaqueError);\n\n return err == Error.COMPTROLLER_REJECTION ? 1000 + opaqueError : uint256(err);\n }\n}\n" + }, + "contracts/src/compound/Exponential.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./CarefulMath.sol\";\nimport \"./ExponentialNoError.sol\";\n\n/**\n * @title Exponential module for storing fixed-precision decimals\n * @author Compound\n * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError\n * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.\n * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:\n * `Exp({mantissa: 5100000000000000000})`.\n */\ncontract Exponential is CarefulMath, ExponentialNoError {\n /**\n * @dev Creates an exponential from numerator and denominator values.\n * Note: Returns an error if (`num` * 10e18) > MAX_INT,\n * or if `denom` is zero.\n */\n function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) {\n (MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale);\n if (err0 != MathError.NO_ERROR) {\n return (err0, Exp({ mantissa: 0 }));\n }\n\n (MathError err1, uint256 rational) = divUInt(scaledNumerator, denom);\n if (err1 != MathError.NO_ERROR) {\n return (err1, Exp({ mantissa: 0 }));\n }\n\n return (MathError.NO_ERROR, Exp({ mantissa: rational }));\n }\n\n /**\n * @dev Adds two exponentials, returning a new exponential.\n */\n function addExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {\n (MathError error, uint256 result) = addUInt(a.mantissa, b.mantissa);\n\n return (error, Exp({ mantissa: result }));\n }\n\n /**\n * @dev Subtracts two exponentials, returning a new exponential.\n */\n function subExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {\n (MathError error, uint256 result) = subUInt(a.mantissa, b.mantissa);\n\n return (error, Exp({ mantissa: result }));\n }\n\n /**\n * @dev Multiply an Exp by a scalar, returning a new Exp.\n */\n function mulScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {\n (MathError err0, uint256 scaledMantissa) = mulUInt(a.mantissa, scalar);\n if (err0 != MathError.NO_ERROR) {\n return (err0, Exp({ mantissa: 0 }));\n }\n\n return (MathError.NO_ERROR, Exp({ mantissa: scaledMantissa }));\n }\n\n /**\n * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.\n */\n function mulScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (MathError, uint256) {\n (MathError err, Exp memory product) = mulScalar(a, scalar);\n if (err != MathError.NO_ERROR) {\n return (err, 0);\n }\n\n return (MathError.NO_ERROR, truncate(product));\n }\n\n /**\n * @dev Divide an Exp by a scalar, returning a new Exp.\n */\n function divScalar(Exp memory a, uint256 scalar) internal pure returns (MathError, Exp memory) {\n (MathError err0, uint256 descaledMantissa) = divUInt(a.mantissa, scalar);\n if (err0 != MathError.NO_ERROR) {\n return (err0, Exp({ mantissa: 0 }));\n }\n\n return (MathError.NO_ERROR, Exp({ mantissa: descaledMantissa }));\n }\n\n /**\n * @dev Divide a scalar by an Exp, returning a new Exp.\n */\n function divScalarByExp(uint256 scalar, Exp memory divisor) internal pure returns (MathError, Exp memory) {\n /*\n We are doing this as:\n getExp(mulUInt(expScale, scalar), divisor.mantissa)\n\n How it works:\n Exp = a / b;\n Scalar = s;\n `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`\n */\n (MathError err0, uint256 numerator) = mulUInt(expScale, scalar);\n if (err0 != MathError.NO_ERROR) {\n return (err0, Exp({ mantissa: 0 }));\n }\n return getExp(numerator, divisor.mantissa);\n }\n\n /**\n * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.\n */\n function divScalarByExpTruncate(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) {\n (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);\n if (err != MathError.NO_ERROR) {\n return (err, 0);\n }\n\n return (MathError.NO_ERROR, truncate(fraction));\n }\n\n /**\n * @dev Multiplies two exponentials, returning a new exponential.\n */\n function mulExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {\n (MathError err0, uint256 doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);\n if (err0 != MathError.NO_ERROR) {\n return (err0, Exp({ mantissa: 0 }));\n }\n\n // We add half the scale before dividing so that we get rounding instead of truncation.\n // See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717\n // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.\n (MathError err1, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);\n if (err1 != MathError.NO_ERROR) {\n return (err1, Exp({ mantissa: 0 }));\n }\n\n (MathError err2, uint256 product) = divUInt(doubleScaledProductWithHalfScale, expScale);\n // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.\n assert(err2 == MathError.NO_ERROR);\n\n return (MathError.NO_ERROR, Exp({ mantissa: product }));\n }\n\n /**\n * @dev Multiplies two exponentials given their mantissas, returning a new exponential.\n */\n function mulExp(uint256 a, uint256 b) internal pure returns (MathError, Exp memory) {\n return mulExp(Exp({ mantissa: a }), Exp({ mantissa: b }));\n }\n\n /**\n * @dev Multiplies three exponentials, returning a new exponential.\n */\n function mulExp3(\n Exp memory a,\n Exp memory b,\n Exp memory c\n ) internal pure returns (MathError, Exp memory) {\n (MathError err, Exp memory ab) = mulExp(a, b);\n if (err != MathError.NO_ERROR) {\n return (err, ab);\n }\n return mulExp(ab, c);\n }\n\n /**\n * @dev Divides two exponentials, returning a new exponential.\n * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,\n * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)\n */\n function divExp(Exp memory a, Exp memory b) internal pure returns (MathError, Exp memory) {\n return getExp(a.mantissa, b.mantissa);\n }\n}\n" + }, + "contracts/src/compound/ExponentialNoError.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\n/**\n * @title Exponential module for storing fixed-precision decimals\n * @author Compound\n * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.\n * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:\n * `Exp({mantissa: 5100000000000000000})`.\n */\ncontract ExponentialNoError {\n uint256 constant expScale = 1e18;\n uint256 constant doubleScale = 1e36;\n uint256 constant halfExpScale = expScale / 2;\n uint256 constant mantissaOne = expScale;\n\n struct Exp {\n uint256 mantissa;\n }\n\n struct Double {\n uint256 mantissa;\n }\n\n /**\n * @dev Truncates the given exp to a whole number value.\n * For example, truncate(Exp{mantissa: 15 * expScale}) = 15\n */\n function truncate(Exp memory exp) internal pure returns (uint256) {\n // Note: We are not using careful math here as we're performing a division that cannot fail\n return exp.mantissa / expScale;\n }\n\n /**\n * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.\n */\n function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) {\n Exp memory product = mul_(a, scalar);\n return truncate(product);\n }\n\n /**\n * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.\n */\n function mul_ScalarTruncateAddUInt(\n Exp memory a,\n uint256 scalar,\n uint256 addend\n ) internal pure returns (uint256) {\n Exp memory product = mul_(a, scalar);\n return add_(truncate(product), addend);\n }\n\n /**\n * @dev Checks if first Exp is less than second Exp.\n */\n function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {\n return left.mantissa < right.mantissa;\n }\n\n /**\n * @dev Checks if left Exp <= right Exp.\n */\n function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) {\n return left.mantissa <= right.mantissa;\n }\n\n /**\n * @dev Checks if left Exp > right Exp.\n */\n function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {\n return left.mantissa > right.mantissa;\n }\n\n /**\n * @dev returns true if Exp is exactly zero\n */\n function isZeroExp(Exp memory value) internal pure returns (bool) {\n return value.mantissa == 0;\n }\n\n function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) {\n require(n < 2**224, errorMessage);\n return uint224(n);\n }\n\n function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {\n require(n < 2**32, errorMessage);\n return uint32(n);\n }\n\n function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {\n return Exp({ mantissa: add_(a.mantissa, b.mantissa) });\n }\n\n function add_(Double memory a, Double memory b) internal pure returns (Double memory) {\n return Double({ mantissa: add_(a.mantissa, b.mantissa) });\n }\n\n function add_(uint256 a, uint256 b) internal pure returns (uint256) {\n return add_(a, b, \"addition overflow\");\n }\n\n function add_(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, errorMessage);\n return c;\n }\n\n function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {\n return Exp({ mantissa: sub_(a.mantissa, b.mantissa) });\n }\n\n function sub_(Double memory a, Double memory b) internal pure returns (Double memory) {\n return Double({ mantissa: sub_(a.mantissa, b.mantissa) });\n }\n\n function sub_(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub_(a, b, \"subtraction underflow\");\n }\n\n function sub_(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n return a - b;\n }\n\n function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {\n return Exp({ mantissa: mul_(a.mantissa, b.mantissa) / expScale });\n }\n\n function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {\n return Exp({ mantissa: mul_(a.mantissa, b) });\n }\n\n function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {\n return mul_(a, b.mantissa) / expScale;\n }\n\n function mul_(Double memory a, Double memory b) internal pure returns (Double memory) {\n return Double({ mantissa: mul_(a.mantissa, b.mantissa) / doubleScale });\n }\n\n function mul_(Double memory a, uint256 b) internal pure returns (Double memory) {\n return Double({ mantissa: mul_(a.mantissa, b) });\n }\n\n function mul_(uint256 a, Double memory b) internal pure returns (uint256) {\n return mul_(a, b.mantissa) / doubleScale;\n }\n\n function mul_(uint256 a, uint256 b) internal pure returns (uint256) {\n return mul_(a, b, \"multiplication overflow\");\n }\n\n function mul_(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n if (a == 0 || b == 0) {\n return 0;\n }\n uint256 c = a * b;\n require(c / a == b, errorMessage);\n return c;\n }\n\n function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {\n return Exp({ mantissa: div_(mul_(a.mantissa, expScale), b.mantissa) });\n }\n\n function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {\n return Exp({ mantissa: div_(a.mantissa, b) });\n }\n\n function div_(uint256 a, Exp memory b) internal pure returns (uint256) {\n return div_(mul_(a, expScale), b.mantissa);\n }\n\n function div_(Double memory a, Double memory b) internal pure returns (Double memory) {\n return Double({ mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa) });\n }\n\n function div_(Double memory a, uint256 b) internal pure returns (Double memory) {\n return Double({ mantissa: div_(a.mantissa, b) });\n }\n\n function div_(uint256 a, Double memory b) internal pure returns (uint256) {\n return div_(mul_(a, doubleScale), b.mantissa);\n }\n\n function div_(uint256 a, uint256 b) internal pure returns (uint256) {\n return div_(a, b, \"divide by zero\");\n }\n\n function div_(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n return a / b;\n }\n\n function fraction(uint256 a, uint256 b) internal pure returns (Double memory) {\n return Double({ mantissa: div_(mul_(a, doubleScale), b) });\n }\n}\n" + }, + "contracts/src/compound/IERC4626.sol": { + "content": "pragma solidity >=0.8.0;\npragma experimental ABIEncoderV2;\n\nimport { EIP20Interface } from \"./EIP20Interface.sol\";\n\ninterface IERC4626 is EIP20Interface {\n /*----------------------------------------------------------------\n Events\n ----------------------------------------------------------------*/\n\n event Deposit(address indexed from, address indexed to, uint256 value);\n\n event Withdraw(address indexed from, address indexed to, uint256 value);\n\n /*----------------------------------------------------------------\n Mutable Functions\n ----------------------------------------------------------------*/\n\n /**\n @notice Deposit a specific amount of underlying tokens.\n @param underlyingAmount The amount of the underlying token to deposit.\n @param to The address to receive shares corresponding to the deposit\n @return shares The shares in the vault credited to `to`\n */\n function deposit(uint256 underlyingAmount, address to) external returns (uint256 shares);\n\n /**\n @notice Mint an exact amount of shares for a variable amount of underlying tokens.\n @param shareAmount The amount of vault shares to mint.\n @param to The address to receive shares corresponding to the mint.\n @return underlyingAmount The amount of the underlying tokens deposited from the mint call.\n */\n function mint(uint256 shareAmount, address to) external returns (uint256 underlyingAmount);\n\n /**\n @notice Withdraw a specific amount of underlying tokens.\n @param underlyingAmount The amount of the underlying token to withdraw.\n @param to The address to receive underlying corresponding to the withdrawal.\n @param from The address to burn shares from corresponding to the withdrawal.\n @return shares The shares in the vault burned from sender\n */\n function withdraw(\n uint256 underlyingAmount,\n address to,\n address from\n ) external returns (uint256 shares);\n\n /**\n @notice Redeem a specific amount of shares for underlying tokens.\n @param shareAmount The amount of shares to redeem.\n @param to The address to receive underlying corresponding to the redemption.\n @param from The address to burn shares from corresponding to the redemption.\n @return value The underlying amount transferred to `to`.\n */\n function redeem(\n uint256 shareAmount,\n address to,\n address from\n ) external returns (uint256 value);\n\n /*----------------------------------------------------------------\n View Functions\n ----------------------------------------------------------------*/\n /** \n @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.\n @return the address of the asset\n */\n function asset() external view returns (address);\n\n /** \n @notice Returns a user's Vault balance in underlying tokens.\n @param user The user to get the underlying balance of.\n @return balance The user's Vault balance in underlying tokens.\n */\n function balanceOfUnderlying(address user) external view returns (uint256 balance);\n\n /** \n @notice Calculates the total amount of underlying tokens the Vault manages.\n @return The total amount of underlying tokens the Vault manages.\n */\n function totalAssets() external view returns (uint256);\n\n /** \n @notice Returns the value in underlying terms of one vault token. \n */\n function exchangeRate() external view returns (uint256);\n\n /**\n @notice Returns the amount of vault tokens that would be obtained if depositing a given amount of underlying tokens in a `deposit` call.\n @param underlyingAmount the input amount of underlying tokens\n @return shareAmount the corresponding amount of shares out from a deposit call with `underlyingAmount` in\n */\n function previewDeposit(uint256 underlyingAmount) external view returns (uint256 shareAmount);\n\n /**\n @notice Returns the amount of underlying tokens that would be deposited if minting a given amount of shares in a `mint` call.\n @param shareAmount the amount of shares from a mint call.\n @return underlyingAmount the amount of underlying tokens corresponding to the mint call\n */\n function previewMint(uint256 shareAmount) external view returns (uint256 underlyingAmount);\n\n /**\n @notice Returns the amount of vault tokens that would be burned if withdrawing a given amount of underlying tokens in a `withdraw` call.\n @param underlyingAmount the input amount of underlying tokens\n @return shareAmount the corresponding amount of shares out from a withdraw call with `underlyingAmount` in\n */\n function previewWithdraw(uint256 underlyingAmount) external view returns (uint256 shareAmount);\n\n /**\n @notice Returns the amount of underlying tokens that would be obtained if redeeming a given amount of shares in a `redeem` call.\n @param shareAmount the amount of shares from a redeem call.\n @return underlyingAmount the amount of underlying tokens corresponding to the redeem call\n */\n function previewRedeem(uint256 shareAmount) external view returns (uint256 underlyingAmount);\n}\n" + }, + "contracts/src/compound/IFeeDistributor.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../ionic/AuthoritiesRegistry.sol\";\n\ninterface IFeeDistributor {\n function minBorrowEth() external view returns (uint256);\n\n function maxUtilizationRate() external view returns (uint256);\n\n function interestFeeRate() external view returns (uint256);\n\n function latestComptrollerImplementation(address oldImplementation) external view returns (address);\n\n function latestCErc20Delegate(uint8 delegateType)\n external\n view\n returns (address cErc20Delegate, bytes memory becomeImplementationData);\n\n function latestPluginImplementation(address oldImplementation) external view returns (address);\n\n function getComptrollerExtensions(address comptroller) external view returns (address[] memory);\n\n function getCErc20DelegateExtensions(address cErc20Delegate) external view returns (address[] memory);\n\n function deployCErc20(\n uint8 delegateType,\n bytes calldata constructorData,\n bytes calldata becomeImplData\n ) external returns (address);\n\n function canCall(\n address pool,\n address user,\n address target,\n bytes4 functionSig\n ) external view returns (bool);\n\n function authoritiesRegistry() external view returns (AuthoritiesRegistry);\n\n fallback() external payable;\n\n receive() external payable;\n}\n" + }, + "contracts/src/compound/InterestRateModel.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\n/**\n * @title Compound's InterestRateModel Interface\n * @author Compound\n */\nabstract contract InterestRateModel {\n /// @notice Indicator that this is an InterestRateModel contract (for inspection)\n bool public constant isInterestRateModel = true;\n\n /**\n * @notice Calculates the current borrow interest rate per block\n * @param cash The total amount of cash the market has\n * @param borrows The total amount of borrows the market has outstanding\n * @param reserves The total amount of reserves the market has\n * @return The borrow rate per block (as a percentage, and scaled by 1e18)\n */\n function getBorrowRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves\n ) public view virtual returns (uint256);\n\n /**\n * @notice Calculates the current supply interest rate per block\n * @param cash The total amount of cash the market has\n * @param borrows The total amount of borrows the market has outstanding\n * @param reserves The total amount of reserves the market has\n * @param reserveFactorMantissa The current reserve factor the market has\n * @return The supply rate per block (as a percentage, and scaled by 1e18)\n */\n function getSupplyRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves,\n uint256 reserveFactorMantissa\n ) public view virtual returns (uint256);\n}\n" + }, + "contracts/src/compound/JumpRateModel.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./InterestRateModel.sol\";\n\n/**\n * @title Compound's JumpRateModel Contract\n * @author Compound\n */\ncontract JumpRateModel is InterestRateModel {\n event NewInterestParams(\n uint256 baseRatePerBlock,\n uint256 multiplierPerBlock,\n uint256 jumpMultiplierPerBlock,\n uint256 kink\n );\n\n /**\n * @notice The approximate number of blocks per year that is assumed by the interest rate model\n */\n uint256 public blocksPerYear;\n\n /**\n * @notice The multiplier of utilization rate that gives the slope of the interest rate\n */\n uint256 public multiplierPerBlock;\n\n /**\n * @notice The base interest rate which is the y-intercept when utilization rate is 0\n */\n uint256 public baseRatePerBlock;\n\n /**\n * @notice The multiplierPerBlock after hitting a specified utilization point\n */\n uint256 public jumpMultiplierPerBlock;\n\n /**\n * @notice The utilization point at which the jump multiplier is applied\n */\n uint256 public kink;\n\n /**\n * @notice Construct an interest rate model\n * @param _blocksPerYear The approximate number of blocks per year\n * @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)\n * @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)\n * @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point\n * @param kink_ The utilization point at which the jump multiplier is applied\n */\n constructor(\n uint256 _blocksPerYear,\n uint256 baseRatePerYear,\n uint256 multiplierPerYear,\n uint256 jumpMultiplierPerYear,\n uint256 kink_\n ) {\n blocksPerYear = _blocksPerYear;\n baseRatePerBlock = baseRatePerYear / blocksPerYear;\n multiplierPerBlock = multiplierPerYear / blocksPerYear;\n jumpMultiplierPerBlock = jumpMultiplierPerYear / blocksPerYear;\n kink = kink_;\n\n emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink);\n }\n\n /**\n * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`\n * @param cash The amount of cash in the market\n * @param borrows The amount of borrows in the market\n * @param reserves The amount of reserves in the market (currently unused)\n * @return The utilization rate as a mantissa between [0, 1e18]\n */\n function utilizationRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves\n ) public pure returns (uint256) {\n // Utilization rate is 0 when there are no borrows\n if (borrows == 0) {\n return 0;\n }\n\n return (borrows * 1e18) / (cash + borrows - reserves);\n }\n\n /**\n * @notice Calculates the current borrow rate per block, with the error code expected by the market\n * @param cash The amount of cash in the market\n * @param borrows The amount of borrows in the market\n * @param reserves The amount of reserves in the market\n * @return The borrow rate percentage per block as a mantissa (scaled by 1e18)\n */\n function getBorrowRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves\n ) public view override returns (uint256) {\n uint256 util = utilizationRate(cash, borrows, reserves);\n\n if (util <= kink) {\n return ((util * multiplierPerBlock) / 1e18) + baseRatePerBlock;\n } else {\n uint256 normalRate = ((kink * multiplierPerBlock) / 1e18) + baseRatePerBlock;\n uint256 excessUtil = util - kink;\n return ((excessUtil * jumpMultiplierPerBlock) / 1e18) + normalRate;\n }\n }\n\n /**\n * @notice Calculates the current supply rate per block\n * @param cash The amount of cash in the market\n * @param borrows The amount of borrows in the market\n * @param reserves The amount of reserves in the market\n * @param reserveFactorMantissa The current reserve factor for the market\n * @return The supply rate percentage per block as a mantissa (scaled by 1e18)\n */\n function getSupplyRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves,\n uint256 reserveFactorMantissa\n ) public view virtual override returns (uint256) {\n uint256 oneMinusReserveFactor = 1e18 - reserveFactorMantissa;\n uint256 borrowRate = getBorrowRate(cash, borrows, reserves);\n uint256 rateToPool = (borrowRate * oneMinusReserveFactor) / 1e18;\n return (utilizationRate(cash, borrows, reserves) * rateToPool) / 1e18;\n }\n}\n" + }, + "contracts/src/compound/PriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { ICErc20 } from \"./CTokenInterfaces.sol\";\n\nabstract contract PriceOracle {\n /// @notice Indicator that this is a PriceOracle contract (for inspection)\n bool public constant isPriceOracle = true;\n\n /**\n * @notice Get the underlying price of a cToken asset\n * @param cToken The cToken to get the underlying price of\n * @return The underlying asset price mantissa (scaled by 1e18).\n * Zero means the price is unavailable.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view virtual returns (uint256);\n}\n" + }, + "contracts/src/compound/SafeMath.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\n// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol\n// Subject to the MIT license.\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n * - Addition cannot overflow.\n */\n function add(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, errorMessage);\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot underflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction underflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n * - Subtraction cannot underflow.\n */\n function sub(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n * - Multiplication cannot overflow.\n */\n function mul(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, errorMessage);\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers.\n * Reverts on division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers.\n * Reverts with custom message on division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function div(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n * - The divisor cannot be zero.\n */\n function mod(\n uint256 a,\n uint256 b,\n string memory errorMessage\n ) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n" + }, + "contracts/src/compound/Timelock.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./SafeMath.sol\";\n\ncontract Timelock {\n using SafeMath for uint256;\n\n event NewAdmin(address indexed newAdmin);\n event NewPendingAdmin(address indexed newPendingAdmin);\n event NewDelay(uint256 indexed newDelay);\n event CancelTransaction(\n bytes32 indexed txHash,\n address indexed target,\n uint256 value,\n string signature,\n bytes data,\n uint256 eta\n );\n event ExecuteTransaction(\n bytes32 indexed txHash,\n address indexed target,\n uint256 value,\n string signature,\n bytes data,\n uint256 eta\n );\n event QueueTransaction(\n bytes32 indexed txHash,\n address indexed target,\n uint256 value,\n string signature,\n bytes data,\n uint256 eta\n );\n\n uint256 public constant GRACE_PERIOD = 14 days;\n uint256 public constant MINIMUM_DELAY = 2 days;\n uint256 public constant MAXIMUM_DELAY = 30 days;\n\n address public admin;\n address public pendingAdmin;\n uint256 public delay;\n\n mapping(bytes32 => bool) public queuedTransactions;\n\n constructor(address admin_, uint256 delay_) {\n require(delay_ >= MINIMUM_DELAY, \"Timelock::constructor: Delay must exceed minimum delay.\");\n require(delay_ <= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\");\n\n admin = admin_;\n delay = delay_;\n }\n\n receive() external payable {}\n\n function setDelay(uint256 delay_) public {\n require(msg.sender == address(this), \"Timelock::setDelay: Call must come from Timelock.\");\n require(delay_ >= MINIMUM_DELAY, \"Timelock::setDelay: Delay must exceed minimum delay.\");\n require(delay_ <= MAXIMUM_DELAY, \"Timelock::setDelay: Delay must not exceed maximum delay.\");\n delay = delay_;\n\n emit NewDelay(delay);\n }\n\n function acceptAdmin() public {\n require(msg.sender == pendingAdmin, \"Timelock::acceptAdmin: Call must come from pendingAdmin.\");\n admin = msg.sender;\n pendingAdmin = address(0);\n\n emit NewAdmin(admin);\n }\n\n function setPendingAdmin(address pendingAdmin_) public {\n require(msg.sender == address(this), \"Timelock::setPendingAdmin: Call must come from Timelock.\");\n pendingAdmin = pendingAdmin_;\n\n emit NewPendingAdmin(pendingAdmin);\n }\n\n function queueTransaction(\n address target,\n uint256 value,\n string memory signature,\n bytes memory data,\n uint256 eta\n ) public returns (bytes32) {\n require(msg.sender == admin, \"Timelock::queueTransaction: Call must come from admin.\");\n require(\n eta >= getBlockTimestamp().add(delay),\n \"Timelock::queueTransaction: Estimated execution block must satisfy delay.\"\n );\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n queuedTransactions[txHash] = true;\n\n emit QueueTransaction(txHash, target, value, signature, data, eta);\n return txHash;\n }\n\n function cancelTransaction(\n address target,\n uint256 value,\n string memory signature,\n bytes memory data,\n uint256 eta\n ) public {\n require(msg.sender == admin, \"Timelock::cancelTransaction: Call must come from admin.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n queuedTransactions[txHash] = false;\n\n emit CancelTransaction(txHash, target, value, signature, data, eta);\n }\n\n function executeTransaction(\n address target,\n uint256 value,\n string memory signature,\n bytes memory data,\n uint256 eta\n ) public payable returns (bytes memory) {\n require(msg.sender == admin, \"Timelock::executeTransaction: Call must come from admin.\");\n\n bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));\n require(queuedTransactions[txHash], \"Timelock::executeTransaction: Transaction hasn't been queued.\");\n require(getBlockTimestamp() >= eta, \"Timelock::executeTransaction: Transaction hasn't surpassed time lock.\");\n require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), \"Timelock::executeTransaction: Transaction is stale.\");\n\n queuedTransactions[txHash] = false;\n\n bytes memory callData;\n\n if (bytes(signature).length == 0) {\n callData = data;\n } else {\n callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);\n }\n\n // solium-disable-next-line security/no-call-value\n (bool success, bytes memory returnData) = target.call{ value: value }(callData);\n require(success, \"Timelock::executeTransaction: Transaction execution reverted.\");\n\n emit ExecuteTransaction(txHash, target, value, signature, data, eta);\n\n return returnData;\n }\n\n function getBlockTimestamp() internal view returns (uint256) {\n // solium-disable-next-line security/no-block-members\n return block.timestamp;\n }\n}\n" + }, + "contracts/src/compound/Unitroller.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./ErrorReporter.sol\";\nimport \"./ComptrollerStorage.sol\";\nimport \"./Comptroller.sol\";\nimport { DiamondExtension, DiamondBase, LibDiamond } from \"../ionic/DiamondExtension.sol\";\n\n/**\n * @title Unitroller\n * @dev Storage for the comptroller is at this address, while execution is delegated via the Diamond Extensions\n * CTokens should reference this contract as their comptroller.\n */\ncontract Unitroller is ComptrollerV3Storage, ComptrollerErrorReporter, DiamondBase {\n /**\n * @notice Event emitted when the admin rights are changed\n */\n event AdminRightsToggled(bool hasRights);\n\n /**\n * @notice Emitted when pendingAdmin is changed\n */\n event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);\n\n /**\n * @notice Emitted when pendingAdmin is accepted, which means admin is updated\n */\n event NewAdmin(address oldAdmin, address newAdmin);\n\n constructor(address payable _ionicAdmin) {\n admin = msg.sender;\n ionicAdmin = _ionicAdmin;\n }\n\n /*** Admin Functions ***/\n\n /**\n * @notice Toggles admin rights.\n * @param hasRights Boolean indicating if the admin is to have rights.\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _toggleAdminRights(bool hasRights) external returns (uint256) {\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.TOGGLE_ADMIN_RIGHTS_OWNER_CHECK);\n }\n\n // Check that rights have not already been set to the desired value\n if (adminHasRights == hasRights) return uint256(Error.NO_ERROR);\n\n adminHasRights = hasRights;\n emit AdminRightsToggled(hasRights);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\n * @param newPendingAdmin New pending admin.\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _setPendingAdmin(address newPendingAdmin) public returns (uint256) {\n if (!hasAdminRights()) {\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);\n }\n\n address oldPendingAdmin = pendingAdmin;\n pendingAdmin = newPendingAdmin;\n emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);\n\n return uint256(Error.NO_ERROR);\n }\n\n /**\n * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\n * @dev Admin function for pending admin to accept role and update admin\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\n */\n function _acceptAdmin() public returns (uint256) {\n // Check caller is pendingAdmin and pendingAdmin ≠ address(0)\n if (msg.sender != pendingAdmin || msg.sender == address(0)) {\n return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);\n }\n\n // Save current values for inclusion in log\n address oldAdmin = admin;\n address oldPendingAdmin = pendingAdmin;\n\n admin = pendingAdmin;\n pendingAdmin = address(0);\n\n emit NewAdmin(oldAdmin, admin);\n emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\n\n return uint256(Error.NO_ERROR);\n }\n\n function comptrollerImplementation() public view returns (address) {\n return LibDiamond.getExtensionForFunction(bytes4(keccak256(bytes(\"_deployMarket(uint8,bytes,bytes,uint256)\"))));\n }\n\n /**\n * @dev upgrades the implementation if necessary\n */\n function _upgrade() external {\n require(msg.sender == address(this) || hasAdminRights(), \"!self || !admin\");\n\n address currentImplementation = comptrollerImplementation();\n address latestComptrollerImplementation = IFeeDistributor(ionicAdmin).latestComptrollerImplementation(\n currentImplementation\n );\n\n _updateExtensions(latestComptrollerImplementation);\n\n if (currentImplementation != latestComptrollerImplementation) {\n // reinitialize\n _functionCall(address(this), abi.encodeWithSignature(\"_becomeImplementation()\"), \"!become impl\");\n }\n }\n\n function _functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n (bool success, bytes memory returndata) = target.call(data);\n\n if (!success) {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n\n return returndata;\n }\n\n function _updateExtensions(address currentComptroller) internal {\n address[] memory latestExtensions = IFeeDistributor(ionicAdmin).getComptrollerExtensions(currentComptroller);\n address[] memory currentExtensions = LibDiamond.listExtensions();\n\n // removed the current (old) extensions\n for (uint256 i = 0; i < currentExtensions.length; i++) {\n LibDiamond.removeExtension(DiamondExtension(currentExtensions[i]));\n }\n // add the new extensions\n for (uint256 i = 0; i < latestExtensions.length; i++) {\n LibDiamond.addExtension(DiamondExtension(latestExtensions[i]));\n }\n }\n\n /**\n * @dev register a logic extension\n * @param extensionToAdd the extension whose functions are to be added\n * @param extensionToReplace the extension whose functions are to be removed/replaced\n */\n function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) external override {\n require(hasAdminRights(), \"!unauthorized\");\n LibDiamond.registerExtension(extensionToAdd, extensionToReplace);\n }\n}\n" + }, + "contracts/src/EmissionsManager.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\nimport { SafeTransferLib } from \"solmate/utils/SafeTransferLib.sol\";\n\nimport { Ownable2StepUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol\";\nimport { IonicFlywheelCore } from \"./ionic/strategies/flywheel/IonicFlywheelCore.sol\";\nimport { IonicComptroller } from \"./compound/ComptrollerInterface.sol\";\nimport { BasePriceOracle } from \"./oracles/BasePriceOracle.sol\";\nimport { ICErc20 } from \"./compound/CTokenInterfaces.sol\";\nimport { PoolDirectory } from \"./PoolDirectory.sol\";\nimport { IEmissionsManager } from \"./IEmissionsManager.sol\";\nimport { IveION } from \"./veION/interfaces/IveION.sol\";\n\ninterface Oracle {\n function getUnderlyingPrice(address) external returns (uint256);\n}\n\ncontract EmissionsManager is IEmissionsManager, Ownable2StepUpgradeable {\n using SafeTransferLib for ERC20;\n\n address public protocolAddress;\n uint256 public collateralBp;\n PoolDirectory public fpd;\n ERC20 public rewardToken;\n address public veION;\n\n bytes public nonBlacklistableTargetBytecode;\n mapping(address => bool) public isBlacklisted;\n mapping(address => bool) public nonBlacklistable;\n\n uint256 public constant MAXIMUM_BASIS_POINTS = 10_000;\n uint256 public constant BLACKLISTER_SHARE = 80;\n uint256 public constant PROTOCOL_SHARE = 20;\n\n modifier onlyBlacklistableBytecode(address _addr) {\n bytes memory code = _addr.code;\n require(keccak256(code) != keccak256(nonBlacklistableTargetBytecode), \"Non-blacklistable bytecode\");\n _;\n }\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n function initialize(\n PoolDirectory _fpd,\n address _protocolAddress,\n ERC20 _rewardToken,\n uint256 _collateralBp,\n bytes memory _nonBlacklistableTargetBytecode\n ) public initializer {\n if (address(_fpd) == address(0)) revert InvalidPoolDirectoryAaddress();\n if (_protocolAddress == address(0)) revert InvalidProtocolAddress();\n if (address(_rewardToken) == address(0)) revert InvalidRewardTokenAddress();\n if (_collateralBp >= MAXIMUM_BASIS_POINTS) revert CollateralBasisPointsExceedMaximum();\n\n __Ownable2Step_init();\n protocolAddress = _protocolAddress;\n fpd = _fpd;\n rewardToken = _rewardToken;\n collateralBp = _collateralBp;\n nonBlacklistableTargetBytecode = _nonBlacklistableTargetBytecode;\n\n emit Initialized(_protocolAddress, address(_rewardToken), _collateralBp, _nonBlacklistableTargetBytecode);\n }\n\n function setVeIon(IveION _veIon) external onlyOwner {\n if (address(_veIon) == address(0)) revert InvalidVeIONAddress();\n veION = address(_veIon);\n emit VeIonSet(address(_veIon));\n }\n\n function setCollateralBp(uint256 _collateralBp) external onlyOwner {\n if (_collateralBp >= MAXIMUM_BASIS_POINTS) revert MaximumLimitExceeded();\n collateralBp = _collateralBp;\n emit CollateralBpSet(_collateralBp);\n }\n\n function setNonBlacklistableAddress(address _user, bool _isNonBlacklistable) external onlyOwner {\n nonBlacklistable[_user] = _isNonBlacklistable;\n emit NonBlacklistableAddressSet(_user, _isNonBlacklistable);\n }\n\n function setNonBlacklistableTargetBytecode(bytes memory _newBytecode) external onlyOwner {\n nonBlacklistableTargetBytecode = _newBytecode;\n emit NonBlacklistableTargetBytecodeSet(_newBytecode);\n }\n\n function setProtocolAddress(address _newProtocolAddress) external onlyOwner {\n require(_newProtocolAddress != address(0), \"Invalid address\");\n protocolAddress = _newProtocolAddress;\n }\n\n function _getUserTotalCollateral(address _user) internal view returns (uint256) {\n uint256 totalColateralInETH = 0;\n (, PoolDirectory.Pool[] memory pools) = fpd.getActivePools();\n uint256 poolsLength = pools.length;\n for (uint256 i = 0; i < poolsLength; i++) {\n IonicComptroller comptroller = IonicComptroller(pools[i].comptroller);\n BasePriceOracle oracle = comptroller.oracle();\n ICErc20[] memory cTokens = comptroller.getAssetsIn(_user);\n uint256 cTokensLength = cTokens.length;\n for (uint256 j = 0; j < cTokensLength; j++) {\n uint256 supplyBalance = cTokens[j].balanceOfUnderlying(_user);\n uint256 collateralInETH = (supplyBalance * oracle.getUnderlyingPrice(cTokens[j])) / 1e18;\n totalColateralInETH += collateralInETH;\n }\n }\n return totalColateralInETH;\n }\n\n function getUserTotalCollateral(address _user) external view returns (uint256) {\n return _getUserTotalCollateral(_user);\n }\n\n function _checkCollateralRatio(address _user) internal view returns (bool) {\n uint256 userCollateralValue = _getUserTotalCollateral(_user);\n if (userCollateralValue == 0) return true;\n uint256 userLPValue = IveION(veION).getTotalEthValueOfTokens(_user);\n if ((userLPValue * MAXIMUM_BASIS_POINTS) / userCollateralValue >= collateralBp) {\n return true;\n } else return false;\n }\n\n function reportUser(address _user) external onlyBlacklistableBytecode(_user) {\n require(!nonBlacklistable[_user], \"Non-blacklistable user\");\n require(!isBlacklisted[_user], \"Already blacklisted\");\n require(!_checkCollateralRatio(_user), \"LP balance above threshold\");\n isBlacklisted[_user] = true;\n _blacklistUserAndClaimEmissions(_user);\n }\n\n function whitelistUser(address _user) external {\n require(isBlacklisted[_user], \"Already whitelisted\");\n require(_checkCollateralRatio(_user), \"LP balance below threshold\");\n isBlacklisted[_user] = false;\n (, PoolDirectory.Pool[] memory pools) = fpd.getActivePools();\n uint256 poolsLength = pools.length;\n for (uint256 i = 0; i < poolsLength; i++) {\n IonicComptroller comptroller = IonicComptroller(pools[i].comptroller);\n ICErc20[] memory cTokens = comptroller.getAssetsIn(_user);\n uint256 cTokensLength = cTokens.length;\n for (uint256 j = 0; j < cTokensLength; j++) {\n address[] memory flywheelAddresses = comptroller.getAccruingFlywheels();\n uint256 flywheelAddressesLength = flywheelAddresses.length;\n for (uint256 k = 0; k < flywheelAddressesLength; k++) {\n IonicFlywheelCore flywheel = IonicFlywheelCore(flywheelAddresses[k]);\n if (address(flywheel.rewardToken()) == address(rewardToken)) {\n flywheel.whitelistUser(ERC20(address(cTokens[j])), _user);\n flywheel.accrue(ERC20(address(cTokens[j])), _user);\n }\n }\n }\n }\n }\n\n function isUserBlacklisted(address _user) external view returns (bool) {\n return isBlacklisted[_user];\n }\n\n function isUserBlacklistable(address _user) external view returns (bool) {\n if (nonBlacklistable[_user] || keccak256(_user.code) == keccak256(nonBlacklistableTargetBytecode)) {\n return false;\n }\n return !_checkCollateralRatio(_user) && !isBlacklisted[_user];\n }\n\n function _blacklistUserAndClaimEmissions(address user) internal {\n uint256 balanceBefore = ERC20(rewardToken).balanceOf(address(this));\n (, PoolDirectory.Pool[] memory pools) = fpd.getActivePools();\n uint256 poolsLength = pools.length;\n for (uint256 i = 0; i < poolsLength; i++) {\n IonicComptroller comptroller = IonicComptroller(pools[i].comptroller);\n ERC20[] memory markets;\n {\n ICErc20[] memory cerc20s = comptroller.getAllMarkets();\n uint256 cerc20sLength = cerc20s.length;\n markets = new ERC20[](cerc20sLength);\n for (uint256 j = 0; j < cerc20sLength; j++) {\n markets[j] = ERC20(address(cerc20s[j]));\n }\n }\n\n address[] memory flywheelAddresses = comptroller.getAccruingFlywheels();\n uint256 flywheelAddressesLength = flywheelAddresses.length;\n for (uint256 k = 0; k < flywheelAddressesLength; k++) {\n IonicFlywheelCore flywheel = IonicFlywheelCore(flywheelAddresses[k]);\n if (address(flywheel.rewardToken()) == address(rewardToken)) {\n uint256 marketsLength = markets.length;\n for (uint256 m = 0; m < marketsLength; m++) {\n flywheel.accrue(markets[m], user);\n flywheel.updateBlacklistBalances(markets[m], user);\n }\n flywheel.takeRewardsFromUser(user, address(this));\n }\n }\n }\n\n uint256 balanceAfter = ERC20(rewardToken).balanceOf(address(this));\n uint256 totalClaimed = balanceAfter - balanceBefore;\n if (totalClaimed > 0) {\n rewardToken.safeTransfer(msg.sender, (totalClaimed * BLACKLISTER_SHARE) / 100);\n rewardToken.safeTransfer(protocolAddress, (totalClaimed * PROTOCOL_SHARE) / 100);\n }\n }\n}\n" + }, + "contracts/src/external/aerodrome/IAerodromeRouter.sol": { + "content": "// SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.10;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20_Router {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address from, address to, uint256 amount) external returns (bool);\n}\n\ninterface IWETH is IERC20_Router {\n function deposit() external payable;\n\n function withdraw(uint256) external;\n}\n\ninterface IRouter_Aerodrome {\n struct Route {\n address from;\n address to;\n bool stable;\n address factory;\n }\n\n error ETHTransferFailed();\n error Expired();\n error InsufficientAmount();\n error InsufficientAmountA();\n error InsufficientAmountB();\n error InsufficientAmountADesired();\n error InsufficientAmountBDesired();\n error InsufficientAmountAOptimal();\n error InsufficientLiquidity();\n error InsufficientOutputAmount();\n error InvalidAmountInForETHDeposit();\n error InvalidTokenInForETHDeposit();\n error InvalidPath();\n error InvalidRouteA();\n error InvalidRouteB();\n error OnlyWETH();\n error PoolDoesNotExist();\n error PoolFactoryDoesNotExist();\n error SameAddresses();\n error ZeroAddress();\n\n /// @notice Address of FactoryRegistry.sol\n function factoryRegistry() external view returns (address);\n\n /// @notice Address of Protocol PoolFactory.sol\n function defaultFactory() external view returns (address);\n\n /// @notice Address of Voter.sol\n function voter() external view returns (address);\n\n /// @notice Interface of WETH contract used for WETH => ETH wrapping/unwrapping\n function weth() external view returns (IWETH);\n\n /// @dev Represents Ether. Used by zapper to determine whether to return assets as ETH/WETH.\n function ETHER() external view returns (address);\n\n /// @dev Struct containing information necessary to zap in and out of pools\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable Stable or volatile pool\n /// @param factory factory of pool\n /// @param amountOutMinA Minimum amount expected from swap leg of zap via routesA\n /// @param amountOutMinB Minimum amount expected from swap leg of zap via routesB\n /// @param amountAMin Minimum amount of tokenA expected from liquidity leg of zap\n /// @param amountBMin Minimum amount of tokenB expected from liquidity leg of zap\n struct Zap {\n address tokenA;\n address tokenB;\n bool stable;\n address factory;\n uint256 amountOutMinA;\n uint256 amountOutMinB;\n uint256 amountAMin;\n uint256 amountBMin;\n }\n\n /// @notice Sort two tokens by which address value is less than the other\n /// @param tokenA Address of token to sort\n /// @param tokenB Address of token to sort\n /// @return token0 Lower address value between tokenA and tokenB\n /// @return token1 Higher address value between tokenA and tokenB\n function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1);\n\n /// @notice Calculate the address of a pool by its' factory.\n /// Used by all Router functions containing a `Route[]` or `_factory` argument.\n /// Reverts if _factory is not approved by the FactoryRegistry\n /// @dev Returns a randomly generated address for a nonexistent pool\n /// @param tokenA Address of token to query\n /// @param tokenB Address of token to query\n /// @param stable True if pool is stable, false if volatile\n /// @param _factory Address of factory which created the pool\n function poolFor(address tokenA, address tokenB, bool stable, address _factory) external view returns (address pool);\n\n /// @notice Fetch and sort the reserves for a pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @param _factory Address of PoolFactory for tokenA and tokenB\n /// @return reserveA Amount of reserves of the sorted token A\n /// @return reserveB Amount of reserves of the sorted token B\n function getReserves(\n address tokenA,\n address tokenB,\n bool stable,\n address _factory\n ) external view returns (uint256 reserveA, uint256 reserveB);\n\n /// @notice Perform chained getAmountOut calculations on any number of pools\n function getAmountsOut(uint256 amountIn, Route[] memory routes) external view returns (uint256[] memory amounts);\n\n // **** ADD LIQUIDITY ****\n\n /// @notice Quote the amount deposited into a Pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @param _factory Address of PoolFactory for tokenA and tokenB\n /// @param amountADesired Amount of tokenA desired to deposit\n /// @param amountBDesired Amount of tokenB desired to deposit\n /// @return amountA Amount of tokenA to actually deposit\n /// @return amountB Amount of tokenB to actually deposit\n /// @return liquidity Amount of liquidity token returned from deposit\n function quoteAddLiquidity(\n address tokenA,\n address tokenB,\n bool stable,\n address _factory,\n uint256 amountADesired,\n uint256 amountBDesired\n ) external view returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n /// @notice Quote the amount of liquidity removed from a Pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @param _factory Address of PoolFactory for tokenA and tokenB\n /// @param liquidity Amount of liquidity to remove\n /// @return amountA Amount of tokenA received\n /// @return amountB Amount of tokenB received\n function quoteRemoveLiquidity(\n address tokenA,\n address tokenB,\n bool stable,\n address _factory,\n uint256 liquidity\n ) external view returns (uint256 amountA, uint256 amountB);\n\n /// @notice Add liquidity of two tokens to a Pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @param amountADesired Amount of tokenA desired to deposit\n /// @param amountBDesired Amount of tokenB desired to deposit\n /// @param amountAMin Minimum amount of tokenA to deposit\n /// @param amountBMin Minimum amount of tokenB to deposit\n /// @param to Recipient of liquidity token\n /// @param deadline Deadline to receive liquidity\n /// @return amountA Amount of tokenA to actually deposit\n /// @return amountB Amount of tokenB to actually deposit\n /// @return liquidity Amount of liquidity token returned from deposit\n function addLiquidity(\n address tokenA,\n address tokenB,\n bool stable,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n /// @notice Add liquidity of a token and WETH (transferred as ETH) to a Pool\n /// @param token .\n /// @param stable True if pool is stable, false if volatile\n /// @param amountTokenDesired Amount of token desired to deposit\n /// @param amountTokenMin Minimum amount of token to deposit\n /// @param amountETHMin Minimum amount of ETH to deposit\n /// @param to Recipient of liquidity token\n /// @param deadline Deadline to add liquidity\n /// @return amountToken Amount of token to actually deposit\n /// @return amountETH Amount of tokenETH to actually deposit\n /// @return liquidity Amount of liquidity token returned from deposit\n function addLiquidityETH(\n address token,\n bool stable,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);\n\n // **** REMOVE LIQUIDITY ****\n\n /// @notice Remove liquidity of two tokens from a Pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @param liquidity Amount of liquidity to remove\n /// @param amountAMin Minimum amount of tokenA to receive\n /// @param amountBMin Minimum amount of tokenB to receive\n /// @param to Recipient of tokens received\n /// @param deadline Deadline to remove liquidity\n /// @return amountA Amount of tokenA received\n /// @return amountB Amount of tokenB received\n function removeLiquidity(\n address tokenA,\n address tokenB,\n bool stable,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n /// @notice Remove liquidity of a token and WETH (returned as ETH) from a Pool\n /// @param token .\n /// @param stable True if pool is stable, false if volatile\n /// @param liquidity Amount of liquidity to remove\n /// @param amountTokenMin Minimum amount of token to receive\n /// @param amountETHMin Minimum amount of ETH to receive\n /// @param to Recipient of liquidity token\n /// @param deadline Deadline to receive liquidity\n /// @return amountToken Amount of token received\n /// @return amountETH Amount of ETH received\n function removeLiquidityETH(\n address token,\n bool stable,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n /// @notice Remove liquidity of a fee-on-transfer token and WETH (returned as ETH) from a Pool\n /// @param token .\n /// @param stable True if pool is stable, false if volatile\n /// @param liquidity Amount of liquidity to remove\n /// @param amountTokenMin Minimum amount of token to receive\n /// @param amountETHMin Minimum amount of ETH to receive\n /// @param to Recipient of liquidity token\n /// @param deadline Deadline to receive liquidity\n /// @return amountETH Amount of ETH received\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address token,\n bool stable,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountETH);\n\n // **** SWAP ****\n\n /// @notice Swap one token for another\n /// @param amountIn Amount of token in\n /// @param amountOutMin Minimum amount of desired token received\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n /// @return amounts Array of amounts returned per route\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /// @notice Swap ETH for a token\n /// @param amountOutMin Minimum amount of desired token received\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n /// @return amounts Array of amounts returned per route\n function swapExactETHForTokens(\n uint256 amountOutMin,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n /// @notice Swap a token for WETH (returned as ETH)\n /// @param amountIn Amount of token in\n /// @param amountOutMin Minimum amount of desired ETH\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n /// @return amounts Array of amounts returned per route\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /// @notice Swap one token for another without slippage protection\n /// @return amounts Array of amounts to swap per route\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n function UNSAFE_swapExactTokensForTokens(\n uint256[] memory amounts,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory);\n\n // **** SWAP (supporting fee-on-transfer tokens) ****\n\n /// @notice Swap one token for another supporting fee-on-transfer tokens\n /// @param amountIn Amount of token in\n /// @param amountOutMin Minimum amount of desired token received\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external;\n\n /// @notice Swap ETH for a token supporting fee-on-transfer tokens\n /// @param amountOutMin Minimum amount of desired token received\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n function swapExactETHForTokensSupportingFeeOnTransferTokens(\n uint256 amountOutMin,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external payable;\n\n /// @notice Swap a token for WETH (returned as ETH) supporting fee-on-transfer tokens\n /// @param amountIn Amount of token in\n /// @param amountOutMin Minimum amount of desired ETH\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n function swapExactTokensForETHSupportingFeeOnTransferTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external;\n\n /// @notice Zap a token A into a pool (B, C). (A can be equal to B or C).\n /// Supports standard ERC20 tokens only (i.e. not fee-on-transfer tokens etc).\n /// Slippage is required for the initial swap.\n /// Additional slippage may be required when adding liquidity as the\n /// price of the token may have changed.\n /// @param tokenIn Token you are zapping in from (i.e. input token).\n /// @param amountInA Amount of input token you wish to send down routesA\n /// @param amountInB Amount of input token you wish to send down routesB\n /// @param zapInPool Contains zap struct information. See Zap struct.\n /// @param routesA Route used to convert input token to tokenA\n /// @param routesB Route used to convert input token to tokenB\n /// @param to Address you wish to mint liquidity to.\n /// @param stake Auto-stake liquidity in corresponding gauge.\n /// @return liquidity Amount of LP tokens created from zapping in.\n function zapIn(\n address tokenIn,\n uint256 amountInA,\n uint256 amountInB,\n Zap calldata zapInPool,\n Route[] calldata routesA,\n Route[] calldata routesB,\n address to,\n bool stake\n ) external payable returns (uint256 liquidity);\n\n /// @notice Zap out a pool (B, C) into A.\n /// Supports standard ERC20 tokens only (i.e. not fee-on-transfer tokens etc).\n /// Slippage is required for the removal of liquidity.\n /// Additional slippage may be required on the swap as the\n /// price of the token may have changed.\n /// @param tokenOut Token you are zapping out to (i.e. output token).\n /// @param liquidity Amount of liquidity you wish to remove.\n /// @param zapOutPool Contains zap struct information. See Zap struct.\n /// @param routesA Route used to convert tokenA into output token.\n /// @param routesB Route used to convert tokenB into output token.\n function zapOut(\n address tokenOut,\n uint256 liquidity,\n Zap calldata zapOutPool,\n Route[] calldata routesA,\n Route[] calldata routesB\n ) external;\n\n /// @notice Used to generate params required for zapping in.\n /// Zap in => remove liquidity then swap.\n /// Apply slippage to expected swap values to account for changes in reserves in between.\n /// @dev Output token refers to the token you want to zap in from.\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable .\n /// @param _factory .\n /// @param amountInA Amount of input token you wish to send down routesA\n /// @param amountInB Amount of input token you wish to send down routesB\n /// @param routesA Route used to convert input token to tokenA\n /// @param routesB Route used to convert input token to tokenB\n /// @return amountOutMinA Minimum output expected from swapping input token to tokenA.\n /// @return amountOutMinB Minimum output expected from swapping input token to tokenB.\n /// @return amountAMin Minimum amount of tokenA expected from depositing liquidity.\n /// @return amountBMin Minimum amount of tokenB expected from depositing liquidity.\n function generateZapInParams(\n address tokenA,\n address tokenB,\n bool stable,\n address _factory,\n uint256 amountInA,\n uint256 amountInB,\n Route[] calldata routesA,\n Route[] calldata routesB\n ) external view returns (uint256 amountOutMinA, uint256 amountOutMinB, uint256 amountAMin, uint256 amountBMin);\n\n /// @notice Used to generate params required for zapping out.\n /// Zap out => swap then add liquidity.\n /// Apply slippage to expected liquidity values to account for changes in reserves in between.\n /// @dev Output token refers to the token you want to zap out of.\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable .\n /// @param _factory .\n /// @param liquidity Amount of liquidity being zapped out of into a given output token.\n /// @param routesA Route used to convert tokenA into output token.\n /// @param routesB Route used to convert tokenB into output token.\n /// @return amountOutMinA Minimum output expected from swapping tokenA into output token.\n /// @return amountOutMinB Minimum output expected from swapping tokenB into output token.\n /// @return amountAMin Minimum amount of tokenA expected from withdrawing liquidity.\n /// @return amountBMin Minimum amount of tokenB expected from withdrawing liquidity.\n function generateZapOutParams(\n address tokenA,\n address tokenB,\n bool stable,\n address _factory,\n uint256 liquidity,\n Route[] calldata routesA,\n Route[] calldata routesB\n ) external view returns (uint256 amountOutMinA, uint256 amountOutMinB, uint256 amountAMin, uint256 amountBMin);\n\n /// @notice Used by zapper to determine appropriate ratio of A to B to deposit liquidity. Assumes stable pool.\n /// @dev Returns stable liquidity ratio of B to (A + B).\n /// E.g. if ratio is 0.4, it means there is more of A than there is of B.\n /// Therefore you should deposit more of token A than B.\n /// @param tokenA tokenA of stable pool you are zapping into.\n /// @param tokenB tokenB of stable pool you are zapping into.\n /// @param factory Factory that created stable pool.\n /// @return ratio Ratio of token0 to token1 required to deposit into zap.\n function quoteStableLiquidityRatio(\n address tokenA,\n address tokenB,\n address factory\n ) external view returns (uint256 ratio);\n}\n" + }, + "contracts/src/external/aerodrome/IAerodromeSwapRouter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.10;\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via CL\ninterface ISwapRouter_Aerodrome {\n struct ExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n int24 tickSpacing;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactInputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n int24 tickSpacing;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\n\n struct ExactOutputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\n}\n" + }, + "contracts/src/external/algebra/IAlgebraFactory.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/**\n * @title The interface for the Algebra Factory\n * @dev Credit to Uniswap Labs under GPL-2.0-or-later license:\n * https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces\n */\ninterface IAlgebraFactory {\n /**\n * @notice Emitted when the owner of the factory is changed\n * @param newOwner The owner after the owner was changed\n */\n event Owner(address indexed newOwner);\n\n /**\n * @notice Emitted when the vault address is changed\n * @param newVaultAddress The vault address after the address was changed\n */\n event VaultAddress(address indexed newVaultAddress);\n\n /**\n * @notice Emitted when a pool is created\n * @param token0 The first token of the pool by address sort order\n * @param token1 The second token of the pool by address sort order\n * @param pool The address of the created pool\n */\n event Pool(address indexed token0, address indexed token1, address pool);\n\n /**\n * @notice Emitted when the farming address is changed\n * @param newFarmingAddress The farming address after the address was changed\n */\n event FarmingAddress(address indexed newFarmingAddress);\n\n event FeeConfiguration(\n uint16 alpha1,\n uint16 alpha2,\n uint32 beta1,\n uint32 beta2,\n uint16 gamma1,\n uint16 gamma2,\n uint32 volumeBeta,\n uint16 volumeGamma,\n uint16 baseFee\n );\n\n /**\n * @notice Returns the current owner of the factory\n * @dev Can be changed by the current owner via setOwner\n * @return The address of the factory owner\n */\n function owner() external view returns (address);\n\n /**\n * @notice Returns the current poolDeployerAddress\n * @return The address of the poolDeployer\n */\n function poolDeployer() external view returns (address);\n\n /**\n * @dev Is retrieved from the pools to restrict calling\n * certain functions not by a tokenomics contract\n * @return The tokenomics contract address\n */\n function farmingAddress() external view returns (address);\n\n function vaultAddress() external view returns (address);\n\n /**\n * @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\n * @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\n * @param tokenA The contract address of either token0 or token1\n * @param tokenB The contract address of the other token\n * @return pool The pool address\n */\n function poolByPair(address tokenA, address tokenB) external view returns (address pool);\n\n /**\n * @notice Creates a pool for the given two tokens and fee\n * @param tokenA One of the two tokens in the desired pool\n * @param tokenB The other of the two tokens in the desired pool\n * @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\n * from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\n * are invalid.\n * @return pool The address of the newly created pool\n */\n function createPool(address tokenA, address tokenB) external returns (address pool);\n\n /**\n * @notice Updates the owner of the factory\n * @dev Must be called by the current owner\n * @param _owner The new owner of the factory\n */\n function setOwner(address _owner) external;\n\n /**\n * @dev updates tokenomics address on the factory\n * @param _farmingAddress The new tokenomics contract address\n */\n function setFarmingAddress(address _farmingAddress) external;\n\n /**\n * @dev updates vault address on the factory\n * @param _vaultAddress The new vault contract address\n */\n function setVaultAddress(address _vaultAddress) external;\n\n /**\n * @notice Changes initial fee configuration for new pools\n * @dev changes coefficients for sigmoids: α / (1 + e^( (β-x) / γ))\n * alpha1 + alpha2 + baseFee (max possible fee) must be <= type(uint16).max\n * gammas must be > 0\n * @param alpha1 max value of the first sigmoid\n * @param alpha2 max value of the second sigmoid\n * @param beta1 shift along the x-axis for the first sigmoid\n * @param beta2 shift along the x-axis for the second sigmoid\n * @param gamma1 horizontal stretch factor for the first sigmoid\n * @param gamma2 horizontal stretch factor for the second sigmoid\n * @param volumeBeta shift along the x-axis for the outer volume-sigmoid\n * @param volumeGamma horizontal stretch factor the outer volume-sigmoid\n * @param baseFee minimum possible fee\n */\n function setBaseFeeConfiguration(\n uint16 alpha1,\n uint16 alpha2,\n uint32 beta1,\n uint32 beta2,\n uint16 gamma1,\n uint16 gamma2,\n uint32 volumeBeta,\n uint16 volumeGamma,\n uint16 baseFee\n ) external;\n}\n" + }, + "contracts/src/external/algebra/IAlgebraPool.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\nimport \"./IAlgebraPoolState.sol\";\nimport \"./IAlgebraPoolActions.sol\";\n\n/// @title Pool state that can change\n/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:\n/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces\ninterface IAlgebraPool is IAlgebraPoolState, IAlgebraPoolActions {\n /**\n * @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n * @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n * the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n * you must call it with secondsAgos = [3600, 0].\n * @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n * log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n * @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n * @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n * @return secondsPerLiquidityCumulatives Cumulative seconds per liquidity-in-range value as of each `secondsAgos`\n * from the current block timestamp\n * @return volatilityCumulatives Cumulative standard deviation as of each `secondsAgos`\n * @return volumePerAvgLiquiditys Cumulative swap volume per liquidity as of each `secondsAgos`\n */\n function getTimepoints(uint32[] calldata secondsAgos)\n external\n view\n returns (\n int56[] memory tickCumulatives,\n uint160[] memory secondsPerLiquidityCumulatives,\n uint112[] memory volatilityCumulatives,\n uint256[] memory volumePerAvgLiquiditys\n );\n\n function factory() external view returns (address);\n\n function token0() external view returns (address);\n\n function token1() external view returns (address);\n\n function tickSpacing() external view returns (int24);\n}\n" + }, + "contracts/src/external/algebra/IAlgebraPoolActions.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:\n/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces\ninterface IAlgebraPoolActions {\n /**\n * @notice Sets the initial price for the pool\n * @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n * @param price the initial sqrt price of the pool as a Q64.96\n */\n function initialize(uint160 price) external;\n\n /**\n * @notice Adds liquidity for the given recipient/bottomTick/topTick position\n * @dev The caller of this method receives a callback in the form of IAlgebraMintCallback# AlgebraMintCallback\n * in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n * on bottomTick, topTick, the amount of liquidity, and the current price.\n * @param sender The address which will receive potential surplus of paid tokens\n * @param recipient The address for which the liquidity will be created\n * @param bottomTick The lower tick of the position in which to add liquidity\n * @param topTick The upper tick of the position in which to add liquidity\n * @param amount The desired amount of liquidity to mint\n * @param data Any data that should be passed through to the callback\n * @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n * @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n * @return liquidityActual The actual minted amount of liquidity\n */\n function mint(\n address sender,\n address recipient,\n int24 bottomTick,\n int24 topTick,\n uint128 amount,\n bytes calldata data\n )\n external\n returns (\n uint256 amount0,\n uint256 amount1,\n uint128 liquidityActual\n );\n\n /**\n * @notice Collects tokens owed to a position\n * @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n * Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n * amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n * actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n * @param recipient The address which should receive the fees collected\n * @param bottomTick The lower tick of the position for which to collect fees\n * @param topTick The upper tick of the position for which to collect fees\n * @param amount0Requested How much token0 should be withdrawn from the fees owed\n * @param amount1Requested How much token1 should be withdrawn from the fees owed\n * @return amount0 The amount of fees collected in token0\n * @return amount1 The amount of fees collected in token1\n */\n function collect(\n address recipient,\n int24 bottomTick,\n int24 topTick,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n\n /**\n * @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n * @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n * @dev Fees must be collected separately via a call to #collect\n * @param bottomTick The lower tick of the position for which to burn liquidity\n * @param topTick The upper tick of the position for which to burn liquidity\n * @param amount How much liquidity to burn\n * @return amount0 The amount of token0 sent to the recipient\n * @return amount1 The amount of token1 sent to the recipient\n */\n function burn(\n int24 bottomTick,\n int24 topTick,\n uint128 amount\n ) external returns (uint256 amount0, uint256 amount1);\n\n /**\n * @notice Swap token0 for token1, or token1 for token0\n * @dev The caller of this method receives a callback in the form of IAlgebraSwapCallback# AlgebraSwapCallback\n * @param recipient The address to receive the output of the swap\n * @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0\n * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n * @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n * value after the swap. If one for zero, the price cannot be greater than this value after the swap\n * @param data Any data to be passed through to the callback. If using the Router it should contain\n * SwapRouter#SwapCallbackData\n * @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n * @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n */\n function swap(\n address recipient,\n bool zeroToOne,\n int256 amountSpecified,\n uint160 limitSqrtPrice,\n bytes calldata data\n ) external returns (int256 amount0, int256 amount1);\n\n /**\n * @notice Swap token0 for token1, or token1 for token0 (tokens that have fee on transfer)\n * @dev The caller of this method receives a callback in the form of I AlgebraSwapCallback# AlgebraSwapCallback\n * @param sender The address called this function (Comes from the Router)\n * @param recipient The address to receive the output of the swap\n * @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0\n * @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n * @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n * value after the swap. If one for zero, the price cannot be greater than this value after the swap\n * @param data Any data to be passed through to the callback. If using the Router it should contain\n * SwapRouter#SwapCallbackData\n * @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n * @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n */\n function swapSupportingFeeOnInputTokens(\n address sender,\n address recipient,\n bool zeroToOne,\n int256 amountSpecified,\n uint160 limitSqrtPrice,\n bytes calldata data\n ) external returns (int256 amount0, int256 amount1);\n\n /**\n * @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n * @dev The caller of this method receives a callback in the form of IAlgebraFlashCallback# AlgebraFlashCallback\n * @dev All excess tokens paid in the callback are distributed to liquidity providers as an additional fee. So this method can be used\n * to donate underlying tokens to currently in-range liquidity providers by calling with 0 amount{0,1} and sending\n * the donation amount(s) from the callback\n * @param recipient The address which will receive the token0 and token1 amounts\n * @param amount0 The amount of token0 to send\n * @param amount1 The amount of token1 to send\n * @param data Any data to be passed through to the callback\n */\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external;\n}\n" + }, + "contracts/src/external/algebra/IAlgebraPoolState.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:\n/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces\ninterface IAlgebraPoolState {\n /**\n * @notice The globalState structure in the pool stores many values but requires only one slot\n * and is exposed as a single method to save gas when accessed externally.\n * @return price The current price of the pool as a sqrt(token1/token0) Q64.96 value;\n * Returns tick The current tick of the pool, i.e. according to the last tick transition that was run;\n * Returns This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick\n * boundary;\n * Returns fee The last pool fee value in hundredths of a bip, i.e. 1e-6;\n * Returns timepointIndex The index of the last written timepoint;\n * Returns communityFeeToken0 The community fee percentage of the swap fee in thousandths (1e-3) for token0;\n * Returns communityFeeToken1 The community fee percentage of the swap fee in thousandths (1e-3) for token1;\n * Returns unlocked Whether the pool is currently locked to reentrancy;\n */\n function globalState()\n external\n view\n returns (\n uint160 price,\n int24 tick,\n uint16 fee,\n uint16 timepointIndex,\n uint8 communityFeeToken0,\n uint8 communityFeeToken1,\n bool unlocked\n );\n\n /**\n * @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n * @dev This value can overflow the uint256\n */\n function totalFeeGrowth0Token() external view returns (uint256);\n\n /**\n * @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n * @dev This value can overflow the uint256\n */\n function totalFeeGrowth1Token() external view returns (uint256);\n\n /**\n * @notice The currently in range liquidity available to the pool\n * @dev This value has no relationship to the total liquidity across all ticks.\n * Returned value cannot exceed type(uint128).max\n */\n function liquidity() external view returns (uint128);\n\n /**\n * @notice Look up information about a specific tick in the pool\n * @dev This is a public structure, so the `return` natspec tags are omitted.\n * @param tick The tick to look up\n * @return liquidityTotal the total amount of position liquidity that uses the pool either as tick lower or\n * tick upper;\n * Returns liquidityDelta how much liquidity changes when the pool price crosses the tick;\n * Returns outerFeeGrowth0Token the fee growth on the other side of the tick from the current tick in token0;\n * Returns outerFeeGrowth1Token the fee growth on the other side of the tick from the current tick in token1;\n * Returns outerTickCumulative the cumulative tick value on the other side of the tick from the current tick;\n * Returns outerSecondsPerLiquidity the seconds spent per liquidity on the other side of the tick from the current tick;\n * Returns outerSecondsSpent the seconds spent on the other side of the tick from the current tick;\n * Returns initialized Set to true if the tick is initialized, i.e. liquidityTotal is greater than 0\n * otherwise equal to false. Outside values can only be used if the tick is initialized.\n * In addition, these values are only relative and must be used only in comparison to previous snapshots for\n * a specific position.\n */\n function ticks(int24 tick)\n external\n view\n returns (\n uint128 liquidityTotal,\n int128 liquidityDelta,\n uint256 outerFeeGrowth0Token,\n uint256 outerFeeGrowth1Token,\n int56 outerTickCumulative,\n uint160 outerSecondsPerLiquidity,\n uint32 outerSecondsSpent,\n bool initialized\n );\n\n /** @notice Returns 256 packed tick initialized boolean values. See TickTable for more information */\n function tickTable(int16 wordPosition) external view returns (uint256);\n\n /**\n * @notice Returns the information about a position by the position's key\n * @dev This is a public mapping of structures, so the `return` natspec tags are omitted.\n * @param key The position's key is a hash of a preimage composed by the owner, bottomTick and topTick\n * @return liquidityAmount The amount of liquidity in the position;\n * Returns lastLiquidityAddTimestamp Timestamp of last adding of liquidity;\n * Returns innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke;\n * Returns innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke;\n * Returns fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke;\n * Returns fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke\n */\n function positions(bytes32 key)\n external\n view\n returns (\n uint128 liquidityAmount,\n uint32 lastLiquidityAddTimestamp,\n uint256 innerFeeGrowth0Token,\n uint256 innerFeeGrowth1Token,\n uint128 fees0,\n uint128 fees1\n );\n\n /**\n * @notice Returns data about a specific timepoint index\n * @param index The element of the timepoints array to fetch\n * @dev You most likely want to use #getTimepoints() instead of this method to get an timepoint as of some amount of time\n * ago, rather than at a specific index in the array.\n * This is a public mapping of structures, so the `return` natspec tags are omitted.\n * @return initialized whether the timepoint has been initialized and the values are safe to use;\n * Returns blockTimestamp The timestamp of the timepoint;\n * Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the timepoint timestamp;\n * Returns secondsPerLiquidityCumulative the seconds per in range liquidity for the life of the pool as of the timepoint timestamp;\n * Returns volatilityCumulative Cumulative standard deviation for the life of the pool as of the timepoint timestamp;\n * Returns averageTick Time-weighted average tick;\n * Returns volumePerLiquidityCumulative Cumulative swap volume per liquidity for the life of the pool as of the timepoint timestamp;\n */\n function timepoints(uint256 index)\n external\n view\n returns (\n bool initialized,\n uint32 blockTimestamp,\n int56 tickCumulative,\n uint160 secondsPerLiquidityCumulative,\n uint88 volatilityCumulative,\n int24 averageTick,\n uint144 volumePerLiquidityCumulative\n );\n\n /**\n * @notice Returns the information about active incentive\n * @dev if there is no active incentive at the moment, virtualPool,endTimestamp,startTimestamp would be equal to 0\n * @return virtualPool The address of a virtual pool associated with the current active incentive\n */\n function activeIncentive() external view returns (address virtualPool);\n\n /**\n * @notice Returns the lock time for added liquidity\n */\n function liquidityCooldown() external view returns (uint32 cooldownInSeconds);\n}\n" + }, + "contracts/src/external/algebra/IAlgebraSwapCallback.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IAlgebraPoolActions#swap\n/// @notice Any contract that calls IAlgebraPoolActions#swap must implement this interface\n/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:\n/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces\ninterface IAlgebraSwapCallback {\n /// @notice Called to `msg.sender` after executing a swap via IAlgebraPool#swap.\n /// @dev In the implementation you must pay the pool tokens owed for the swap.\n /// The caller of this method must be checked to be a AlgebraPool deployed by the canonical AlgebraFactory.\n /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n /// @param data Any data passed through by the caller via the IAlgebraPoolActions#swap call\n function algebraSwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external;\n}\n" + }, + "contracts/src/external/algebra/ISwapRouter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\n\nimport \"./IAlgebraSwapCallback.sol\";\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Algebra\n/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:\n/// https://github.com/Uniswap/v3-periphery\ninterface IAlgebraSwapRouter is IAlgebraSwapCallback {\n struct ExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n uint160 limitSqrtPrice;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactInputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n uint160 limitSqrtPrice;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\n\n struct ExactOutputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n /// @dev Unlike standard swaps, handles transferring from user before the actual swap.\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingleSupportingFeeOnTransferTokens(ExactInputSingleParams calldata params)\n external\n returns (uint256 amountOut);\n}\n" + }, + "contracts/src/external/api3/IProxy.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IProxy {\n function read() external view returns (int224 value, uint32 timestamp);\n\n function api3ServerV1() external view returns (address);\n}\n" + }, + "contracts/src/external/chainlink/AggregatorInterface.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\ninterface AggregatorInterface {\n function latestAnswer() external view returns (int256);\n\n function latestTimestamp() external view returns (uint256);\n\n function latestRound() external view returns (uint256);\n\n function getAnswer(uint256 roundId) external view returns (int256);\n\n function getTimestamp(uint256 roundId) external view returns (uint256);\n\n event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);\n\n event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);\n}\n" + }, + "contracts/src/external/chainlink/AggregatorV2V3Interface.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport \"./AggregatorInterface.sol\";\nimport \"./AggregatorV3Interface.sol\";\n\ninterface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}\n" + }, + "contracts/src/external/chainlink/AggregatorV3Interface.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\ninterface AggregatorV3Interface {\n function decimals() external view returns (uint8);\n\n function description() external view returns (string memory);\n\n function version() external view returns (uint256);\n\n // getRoundData and latestRoundData should both raise \"No data present\"\n // if they do not have data to report, instead of returning unset values\n // which could be misinterpreted as actual reported values.\n function getRoundData(uint80 _roundId)\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n function latestRoundData()\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n}\n" + }, + "contracts/src/external/chainlink/Denominations.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nlibrary Denominations {\n address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;\n address public constant BTC = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;\n\n // Fiat currencies follow https://en.wikipedia.org/wiki/ISO_4217\n address public constant USD = address(840);\n address public constant GBP = address(826);\n address public constant EUR = address(978);\n address public constant JPY = address(392);\n address public constant KRW = address(410);\n address public constant CNY = address(156);\n address public constant AUD = address(36);\n address public constant CAD = address(124);\n address public constant CHF = address(756);\n address public constant ARS = address(32);\n address public constant PHP = address(608);\n address public constant NZD = address(554);\n address public constant SGD = address(702);\n address public constant NGN = address(566);\n address public constant ZAR = address(710);\n address public constant RUB = address(643);\n address public constant INR = address(356);\n address public constant BRL = address(986);\n}\n" + }, + "contracts/src/external/chainlink/FeedRegistryInterface.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport \"./AggregatorV2V3Interface.sol\";\n\ninterface FeedRegistryInterface {\n struct Phase {\n uint16 phaseId;\n uint80 startingAggregatorRoundId;\n uint80 endingAggregatorRoundId;\n }\n\n event FeedProposed(\n address indexed asset,\n address indexed denomination,\n address indexed proposedAggregator,\n address currentAggregator,\n address sender\n );\n event FeedConfirmed(\n address indexed asset,\n address indexed denomination,\n address indexed latestAggregator,\n address previousAggregator,\n uint16 nextPhaseId,\n address sender\n );\n\n // V3 AggregatorV3Interface\n\n function decimals(address base, address quote) external view returns (uint8);\n\n function description(address base, address quote) external view returns (string memory);\n\n function version(address base, address quote) external view returns (uint256);\n\n function latestRoundData(address base, address quote)\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n function getRoundData(\n address base,\n address quote,\n uint80 _roundId\n )\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n // V2 AggregatorInterface\n\n function latestAnswer(address base, address quote) external view returns (int256 answer);\n\n function latestTimestamp(address base, address quote) external view returns (uint256 timestamp);\n\n function latestRound(address base, address quote) external view returns (uint256 roundId);\n\n function getAnswer(\n address base,\n address quote,\n uint256 roundId\n ) external view returns (int256 answer);\n\n function getTimestamp(\n address base,\n address quote,\n uint256 roundId\n ) external view returns (uint256 timestamp);\n\n // Registry getters\n\n function getFeed(address base, address quote) external view returns (AggregatorV2V3Interface aggregator);\n\n function getPhaseFeed(\n address base,\n address quote,\n uint16 phaseId\n ) external view returns (AggregatorV2V3Interface aggregator);\n\n function isFeedEnabled(address aggregator) external view returns (bool);\n\n function getPhase(\n address base,\n address quote,\n uint16 phaseId\n ) external view returns (Phase memory phase);\n\n // Round helpers\n\n function getRoundFeed(\n address base,\n address quote,\n uint80 roundId\n ) external view returns (AggregatorV2V3Interface aggregator);\n\n function getPhaseRange(\n address base,\n address quote,\n uint16 phaseId\n ) external view returns (uint80 startingRoundId, uint80 endingRoundId);\n\n function getPreviousRoundId(\n address base,\n address quote,\n uint80 roundId\n ) external view returns (uint80 previousRoundId);\n\n function getNextRoundId(\n address base,\n address quote,\n uint80 roundId\n ) external view returns (uint80 nextRoundId);\n\n // Feed management\n\n function proposeFeed(\n address base,\n address quote,\n address aggregator\n ) external;\n\n function confirmFeed(\n address base,\n address quote,\n address aggregator\n ) external;\n\n // Proposed aggregator\n\n function getProposedFeed(address base, address quote)\n external\n view\n returns (AggregatorV2V3Interface proposedAggregator);\n\n function proposedGetRoundData(\n address base,\n address quote,\n uint80 roundId\n )\n external\n view\n returns (\n uint80 id,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n function proposedLatestRoundData(address base, address quote)\n external\n view\n returns (\n uint80 id,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n // Phases\n function getCurrentPhaseId(address base, address quote) external view returns (uint16 currentPhaseId);\n}\n" + }, + "contracts/src/external/compound/ICErc20.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity >=0.8.0;\n\nimport \"./ICToken.sol\";\n\n/**\n * @title Compound's CErc20 Contract\n * @notice CTokens which wrap an EIP-20 underlying\n * @author Compound\n */\ninterface ICErc20Compound is ICToken {\n function underlying() external view returns (address);\n\n function liquidateBorrow(\n address borrower,\n uint256 repayAmount,\n ICToken cTokenCollateral\n ) external returns (uint256);\n\n function getTotalUnderlyingSupplied() external view returns (uint256);\n}\n" + }, + "contracts/src/external/compound/IComptroller.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity >=0.8.0;\n\nimport \"./IPriceOracle.sol\";\nimport \"./ICToken.sol\";\nimport \"./IUnitroller.sol\";\nimport \"./IRewardsDistributor.sol\";\n\n/**\n * @title Compound's Comptroller Contract\n * @author Compound\n */\ninterface IComptroller {\n function admin() external view returns (address);\n\n function adminHasRights() external view returns (bool);\n\n function ionicAdminHasRights() external view returns (bool);\n\n function oracle() external view returns (IPriceOracle);\n\n function pauseGuardian() external view returns (address);\n\n function closeFactorMantissa() external view returns (uint256);\n\n function liquidationIncentiveMantissa() external view returns (uint256);\n\n function markets(address cToken) external view returns (bool, uint256);\n\n function getAssetsIn(address account) external view returns (ICToken[] memory);\n\n function checkMembership(address account, ICToken cToken) external view returns (bool);\n\n function getHypotheticalAccountLiquidity(\n address account,\n address cTokenModify,\n uint256 redeemTokens,\n uint256 borrowAmount,\n uint256 repayAmount\n )\n external\n view\n returns (\n uint256,\n uint256,\n uint256\n );\n\n function getAccountLiquidity(address account)\n external\n view\n returns (\n uint256,\n uint256,\n uint256\n );\n\n function _setPriceOracle(IPriceOracle newOracle) external returns (uint256);\n\n function _setCloseFactor(uint256 newCloseFactorMantissa) external returns (uint256);\n\n function _setCollateralFactor(ICToken market, uint256 newCollateralFactorMantissa) external returns (uint256);\n\n function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external returns (uint256);\n\n function _become(IUnitroller unitroller) external;\n\n function borrowGuardianPaused(address cToken) external view returns (bool);\n\n function mintGuardianPaused(address cToken) external view returns (bool);\n\n function getRewardsDistributors() external view returns (address[] memory);\n\n function getAllMarkets() external view returns (ICToken[] memory);\n\n function getAllBorrowers() external view returns (address[] memory);\n\n function suppliers(address account) external view returns (bool);\n\n function supplyCaps(address cToken) external view returns (uint256);\n\n function borrowCaps(address cToken) external view returns (uint256);\n\n function enforceWhitelist() external view returns (bool);\n\n function enterMarkets(address[] memory cTokens) external returns (uint256[] memory);\n\n function exitMarket(address cTokenAddress) external returns (uint256);\n\n function autoImplementation() external view returns (bool);\n\n function isUserOfPool(address user) external view returns (bool);\n\n function whitelist(address account) external view returns (bool);\n\n function _setWhitelistEnforcement(bool enforce) external returns (uint256);\n\n function _setWhitelistStatuses(address[] calldata _suppliers, bool[] calldata statuses) external returns (uint256);\n\n function _toggleAutoImplementations(bool enabled) external returns (uint256);\n\n function _deployMarket(\n bool isCEther,\n bytes memory constructorData,\n bytes calldata becomeImplData,\n uint256 collateralFactorMantissa\n ) external returns (uint256);\n\n function getMaxRedeemOrBorrow(\n address account,\n ICToken cTokenModify,\n bool isBorrow\n ) external view returns (uint256);\n\n function borrowCapForCollateral(address borrowed, address collateral) external view returns (uint256);\n\n function borrowingAgainstCollateralBlacklist(address borrowed, address collateral) external view returns (bool);\n\n function isDeprecated(ICToken cToken) external view returns (bool);\n\n function getWhitelistedSuppliersSupply(address cToken) external view returns (uint256 supplied);\n\n function getWhitelistedBorrowersBorrows(address cToken) external view returns (uint256 borrowed);\n}\n" + }, + "contracts/src/external/compound/ICToken.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity >=0.8.0;\n\n/**\n * @title Compound's CToken Contract\n * @notice Abstract base for CTokens\n * @author Compound\n */\ninterface ICToken {\n function admin() external view returns (address);\n\n function adminHasRights() external view returns (bool);\n\n function ionicAdminHasRights() external view returns (bool);\n\n function symbol() external view returns (string memory);\n\n function comptroller() external view returns (address);\n\n function adminFeeMantissa() external view returns (uint256);\n\n function ionicFeeMantissa() external view returns (uint256);\n\n function reserveFactorMantissa() external view returns (uint256);\n\n function totalReserves() external view returns (uint256);\n\n function totalAdminFees() external view returns (uint256);\n\n function totalIonicFees() external view returns (uint256);\n\n function isCToken() external view returns (bool);\n\n function isCEther() external view returns (bool);\n\n function balanceOf(address owner) external view returns (uint256);\n\n function balanceOfUnderlying(address owner) external returns (uint256);\n\n function borrowRatePerBlock() external view returns (uint256);\n\n function supplyRatePerBlock() external view returns (uint256);\n\n function totalBorrowsCurrent() external returns (uint256);\n\n function totalBorrows() external view returns (uint256);\n\n function totalSupply() external view returns (uint256);\n\n function borrowBalanceStored(address account) external view returns (uint256);\n\n function borrowBalanceCurrent(address account) external returns (uint256);\n\n function exchangeRateCurrent() external returns (uint256);\n\n function exchangeRateStored() external view returns (uint256);\n\n function accrueInterest() external returns (uint256);\n\n function getCash() external view returns (uint256);\n\n function mint(uint256 mintAmount) external returns (uint256);\n\n function redeem(uint256 redeemTokens) external returns (uint256);\n\n function redeemUnderlying(uint256 redeemAmount) external returns (uint256);\n\n function borrow(uint256 borrowAmount) external returns (uint256);\n\n function repayBorrow(uint256 repayAmount) external returns (uint256);\n\n function protocolSeizeShareMantissa() external view returns (uint256);\n\n function feeSeizeShareMantissa() external view returns (uint256);\n\n function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);\n\n function _setAdminFee(uint256 newAdminFeeMantissa) external returns (uint256);\n}\n" + }, + "contracts/src/external/compound/IPriceOracle.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity >=0.8.0;\n\nimport \"./ICToken.sol\";\n\ninterface IPriceOracle {\n /**\n * @notice Get the underlying price of a cToken asset\n * @param cToken The cToken to get the underlying price of\n * @return The underlying asset price mantissa (scaled by 1e18).\n * Zero means the price is unavailable.\n */\n function getUnderlyingPrice(ICToken cToken) external view returns (uint256);\n}\n" + }, + "contracts/src/external/compound/IRewardsDistributor.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity >=0.8.0;\n\nimport \"./ICToken.sol\";\n\n/**\n * @title RewardsDistributor\n * @author Compound\n */\ninterface IRewardsDistributor {\n /// @dev The token to reward (i.e., COMP)\n function rewardToken() external view returns (address);\n\n /// @notice The portion of compRate that each market currently receives\n function compSupplySpeeds(address) external view returns (uint256);\n\n /// @notice The portion of compRate that each market currently receives\n function compBorrowSpeeds(address) external view returns (uint256);\n\n /// @notice The COMP accrued but not yet transferred to each user\n function compAccrued(address) external view returns (uint256);\n\n /**\n * @notice Keeps the flywheel moving pre-mint and pre-redeem\n * @dev Called by the Comptroller\n * @param cToken The relevant market\n * @param supplier The minter/redeemer\n */\n function flywheelPreSupplierAction(address cToken, address supplier) external;\n\n /**\n * @notice Keeps the flywheel moving pre-borrow and pre-repay\n * @dev Called by the Comptroller\n * @param cToken The relevant market\n * @param borrower The borrower\n */\n function flywheelPreBorrowerAction(address cToken, address borrower) external;\n\n /**\n * @notice Returns an array of all markets.\n */\n function getAllMarkets() external view returns (ICToken[] memory);\n}\n" + }, + "contracts/src/external/compound/IUnitroller.sol": { + "content": "// SPDX-License-Identifier: BSD-3-Clause\npragma solidity >=0.8.0;\n\n/**\n * @title ComptrollerCore\n * @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`.\n * CTokens should reference this contract as their comptroller.\n */\ninterface IUnitroller {\n function _setPendingImplementation(address newPendingImplementation) external returns (uint256);\n\n function _setPendingAdmin(address newPendingAdmin) external returns (uint256);\n}\n" + }, + "contracts/src/external/curve/ICurveLiquidityGaugeV2.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\ninterface ICurveLiquidityGaugeV2 {\n function lp_token() external view returns (address);\n\n function deposit(uint256 _value) external;\n\n function withdraw(uint256 _value) external;\n}\n" + }, + "contracts/src/external/curve/ICurvePool.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ninterface ICurvePool is IERC20Upgradeable {\n function get_virtual_price() external view returns (uint256);\n\n function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external;\n\n function calc_withdraw_one_coin(uint256 _burn_amount, int128 i) external view returns (uint256);\n\n function add_liquidity(uint256[2] calldata _amounts, uint256 _min_mint_amount) external returns (uint256);\n\n function exchange(int128 i, int128 j, uint256 dx, uint256 min_dy) external returns (uint256);\n\n function get_dy(int128 i, int128 j, uint256 _dx) external view returns (uint256);\n\n function coins(uint256 index) external view returns (address);\n\n function lp_token() external view returns (address);\n}\n" + }, + "contracts/src/external/curve/ICurveRegistry.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\ninterface ICurveRegistry {\n function get_n_coins(address lp) external view returns (uint256);\n\n function get_coins(address pool) external view returns (address[8] memory);\n\n function get_pool_from_lp_token(address lp) external view returns (address);\n}\n" + }, + "contracts/src/external/curve/ICurveStableSwap.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ninterface ICurveStableSwap is IERC20Upgradeable {\n function get_balances() external view returns (uint256[2] memory);\n\n function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_amount) external;\n}\n" + }, + "contracts/src/external/curve/ICurveV2Pool.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { ICurvePool } from \"./ICurvePool.sol\";\n\ninterface ICurveV2Pool is ICurvePool {\n function price_oracle() external view returns (uint256);\n\n function lp_price() external view returns (uint256);\n\n function coins(uint256 arg0) external view returns (address);\n}\n" + }, + "contracts/src/external/hypernative/interfaces/IHypernativeOracle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.22;\n\ninterface IHypernativeOracle {\n function register(address account, bool isStrictMode) external;\n function validateForbiddenAccountInteraction(address sender) external view;\n function validateForbiddenContextInteraction(address origin, address sender) external view;\n function validateBlacklistedAccountInteraction(address sender) external;\n}" + }, + "contracts/src/external/pyth/IExpressRelay.sol": { + "content": "// SPDX-License-Identifier: Apache 2\npragma solidity ^0.8.0;\n\ninterface IExpressRelay {\n // Check if the combination of protocol and permissionKey is allowed within this transaction.\n // This will return true if and only if it's being called while executing the auction winner(s) call.\n // @param protocolFeeReceiver The address of the protocol that is gating an action behind this permission\n // @param permissionId The id that represents the action being gated\n // @return permissioned True if the permission is allowed, false otherwise\n function isPermissioned(\n address protocolFeeReceiver,\n bytes calldata permissionId\n ) external view returns (bool permissioned);\n}\n" + }, + "contracts/src/external/pyth/IExpressRelayFeeReceiver.sol": { + "content": "// SPDX-License-Identifier: Apache 2\npragma solidity ^0.8.0;\n\ninterface IExpressRelayFeeReceiver {\n // Receive the proceeds of an auction.\n // @param permissionKey The permission key where the auction was conducted on.\n function receiveAuctionProceedings(\n bytes calldata permissionKey\n ) external payable;\n}\n" + }, + "contracts/src/external/redstone/IRedstoneOracle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\ninterface IRedstoneOracle {\n function priceOf(address asset) external view returns (uint256);\n\n function priceOfETH() external view returns (uint256);\n\n function getDataFeedIdForAsset(address asset) external view returns (bytes32);\n\n function getDataFeedIds() external view returns (bytes32[] memory dataFeedIds);\n}\n" + }, + "contracts/src/external/uniswap/FullMath.sol": { + "content": "// SPDX-License-Identifier: MIT\n\n// From Uniswap3 Core\n\n// Updated to Solidity 0.8 by Midas Capital:\n// * Rewrite unary negation of denominator, which is a uint\n// * Wrapped function bodies with \"unchecked {}\" so as to not add any extra gas costs\n\npragma solidity ^0.8.0;\n\n/// @title Contains 512-bit math functions\n/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision\n/// @dev Handles \"phantom overflow\" i.e., allows multiplication and division where an intermediate value overflows 256 bits\nlibrary FullMath {\n /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv\n function mulDiv(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = a * b\n // Compute the product mod 2**256 and mod 2**256 - 1\n // then use the Chinese Remainder Theorem to reconstruct\n // the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2**256 + prod0\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(a, b, not(0))\n prod0 := mul(a, b)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division\n if (prod1 == 0) {\n require(denominator > 0);\n assembly {\n result := div(prod0, denominator)\n }\n return result;\n }\n\n // Make sure the result is less than 2**256.\n // Also prevents denominator == 0\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0]\n // Compute remainder using mulmod\n uint256 remainder;\n assembly {\n remainder := mulmod(a, b, denominator)\n }\n // Subtract 256 bit number from 512 bit number\n assembly {\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator\n // Compute largest power of two divisor of denominator.\n // Always >= 1.\n uint256 twos = denominator & (~denominator + 1);\n\n // Divide denominator by power of two\n assembly {\n denominator := div(denominator, twos)\n }\n\n // Divide [prod1 prod0] by the factors of two\n assembly {\n prod0 := div(prod0, twos)\n }\n // Shift in bits from prod1 into prod0. For this we need\n // to flip `twos` such that it is 2**256 / twos.\n // If twos is zero, then it becomes one\n assembly {\n twos := add(div(sub(0, twos), twos), 1)\n }\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2**256\n // Now that denominator is an odd number, it has an inverse\n // modulo 2**256 such that denominator * inv = 1 mod 2**256.\n // Compute the inverse by starting with a seed that is correct\n // correct for four bits. That is, denominator * inv = 1 mod 2**4\n uint256 inv = (3 * denominator) ^ 2;\n // Now use Newton-Raphson iteration to improve the precision.\n // Thanks to Hensel's lifting lemma, this also works in modular\n // arithmetic, doubling the correct bits in each step.\n inv *= 2 - denominator * inv; // inverse mod 2**8\n inv *= 2 - denominator * inv; // inverse mod 2**16\n inv *= 2 - denominator * inv; // inverse mod 2**32\n inv *= 2 - denominator * inv; // inverse mod 2**64\n inv *= 2 - denominator * inv; // inverse mod 2**128\n inv *= 2 - denominator * inv; // inverse mod 2**256\n\n // Because the division is now exact we can divide by multiplying\n // with the modular inverse of denominator. This will give us the\n // correct result modulo 2**256. Since the precoditions guarantee\n // that the outcome is less than 2**256, this is the final result.\n // We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inv;\n return result;\n }\n }\n\n /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n /// @param a The multiplicand\n /// @param b The multiplier\n /// @param denominator The divisor\n /// @return result The 256-bit result\n function mulDivRoundingUp(\n uint256 a,\n uint256 b,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n result = mulDiv(a, b, denominator);\n if (mulmod(a, b, denominator) > 0) {\n require(result < type(uint256).max);\n result++;\n }\n }\n }\n}\n" + }, + "contracts/src/external/uniswap/ISwapRouter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Uniswap V3\ninterface ISwapRouter {\n struct ExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n uint160 sqrtPriceLimitX96;\n }\n\n struct ExactInputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountIn;\n uint256 amountOutMinimum;\n }\n\n struct ExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n uint160 sqrtPriceLimitX96;\n }\n\n struct ExactOutputParams {\n bytes path;\n address recipient;\n uint256 deadline;\n uint256 amountOut;\n uint256 amountInMaximum;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n function exactInput(ExactInputParams calldata params) external returns (uint256 amountOut);\n\n function exactOutputSingle(ExactOutputSingleParams calldata params) external returns (uint256 amountIn);\n\n function exactOutput(ExactOutputParams calldata params) external returns (uint256 amountIn);\n\n function factory() external returns (address);\n\n function multicall(uint256 deadline, bytes[] calldata data) external payable returns (bytes[] memory);\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV1Exchange.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\ninterface IUniswapV1Exchange {\n function tokenToEthSwapInput(\n uint256 tokens_sold,\n uint256 min_eth,\n uint256 deadline\n ) external returns (uint256);\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV1Factory.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\ninterface IUniswapV1Factory {\n function getExchange(address token) external view returns (address);\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV2Callee.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\ninterface IUniswapV2Callee {\n function uniswapV2Call(\n address sender,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external;\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV2Factory.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\ninterface IUniswapV2Factory {\n event PairCreated(address indexed token0, address indexed token1, address pair, uint256);\n\n function feeTo() external view returns (address);\n\n function feeToSetter() external view returns (address);\n\n function getPair(address tokenA, address tokenB) external view returns (address pair);\n\n function allPairs(uint256) external view returns (address pair);\n\n function allPairsLength() external view returns (uint256);\n\n function createPair(address tokenA, address tokenB) external returns (address pair);\n\n function setFeeTo(address) external;\n\n function setFeeToSetter(address) external;\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV2Pair.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\ninterface IUniswapV2Pair {\n event Approval(address indexed owner, address indexed spender, uint256 value);\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n function name() external pure returns (string memory);\n\n function symbol() external pure returns (string memory);\n\n function decimals() external pure returns (uint8);\n\n function totalSupply() external view returns (uint256);\n\n function balanceOf(address owner) external view returns (uint256);\n\n function allowance(address owner, address spender) external view returns (uint256);\n\n function approve(address spender, uint256 value) external returns (bool);\n\n function transfer(address to, uint256 value) external returns (bool);\n\n function transferFrom(\n address from,\n address to,\n uint256 value\n ) external returns (bool);\n\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n\n function PERMIT_TYPEHASH() external pure returns (bytes32);\n\n function nonces(address owner) external view returns (uint256);\n\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n event Mint(address indexed sender, uint256 amount0, uint256 amount1);\n event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to);\n event Swap(\n address indexed sender,\n uint256 amount0In,\n uint256 amount1In,\n uint256 amount0Out,\n uint256 amount1Out,\n address indexed to\n );\n event Sync(uint112 reserve0, uint112 reserve1);\n\n function MINIMUM_LIQUIDITY() external pure returns (uint256);\n\n function factory() external view returns (address);\n\n function token0() external view returns (address);\n\n function token1() external view returns (address);\n\n function getReserves()\n external\n view\n returns (\n uint112 reserve0,\n uint112 reserve1,\n uint32 blockTimestampLast\n );\n\n function price0CumulativeLast() external view returns (uint256);\n\n function price1CumulativeLast() external view returns (uint256);\n\n function kLast() external view returns (uint256);\n\n function mint(address to) external returns (uint256 liquidity);\n\n function burn(address to) external returns (uint256 amount0, uint256 amount1);\n\n function swap(\n uint256 amount0Out,\n uint256 amount1Out,\n address to,\n bytes calldata data\n ) external;\n\n function skim(address to) external;\n\n function sync() external;\n\n function initialize(address, address) external;\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV2Router01.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\ninterface IUniswapV2Router01 {\n function factory() external pure returns (address);\n\n function WETH() external pure returns (address);\n\n function addLiquidity(\n address tokenA,\n address tokenB,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n )\n external\n returns (\n uint256 amountA,\n uint256 amountB,\n uint256 liquidity\n );\n\n function addLiquidityETH(\n address token,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n )\n external\n payable\n returns (\n uint256 amountToken,\n uint256 amountETH,\n uint256 liquidity\n );\n\n function removeLiquidity(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETH(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function removeLiquidityWithPermit(\n address tokenA,\n address tokenB,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountA, uint256 amountB);\n\n function removeLiquidityETHWithPermit(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapTokensForExactTokens(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapExactETHForTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function swapTokensForExactETH(\n uint256 amountOut,\n uint256 amountInMax,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n function swapETHForExactTokens(\n uint256 amountOut,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n function quote(\n uint256 amountA,\n uint256 reserveA,\n uint256 reserveB\n ) external pure returns (uint256 amountB);\n\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountOut);\n\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut\n ) external pure returns (uint256 amountIn);\n\n function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);\n\n function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV2Router02.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\nimport \"./IUniswapV2Router01.sol\";\n\ninterface IUniswapV2Router02 is IUniswapV2Router01 {\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountETH);\n\n function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(\n address token,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline,\n bool approveMax,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external returns (uint256 amountETH);\n\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external;\n\n function swapExactTokensForTokensSupportingFeeOnTransferTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n address referrer,\n uint256 deadline\n ) external;\n\n function swapExactETHForTokensSupportingFeeOnTransferTokens(\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external payable;\n\n function swapExactTokensForETHSupportingFeeOnTransferTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n address[] calldata path,\n address to,\n uint256 deadline\n ) external;\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV3Factory.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title The interface for the Uniswap V3 Factory\n/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees\ninterface IUniswapV3Factory {\n /// @notice Emitted when the owner of the factory is changed\n /// @param oldOwner The owner before the owner was changed\n /// @param newOwner The owner after the owner was changed\n event OwnerChanged(address indexed oldOwner, address indexed newOwner);\n\n /// @notice Emitted when a pool is created\n /// @param token0 The first token of the pool by address sort order\n /// @param token1 The second token of the pool by address sort order\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks\n /// @param pool The address of the created pool\n event PoolCreated(\n address indexed token0,\n address indexed token1,\n uint24 indexed fee,\n int24 tickSpacing,\n address pool\n );\n\n /// @notice Emitted when a new fee amount is enabled for pool creation via the factory\n /// @param fee The enabled fee, denominated in hundredths of a bip\n /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee\n event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);\n\n /// @notice Returns the current owner of the factory\n /// @dev Can be changed by the current owner via setOwner\n /// @return The address of the factory owner\n function owner() external view returns (address);\n\n /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled\n /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context\n /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee\n /// @return The tick spacing\n function feeAmountTickSpacing(uint24 fee) external view returns (int24);\n\n /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist\n /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order\n /// @param tokenA The contract address of either token0 or token1\n /// @param tokenB The contract address of the other token\n /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip\n /// @return pool The pool address\n function getPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external view returns (address pool);\n\n /// @notice Creates a pool for the given two tokens and fee\n /// @param tokenA One of the two tokens in the desired pool\n /// @param tokenB The other of the two tokens in the desired pool\n /// @param fee The desired fee for the pool\n /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved\n /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments\n /// are invalid.\n /// @return pool The address of the newly created pool\n function createPool(\n address tokenA,\n address tokenB,\n uint24 fee\n ) external returns (address pool);\n\n /// @notice Updates the owner of the factory\n /// @dev Must be called by the current owner\n /// @param _owner The new owner of the factory\n function setOwner(address _owner) external;\n\n /// @notice Enables a fee amount with the given tickSpacing\n /// @dev Fee amounts may never be removed once enabled\n /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)\n /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount\n function enableFeeAmount(uint24 fee, int24 tickSpacing) external;\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV3FlashCallback.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#flash\n/// @notice Any contract that calls IUniswapV3PoolActions#flash must implement this interface\ninterface IUniswapV3FlashCallback {\n /// @notice Called to `msg.sender` after transferring to the recipient from IUniswapV3Pool#flash.\n /// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// @param fee0 The fee amount in token0 due to the pool by the end of the flash\n /// @param fee1 The fee amount in token1 due to the pool by the end of the flash\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#flash call\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external;\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV3Pool.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\nimport \"./IUniswapV3PoolActions.sol\";\n\ninterface IUniswapV3Pool is IUniswapV3PoolActions {\n function token0() external view returns (address);\n\n function token1() external view returns (address);\n\n function fee() external view returns (uint24);\n\n function slot0()\n external\n view\n returns (\n uint160 sqrtPriceX96,\n int24 tick,\n uint16 observationIndex,\n uint16 observationCardinality,\n uint16 observationCardinalityNext,\n uint8 feeProtocol,\n bool unlocked\n );\n\n function liquidity() external view returns (uint128);\n\n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory liquidityCumulatives);\n\n function observations(uint256 index)\n external\n view\n returns (\n uint32 blockTimestamp,\n int56 tickCumulative,\n uint160 liquidityCumulative,\n bool initialized\n );\n\n function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n function ticks(int24 tick)\n external\n view\n returns (\n uint128 liquidityGross,\n int128 liquidityNet,\n uint256 feeGrowthOutside0X128,\n uint256 feeGrowthOutside1X128,\n int56 tickCumulativeOutside,\n uint160 secondsPerLiquidityOutsideX128,\n uint32 secondsOutside,\n bool initialized\n );\n\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n\n function positions(bytes32 key)\n external\n view\n returns (\n uint128 _liquidity,\n uint256 feeGrowthInside0LastX128,\n uint256 feeGrowthInside1LastX128,\n uint128 tokensOwed0,\n uint128 tokensOwed1\n );\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV3PoolActions.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissionless pool actions\n/// @notice Contains pool methods that can be called by anyone\ninterface IUniswapV3PoolActions {\n /// @notice Sets the initial price for the pool\n /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value\n /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96\n function initialize(uint160 sqrtPriceX96) external;\n\n /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position\n /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback\n /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends\n /// on tickLower, tickUpper, the amount of liquidity, and the current price.\n /// @param recipient The address for which the liquidity will be created\n /// @param tickLower The lower tick of the position in which to add liquidity\n /// @param tickUpper The upper tick of the position in which to add liquidity\n /// @param amount The amount of liquidity to mint\n /// @param data Any data that should be passed through to the callback\n /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback\n /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback\n function mint(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount,\n bytes calldata data\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Collects tokens owed to a position\n /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.\n /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or\n /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the\n /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.\n /// @param recipient The address which should receive the fees collected\n /// @param tickLower The lower tick of the position for which to collect fees\n /// @param tickUpper The upper tick of the position for which to collect fees\n /// @param amount0Requested How much token0 should be withdrawn from the fees owed\n /// @param amount1Requested How much token1 should be withdrawn from the fees owed\n /// @return amount0 The amount of fees collected in token0\n /// @return amount1 The amount of fees collected in token1\n function collect(\n address recipient,\n int24 tickLower,\n int24 tickUpper,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n\n /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position\n /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0\n /// @dev Fees must be collected separately via a call to #collect\n /// @param tickLower The lower tick of the position for which to burn liquidity\n /// @param tickUpper The upper tick of the position for which to burn liquidity\n /// @param amount How much liquidity to burn\n /// @return amount0 The amount of token0 sent to the recipient\n /// @return amount1 The amount of token1 sent to the recipient\n function burn(\n int24 tickLower,\n int24 tickUpper,\n uint128 amount\n ) external returns (uint256 amount0, uint256 amount1);\n\n /// @notice Swap token0 for token1, or token1 for token0\n /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback\n /// @param recipient The address to receive the output of the swap\n /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0\n /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)\n /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this\n /// value after the swap. If one for zero, the price cannot be greater than this value after the swap\n /// @param data Any data to be passed through to the callback\n /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive\n /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive\n function swap(\n address recipient,\n bool zeroForOne,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bytes calldata data\n ) external returns (int256 amount0, int256 amount1);\n\n /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback\n /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback\n /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling\n /// with 0 amount{0,1} and sending the donation amount(s) from the callback\n /// @param recipient The address which will receive the token0 and token1 amounts\n /// @param amount0 The amount of token0 to send\n /// @param amount1 The amount of token1 to send\n /// @param data Any data to be passed through to the callback\n function flash(\n address recipient,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external;\n\n /// @notice Increase the maximum number of price and liquidity observations that this pool will store\n /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to\n /// the input observationCardinalityNext.\n /// @param observationCardinalityNext The desired minimum number of observations for the pool to store\n function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV3PoolImmutables.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that never changes\n/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values\ninterface IUniswapV3PoolImmutables {\n /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface\n /// @return The contract address\n function factory() external view returns (address);\n\n /// @notice The first of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token0() external view returns (address);\n\n /// @notice The second of the two tokens of the pool, sorted by address\n /// @return The token contract address\n function token1() external view returns (address);\n\n /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6\n /// @return The fee\n function fee() external view returns (uint24);\n\n /// @notice The pool tick spacing\n /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive\n /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...\n /// This value is an int24 to avoid casting even though it is always positive.\n /// @return The tick spacing\n function tickSpacing() external view returns (int24);\n\n /// @notice The maximum amount of position liquidity that can use any tick in the range\n /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and\n /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool\n /// @return The max amount of liquidity per tick\n function maxLiquidityPerTick() external view returns (uint128);\n}\n" + }, + "contracts/src/external/uniswap/IUniswapV3SwapCallback.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Callback for IUniswapV3PoolActions#swap\n/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface\ninterface IUniswapV3SwapCallback {\n /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.\n /// @dev In the implementation you must pay the pool tokens owed for the swap.\n /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.\n /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.\n /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.\n /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by\n /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.\n /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call\n function uniswapV3SwapCallback(\n int256 amount0Delta,\n int256 amount1Delta,\n bytes calldata data\n ) external;\n}\n" + }, + "contracts/src/external/uniswap/IV3SwapRouter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\nimport './IUniswapV3SwapCallback.sol';\n\n/// @title Router token swapping functionality\n/// @notice Functions for swapping tokens via Uniswap V3\ninterface IV3SwapRouter is IUniswapV3SwapCallback {\n struct ExactInputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 amountIn;\n uint256 amountOutMinimum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another token\n /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,\n /// and swap the entire amount, enabling contracts to send tokens before calling this function.\n /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactInputParams {\n bytes path;\n address recipient;\n uint256 amountIn;\n uint256 amountOutMinimum;\n }\n\n /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path\n /// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,\n /// and swap the entire amount, enabling contracts to send tokens before calling this function.\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata\n /// @return amountOut The amount of the received token\n function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);\n\n struct ExactOutputSingleParams {\n address tokenIn;\n address tokenOut;\n uint24 fee;\n address recipient;\n uint256 amountOut;\n uint256 amountInMaximum;\n uint160 sqrtPriceLimitX96;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another token\n /// that may remain in the router after the swap.\n /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);\n\n struct ExactOutputParams {\n bytes path;\n address recipient;\n uint256 amountOut;\n uint256 amountInMaximum;\n }\n\n /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)\n /// that may remain in the router after the swap.\n /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata\n /// @return amountIn The amount of the input token\n function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);\n}\n" + }, + "contracts/src/external/uniswap/LiquidityAmounts.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.5.0;\n\nimport { FullMath } from \"./FullMath.sol\";\n\nlibrary FixedPoint96 {\n uint8 internal constant RESOLUTION = 96;\n uint256 internal constant Q96 = 0x1000000000000000000000000;\n}\n\n/// @title Liquidity amount functions\n/// @notice Provides functions for computing liquidity amounts from token amounts and prices\nlibrary LiquidityAmounts {\n function toUint128(uint256 x) private pure returns (uint128 y) {\n require((y = uint128(x)) == x);\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token0 and price range\n /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)).\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param amount0 The amount0 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount0(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);\n return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the amount of liquidity received for a given amount of token1 and price range\n /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param amount1 The amount1 being sent in\n /// @return liquidity The amount of returned liquidity\n function getLiquidityForAmount1(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));\n }\n\n /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current\n /// pool prices and the prices at the tick boundaries\n function getLiquidityForAmounts(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint256 amount0,\n uint256 amount1\n ) internal pure returns (uint128 liquidity) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);\n uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);\n\n liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;\n } else {\n liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);\n }\n }\n\n /// @notice Computes the amount of token0 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The liquidity being valued\n /// @return amount0 The amount0\n function getAmount0ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n FullMath.mulDiv(uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96) /\n sqrtRatioAX96;\n }\n\n /// @notice Computes the amount of token1 for a given amount of liquidity and a price range\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The liquidity being valued\n /// @return amount1 The amount1\n function getAmount1ForLiquidity(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current\n /// pool prices and the prices at the tick boundaries\n function getAmountsForLiquidity(\n uint160 sqrtRatioX96,\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity\n ) internal pure returns (uint256 amount0, uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n if (sqrtRatioX96 <= sqrtRatioAX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n } else if (sqrtRatioX96 < sqrtRatioBX96) {\n amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);\n } else {\n amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);\n }\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/interfaces/IQuoter.sol": { + "content": "// SPDX-License-Identifier: BUSL-1.1\npragma solidity >=0.8.0 <0.9.0;\n\ninterface IQuoter {\n function estimateMaxSwapUniswapV3(\n address _fromToken,\n address _toToken,\n uint256 _amount,\n uint24 _poolFee\n ) external view returns (uint256);\n\n function estimateMinSwapUniswapV3(\n address _fromToken,\n address _toToken,\n uint256 _amount,\n uint24 _poolFee\n ) external view returns (uint256);\n}\n" + }, + "contracts/src/external/uniswap/quoter/interfaces/IUniswapV3Quoter.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.7.5;\npragma abicoder v2;\n\n/// @title Quoter Interface\n/// @notice Supports quoting the calculated amounts from exact input or exact output swaps\n/// @dev These functions are not marked view because they rely on calling non-view functions and reverting\n/// to compute the result. They are also not gas efficient and should not be called on-chain.\ninterface IUniswapV3Quoter {\n /// @notice Returns the amount out received for a given exact input swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee\n /// @param amountIn The amount of the first token to swap\n /// @return amountOut The amount of the last token that would be received\n function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut);\n\n /// @notice Returns the amount out received for a given exact input but for a swap of a single pool\n /// @param tokenIn The token being swapped in\n /// @param tokenOut The token being swapped out\n /// @param fee The fee of the token pool to consider for the pair\n /// @param amountIn The desired input amount\n /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountOut The amount of `tokenOut` that would be received\n function quoteExactInputSingle(\n address tokenIn,\n address tokenOut,\n uint24 fee,\n uint256 amountIn,\n uint160 sqrtPriceLimitX96\n ) external returns (uint256 amountOut);\n\n /// @notice Returns the amount in required for a given exact output swap without executing the swap\n /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order\n /// @param amountOut The amount of the last token to receive\n /// @return amountIn The amount of first token required to be paid\n function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn);\n\n /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool\n /// @param tokenIn The token being swapped in\n /// @param tokenOut The token being swapped out\n /// @param fee The fee of the token pool to consider for the pair\n /// @param amountOut The desired output amount\n /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap\n /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`\n function quoteExactOutputSingle(\n address tokenIn,\n address tokenOut,\n uint24 fee,\n uint256 amountOut,\n uint160 sqrtPriceLimitX96\n ) external returns (uint256 amountIn);\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/BitMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.0;\n\n/// @title BitMath\n/// @dev This library provides functionality for computing bit properties of an unsigned integer\nlibrary BitMath {\n /// @notice Returns the index of the most significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1)\n /// @param x the value for which to compute the most significant bit, must be greater than 0\n /// @return r the index of the most significant bit\n function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n if (x >= 0x100000000000000000000000000000000) {\n x >>= 128;\n r += 128;\n }\n if (x >= 0x10000000000000000) {\n x >>= 64;\n r += 64;\n }\n if (x >= 0x100000000) {\n x >>= 32;\n r += 32;\n }\n if (x >= 0x10000) {\n x >>= 16;\n r += 16;\n }\n if (x >= 0x100) {\n x >>= 8;\n r += 8;\n }\n if (x >= 0x10) {\n x >>= 4;\n r += 4;\n }\n if (x >= 0x4) {\n x >>= 2;\n r += 2;\n }\n if (x >= 0x2) r += 1;\n }\n\n /// @notice Returns the index of the least significant bit of the number,\n /// where the least significant bit is at index 0 and the most significant bit is at index 255\n /// @dev The function satisfies the property:\n /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0)\n /// @param x the value for which to compute the least significant bit, must be greater than 0\n /// @return r the index of the least significant bit\n function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {\n require(x > 0);\n\n r = 255;\n if (x & type(uint128).max > 0) {\n r -= 128;\n } else {\n x >>= 128;\n }\n if (x & type(uint64).max > 0) {\n r -= 64;\n } else {\n x >>= 64;\n }\n if (x & type(uint32).max > 0) {\n r -= 32;\n } else {\n x >>= 32;\n }\n if (x & type(uint16).max > 0) {\n r -= 16;\n } else {\n x >>= 16;\n }\n if (x & type(uint8).max > 0) {\n r -= 8;\n } else {\n x >>= 8;\n }\n if (x & 0xf > 0) {\n r -= 4;\n } else {\n x >>= 4;\n }\n if (x & 0x3 > 0) {\n r -= 2;\n } else {\n x >>= 2;\n }\n if (x & 0x1 > 0) r -= 1;\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/FixedPoint96.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.4.0;\n\n/// @title FixedPoint96\n/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)\n/// @dev Used in SqrtPriceMath.sol\nlibrary FixedPoint96 {\n uint8 internal constant RESOLUTION = 96;\n uint256 internal constant Q96 = 0x1000000000000000000000000; // 2^96\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/LiquidityMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.0;\n\n/// @title Math library for liquidity\nlibrary LiquidityMath {\n /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows\n /// @param x The liquidity before change\n /// @param y The delta by which liquidity should be changed\n /// @return z The liquidity delta\n function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) {\n if (y < 0) {\n require((z = x - uint128(-y)) < x, \"LS\");\n } else {\n require((z = x + uint128(y)) >= x, \"LA\");\n }\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/LowGasSafeMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.0;\n\n/// @title Optimized overflow and underflow safe math operations\n/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost\nlibrary LowGasSafeMath {\n /// @notice Returns x + y, reverts if sum overflows uint256\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x + y) >= x);\n }\n\n /// @notice Returns x - y, reverts if underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require((z = x - y) <= x);\n }\n\n /// @notice Returns x * y, reverts if overflows\n /// @param x The multiplicand\n /// @param y The multiplier\n /// @return z The product of x and y\n function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {\n require(x == 0 || (z = x * y) / x == y);\n }\n\n /// @notice Returns x + y, reverts if overflows or underflows\n /// @param x The augend\n /// @param y The addend\n /// @return z The sum of x and y\n function add(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x + y) >= x == (y >= 0));\n }\n\n /// @notice Returns x - y, reverts if overflows or underflows\n /// @param x The minuend\n /// @param y The subtrahend\n /// @return z The difference of x and y\n function sub(int256 x, int256 y) internal pure returns (int256 z) {\n require((z = x - y) <= x == (y >= 0));\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/SafeCast.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.0;\n\n/// @title Safe casting methods\n/// @notice Contains methods for safely casting between types\nlibrary SafeCast {\n /// @notice Cast a uint256 to a uint160, revert on overflow\n /// @param y The uint256 to be downcasted\n /// @return z The downcasted integer, now type uint160\n function toUint160(uint256 y) internal pure returns (uint160 z) {\n require((z = uint160(y)) == y);\n }\n\n /// @notice Cast a int256 to a int128, revert on overflow or underflow\n /// @param y The int256 to be downcasted\n /// @return z The downcasted integer, now type int128\n function toInt128(int256 y) internal pure returns (int128 z) {\n require((z = int128(y)) == y);\n }\n\n /// @notice Cast a uint256 to a int256, revert on overflow\n /// @param y The uint256 to be casted\n /// @return z The casted integer, now type int256\n function toInt256(uint256 y) internal pure returns (int256 z) {\n require(y < 2**255);\n z = int256(y);\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/SqrtPriceMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.0;\n\nimport \"./LowGasSafeMath.sol\";\nimport \"./SafeCast.sol\";\n\nimport \"../../FullMath.sol\";\nimport \"./UnsafeMath.sol\";\nimport \"./FixedPoint96.sol\";\nimport \"./BitMath.sol\";\n\n/// @title Functions based on Q64.96 sqrt price and liquidity\n/// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas\nlibrary SqrtPriceMath {\n using LowGasSafeMath for uint256;\n using SafeCast for uint256;\n\n /// @notice Gets the next sqrt price given a delta of token0\n /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the\n /// price less in order to not send too much output.\n /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96),\n /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount).\n /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token0 to add or remove from virtual reserves\n /// @param add Whether to add or remove the amount of token0\n /// @return The price after adding or removing amount, depending on add\n function getNextSqrtPriceFromAmount0RoundingUp(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price\n if (amount == 0) return sqrtPX96;\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n\n bool overflow = false;\n if (numerator1 != 0 && sqrtPX96 != 0)\n overflow = uint256(BitMath.mostSignificantBit(numerator1)) + uint256(BitMath.mostSignificantBit(sqrtPX96)) >= 254;\n\n if (add) {\n uint256 product;\n if ((product = amount * sqrtPX96) / amount == sqrtPX96) {\n product = overflow ? FullMath.mulDivRoundingUp(amount, sqrtPX96, uint256(liquidity)) : product;\n numerator1 = overflow ? FixedPoint96.Q96 : numerator1;\n uint256 denominator = numerator1 + product;\n if (denominator >= numerator1) {\n // always fits in 160 bits\n return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator));\n }\n }\n\n return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount)));\n } else {\n uint256 product;\n // if the product overflows, we know the denominator underflows\n // in addition, we must check that the denominator does not underflow\n require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product);\n product = overflow ? FullMath.mulDivRoundingUp(amount, sqrtPX96, uint256(liquidity)) : product;\n numerator1 = overflow ? FixedPoint96.Q96 : numerator1;\n uint256 denominator = numerator1 - product;\n return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160();\n }\n }\n\n /// @notice Gets the next sqrt price given a delta of token1\n /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least\n /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the\n /// price less in order to not send too much output.\n /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity\n /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta\n /// @param liquidity The amount of usable liquidity\n /// @param amount How much of token1 to add, or remove, from virtual reserves\n /// @param add Whether to add, or remove, the amount of token1\n /// @return The price after adding or removing `amount`\n function getNextSqrtPriceFromAmount1RoundingDown(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amount,\n bool add\n ) internal pure returns (uint160) {\n // if we're adding (subtracting), rounding down requires rounding the quotient down (up)\n // in both cases, avoid a mulDiv for most inputs\n if (add) {\n uint256 quotient = (\n amount <= type(uint160).max\n ? (amount << FixedPoint96.RESOLUTION) / liquidity\n : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity)\n );\n\n return uint256(sqrtPX96).add(quotient).toUint160();\n } else {\n uint256 quotient = (\n amount <= type(uint160).max\n ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity)\n : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity)\n );\n\n require(sqrtPX96 > quotient);\n // always fits 160 bits\n return uint160(sqrtPX96 - quotient);\n }\n }\n\n /// @notice Gets the next sqrt price given an input amount of token0 or token1\n /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds\n /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountIn How much of token0, or token1, is being swapped in\n /// @param zeroForOne Whether the amount in is token0 or token1\n /// @return sqrtQX96 The price after adding the input amount to token0 or token1\n function getNextSqrtPriceFromInput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountIn,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we don't pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true)\n : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true);\n }\n\n /// @notice Gets the next sqrt price given an output amount of token0 or token1\n /// @dev Throws if price or liquidity are 0 or the next price is out of bounds\n /// @param sqrtPX96 The starting price before accounting for the output amount\n /// @param liquidity The amount of usable liquidity\n /// @param amountOut How much of token0, or token1, is being swapped out\n /// @param zeroForOne Whether the amount out is token0 or token1\n /// @return sqrtQX96 The price after removing the output amount of token0 or token1\n function getNextSqrtPriceFromOutput(\n uint160 sqrtPX96,\n uint128 liquidity,\n uint256 amountOut,\n bool zeroForOne\n ) internal pure returns (uint160 sqrtQX96) {\n require(sqrtPX96 > 0);\n require(liquidity > 0);\n\n // round to make sure that we pass the target price\n return\n zeroForOne\n ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false)\n : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false);\n }\n\n /// @notice Gets the amount0 delta between two prices\n /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),\n /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up or down\n /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount0) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION;\n uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96;\n require(sqrtRatioAX96 > 0);\n\n bool overflow = false;\n if (numerator1 != 0 && numerator2 != 0)\n overflow =\n uint256(BitMath.mostSignificantBit(numerator1)) + uint256(BitMath.mostSignificantBit(numerator2)) >= 254;\n\n if (overflow) {\n return\n roundUp\n ? FullMath.mulDivRoundingUp(\n FullMath.mulDivRoundingUp(uint256(liquidity), numerator2, sqrtRatioBX96),\n FixedPoint96.Q96,\n sqrtRatioAX96\n )\n : FullMath.mulDiv(\n FullMath.mulDiv(uint256(liquidity), numerator2, sqrtRatioBX96),\n FixedPoint96.Q96,\n sqrtRatioAX96\n );\n } else {\n return\n roundUp\n ? UnsafeMath.divRoundingUp(FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96)\n : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96;\n }\n }\n\n /// @notice Gets the amount1 delta between two prices\n /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The amount of usable liquidity\n /// @param roundUp Whether to round the amount up, or down\n /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n uint128 liquidity,\n bool roundUp\n ) internal pure returns (uint256 amount1) {\n if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);\n\n return\n roundUp\n ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96)\n : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);\n }\n\n /// @notice Helper that gets signed token0 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount0 delta\n /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices\n function getAmount0Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount0) {\n return\n liquidity < 0\n ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n\n /// @notice Helper that gets signed token1 delta\n /// @param sqrtRatioAX96 A sqrt price\n /// @param sqrtRatioBX96 Another sqrt price\n /// @param liquidity The change in liquidity for which to compute the amount1 delta\n /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices\n function getAmount1Delta(\n uint160 sqrtRatioAX96,\n uint160 sqrtRatioBX96,\n int128 liquidity\n ) internal pure returns (int256 amount1) {\n return\n liquidity < 0\n ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256()\n : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256();\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/SwapMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.0;\n\nimport \"../../FullMath.sol\";\nimport \"./SqrtPriceMath.sol\";\n\n/// @title Computes the result of a swap within ticks\n/// @notice Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.\nlibrary SwapMath {\n /// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap\n /// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive\n /// @param sqrtRatioCurrentX96 The current sqrt price of the pool\n /// @param sqrtRatioTargetX96 The price that cannot be exceeded, from which the direction of the swap is inferred\n /// @param liquidity The usable liquidity\n /// @param amountRemaining How much input or output amount is remaining to be swapped in/out\n /// @param feePips The fee taken from the input amount, expressed in hundredths of a bip\n /// @return sqrtRatioNextX96 The price after swapping the amount in/out, not to exceed the price target\n /// @return amountIn The amount to be swapped in, of either token0 or token1, based on the direction of the swap\n /// @return amountOut The amount to be received, of either token0 or token1, based on the direction of the swap\n /// @return feeAmount The amount of input that will be taken as a fee\n function computeSwapStep(\n uint160 sqrtRatioCurrentX96,\n uint160 sqrtRatioTargetX96,\n uint128 liquidity,\n int256 amountRemaining,\n uint24 feePips,\n bool zeroForOne\n )\n internal\n pure\n returns (\n uint160 sqrtRatioNextX96,\n uint256 amountIn,\n uint256 amountOut,\n uint256 feeAmount\n )\n {\n require(zeroForOne == sqrtRatioCurrentX96 >= sqrtRatioTargetX96, \"SPD\");\n bool exactIn = amountRemaining >= 0;\n\n if (exactIn) {\n uint256 amountRemainingLessFee = FullMath.mulDiv(uint256(amountRemaining), 1e6 - feePips, 1e6);\n amountIn = zeroForOne\n ? SqrtPriceMath.getAmount0Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, true)\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, true);\n if (amountRemainingLessFee >= amountIn) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromInput(\n sqrtRatioCurrentX96,\n liquidity,\n amountRemainingLessFee,\n zeroForOne\n );\n } else {\n amountOut = zeroForOne\n ? SqrtPriceMath.getAmount1Delta(sqrtRatioTargetX96, sqrtRatioCurrentX96, liquidity, false)\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioTargetX96, liquidity, false);\n\n if (uint256(-amountRemaining) >= amountOut) sqrtRatioNextX96 = sqrtRatioTargetX96;\n else\n sqrtRatioNextX96 = SqrtPriceMath.getNextSqrtPriceFromOutput(\n sqrtRatioCurrentX96,\n liquidity,\n uint256(-amountRemaining),\n zeroForOne\n );\n }\n\n bool max = sqrtRatioTargetX96 == sqrtRatioNextX96;\n\n // get the input/output amounts\n if (zeroForOne) {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount0Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount1Delta(sqrtRatioNextX96, sqrtRatioCurrentX96, liquidity, false);\n } else {\n amountIn = max && exactIn\n ? amountIn\n : SqrtPriceMath.getAmount1Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, true);\n amountOut = max && !exactIn\n ? amountOut\n : SqrtPriceMath.getAmount0Delta(sqrtRatioCurrentX96, sqrtRatioNextX96, liquidity, false);\n }\n\n // cap the output amount to not exceed the remaining output amount\n if (!exactIn && amountOut > uint256(-amountRemaining)) {\n amountOut = uint256(-amountRemaining);\n }\n\n if (exactIn && sqrtRatioNextX96 != sqrtRatioTargetX96) {\n // we didn't reach the target, so take the remainder of the maximum input as fee\n feeAmount = uint256(amountRemaining) - amountIn;\n } else {\n feeAmount = FullMath.mulDivRoundingUp(amountIn, feePips, 1e6 - feePips);\n }\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/Tick.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.0;\n\nimport \"./LowGasSafeMath.sol\";\nimport \"./SafeCast.sol\";\n\nimport \"../../TickMath.sol\";\nimport \"./LiquidityMath.sol\";\n\n/// @title Tick\n/// @notice Contains functions for managing tick processes and relevant calculations\n\n/// Ithil to modify it, since it does not have access to storage arrays\nlibrary Tick {\n using LowGasSafeMath for int256;\n using SafeCast for int256;\n\n // info stored for each initialized individual tick\n struct Info {\n // the total position liquidity that references this tick\n uint128 liquidityGross;\n // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left),\n int128 liquidityNet;\n // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint256 feeGrowthOutside0X128;\n uint256 feeGrowthOutside1X128;\n // the cumulative tick value on the other side of the tick\n int56 tickCumulativeOutside;\n // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint160 secondsPerLiquidityOutsideX128;\n // the seconds spent on the other side of the tick (relative to the current tick)\n // only has relative meaning, not absolute — the value depends on when the tick is initialized\n uint32 secondsOutside;\n // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0\n // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks\n bool initialized;\n }\n\n /// @notice Derives max liquidity per tick from given tick spacing\n /// @dev Executed within the pool constructor\n /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing`\n /// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ...\n /// @return The max liquidity per tick\n function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) internal pure returns (uint128) {\n int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing;\n int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing;\n uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1;\n return type(uint128).max / numTicks;\n }\n\n /// @notice Retrieves fee growth data\n /// Ithil: only use it with lower = self[tickLower] and upper = self[tickUpper]\n /// @param lower The info of the lower tick boundary of the position\n /// @param upper The info of the upper tick boundary of the position\n /// @param tickLower The lower tick boundary of the position\n /// @param tickUpper The upper tick boundary of the position\n /// @param tickCurrent The current tick\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries\n /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries\n function getFeeGrowthInside(\n Tick.Info memory lower,\n Tick.Info memory upper,\n int24 tickLower,\n int24 tickUpper,\n int24 tickCurrent,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128\n ) internal pure returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) {\n // calculate fee growth below\n uint256 feeGrowthBelow0X128;\n uint256 feeGrowthBelow1X128;\n if (tickCurrent >= tickLower) {\n feeGrowthBelow0X128 = lower.feeGrowthOutside0X128;\n feeGrowthBelow1X128 = lower.feeGrowthOutside1X128;\n } else {\n feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128;\n feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128;\n }\n\n // calculate fee growth above\n uint256 feeGrowthAbove0X128;\n uint256 feeGrowthAbove1X128;\n if (tickCurrent < tickUpper) {\n feeGrowthAbove0X128 = upper.feeGrowthOutside0X128;\n feeGrowthAbove1X128 = upper.feeGrowthOutside1X128;\n } else {\n feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128;\n feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128;\n }\n\n feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128;\n feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128;\n }\n\n /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa\n /// Ithil: always use with info = self[tick]\n /// @param info The info tick that will be updated\n /// @param tick The tick that will be updated\n /// @param tickCurrent The current tick\n /// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @param secondsPerLiquidityCumulativeX128 The all-time seconds per max(1, liquidity) of the pool\n /// @param tickCumulative The tick * time elapsed since the pool was first initialized\n /// @param time The current block timestamp cast to a uint32\n /// @param upper true for updating a position's upper tick, or false for updating a position's lower tick\n /// @param maxLiquidity The maximum liquidity allocation for a single tick\n /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa\n function update(\n Tick.Info memory info,\n int24 tick,\n int24 tickCurrent,\n int128 liquidityDelta,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128,\n uint160 secondsPerLiquidityCumulativeX128,\n int56 tickCumulative,\n uint32 time,\n bool upper,\n uint128 maxLiquidity\n ) internal pure returns (bool flipped) {\n uint128 liquidityGrossBefore = info.liquidityGross;\n uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, liquidityDelta);\n\n require(liquidityGrossAfter <= maxLiquidity, \"LO\");\n\n flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0);\n\n if (liquidityGrossBefore == 0) {\n // by convention, we assume that all growth before a tick was initialized happened _below_ the tick\n if (tick <= tickCurrent) {\n info.feeGrowthOutside0X128 = feeGrowthGlobal0X128;\n info.feeGrowthOutside1X128 = feeGrowthGlobal1X128;\n info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128;\n info.tickCumulativeOutside = tickCumulative;\n info.secondsOutside = time;\n }\n info.initialized = true;\n }\n\n info.liquidityGross = liquidityGrossAfter;\n\n // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)\n info.liquidityNet = upper\n ? int256(info.liquidityNet).sub(liquidityDelta).toInt128()\n : int256(info.liquidityNet).add(liquidityDelta).toInt128();\n }\n\n /// @notice Transitions to next tick as needed by price movement\n /// @param info The result of the mapping containing all tick information for initialized ticks\n /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0\n /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1\n /// @param secondsPerLiquidityCumulativeX128 The current seconds per liquidity\n /// @param tickCumulative The tick * time elapsed since the pool was first initialized\n /// @param time The current block.timestamp\n /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)\n function cross(\n Tick.Info memory info,\n uint256 feeGrowthGlobal0X128,\n uint256 feeGrowthGlobal1X128,\n uint160 secondsPerLiquidityCumulativeX128,\n int56 tickCumulative,\n uint32 time\n ) internal pure returns (int128 liquidityNet) {\n info.feeGrowthOutside0X128 = feeGrowthGlobal0X128 - info.feeGrowthOutside0X128;\n info.feeGrowthOutside1X128 = feeGrowthGlobal1X128 - info.feeGrowthOutside1X128;\n info.secondsPerLiquidityOutsideX128 = secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128;\n info.tickCumulativeOutside = tickCumulative - info.tickCumulativeOutside;\n info.secondsOutside = time - info.secondsOutside;\n liquidityNet = info.liquidityNet;\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/TickBitmap.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.0;\n\nimport \"./BitMath.sol\";\n\n/// @title Packed tick initialized state library\n/// @notice Stores a packed mapping of tick index to its initialized state\n/// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.\nlibrary TickBitmap {\n /// @notice Computes the position in the mapping where the initialized bit for a tick lives\n /// @param tick The tick for which to compute the position\n /// @return wordPos The key in the mapping containing the word in which the bit is stored\n /// @return bitPos The bit position in the word where the flag is stored\n /// @dev simply divides @param tick by 256 with remainder: tick = wordPos * 256 + bitPos\n function position(int24 tick) internal pure returns (int16 wordPos, uint8 bitPos) {\n wordPos = int16(tick >> 8);\n bitPos = uint8(int8(tick % 256));\n }\n\n /// Written by Ithil\n function computeWordPos(\n int24 tick,\n int24 tickSpacing,\n bool lte\n ) internal pure returns (int16 wordPos) {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n (wordPos, ) = lte ? position(compressed) : position(compressed + 1);\n }\n\n /// @notice Flips the initialized state for a given tick from false to true, or vice versa\n /// @param selfResult The result of the mapping in which to flip the tick (Ithil modified)\n /// @param tick The tick to flip\n /// @param tickSpacing The spacing between usable ticks\n function flipTick(\n uint256 selfResult,\n int24 tick,\n int24 tickSpacing\n ) internal pure {\n require(tick % tickSpacing == 0); // ensure that the tick is spaced\n (, uint8 bitPos) = position(tick / tickSpacing);\n uint256 mask = 1 << bitPos;\n selfResult ^= mask;\n }\n\n /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either\n /// to the left (less than or equal to) or right (greater than) of the given tick\n /// @param selfResult The result of the mapping in which to compute the next initialized tick (Ithil modified)\n /// @param tick The starting tick\n /// @param tickSpacing The spacing between usable ticks\n /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick)\n /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick\n /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks\n function nextInitializedTickWithinOneWord(\n uint256 selfResult,\n int24 tick,\n int24 tickSpacing,\n bool lte\n ) internal pure returns (int24 next, bool initialized) {\n int24 compressed = tick / tickSpacing;\n if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n if (lte) {\n (, uint8 bitPos) = position(compressed);\n // all the 1s at or to the right of the current bitPos\n uint256 mask = (1 << bitPos) - 1 + (1 << bitPos);\n uint256 masked = selfResult & mask;\n\n // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed - int24(uint24(bitPos) - uint24(BitMath.mostSignificantBit(masked)))) * tickSpacing\n : (compressed - int24(uint24(bitPos))) * tickSpacing;\n } else {\n // start from the word of the next tick, since the current tick state doesn't matter\n (, uint8 bitPos) = position(compressed + 1);\n // all the 1s at or to the left of the bitPos\n uint256 mask = ~((1 << bitPos) - 1);\n uint256 masked = selfResult & mask;\n\n // if there are no initialized ticks to the left of the current tick, return leftmost in the word\n initialized = masked != 0;\n // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick\n next = initialized\n ? (compressed + 1 + int24(uint24(BitMath.leastSignificantBit(masked) - bitPos))) * tickSpacing\n : (compressed + 1 + int24(uint24(type(uint8).max - bitPos))) * tickSpacing;\n }\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/libraries/UnsafeMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.5.0;\n\n/// @title Math functions that do not check inputs or outputs\n/// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks\nlibrary UnsafeMath {\n /// @notice Returns ceil(x / y)\n /// @dev division by 0 has unspecified behavior, and must be checked externally\n /// @param x The dividend\n /// @param y The divisor\n /// @return z The quotient, ceil(x / y)\n function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n z := add(div(x, y), gt(mod(x, y), 0))\n }\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/Quoter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0 <0.9.0;\npragma experimental ABIEncoderV2;\n\nimport \"../IUniswapV3Factory.sol\";\nimport \"./interfaces/IQuoter.sol\";\nimport \"./UniswapV3Quoter.sol\";\n\ncontract Quoter is IQuoter, UniswapV3Quoter {\n IUniswapV3Factory internal uniV3Factory; // TODO should it be immutable?\n\n constructor(address _uniV3Factory) {\n uniV3Factory = IUniswapV3Factory(_uniV3Factory);\n }\n\n // This should be equal to quoteExactInputSingle(_fromToken, _toToken, _poolFee, _amount, 0)\n // todo: add price limit\n function estimateMaxSwapUniswapV3(\n address _fromToken,\n address _toToken,\n uint256 _amount,\n uint24 _poolFee\n ) public view override returns (uint256) {\n address pool = uniV3Factory.getPool(_fromToken, _toToken, _poolFee);\n\n return _estimateOutputSingle(_toToken, _fromToken, _amount, pool);\n }\n\n // This should be equal to quoteExactOutputSingle(_fromToken, _toToken, _poolFee, _amount, 0)\n // todo: add price limit\n function estimateMinSwapUniswapV3(\n address _fromToken,\n address _toToken,\n uint256 _amount,\n uint24 _poolFee\n ) public view override returns (uint256) {\n address pool = uniV3Factory.getPool(_fromToken, _toToken, _poolFee);\n\n return _estimateInputSingle(_fromToken, _toToken, _amount, pool);\n }\n\n // todo: add price limit\n function _estimateOutputSingle(\n address _fromToken,\n address _toToken,\n uint256 _amount,\n address _pool\n ) internal view returns (uint256 amountOut) {\n bool zeroForOne = _fromToken > _toToken;\n // todo: price limit?\n (int256 amount0, int256 amount1) = quoteSwap(\n _pool,\n int256(_amount),\n zeroForOne ? (TickMath.MIN_SQRT_RATIO + 1) : (TickMath.MAX_SQRT_RATIO - 1),\n zeroForOne\n );\n if (zeroForOne) amountOut = amount1 > 0 ? uint256(amount1) : uint256(-amount1);\n else amountOut = amount0 > 0 ? uint256(amount0) : uint256(-amount0);\n }\n\n // todo: add price limit\n function _estimateInputSingle(\n address _fromToken,\n address _toToken,\n uint256 _amount,\n address _pool\n ) internal view returns (uint256 amountOut) {\n bool zeroForOne = _fromToken < _toToken;\n // todo: price limit?\n (int256 amount0, int256 amount1) = quoteSwap(\n _pool,\n -int256(_amount),\n zeroForOne ? (TickMath.MIN_SQRT_RATIO + 1) : (TickMath.MAX_SQRT_RATIO - 1),\n zeroForOne\n );\n if (zeroForOne) amountOut = amount0 > 0 ? uint256(amount0) : uint256(-amount0);\n else amountOut = amount1 > 0 ? uint256(amount1) : uint256(-amount1);\n }\n\n function doesPoolExist(address _token0, address _token1) external view returns (bool) {\n // try 0.05%\n address pool = uniV3Factory.getPool(_token0, _token1, 500);\n if (pool != address(0)) return true;\n\n // try 0.3%\n pool = uniV3Factory.getPool(_token0, _token1, 3000);\n if (pool != address(0)) return true;\n\n // try 1%\n pool = uniV3Factory.getPool(_token0, _token1, 10000);\n if (pool != address(0)) return true;\n else return false;\n }\n}\n" + }, + "contracts/src/external/uniswap/quoter/UniswapV3Quoter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.7.6;\n\nimport \"./libraries/LowGasSafeMath.sol\";\nimport \"./libraries/SafeCast.sol\";\nimport \"./libraries/Tick.sol\";\nimport \"./libraries/TickBitmap.sol\";\n\nimport \"../FullMath.sol\";\nimport \"../TickMath.sol\";\nimport \"./libraries/LiquidityMath.sol\";\nimport \"./libraries/SqrtPriceMath.sol\";\nimport \"./libraries/SwapMath.sol\";\n\nimport \"./interfaces/IUniswapV3Quoter.sol\";\nimport \"../IUniswapV3Pool.sol\";\nimport \"../IUniswapV3PoolImmutables.sol\";\n\ncontract UniswapV3Quoter {\n using LowGasSafeMath for int256;\n using SafeCast for uint256;\n using Tick for mapping(int24 => Tick.Info);\n\n struct PoolState {\n // the current price\n uint160 sqrtPriceX96;\n // the current tick\n int24 tick;\n // the tick spacing\n int24 tickSpacing;\n // the pool's fee\n uint24 fee;\n // the pool's liquidity\n uint128 liquidity;\n // whether the pool is locked\n bool unlocked;\n }\n\n // accumulated protocol fees in token0/token1 units\n struct ProtocolFees {\n uint128 token0;\n uint128 token1;\n }\n\n // the top level state of the swap, the results of which are recorded in storage at the end\n struct SwapState {\n // the amount remaining to be swapped in/out of the input/output asset\n int256 amountSpecifiedRemaining;\n // the amount already swapped out/in of the output/input asset\n int256 amountCalculated;\n // current sqrt(price)\n uint160 sqrtPriceX96;\n // the tick associated with the current price\n int24 tick;\n // the current liquidity in range\n uint128 liquidity;\n }\n\n struct StepComputations {\n // the price at the beginning of the step\n uint160 sqrtPriceStartX96;\n // the next tick to swap to from the current tick in the swap direction\n int24 tickNext;\n // whether tickNext is initialized or not\n bool initialized;\n // sqrt(price) for the next tick (1/0)\n uint160 sqrtPriceNextX96;\n // how much is being swapped in in this step\n uint256 amountIn;\n // how much is being swapped out\n uint256 amountOut;\n // how much fee is being paid in\n uint256 feeAmount;\n }\n\n struct InitialState {\n address poolAddress;\n PoolState poolState;\n uint256 feeGrowthGlobal0X128;\n uint256 feeGrowthGlobal1X128;\n }\n\n struct NextTickPassage {\n int24 tick;\n int24 tickSpacing;\n }\n\n function fetchState(address _pool) internal view returns (PoolState memory poolState) {\n IUniswapV3Pool pool = IUniswapV3Pool(_pool);\n (uint160 sqrtPriceX96, int24 tick, , , , , bool unlocked) = pool.slot0(); // external call\n uint128 liquidity = pool.liquidity(); // external call\n int24 tickSpacing = IUniswapV3PoolImmutables(_pool).tickSpacing(); // external call\n uint24 fee = IUniswapV3PoolImmutables(_pool).fee(); // external call\n poolState = PoolState(sqrtPriceX96, tick, tickSpacing, fee, liquidity, unlocked);\n }\n\n function setInitialState(\n PoolState memory initialPoolState,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bool zeroForOne\n )\n internal\n pure\n returns (\n SwapState memory state,\n uint128 liquidity,\n uint160 sqrtPriceX96\n )\n {\n liquidity = initialPoolState.liquidity;\n\n sqrtPriceX96 = initialPoolState.sqrtPriceX96;\n\n require(\n zeroForOne\n ? sqrtPriceLimitX96 < initialPoolState.sqrtPriceX96 && sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO\n : sqrtPriceLimitX96 > initialPoolState.sqrtPriceX96 && sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,\n \"SPL\"\n );\n\n state = SwapState({\n amountSpecifiedRemaining: amountSpecified,\n amountCalculated: 0,\n sqrtPriceX96: initialPoolState.sqrtPriceX96,\n tick: initialPoolState.tick,\n liquidity: 0 // to be modified after initialization\n });\n }\n\n function getNextTickAndPrice(\n int24 tickSpacing,\n int24 currentTick,\n IUniswapV3Pool pool,\n bool zeroForOne\n )\n internal\n view\n returns (\n int24 tickNext,\n bool initialized,\n uint160 sqrtPriceNextX96\n )\n {\n int24 compressed = currentTick / tickSpacing;\n if (!zeroForOne) compressed++;\n if (currentTick < 0 && currentTick % tickSpacing != 0) compressed--; // round towards negative infinity\n\n uint256 selfResult = pool.tickBitmap(int16(compressed >> 8)); // external call\n\n (tickNext, initialized) = TickBitmap.nextInitializedTickWithinOneWord(\n selfResult,\n currentTick,\n tickSpacing,\n zeroForOne\n );\n\n if (tickNext < TickMath.MIN_TICK) {\n tickNext = TickMath.MIN_TICK;\n } else if (tickNext > TickMath.MAX_TICK) {\n tickNext = TickMath.MAX_TICK;\n }\n sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(tickNext);\n }\n\n function processSwapWithinTick(\n IUniswapV3Pool pool,\n PoolState memory initialPoolState,\n SwapState memory state,\n uint160 firstSqrtPriceX96,\n uint128 firstLiquidity,\n uint160 sqrtPriceLimitX96,\n bool zeroForOne,\n bool exactAmount\n )\n internal\n view\n returns (\n uint160 sqrtPriceNextX96,\n uint160 finalSqrtPriceX96,\n uint128 finalLiquidity\n )\n {\n StepComputations memory step;\n\n step.sqrtPriceStartX96 = firstSqrtPriceX96;\n\n (step.tickNext, step.initialized, sqrtPriceNextX96) = getNextTickAndPrice(\n initialPoolState.tickSpacing,\n state.tick,\n pool,\n zeroForOne\n );\n\n (finalSqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(\n firstSqrtPriceX96,\n (zeroForOne ? sqrtPriceNextX96 < sqrtPriceLimitX96 : sqrtPriceNextX96 > sqrtPriceLimitX96)\n ? sqrtPriceLimitX96\n : sqrtPriceNextX96,\n firstLiquidity,\n state.amountSpecifiedRemaining,\n initialPoolState.fee,\n zeroForOne\n );\n\n if (exactAmount) {\n state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();\n state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());\n } else {\n state.amountSpecifiedRemaining += step.amountOut.toInt256();\n state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());\n }\n\n if (finalSqrtPriceX96 == sqrtPriceNextX96) {\n if (step.initialized) {\n (, int128 liquidityNet, , , , , , ) = pool.ticks(step.tickNext);\n if (zeroForOne) liquidityNet = -liquidityNet;\n finalLiquidity = LiquidityMath.addDelta(firstLiquidity, liquidityNet);\n }\n state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;\n } else if (finalSqrtPriceX96 != step.sqrtPriceStartX96) {\n // recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved\n state.tick = TickMath.getTickAtSqrtRatio(finalSqrtPriceX96);\n }\n }\n\n function returnedAmount(\n SwapState memory state,\n int256 amountSpecified,\n bool zeroForOne\n ) internal pure returns (int256 amount0, int256 amount1) {\n if (amountSpecified > 0) {\n (amount0, amount1) = zeroForOne\n ? (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated)\n : (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining);\n } else {\n (amount0, amount1) = zeroForOne\n ? (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining)\n : (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated);\n }\n }\n\n function quoteSwap(\n address poolAddress,\n int256 amountSpecified,\n uint160 sqrtPriceLimitX96,\n bool zeroForOne\n ) internal view returns (int256 amount0, int256 amount1) {\n bool exactAmount = amountSpecified > 0;\n\n PoolState memory initialPoolState = fetchState(poolAddress);\n uint160 sqrtPriceNextX96;\n\n (SwapState memory state, uint128 liquidity, uint160 sqrtPriceX96) = setInitialState(\n initialPoolState,\n amountSpecified,\n sqrtPriceLimitX96,\n zeroForOne\n );\n\n while (state.amountSpecifiedRemaining != 0 && sqrtPriceX96 != sqrtPriceLimitX96)\n (sqrtPriceNextX96, sqrtPriceX96, liquidity) = processSwapWithinTick(\n IUniswapV3Pool(poolAddress),\n initialPoolState,\n state,\n sqrtPriceX96,\n liquidity,\n sqrtPriceLimitX96,\n zeroForOne,\n exactAmount\n );\n\n (amount0, amount1) = returnedAmount(state, amountSpecified, zeroForOne);\n }\n}\n" + }, + "contracts/src/external/uniswap/TickMath.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\n\n// From Uniswap3 Core\n\n// Updated to Solidity 0.8 by Midas Capital:\n// * Cast MAX_TICK to int256 before casting to uint\n// * Wrapped function bodies with \"unchecked {}\" so as to not add any extra gas costs\n\npragma solidity ^0.8.0;\n\n/// @title Math library for computing sqrt prices from ticks and vice versa\n/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports\n/// prices between 2**-128 and 2**128\nlibrary TickMath {\n /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128\n int24 internal constant MIN_TICK = -887272;\n /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128\n int24 internal constant MAX_TICK = -MIN_TICK;\n\n /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)\n uint160 internal constant MIN_SQRT_RATIO = 4295128739;\n /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)\n uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;\n\n /// @notice Calculates sqrt(1.0001^tick) * 2^96\n /// @dev Throws if |tick| > max tick\n /// @param tick The input tick for the above formula\n /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)\n /// at the given tick\n function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {\n unchecked {\n uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));\n require(absTick <= uint256(int256(MAX_TICK)), \"T\");\n\n uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;\n if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;\n if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n\n if (tick > 0) ratio = type(uint256).max / ratio;\n\n // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.\n // we then downcast because we know the result always fits within 160 bits due to our tick input constraint\n // we round up in the division so getTickAtSqrtRatio of the output price is always consistent\n sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));\n }\n }\n\n /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio\n /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may\n /// ever return.\n /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96\n /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio\n function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {\n unchecked {\n // second inequality must be < because the price can never reach the price at the max tick\n require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, \"R\");\n uint256 ratio = uint256(sqrtPriceX96) << 32;\n\n uint256 r = ratio;\n uint256 msb = 0;\n\n assembly {\n let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(5, gt(r, 0xFFFFFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(4, gt(r, 0xFFFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(3, gt(r, 0xFF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(2, gt(r, 0xF))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := shl(1, gt(r, 0x3))\n msb := or(msb, f)\n r := shr(f, r)\n }\n assembly {\n let f := gt(r, 0x1)\n msb := or(msb, f)\n }\n\n if (msb >= 128) r = ratio >> (msb - 127);\n else r = ratio << (127 - msb);\n\n int256 log_2 = (int256(msb) - 128) << 64;\n\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(63, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(62, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(61, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(60, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(59, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(58, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(57, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(56, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(55, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(54, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(53, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(52, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(51, f))\n r := shr(f, r)\n }\n assembly {\n r := shr(127, mul(r, r))\n let f := shr(128, r)\n log_2 := or(log_2, shl(50, f))\n }\n\n int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number\n\n int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);\n int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);\n\n tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;\n }\n }\n}\n" + }, + "contracts/src/external/uniswap/UniswapV2Library.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-only\npragma solidity >=0.8.0;\n\nimport \"./IUniswapV2Pair.sol\";\nimport \"./IUniswapV2Factory.sol\";\n\nlibrary UniswapV2Library {\n // returns sorted token addresses, used to handle return values from pairs sorted in this order\n function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {\n require(tokenA != tokenB, \"UniswapV2Library: IDENTICAL_ADDRESSES\");\n (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n require(token0 != address(0), \"UniswapV2Library: ZERO_ADDRESS\");\n }\n\n function pairFor(\n address factory,\n address tokenA,\n address tokenB\n ) internal view returns (address pair) {\n return IUniswapV2Factory(factory).getPair(tokenA, tokenB);\n }\n\n // fetches and sorts the reserves for a pair\n function getReserves(\n address factory,\n address tokenA,\n address tokenB\n ) internal view returns (uint256 reserveA, uint256 reserveB) {\n (address token0, ) = sortTokens(tokenA, tokenB);\n (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();\n (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);\n }\n\n // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset\n function quote(\n uint256 amountA,\n uint256 reserveA,\n uint256 reserveB\n ) internal pure returns (uint256 amountB) {\n require(amountA > 0, \"UniswapV2Library: INSUFFICIENT_AMOUNT\");\n require(reserveA > 0 && reserveB > 0, \"UniswapV2Library: INSUFFICIENT_LIQUIDITY\");\n amountB = (amountA * reserveB) / reserveA;\n }\n\n // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset\n function getAmountOut(\n uint256 amountIn,\n uint256 reserveIn,\n uint256 reserveOut,\n uint8 flashSwapFee\n ) internal pure returns (uint256 amountOut) {\n require(amountIn > 0, \"UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT\");\n require(reserveIn > 0 && reserveOut > 0, \"UniswapV2Library: INSUFFICIENT_LIQUIDITY\");\n uint256 amountInWithFee = amountIn * (10000 - flashSwapFee);\n uint256 numerator = amountInWithFee * reserveOut;\n uint256 denominator = reserveIn * 10000 + amountInWithFee;\n amountOut = numerator / denominator;\n }\n\n // given an output amount of an asset and pair reserves, returns a required input amount of the other asset\n function getAmountIn(\n uint256 amountOut,\n uint256 reserveIn,\n uint256 reserveOut,\n uint8 flashSwapFee\n ) internal pure returns (uint256 amountIn) {\n require(amountOut > 0, \"UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT\");\n require(reserveIn > 0 && reserveOut > 0, \"UniswapV2Library: INSUFFICIENT_LIQUIDITY\");\n uint256 numerator = reserveIn * amountOut * 10000;\n uint256 denominator = (reserveOut - amountOut) * (10000 - flashSwapFee);\n amountIn = numerator / denominator + 1;\n }\n\n // performs chained getAmountOut calculations on any number of pairs\n function getAmountsOut(\n address factory,\n uint256 amountIn,\n address[] memory path,\n uint8 flashSwapFee\n ) internal view returns (uint256[] memory amounts) {\n require(path.length >= 2, \"UniswapV2Library: INVALID_PATH\");\n amounts = new uint256[](path.length);\n amounts[0] = amountIn;\n for (uint256 i; i < path.length - 1; i++) {\n (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i], path[i + 1]);\n amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, flashSwapFee);\n }\n }\n\n // performs chained getAmountIn calculations on any number of pairs\n function getAmountsIn(\n address factory,\n uint256 amountOut,\n address[] memory path,\n uint8 flashSwapFee\n ) internal view returns (uint256[] memory amounts) {\n require(path.length >= 2, \"UniswapV2Library: INVALID_PATH\");\n amounts = new uint256[](path.length);\n amounts[amounts.length - 1] = amountOut;\n for (uint256 i = path.length - 1; i > 0; i--) {\n (uint256 reserveIn, uint256 reserveOut) = getReserves(factory, path[i - 1], path[i]);\n amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, flashSwapFee);\n }\n }\n}\n" + }, + "contracts/src/external/velodrome/IVelodromeRouter.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IRouter_Velodrome {\n struct Route {\n address from;\n address to;\n bool stable;\n }\n\n error ETHTransferFailed();\n error Expired();\n error InsufficientAmount();\n error InsufficientAmountA();\n error InsufficientAmountB();\n error InsufficientAmountADesired();\n error InsufficientAmountBDesired();\n error InsufficientLiquidity();\n error InsufficientOutputAmount();\n error InvalidPath();\n error OnlyWETH();\n error SameAddresses();\n error ZeroAddress();\n\n /// @notice Address of Velodrome v2 pool factory\n function factory() external view returns (address);\n\n /// @notice Address of Velodrome v2 pool implementation\n function poolImplementation() external view returns (address);\n\n /// @notice Sort two tokens by which address value is less than the other\n /// @param tokenA Address of token to sort\n /// @param tokenB Address of token to sort\n /// @return token0 Lower address value between tokenA and tokenB\n /// @return token1 Higher address value between tokenA and tokenB\n function sortTokens(address tokenA, address tokenB) external pure returns (address token0, address token1);\n\n /// @notice Calculate the address of a pool by its' factory.\n /// @dev Returns a randomly generated address for a nonexistent pool\n /// @param tokenA Address of token to query\n /// @param tokenB Address of token to query\n /// @param stable True if pool is stable, false if volatile\n function poolFor(address tokenA, address tokenB, bool stable) external view returns (address pool);\n\n /// @notice Fetch and sort the reserves for a pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @return reserveA Amount of reserves of the sorted token A\n /// @return reserveB Amount of reserves of the sorted token B\n function getReserves(\n address tokenA,\n address tokenB,\n bool stable\n ) external view returns (uint256 reserveA, uint256 reserveB);\n\n /// @notice Perform chained getAmountOut calculations on any number of pools\n function getAmountsOut(uint256 amountIn, Route[] memory routes) external view returns (uint256[] memory amounts);\n\n // **** ADD LIQUIDITY ****\n\n /// @notice Quote the amount deposited into a Pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @param amountADesired Amount of tokenA desired to deposit\n /// @param amountBDesired Amount of tokenB desired to deposit\n /// @return amountA Amount of tokenA to actually deposit\n /// @return amountB Amount of tokenB to actually deposit\n /// @return liquidity Amount of liquidity token returned from deposit\n function quoteAddLiquidity(\n address tokenA,\n address tokenB,\n bool stable,\n uint256 amountADesired,\n uint256 amountBDesired\n ) external view returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n /// @notice Quote the amount of liquidity removed from a Pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @param liquidity Amount of liquidity to remove\n /// @return amountA Amount of tokenA received\n /// @return amountB Amount of tokenB received\n function quoteRemoveLiquidity(\n address tokenA,\n address tokenB,\n bool stable,\n uint256 liquidity\n ) external view returns (uint256 amountA, uint256 amountB);\n\n /// @notice Add liquidity of two tokens to a Pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @param amountADesired Amount of tokenA desired to deposit\n /// @param amountBDesired Amount of tokenB desired to deposit\n /// @param amountAMin Minimum amount of tokenA to deposit\n /// @param amountBMin Minimum amount of tokenB to deposit\n /// @param to Recipient of liquidity token\n /// @param deadline Deadline to receive liquidity\n /// @return amountA Amount of tokenA to actually deposit\n /// @return amountB Amount of tokenB to actually deposit\n /// @return liquidity Amount of liquidity token returned from deposit\n function addLiquidity(\n address tokenA,\n address tokenB,\n bool stable,\n uint256 amountADesired,\n uint256 amountBDesired,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB, uint256 liquidity);\n\n /// @notice Add liquidity of a token and WETH (transferred as ETH) to a Pool\n /// @param token .\n /// @param stable True if pool is stable, false if volatile\n /// @param amountTokenDesired Amount of token desired to deposit\n /// @param amountTokenMin Minimum amount of token to deposit\n /// @param amountETHMin Minimum amount of ETH to deposit\n /// @param to Recipient of liquidity token\n /// @param deadline Deadline to add liquidity\n /// @return amountToken Amount of token to actually deposit\n /// @return amountETH Amount of tokenETH to actually deposit\n /// @return liquidity Amount of liquidity token returned from deposit\n function addLiquidityETH(\n address token,\n bool stable,\n uint256 amountTokenDesired,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external payable returns (uint256 amountToken, uint256 amountETH, uint256 liquidity);\n\n // **** REMOVE LIQUIDITY ****\n\n /// @notice Remove liquidity of two tokens from a Pool\n /// @param tokenA .\n /// @param tokenB .\n /// @param stable True if pool is stable, false if volatile\n /// @param liquidity Amount of liquidity to remove\n /// @param amountAMin Minimum amount of tokenA to receive\n /// @param amountBMin Minimum amount of tokenB to receive\n /// @param to Recipient of tokens received\n /// @param deadline Deadline to remove liquidity\n /// @return amountA Amount of tokenA received\n /// @return amountB Amount of tokenB received\n function removeLiquidity(\n address tokenA,\n address tokenB,\n bool stable,\n uint256 liquidity,\n uint256 amountAMin,\n uint256 amountBMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountA, uint256 amountB);\n\n /// @notice Remove liquidity of a token and WETH (returned as ETH) from a Pool\n /// @param token .\n /// @param stable True if pool is stable, false if volatile\n /// @param liquidity Amount of liquidity to remove\n /// @param amountTokenMin Minimum amount of token to receive\n /// @param amountETHMin Minimum amount of ETH to receive\n /// @param to Recipient of liquidity token\n /// @param deadline Deadline to receive liquidity\n /// @return amountToken Amount of token received\n /// @return amountETH Amount of ETH received\n function removeLiquidityETH(\n address token,\n bool stable,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountToken, uint256 amountETH);\n\n /// @notice Remove liquidity of a fee-on-transfer token and WETH (returned as ETH) from a Pool\n /// @param token .\n /// @param stable True if pool is stable, false if volatile\n /// @param liquidity Amount of liquidity to remove\n /// @param amountTokenMin Minimum amount of token to receive\n /// @param amountETHMin Minimum amount of ETH to receive\n /// @param to Recipient of liquidity token\n /// @param deadline Deadline to receive liquidity\n /// @return amountETH Amount of ETH received\n function removeLiquidityETHSupportingFeeOnTransferTokens(\n address token,\n bool stable,\n uint256 liquidity,\n uint256 amountTokenMin,\n uint256 amountETHMin,\n address to,\n uint256 deadline\n ) external returns (uint256 amountETH);\n\n /// @notice Swap one token for another\n /// @param amountIn Amount of token in\n /// @param amountOutMin Minimum amount of desired token received\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n /// @return amounts Array of amounts returned per route\n function swapExactTokensForTokens(\n uint256 amountIn,\n uint256 amountOutMin,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\n /// @notice Swap ETH for a token\n /// @param amountOutMin Minimum amount of desired token received\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n /// @return amounts Array of amounts returned per route\n function swapExactETHForTokens(\n uint256 amountOutMin,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external payable returns (uint256[] memory amounts);\n\n /// @notice Swap a token for WETH (returned as ETH)\n /// @param amountIn Amount of token in\n /// @param amountOutMin Minimum amount of desired ETH\n /// @param routes Array of trade routes used in the swap\n /// @param to Recipient of the tokens received\n /// @param deadline Deadline to receive tokens\n /// @return amounts Array of amounts returned per route\n function swapExactTokensForETH(\n uint256 amountIn,\n uint256 amountOutMin,\n Route[] calldata routes,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n}\n" + }, + "contracts/src/FeeDistributor.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/utils/Create2Upgradeable.sol\";\n\nimport { IonicComptroller } from \"./compound/ComptrollerInterface.sol\";\nimport { ICErc20 } from \"./compound/CTokenInterfaces.sol\";\nimport { CErc20Delegator } from \"./compound/CErc20Delegator.sol\";\nimport { CErc20PluginDelegate } from \"./compound/CErc20PluginDelegate.sol\";\nimport { SafeOwnableUpgradeable } from \"./ionic/SafeOwnableUpgradeable.sol\";\nimport { BasePriceOracle } from \"./oracles/BasePriceOracle.sol\";\nimport { DiamondExtension, DiamondBase } from \"./ionic/DiamondExtension.sol\";\nimport { AuthoritiesRegistry } from \"./ionic/AuthoritiesRegistry.sol\";\n\ncontract FeeDistributorStorage {\n struct CDelegateUpgradeData {\n address implementation;\n bytes becomeImplementationData;\n }\n\n /**\n * @notice Maps Unitroller (Comptroller proxy) addresses to the proportion of Ionic pool interest taken as a protocol fee (scaled by 1e18).\n * @dev A value of 0 means unset whereas a negative value means 0.\n */\n mapping(address => int256) public customInterestFeeRates;\n\n /**\n * @dev Latest Comptroller implementation for each existing implementation.\n */\n mapping(address => address) internal _latestComptrollerImplementation;\n\n /**\n * @dev Latest CErc20Delegate implementation for each existing implementation.\n */\n mapping(uint8 => CDelegateUpgradeData) internal _latestCErc20Delegate;\n\n /**\n * @dev Latest Plugin implementation for each existing implementation.\n */\n mapping(address => address) internal _latestPluginImplementation;\n\n mapping(address => DiamondExtension[]) public comptrollerExtensions;\n\n mapping(address => DiamondExtension[]) public cErc20DelegateExtensions;\n\n AuthoritiesRegistry public authoritiesRegistry;\n\n /**\n * @dev used as salt for the creation of new markets\n */\n uint256 public marketsCounter;\n\n /**\n * @dev Minimum borrow balance (in ETH) per user per Ionic pool asset (only checked on new borrows, not redemptions).\n */\n uint256 public minBorrowEth;\n\n /**\n * @dev Maximum utilization rate (scaled by 1e18) for Ionic pool assets (only checked on new borrows, not redemptions).\n * No longer used as of `Rari-Capital/compound-protocol` version `fuse-v1.1.0`.\n */\n uint256 public maxUtilizationRate;\n\n /**\n * @notice The proportion of Ionic pool interest taken as a protocol fee (scaled by 1e18).\n */\n uint256 public defaultInterestFeeRate;\n}\n\n/**\n * @title FeeDistributor\n * @author David Lucid (https://github.com/davidlucid)\n * @notice FeeDistributor controls and receives protocol fees from Ionic pools and relays admin actions to Ionic pools.\n */\ncontract FeeDistributor is SafeOwnableUpgradeable, FeeDistributorStorage {\n using AddressUpgradeable for address;\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /**\n * @dev Initializer that sets initial values of state variables.\n * @param _defaultInterestFeeRate The default proportion of Ionic pool interest taken as a protocol fee (scaled by 1e18).\n */\n function initialize(uint256 _defaultInterestFeeRate) public initializer {\n require(_defaultInterestFeeRate <= 1e18, \"Interest fee rate cannot be more than 100%.\");\n __SafeOwnable_init(msg.sender);\n defaultInterestFeeRate = _defaultInterestFeeRate;\n maxUtilizationRate = type(uint256).max;\n }\n\n function reinitialize(AuthoritiesRegistry _ar) public onlyOwnerOrAdmin {\n authoritiesRegistry = _ar;\n }\n\n /**\n * @dev Sets the default proportion of Ionic pool interest taken as a protocol fee.\n * @param _defaultInterestFeeRate The default proportion of Ionic pool interest taken as a protocol fee (scaled by 1e18).\n */\n function _setDefaultInterestFeeRate(uint256 _defaultInterestFeeRate) external onlyOwner {\n require(_defaultInterestFeeRate <= 1e18, \"Interest fee rate cannot be more than 100%.\");\n defaultInterestFeeRate = _defaultInterestFeeRate;\n }\n\n /**\n * @dev Withdraws accrued fees on interest.\n * @param erc20Contract The ERC20 token address to withdraw. Set to the zero address to withdraw ETH.\n */\n function _withdrawAssets(address erc20Contract) external {\n if (erc20Contract == address(0)) {\n uint256 balance = address(this).balance;\n require(balance > 0, \"No balance available to withdraw.\");\n (bool success, ) = owner().call{ value: balance }(\"\");\n require(success, \"Failed to transfer ETH balance to msg.sender.\");\n } else {\n IERC20Upgradeable token = IERC20Upgradeable(erc20Contract);\n uint256 balance = token.balanceOf(address(this));\n require(balance > 0, \"No token balance available to withdraw.\");\n token.safeTransfer(owner(), balance);\n }\n }\n\n /**\n * @dev Sets the proportion of Ionic pool interest taken as a protocol fee.\n * @param _minBorrowEth Minimum borrow balance (in ETH) per user per Ionic pool asset (only checked on new borrows, not redemptions).\n * @param _maxUtilizationRate Maximum utilization rate (scaled by 1e18) for Ionic pool assets (only checked on new borrows, not redemptions).\n */\n function _setPoolLimits(uint256 _minBorrowEth, uint256 _maxUtilizationRate) external onlyOwner {\n minBorrowEth = _minBorrowEth;\n maxUtilizationRate = _maxUtilizationRate;\n }\n\n function getMinBorrowEth(ICErc20 _ctoken) public view returns (uint256) {\n (, , uint256 borrowBalance, ) = _ctoken.getAccountSnapshot(_msgSender());\n if (borrowBalance == 0) return minBorrowEth;\n IonicComptroller comptroller = IonicComptroller(address(_ctoken.comptroller()));\n BasePriceOracle oracle = comptroller.oracle();\n uint256 underlyingPriceEth = oracle.price(ICErc20(address(_ctoken)).underlying());\n uint256 underlyingDecimals = _ctoken.decimals();\n uint256 borrowBalanceEth = (underlyingPriceEth * borrowBalance) / 10 ** underlyingDecimals;\n if (borrowBalanceEth > minBorrowEth) {\n return 0;\n }\n return minBorrowEth - borrowBalanceEth;\n }\n\n /**\n * @dev Receives native fees.\n */\n receive() external payable {}\n\n /**\n * @dev Sends data to a contract.\n * @param targets The contracts to which `data` will be sent.\n * @param data The data to be sent to each of `targets`.\n */\n function _callPool(address[] calldata targets, bytes[] calldata data) external onlyOwner {\n require(targets.length > 0 && targets.length == data.length, \"Array lengths must be equal and greater than 0.\");\n for (uint256 i = 0; i < targets.length; i++) targets[i].functionCall(data[i]);\n }\n\n /**\n * @dev Sends data to a contract.\n * @param targets The contracts to which `data` will be sent.\n * @param data The data to be sent to each of `targets`.\n */\n function _callPool(address[] calldata targets, bytes calldata data) external onlyOwner {\n require(targets.length > 0, \"No target addresses specified.\");\n for (uint256 i = 0; i < targets.length; i++) targets[i].functionCall(data);\n }\n\n /**\n * @dev Deploys a CToken for an underlying ERC20\n * @param constructorData Encoded construction data for `CToken initialize()`\n */\n function deployCErc20(\n uint8 delegateType,\n bytes calldata constructorData,\n bytes calldata becomeImplData\n ) external returns (address) {\n // Make sure comptroller == msg.sender\n (address underlying, address comptroller) = abi.decode(constructorData[0:64], (address, address));\n require(comptroller == msg.sender, \"Comptroller is not sender.\");\n\n // Deploy CErc20Delegator using msg.sender, underlying, and block.number as a salt\n bytes32 salt = keccak256(abi.encodePacked(msg.sender, underlying, ++marketsCounter));\n\n bytes memory cErc20DelegatorCreationCode = abi.encodePacked(type(CErc20Delegator).creationCode, constructorData);\n address proxy = Create2Upgradeable.deploy(0, salt, cErc20DelegatorCreationCode);\n\n CDelegateUpgradeData memory data = _latestCErc20Delegate[delegateType];\n DiamondExtension delegateAsExtension = DiamondExtension(data.implementation);\n // register the first extension\n DiamondBase(proxy)._registerExtension(delegateAsExtension, DiamondExtension(address(0)));\n // derive and configure the other extensions\n DiamondExtension[] memory ctokenExts = cErc20DelegateExtensions[address(delegateAsExtension)];\n for (uint256 i = 0; i < ctokenExts.length; i++) {\n if (ctokenExts[i] == delegateAsExtension) continue;\n DiamondBase(proxy)._registerExtension(ctokenExts[i], DiamondExtension(address(0)));\n }\n CErc20PluginDelegate(address(proxy))._becomeImplementation(becomeImplData);\n\n return proxy;\n }\n\n /**\n * @dev Latest Comptroller implementation for each existing implementation.\n */\n function latestComptrollerImplementation(address oldImplementation) external view returns (address) {\n return\n _latestComptrollerImplementation[oldImplementation] != address(0)\n ? _latestComptrollerImplementation[oldImplementation]\n : oldImplementation;\n }\n\n /**\n * @dev Sets the latest `Comptroller` upgrade implementation address.\n * @param oldImplementation The old `Comptroller` implementation address to upgrade from.\n * @param newImplementation Latest `Comptroller` implementation address.\n */\n function _setLatestComptrollerImplementation(\n address oldImplementation,\n address newImplementation\n ) external onlyOwner {\n _latestComptrollerImplementation[oldImplementation] = newImplementation;\n }\n\n /**\n * @dev Latest CErc20Delegate implementation for each existing implementation.\n */\n function latestCErc20Delegate(uint8 delegateType) external view returns (address, bytes memory) {\n CDelegateUpgradeData memory data = _latestCErc20Delegate[delegateType];\n bytes memory emptyBytes;\n return\n data.implementation != address(0)\n ? (data.implementation, data.becomeImplementationData)\n : (address(0), emptyBytes);\n }\n\n /**\n * @dev Sets the latest `CErc20Delegate` upgrade implementation address and data.\n * @param delegateType The old `CErc20Delegate` implementation address to upgrade from.\n * @param newImplementation Latest `CErc20Delegate` implementation address.\n * @param becomeImplementationData Data passed to the new implementation via `becomeImplementation` after upgrade.\n */\n function _setLatestCErc20Delegate(\n uint8 delegateType,\n address newImplementation,\n bytes calldata becomeImplementationData\n ) external onlyOwner {\n _latestCErc20Delegate[delegateType] = CDelegateUpgradeData(newImplementation, becomeImplementationData);\n }\n\n /**\n * @dev Latest Plugin implementation for each existing implementation.\n */\n function latestPluginImplementation(address oldImplementation) external view returns (address) {\n return\n _latestPluginImplementation[oldImplementation] != address(0)\n ? _latestPluginImplementation[oldImplementation]\n : oldImplementation;\n }\n\n /**\n * @dev Sets the latest plugin upgrade implementation address.\n * @param oldImplementation The old plugin implementation address to upgrade from.\n * @param newImplementation Latest plugin implementation address.\n */\n function _setLatestPluginImplementation(address oldImplementation, address newImplementation) external onlyOwner {\n _latestPluginImplementation[oldImplementation] = newImplementation;\n }\n\n /**\n * @dev Upgrades a plugin of a CErc20PluginDelegate market to the latest implementation\n * @param cDelegator the proxy address\n * @return if the plugin was upgraded or not\n */\n function _upgradePluginToLatestImplementation(address cDelegator) external onlyOwner returns (bool) {\n CErc20PluginDelegate market = CErc20PluginDelegate(cDelegator);\n\n address oldPluginAddress = address(market.plugin());\n market._updatePlugin(_latestPluginImplementation[oldPluginAddress]);\n address newPluginAddress = address(market.plugin());\n\n return newPluginAddress != oldPluginAddress;\n }\n\n /**\n * @notice Returns the proportion of Ionic pool interest taken as a protocol fee (scaled by 1e18).\n */\n function interestFeeRate() external view returns (uint256) {\n (bool success, bytes memory data) = msg.sender.staticcall(abi.encodeWithSignature(\"comptroller()\"));\n\n if (success && data.length == 32) {\n address comptroller = abi.decode(data, (address));\n int256 customRate = customInterestFeeRates[comptroller];\n if (customRate > 0) return uint256(customRate);\n if (customRate < 0) return 0;\n }\n\n return defaultInterestFeeRate;\n }\n\n /**\n * @dev Sets the proportion of Ionic pool interest taken as a protocol fee.\n * @param comptroller The Unitroller (Comptroller proxy) address.\n * @param rate The proportion of Ionic pool interest taken as a protocol fee (scaled by 1e18).\n */\n function _setCustomInterestFeeRate(address comptroller, int256 rate) external onlyOwner {\n require(rate <= 1e18, \"Interest fee rate cannot be more than 100%.\");\n customInterestFeeRates[comptroller] = rate;\n }\n\n function getComptrollerExtensions(address comptroller) external view returns (DiamondExtension[] memory) {\n return comptrollerExtensions[comptroller];\n }\n\n function _setComptrollerExtensions(address comptroller, DiamondExtension[] calldata extensions) external onlyOwner {\n comptrollerExtensions[comptroller] = extensions;\n }\n\n function _registerComptrollerExtension(\n address payable pool,\n DiamondExtension extensionToAdd,\n DiamondExtension extensionToReplace\n ) external onlyOwner {\n DiamondBase(pool)._registerExtension(extensionToAdd, extensionToReplace);\n }\n\n function getCErc20DelegateExtensions(address cErc20Delegate) external view returns (DiamondExtension[] memory) {\n return cErc20DelegateExtensions[cErc20Delegate];\n }\n\n function _setCErc20DelegateExtensions(\n address cErc20Delegate,\n DiamondExtension[] calldata extensions\n ) external onlyOwner {\n cErc20DelegateExtensions[cErc20Delegate] = extensions;\n }\n\n function autoUpgradePool(IonicComptroller pool) external onlyOwner {\n ICErc20[] memory markets = pool.getAllMarkets();\n\n // auto upgrade the pool\n pool._upgrade();\n\n for (uint8 i = 0; i < markets.length; i++) {\n // upgrade the market\n markets[i]._upgrade();\n }\n }\n\n function canCall(address pool, address user, address target, bytes4 functionSig) external view returns (bool) {\n return authoritiesRegistry.canCall(pool, user, target, functionSig);\n }\n}\n" + }, + "contracts/src/GlobalPauser.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport { IonicComptroller } from \"./compound/ComptrollerInterface.sol\";\nimport { ICErc20 } from \"./compound/CTokenInterfaces.sol\";\nimport { Ownable2Step } from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\n\ninterface IPoolDirectory {\n struct Pool {\n string name;\n address creator;\n address comptroller;\n uint256 blockPosted;\n uint256 timestampPosted;\n }\n\n function getActivePools() external view returns (uint256, Pool[] memory);\n}\n\ncontract GlobalPauser is Ownable2Step {\n IPoolDirectory public poolDirectory;\n mapping(address => bool) public pauseGuardian;\n\n modifier onlyPauseGuardian() {\n require(pauseGuardian[msg.sender], \"!guardian\");\n _;\n }\n\n constructor(address _poolDirectory) Ownable2Step() {\n poolDirectory = IPoolDirectory(_poolDirectory);\n }\n\n function setPauseGuardian(address _pauseGuardian, bool _isPauseGuardian) external onlyOwner {\n pauseGuardian[_pauseGuardian] = _isPauseGuardian;\n }\n\n function pauseAll() external onlyPauseGuardian {\n (, IPoolDirectory.Pool[] memory pools) = poolDirectory.getActivePools();\n for (uint256 i = 0; i < pools.length; i++) {\n ICErc20[] memory markets = IonicComptroller(pools[i].comptroller).getAllMarkets();\n for (uint256 j = 0; j < markets.length; j++) {\n bool isPaused = IonicComptroller(pools[i].comptroller).borrowGuardianPaused(address(markets[j]));\n if (!isPaused) {\n IonicComptroller(pools[i].comptroller)._setBorrowPaused(markets[j], true);\n }\n\n isPaused = IonicComptroller(pools[i].comptroller).mintGuardianPaused(address(markets[j]));\n if (!isPaused) {\n IonicComptroller(pools[i].comptroller)._setMintPaused(markets[j], true);\n }\n }\n }\n }\n}\n" + }, + "contracts/src/IEmissionsManager.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\ninterface IEmissionsManager {\n error InvalidPoolDirectoryAaddress();\n error InvalidProtocolAddress();\n error InvalidRewardTokenAddress();\n error CollateralBasisPointsExceedMaximum();\n error InvalidVeIONAddress();\n error MaximumLimitExceeded();\n\n event Initialized(\n address indexed protocolAddress,\n address indexed rewardToken,\n uint256 collateralBp,\n bytes nonBlacklistableTargetBytecode\n );\n event VeIonSet(address indexed veIon);\n event CollateralBpSet(uint256 collateralBp);\n event NonBlacklistableAddressSet(address indexed user, bool isNonBlacklistable);\n event NonBlacklistableTargetBytecodeSet(bytes newBytecode);\n\n function isUserBlacklisted(address _user) external view returns (bool);\n function isUserBlacklistable(address _user) external view returns (bool);\n}\n" + }, + "contracts/src/ILiquidator.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport { ICErc20 } from \"./compound/CTokenInterfaces.sol\";\nimport \"./liquidators/IRedemptionStrategy.sol\";\nimport \"./liquidators/IFundsConversionStrategy.sol\";\n\ninterface ILiquidator {\n /**\n * borrower The borrower's Ethereum address.\n * repayAmount The amount to repay to liquidate the unhealthy loan.\n * cErc20 The borrowed CErc20 contract to repay.\n * cTokenCollateral The cToken collateral contract to be liquidated.\n * minProfitAmount The minimum amount of profit required for execution (in terms of `exchangeProfitTo`). Reverts if this condition is not met.\n * redemptionStrategies The IRedemptionStrategy contracts to use, if any, to redeem \"special\" collateral tokens (before swapping the output for borrowed tokens to be repaid via Uniswap).\n * strategyData The data for the chosen IRedemptionStrategy contracts, if any.\n */\n struct LiquidateToTokensWithFlashSwapVars {\n address borrower;\n uint256 repayAmount;\n ICErc20 cErc20;\n ICErc20 cTokenCollateral;\n address flashSwapContract;\n uint256 minProfitAmount;\n IRedemptionStrategy[] redemptionStrategies;\n bytes[] strategyData;\n IFundsConversionStrategy[] debtFundingStrategies;\n bytes[] debtFundingStrategiesData;\n }\n\n function redemptionStrategiesWhitelist(address strategy) external view returns (bool);\n\n function safeLiquidate(\n address borrower,\n uint256 repayAmount,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n uint256 minOutputAmount\n ) external returns (uint256);\n\n function safeLiquidateToTokensWithFlashLoan(LiquidateToTokensWithFlashSwapVars calldata vars)\n external\n returns (uint256);\n\n function _whitelistRedemptionStrategy(IRedemptionStrategy strategy, bool whitelisted) external;\n\n function _whitelistRedemptionStrategies(IRedemptionStrategy[] calldata strategies, bool[] calldata whitelisted)\n external;\n\n function setExpressRelay(address _expressRelay) external;\n\n function setPoolLens(address _poolLens) external;\n\n function setHealthFactorThreshold(uint256 _healthFactorThreshold) external;\n}\n" + }, + "contracts/src/ionic/AddressesProvider.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport { SafeOwnableUpgradeable } from \"../ionic/SafeOwnableUpgradeable.sol\";\n\n/**\n * @title AddressesProvider\n * @notice The Addresses Provider serves as a central storage of system internal and external\n * contract addresses that change between deploys and across chains\n * @author Veliko Minkov \n */\ncontract AddressesProvider is SafeOwnableUpgradeable {\n mapping(string => address) private _addresses;\n mapping(address => Contract) public plugins;\n mapping(address => Contract) public flywheelRewards;\n mapping(address => RedemptionStrategy) public redemptionStrategiesConfig;\n mapping(address => FundingStrategy) public fundingStrategiesConfig;\n JarvisPool[] public jarvisPoolsConfig;\n CurveSwapPool[] public curveSwapPoolsConfig;\n mapping(address => mapping(address => address)) public balancerPoolForTokens;\n\n /// @dev Initializer to set the admin that can set and change contracts addresses\n function initialize(address owner) public initializer {\n __SafeOwnable_init(owner);\n }\n\n /**\n * @dev The contract address and a string that uniquely identifies the contract's interface\n */\n struct Contract {\n address addr;\n string contractInterface;\n }\n\n struct RedemptionStrategy {\n address addr;\n string contractInterface;\n address outputToken;\n }\n\n struct FundingStrategy {\n address addr;\n string contractInterface;\n address inputToken;\n }\n\n struct JarvisPool {\n address syntheticToken;\n address collateralToken;\n address liquidityPool;\n uint256 expirationTime;\n }\n\n struct CurveSwapPool {\n address poolAddress;\n address[] coins;\n }\n\n /**\n * @dev sets the address and contract interface ID of the flywheel for the reward token\n * @param rewardToken the reward token address\n * @param flywheelRewardsModule the flywheel rewards module address\n * @param contractInterface a string that uniquely identifies the contract's interface\n */\n function setFlywheelRewards(\n address rewardToken,\n address flywheelRewardsModule,\n string calldata contractInterface\n ) public onlyOwner {\n flywheelRewards[rewardToken] = Contract(flywheelRewardsModule, contractInterface);\n }\n\n /**\n * @dev sets the address and contract interface ID of the ERC4626 plugin for the asset\n * @param asset the asset address\n * @param plugin the ERC4626 plugin address\n * @param contractInterface a string that uniquely identifies the contract's interface\n */\n function setPlugin(\n address asset,\n address plugin,\n string calldata contractInterface\n ) public onlyOwner {\n plugins[asset] = Contract(plugin, contractInterface);\n }\n\n /**\n * @dev sets the address and contract interface ID of the redemption strategy for the asset\n * @param asset the asset address\n * @param strategy redemption strategy address\n * @param contractInterface a string that uniquely identifies the contract's interface\n */\n function setRedemptionStrategy(\n address asset,\n address strategy,\n string calldata contractInterface,\n address outputToken\n ) public onlyOwner {\n redemptionStrategiesConfig[asset] = RedemptionStrategy(strategy, contractInterface, outputToken);\n }\n\n function getRedemptionStrategy(address asset) public view returns (RedemptionStrategy memory) {\n return redemptionStrategiesConfig[asset];\n }\n\n /**\n * @dev sets the address and contract interface ID of the funding strategy for the asset\n * @param asset the asset address\n * @param strategy funding strategy address\n * @param contractInterface a string that uniquely identifies the contract's interface\n */\n function setFundingStrategy(\n address asset,\n address strategy,\n string calldata contractInterface,\n address inputToken\n ) public onlyOwner {\n fundingStrategiesConfig[asset] = FundingStrategy(strategy, contractInterface, inputToken);\n }\n\n function getFundingStrategy(address asset) public view returns (FundingStrategy memory) {\n return fundingStrategiesConfig[asset];\n }\n\n /**\n * @dev configures the Jarvis pool of a Jarvis synthetic token\n * @param syntheticToken the synthetic token address\n * @param collateralToken the collateral token address\n * @param liquidityPool the liquidity pool address\n * @param expirationTime the operation expiration time\n */\n function setJarvisPool(\n address syntheticToken,\n address collateralToken,\n address liquidityPool,\n uint256 expirationTime\n ) public onlyOwner {\n jarvisPoolsConfig.push(JarvisPool(syntheticToken, collateralToken, liquidityPool, expirationTime));\n }\n\n function setCurveSwapPool(address poolAddress, address[] calldata coins) public onlyOwner {\n curveSwapPoolsConfig.push(CurveSwapPool(poolAddress, coins));\n }\n\n /**\n * @dev Sets an address for an id replacing the address saved in the addresses map\n * @param id The id\n * @param newAddress The address to set\n */\n function setAddress(string calldata id, address newAddress) external onlyOwner {\n _addresses[id] = newAddress;\n }\n\n /**\n * @dev Returns an address by id\n * @return The address\n */\n function getAddress(string calldata id) public view returns (address) {\n return _addresses[id];\n }\n\n function getCurveSwapPools() public view returns (CurveSwapPool[] memory) {\n return curveSwapPoolsConfig;\n }\n\n function getJarvisPools() public view returns (JarvisPool[] memory) {\n return jarvisPoolsConfig;\n }\n\n function setBalancerPoolForTokens(\n address inputToken,\n address outputToken,\n address pool\n ) external onlyOwner {\n balancerPoolForTokens[inputToken][outputToken] = pool;\n }\n\n function getBalancerPoolForTokens(address inputToken, address outputToken) external view returns (address) {\n return balancerPoolForTokens[inputToken][outputToken];\n }\n}\n" + }, + "contracts/src/ionic/AuthoritiesRegistry.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { PoolRolesAuthority } from \"../ionic/PoolRolesAuthority.sol\";\nimport { SafeOwnableUpgradeable } from \"../ionic/SafeOwnableUpgradeable.sol\";\nimport { IonicComptroller } from \"../compound/ComptrollerInterface.sol\";\n\nimport { TransparentUpgradeableProxy } from \"@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol\";\n\ncontract AuthoritiesRegistry is SafeOwnableUpgradeable {\n mapping(address => PoolRolesAuthority) public poolsAuthorities;\n PoolRolesAuthority public poolAuthLogic;\n address public leveredPositionsFactory;\n bool public noAuthRequired;\n\n function initialize(address _leveredPositionsFactory) public initializer {\n __SafeOwnable_init(msg.sender);\n leveredPositionsFactory = _leveredPositionsFactory;\n poolAuthLogic = new PoolRolesAuthority();\n }\n\n function reinitialize(address _leveredPositionsFactory) public onlyOwnerOrAdmin {\n leveredPositionsFactory = _leveredPositionsFactory;\n poolAuthLogic = new PoolRolesAuthority();\n // for Neon the auth is not required\n noAuthRequired = block.chainid == 245022934;\n }\n\n function createPoolAuthority(address pool) public onlyOwner returns (PoolRolesAuthority auth) {\n require(address(poolsAuthorities[pool]) == address(0), \"already created\");\n\n TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(address(poolAuthLogic), _getProxyAdmin(), \"\");\n auth = PoolRolesAuthority(address(proxy));\n auth.initialize(address(this));\n poolsAuthorities[pool] = auth;\n\n auth.openPoolSupplierCapabilities(IonicComptroller(pool));\n auth.setUserRole(address(this), auth.REGISTRY_ROLE(), true);\n // sets the registry owner as the auth owner\n reconfigureAuthority(pool);\n }\n\n function reconfigureAuthority(address poolAddress) public {\n IonicComptroller pool = IonicComptroller(poolAddress);\n PoolRolesAuthority auth = poolsAuthorities[address(pool)];\n\n if (msg.sender != poolAddress || address(auth) != address(0)) {\n require(address(auth) != address(0), \"no such authority\");\n require(msg.sender == owner() || msg.sender == poolAddress, \"not owner or pool\");\n\n auth.configureRegistryCapabilities();\n auth.configurePoolSupplierCapabilities(pool);\n auth.configurePoolBorrowerCapabilities(pool);\n // everyone can be a liquidator\n auth.configureOpenPoolLiquidatorCapabilities(pool);\n auth.configureLeveredPositionCapabilities(pool);\n\n if (auth.owner() != owner()) {\n auth.setOwner(owner());\n }\n }\n }\n\n function canCall(\n address pool,\n address user,\n address target,\n bytes4 functionSig\n ) external view returns (bool) {\n PoolRolesAuthority authorityForPool = poolsAuthorities[pool];\n if (address(authorityForPool) == address(0)) {\n return noAuthRequired;\n } else {\n // allow only if an auth exists and it allows the action\n return authorityForPool.canCall(user, target, functionSig);\n }\n }\n\n function setUserRole(\n address pool,\n address user,\n uint8 role,\n bool enabled\n ) external {\n PoolRolesAuthority poolAuth = poolsAuthorities[pool];\n\n require(address(poolAuth) != address(0), \"auth does not exist\");\n require(msg.sender == owner() || msg.sender == leveredPositionsFactory, \"not owner or factory\");\n require(msg.sender != leveredPositionsFactory || role == poolAuth.LEVERED_POSITION_ROLE(), \"only lev pos role\");\n\n poolAuth.setUserRole(user, role, enabled);\n }\n}\n" + }, + "contracts/src/ionic/CollateralSwap.sol": { + "content": "// SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.22;\n\nimport { IERC20, SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { Ownable2Step } from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\n\nimport { IFlashLoanReceiver } from \"./IFlashLoanReceiver.sol\";\nimport { Exponential } from \"../compound/Exponential.sol\";\nimport { ICErc20 } from \"../compound/CTokenInterfaces.sol\";\nimport { IonicComptroller } from \"../compound/ComptrollerInterface.sol\";\n\ncontract CollateralSwap is Ownable2Step, Exponential, IFlashLoanReceiver {\n using SafeERC20 for IERC20;\n\n uint256 public feeBps;\n address public feeRecipient;\n IonicComptroller public comptroller;\n mapping(address => bool) public allowedSwapTargets;\n\n error SwapCollateralFailed();\n error TransferFailed(address market, address user, address target);\n error MintFailed(address market, uint256 errorCode);\n error RedeemFailed(address market, uint256 errorCode);\n error InvalidFlashloanCaller(address caller);\n error InvalidSwapTarget(address target);\n\n constructor(\n uint256 _feeBps,\n address _feeRecipient,\n address _comptroller,\n address[] memory _allowedSwapTargets\n ) Ownable2Step() {\n feeBps = _feeBps;\n feeRecipient = _feeRecipient;\n comptroller = IonicComptroller(_comptroller);\n for (uint256 i = 0; i < _allowedSwapTargets.length; i++) {\n allowedSwapTargets[_allowedSwapTargets[i]] = true;\n }\n }\n\n // ADMIN FUNCTIONS\n\n function setFeeBps(uint256 _feeBps) public onlyOwner {\n feeBps = _feeBps;\n }\n\n function setFeeRecipient(address _feeRecipient) public onlyOwner {\n feeRecipient = _feeRecipient;\n }\n\n function setAllowedSwapTarget(address _target, bool _allowed) public onlyOwner {\n allowedSwapTargets[_target] = _allowed;\n }\n\n function sweep(address token) public onlyOwner {\n IERC20(token).safeTransfer(owner(), IERC20(token).balanceOf(address(this)));\n }\n\n // PUBLIC FUNCTIONS\n\n function swapCollateral(\n uint256 amountUnderlying,\n ICErc20 oldCollateralMarket,\n ICErc20 newCollateralMarket,\n address swapTarget,\n bytes calldata swapData\n ) public {\n oldCollateralMarket.flash(\n amountUnderlying,\n abi.encode(msg.sender, oldCollateralMarket, newCollateralMarket, swapTarget, swapData)\n );\n }\n\n function receiveFlashLoan(address borrowedAsset, uint256 borrowedAmount, bytes calldata data) external {\n // make sure the caller is a valid market\n {\n ICErc20[] memory markets = comptroller.getAllMarkets();\n bool isAllowed = false;\n for (uint256 i = 0; i < markets.length; i++) {\n if (msg.sender == address(markets[i])) {\n isAllowed = true;\n break;\n }\n }\n if (!isAllowed) {\n revert InvalidFlashloanCaller(msg.sender);\n }\n }\n\n (\n address borrower,\n ICErc20 oldCollateralMarket,\n ICErc20 newCollateralMarket,\n address swapTarget,\n bytes memory swapData\n ) = abi.decode(data, (address, ICErc20, ICErc20, address, bytes));\n\n // swap the collateral\n {\n if (!allowedSwapTargets[swapTarget]) {\n revert InvalidSwapTarget(swapTarget);\n }\n IERC20(borrowedAsset).approve(swapTarget, borrowedAmount);\n (bool success, ) = swapTarget.call(swapData);\n if (!success) {\n revert SwapCollateralFailed();\n }\n }\n\n // mint the new collateral\n {\n IERC20 newCollateralAsset = IERC20(newCollateralMarket.underlying());\n uint256 outputAmount = newCollateralAsset.balanceOf(address(this));\n uint256 fee = (outputAmount * feeBps) / 10_000;\n outputAmount -= fee;\n if (fee > 0) {\n newCollateralAsset.safeTransfer(feeRecipient, fee);\n }\n newCollateralAsset.approve(address(newCollateralMarket), outputAmount);\n uint256 mintResult = newCollateralMarket.mint(outputAmount);\n if (mintResult != 0) {\n revert MintFailed(address(newCollateralMarket), mintResult);\n }\n }\n\n // transfer the new collateral to the borrower\n {\n uint256 cTokenBalance = IERC20(address(newCollateralMarket)).balanceOf(address(this));\n IERC20(address(newCollateralMarket)).safeTransfer(borrower, cTokenBalance);\n }\n\n // withdraw the old collateral\n {\n (MathError mErr, uint256 amountCTokensToSwap) = divScalarByExpTruncate(\n borrowedAmount,\n Exp({ mantissa: oldCollateralMarket.exchangeRateCurrent() })\n );\n require(mErr == MathError.NO_ERROR, \"exchange rate error\");\n bool transferStatus = oldCollateralMarket.transferFrom(borrower, address(this), amountCTokensToSwap + 1);\n if (!transferStatus) {\n revert TransferFailed(address(oldCollateralMarket), borrower, address(this));\n }\n uint256 redeemResult = oldCollateralMarket.redeemUnderlying(type(uint256).max);\n if (redeemResult != 0) {\n revert RedeemFailed(address(oldCollateralMarket), redeemResult);\n }\n IERC20(borrowedAsset).approve(address(oldCollateralMarket), borrowedAmount);\n }\n // flashloan gets paid back from redeemed collateral\n }\n}\n" + }, + "contracts/src/ionic/DiamondExtension.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\n/**\n * @notice a base contract for logic extensions that use the diamond pattern storage\n * to map the functions when looking up the extension contract to delegate to.\n */\nabstract contract DiamondExtension {\n /**\n * @return a list of all the function selectors that this logic extension exposes\n */\n function _getExtensionFunctions() external pure virtual returns (bytes4[] memory);\n}\n\n// When no function exists for function called\nerror FunctionNotFound(bytes4 _functionSelector);\n\n// When no extension exists for function called\nerror ExtensionNotFound(bytes4 _functionSelector);\n\n// When the function is already added\nerror FunctionAlreadyAdded(bytes4 _functionSelector, address _currentImpl);\n\nabstract contract DiamondBase {\n /**\n * @dev register a logic extension\n * @param extensionToAdd the extension whose functions are to be added\n * @param extensionToReplace the extension whose functions are to be removed/replaced\n */\n function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) external virtual;\n\n function _listExtensions() public view returns (address[] memory) {\n return LibDiamond.listExtensions();\n }\n\n fallback() external {\n address extension = LibDiamond.getExtensionForFunction(msg.sig);\n if (extension == address(0)) revert FunctionNotFound(msg.sig);\n // Execute external function from extension using delegatecall and return any value.\n assembly {\n // copy function selector and any arguments\n calldatacopy(0, 0, calldatasize())\n // execute function call using the extension\n let result := delegatecall(gas(), extension, 0, calldatasize(), 0, 0)\n // get any return value\n returndatacopy(0, 0, returndatasize())\n // return any return value or error back to the caller\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n}\n\n/**\n * @notice a library to use in a contract, whose logic is extended with diamond extension\n */\nlibrary LibDiamond {\n bytes32 constant DIAMOND_STORAGE_POSITION = keccak256(\"diamond.extensions.diamond.storage\");\n\n struct Function {\n address extension;\n bytes4 selector;\n }\n\n struct LogicStorage {\n Function[] functions;\n address[] extensions;\n }\n\n function getExtensionForFunction(bytes4 msgSig) internal view returns (address) {\n return getExtensionForSelector(msgSig, diamondStorage());\n }\n\n function diamondStorage() internal pure returns (LogicStorage storage ds) {\n bytes32 position = DIAMOND_STORAGE_POSITION;\n assembly {\n ds.slot := position\n }\n }\n\n function listExtensions() internal view returns (address[] memory) {\n return diamondStorage().extensions;\n }\n\n function registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace) internal {\n if (address(extensionToReplace) != address(0)) {\n removeExtension(extensionToReplace);\n }\n addExtension(extensionToAdd);\n }\n\n function removeExtension(DiamondExtension extension) internal {\n LogicStorage storage ds = diamondStorage();\n // remove all functions of the extension to replace\n removeExtensionFunctions(extension);\n for (uint8 i = 0; i < ds.extensions.length; i++) {\n if (ds.extensions[i] == address(extension)) {\n ds.extensions[i] = ds.extensions[ds.extensions.length - 1];\n ds.extensions.pop();\n }\n }\n }\n\n function addExtension(DiamondExtension extension) internal {\n LogicStorage storage ds = diamondStorage();\n for (uint8 i = 0; i < ds.extensions.length; i++) {\n require(ds.extensions[i] != address(extension), \"extension already added\");\n }\n addExtensionFunctions(extension);\n ds.extensions.push(address(extension));\n }\n\n function removeExtensionFunctions(DiamondExtension extension) internal {\n bytes4[] memory fnsToRemove = extension._getExtensionFunctions();\n LogicStorage storage ds = diamondStorage();\n for (uint16 i = 0; i < fnsToRemove.length; i++) {\n bytes4 selectorToRemove = fnsToRemove[i];\n // must never fail\n assert(address(extension) == getExtensionForSelector(selectorToRemove, ds));\n // swap with the last element in the selectorAtIndex array and remove the last element\n uint16 indexToKeep = getIndexForSelector(selectorToRemove, ds);\n ds.functions[indexToKeep] = ds.functions[ds.functions.length - 1];\n ds.functions.pop();\n }\n }\n\n function addExtensionFunctions(DiamondExtension extension) internal {\n bytes4[] memory fnsToAdd = extension._getExtensionFunctions();\n LogicStorage storage ds = diamondStorage();\n uint16 functionsCount = uint16(ds.functions.length);\n for (uint256 functionsIndex = 0; functionsIndex < fnsToAdd.length; functionsIndex++) {\n bytes4 selector = fnsToAdd[functionsIndex];\n address oldImplementation = getExtensionForSelector(selector, ds);\n if (oldImplementation != address(0)) revert FunctionAlreadyAdded(selector, oldImplementation);\n ds.functions.push(Function(address(extension), selector));\n functionsCount++;\n }\n }\n\n function getExtensionForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (address) {\n uint256 fnsLen = ds.functions.length;\n for (uint256 i = 0; i < fnsLen; i++) {\n if (ds.functions[i].selector == selector) return ds.functions[i].extension;\n }\n\n return address(0);\n }\n\n function getIndexForSelector(bytes4 selector, LogicStorage storage ds) internal view returns (uint16) {\n uint16 fnsLen = uint16(ds.functions.length);\n for (uint16 i = 0; i < fnsLen; i++) {\n if (ds.functions[i].selector == selector) return i;\n }\n\n return type(uint16).max;\n }\n}\n" + }, + "contracts/src/ionic/IFlashLoanReceiver.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\ninterface IFlashLoanReceiver {\n function receiveFlashLoan(\n address borrowedAsset,\n uint256 borrowedAmount,\n bytes calldata data\n ) external;\n}\n" + }, + "contracts/src/ionic/irms/AdjustableJumpRateModel.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../../compound/InterestRateModel.sol\";\nimport \"../../compound/SafeMath.sol\";\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\n\n/**\n * @title Compound's JumpRateModel Contract\n * @author Compound\n */\n\nstruct InterestRateModelParams {\n uint256 blocksPerYear; // The approximate number of blocks per year\n uint256 baseRatePerYear; // The approximate target base APR, as a mantissa (scaled by 1e18)\n uint256 multiplierPerYear; // The rate of increase in interest rate wrt utilization (scaled by 1e18)\n uint256 jumpMultiplierPerYear; // The multiplierPerBlock after hitting a specified utilization point\n uint256 kink; // The utilization point at which the jump multiplier is applied\n}\n\ncontract AdjustableJumpRateModel is Ownable, InterestRateModel {\n using SafeMath for uint256;\n\n event NewInterestParams(\n uint256 baseRatePerBlock,\n uint256 multiplierPerBlock,\n uint256 jumpMultiplierPerBlock,\n uint256 kink\n );\n\n /**\n * @notice The approximate number of blocks per year that is assumed by the interest rate model\n */\n uint256 public blocksPerYear;\n\n /**\n * @notice The multiplier of utilization rate that gives the slope of the interest rate\n */\n uint256 public multiplierPerBlock;\n\n /**\n * @notice The base interest rate which is the y-intercept when utilization rate is 0\n */\n uint256 public baseRatePerBlock;\n\n /**\n * @notice The multiplierPerBlock after hitting a specified utilization point\n */\n uint256 public jumpMultiplierPerBlock;\n\n /**\n * @notice The utilization point at which the jump multiplier is applied\n */\n uint256 public kink;\n\n /**\n * @notice Initialise an interest rate model\n */\n\n constructor(InterestRateModelParams memory params) {\n blocksPerYear = params.blocksPerYear;\n baseRatePerBlock = params.baseRatePerYear.div(blocksPerYear);\n multiplierPerBlock = params.multiplierPerYear.div(blocksPerYear);\n jumpMultiplierPerBlock = params.jumpMultiplierPerYear.div(blocksPerYear);\n kink = params.kink;\n\n emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink);\n }\n\n /**\n * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`\n * @param cash The amount of cash in the market\n * @param borrows The amount of borrows in the market\n * @param reserves The amount of reserves in the market (currently unused)\n * @return The utilization rate as a mantissa between [0, 1e18]\n */\n function utilizationRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves\n ) public pure returns (uint256) {\n // Utilization rate is 0 when there are no borrows\n if (borrows == 0) {\n return 0;\n }\n\n return borrows.mul(1e18).div(cash.add(borrows).sub(reserves));\n }\n\n function _setIrmParameters(InterestRateModelParams memory params) public onlyOwner {\n blocksPerYear = params.blocksPerYear;\n baseRatePerBlock = params.baseRatePerYear.div(blocksPerYear);\n multiplierPerBlock = params.multiplierPerYear.div(blocksPerYear);\n jumpMultiplierPerBlock = params.jumpMultiplierPerYear.div(blocksPerYear);\n kink = params.kink;\n emit NewInterestParams(baseRatePerBlock, multiplierPerBlock, jumpMultiplierPerBlock, kink);\n }\n\n /**\n * @notice Calculates the current borrow rate per block, with the error code expected by the market\n * @param cash The amount of cash in the market\n * @param borrows The amount of borrows in the market\n * @param reserves The amount of reserves in the market\n * @return The borrow rate percentage per block as a mantissa (scaled by 1e18)\n */\n function getBorrowRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves\n ) public view override returns (uint256) {\n uint256 util = utilizationRate(cash, borrows, reserves);\n\n if (util <= kink) {\n return util.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock);\n } else {\n uint256 normalRate = kink.mul(multiplierPerBlock).div(1e18).add(baseRatePerBlock);\n uint256 excessUtil = util.sub(kink);\n return excessUtil.mul(jumpMultiplierPerBlock).div(1e18).add(normalRate);\n }\n }\n\n /**\n * @notice Calculates the current supply rate per block\n * @param cash The amount of cash in the market\n * @param borrows The amount of borrows in the market\n * @param reserves The amount of reserves in the market\n * @param reserveFactorMantissa The current reserve factor for the market\n * @return The supply rate percentage per block as a mantissa (scaled by 1e18)\n */\n function getSupplyRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves,\n uint256 reserveFactorMantissa\n ) public view virtual override returns (uint256) {\n uint256 oneMinusReserveFactor = uint256(1e18).sub(reserveFactorMantissa);\n uint256 borrowRate = getBorrowRate(cash, borrows, reserves);\n uint256 rateToPool = borrowRate.mul(oneMinusReserveFactor).div(1e18);\n return utilizationRate(cash, borrows, reserves).mul(rateToPool).div(1e18);\n }\n}\n" + }, + "contracts/src/ionic/irms/PrudentiaInterestRateModel.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { InterestRateModel } from \"../../compound/InterestRateModel.sol\";\n\nimport { IRateComputer } from \"adrastia-periphery/rates/IRateComputer.sol\";\n\nimport { Math } from \"@openzeppelin/contracts/utils/math/Math.sol\";\n\n/**\n * @title Adrastia Prudentia Interest Rate Model\n * @author TRILEZ SOFTWARE INC.\n */\ncontract PrudentiaInterestRateModel is InterestRateModel {\n using Math for uint256;\n\n /**\n * @notice The address of the underlying token for which the interest rate model calculates rates.\n */\n address public immutable underlyingToken;\n\n /**\n * @notice The address of the Adrastia Prudentia interest rate controller.\n */\n IRateComputer public immutable rateController;\n\n /**\n * @notice The approximate number of blocks per year that is assumed by the interest rate model.\n */\n uint256 public immutable blocksPerYear;\n\n /**\n * @notice Construct a new interest rate model that reads from an Adrastia Prudentia interest rate controller.\n *\n * @param blocksPerYear_ The approximate number of blocks per year that is assumed by the interest rate model.\n * @param underlyingToken_ The address of the underlying token for which the interest rate model calculates rates.\n * @param rateController_ The address of the Adrastia Prudentia interest rate controller.\n */\n constructor(\n uint256 blocksPerYear_,\n address underlyingToken_,\n IRateComputer rateController_\n ) {\n if (underlyingToken_ == address(0)) {\n revert(\"PrudentiaInterestRateModel: underlyingToken is the zero address\");\n }\n if (address(rateController_) == address(0)) {\n revert(\"PrudentiaInterestRateModel: rateController is the zero address\");\n }\n\n blocksPerYear = blocksPerYear_;\n underlyingToken = underlyingToken_;\n rateController = rateController_;\n }\n\n /**\n * @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`.\n *\n * @param cash The amount of cash in the market.\n * @param borrows The amount of borrows in the market.\n * @param reserves The amount of reserves in the market.\n *\n * @return The utilization rate as a mantissa between [0, 1e18].\n */\n function utilizationRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves\n ) public pure returns (uint256) {\n uint256 total = cash + borrows - reserves;\n if (total == 0) {\n // Utilization rate is zero when nothing is available (prevents division by zero)\n return 0;\n }\n\n return (borrows * 1e18) / total;\n }\n\n /**\n * @notice Calculates the current borrow rate per block by reading the current rate from the Adrastia Prudentia\n * interest rate controller.\n *\n * @param cash Not used.\n * @param borrows Not used.\n * @param reserves Not used.\n *\n * @return The borrow rate percentage per block as a mantissa (scaled by 1e18).\n */\n function getBorrowRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves\n ) public view override returns (uint256) {\n // Silence unused variable warnings\n cash;\n borrows;\n reserves;\n\n uint256 annualRate = rateController.computeRate(underlyingToken);\n\n return annualRate.ceilDiv(blocksPerYear); // Convert the annual rate to a per-block rate, rounding up\n }\n\n /**\n * @notice Calculates the current supply rate per block.\n *\n * @param cash The amount of cash in the market.\n * @param borrows The amount of borrows in the market.\n * @param reserves The amount of reserves in the market.\n * @param reserveFactorMantissa The current reserve factor for the market.\n *\n * @return The supply rate percentage per block as a mantissa (scaled by 1e18).\n */\n function getSupplyRate(\n uint256 cash,\n uint256 borrows,\n uint256 reserves,\n uint256 reserveFactorMantissa\n ) public view virtual override returns (uint256) {\n uint256 oneMinusReserveFactor = 1e18 - reserveFactorMantissa;\n uint256 borrowRate = getBorrowRate(cash, borrows, reserves);\n uint256 rateToPool = (borrowRate * oneMinusReserveFactor) / 1e18;\n\n return (utilizationRate(cash, borrows, reserves) * rateToPool) / 1e18;\n }\n}\n" + }, + "contracts/src/ionic/levered/ILeveredPositionFactory.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IRedemptionStrategy } from \"../../liquidators/IRedemptionStrategy.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { LeveredPosition } from \"./LeveredPosition.sol\";\nimport { IFeeDistributor } from \"../../compound/IFeeDistributor.sol\";\nimport { ILiquidatorsRegistry } from \"../../liquidators/registry/ILiquidatorsRegistry.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ninterface ILeveredPositionFactoryStorage {\n function feeDistributor() external view returns (IFeeDistributor);\n\n function liquidatorsRegistry() external view returns (ILiquidatorsRegistry);\n\n function blocksPerYear() external view returns (uint256);\n\n function owner() external view returns (address);\n}\n\ninterface ILeveredPositionFactoryBase {\n function _setLiquidatorsRegistry(ILiquidatorsRegistry _liquidatorsRegistry) external;\n\n function _setPairWhitelisted(ICErc20 _collateralMarket, ICErc20 _stableMarket, bool _whitelisted) external;\n}\n\ninterface ILeveredPositionFactoryFirstExtension {\n function getRedemptionStrategies(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external view returns (IRedemptionStrategy[] memory strategies, bytes[] memory strategiesData);\n\n function getMinBorrowNative() external view returns (uint256);\n\n function removeClosedPosition(address closedPosition) external returns (bool removed);\n\n function closeAndRemoveUserPosition(LeveredPosition position) external returns (bool);\n\n function getPositionsByAccount(address account) external view returns (address[] memory, bool[] memory);\n\n function getAccountsWithOpenPositions() external view returns (address[] memory);\n\n function getWhitelistedCollateralMarkets() external view returns (address[] memory);\n\n function getBorrowableMarketsByCollateral(ICErc20 _collateralMarket) external view returns (address[] memory);\n\n function getPositionsExtension(bytes4 msgSig) external view returns (address);\n\n function _setPositionsExtension(bytes4 msgSig, address extension) external;\n}\n\ninterface ILeveredPositionFactorySecondExtension {\n function createPosition(ICErc20 _collateralMarket, ICErc20 _stableMarket) external returns (LeveredPosition);\n\n function createAndFundPosition(\n ICErc20 _collateralMarket,\n ICErc20 _stableMarket,\n IERC20Upgradeable _fundingAsset,\n uint256 _fundingAmount\n ) external returns (LeveredPosition);\n\n function createAndFundPositionAtRatio(\n ICErc20 _collateralMarket,\n ICErc20 _stableMarket,\n IERC20Upgradeable _fundingAsset,\n uint256 _fundingAmount,\n uint256 _leverageRatio\n ) external returns (LeveredPosition);\n}\n\ninterface ILeveredPositionFactoryExtension is\n ILeveredPositionFactoryFirstExtension,\n ILeveredPositionFactorySecondExtension\n{}\n\ninterface ILeveredPositionFactory is\n ILeveredPositionFactoryStorage,\n ILeveredPositionFactoryBase,\n ILeveredPositionFactoryExtension\n{}\n" + }, + "contracts/src/ionic/levered/LeveredPosition.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport { IonicComptroller } from \"../../compound/ComptrollerInterface.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { BasePriceOracle } from \"../../oracles/BasePriceOracle.sol\";\nimport { IFundsConversionStrategy } from \"../../liquidators/IFundsConversionStrategy.sol\";\nimport { IRedemptionStrategy } from \"../../liquidators/IRedemptionStrategy.sol\";\nimport { ILeveredPositionFactory } from \"./ILeveredPositionFactory.sol\";\nimport { IFlashLoanReceiver } from \"../IFlashLoanReceiver.sol\";\nimport { IonicFlywheel } from \"../../ionic/strategies/flywheel/IonicFlywheel.sol\";\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\nimport { LeveredPositionStorage } from \"./LeveredPositionStorage.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ninterface IFlywheelLensRouter_LP {\n function claimAllRewardTokens(address user) external returns (address[] memory, uint256[] memory);\n}\n\ncontract LeveredPosition is LeveredPositionStorage, IFlashLoanReceiver {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n error OnlyWhenClosed();\n error NotPositionOwner();\n error OnlyFactoryOwner();\n error AssetNotRescuable();\n error RepayFlashLoanFailed(address asset, uint256 currentBalance, uint256 repayAmount);\n\n error ConvertFundsFailed();\n error ExitFailed(uint256 errorCode);\n error RedeemFailed(uint256 errorCode);\n error SupplyCollateralFailed(uint256 errorCode);\n error BorrowStableFailed(uint256 errorCode);\n error RepayBorrowFailed(uint256 errorCode);\n error RedeemCollateralFailed(uint256 errorCode);\n error ExtNotFound(bytes4 _functionSelector);\n\n constructor(\n address _positionOwner,\n ICErc20 _collateralMarket,\n ICErc20 _stableMarket\n ) LeveredPositionStorage(_positionOwner) {\n IonicComptroller collateralPool = _collateralMarket.comptroller();\n IonicComptroller stablePool = _stableMarket.comptroller();\n require(collateralPool == stablePool, \"markets pools differ\");\n pool = collateralPool;\n\n collateralMarket = _collateralMarket;\n collateralAsset = IERC20Upgradeable(_collateralMarket.underlying());\n stableMarket = _stableMarket;\n stableAsset = IERC20Upgradeable(_stableMarket.underlying());\n\n factory = ILeveredPositionFactory(msg.sender);\n }\n\n /*----------------------------------------------------------------\n Mutable Functions\n ----------------------------------------------------------------*/\n\n function fundPosition(IERC20Upgradeable fundingAsset, uint256 amount) public {\n fundingAsset.safeTransferFrom(msg.sender, address(this), amount);\n _supplyCollateral(fundingAsset);\n\n if (!pool.checkMembership(address(this), collateralMarket)) {\n address[] memory cTokens = new address[](1);\n cTokens[0] = address(collateralMarket);\n pool.enterMarkets(cTokens);\n }\n }\n\n function closePosition() public returns (uint256) {\n return closePosition(msg.sender);\n }\n\n function closePosition(address withdrawTo) public returns (uint256 withdrawAmount) {\n if (msg.sender != positionOwner && msg.sender != address(factory)) revert NotPositionOwner();\n\n _leverDown(1e18);\n\n // calling accrue and exit allows to redeem the full underlying balance\n collateralMarket.accrueInterest();\n uint256 errorCode = pool.exitMarket(address(collateralMarket));\n if (errorCode != 0) revert ExitFailed(errorCode);\n\n // redeem all cTokens should leave no dust\n errorCode = collateralMarket.redeem(collateralMarket.balanceOf(address(this)));\n if (errorCode != 0) revert RedeemFailed(errorCode);\n\n if (stableAsset.balanceOf(address(this)) > 0) {\n // convert all overborrowed leftovers/profits to the collateral asset\n convertAllTo(stableAsset, collateralAsset);\n }\n\n // withdraw the redeemed collateral\n withdrawAmount = collateralAsset.balanceOf(address(this));\n collateralAsset.safeTransfer(withdrawTo, withdrawAmount);\n }\n\n function adjustLeverageRatio(uint256 targetRatioMantissa) public returns (uint256) {\n if (msg.sender != positionOwner && msg.sender != address(factory)) revert NotPositionOwner();\n\n // anything under 1x means removing the leverage\n if (targetRatioMantissa <= 1e18) _leverDown(1e18);\n\n if (getCurrentLeverageRatio() < targetRatioMantissa) _leverUp(targetRatioMantissa);\n else _leverDown(targetRatioMantissa);\n\n // return the de facto achieved ratio\n return getCurrentLeverageRatio();\n }\n\n function receiveFlashLoan(address assetAddress, uint256 borrowedAmount, bytes calldata data) external override {\n if (msg.sender == address(collateralMarket)) {\n // increasing the leverage ratio\n uint256 stableBorrowAmount = abi.decode(data, (uint256));\n _leverUpPostFL(stableBorrowAmount);\n uint256 positionCollateralBalance = collateralAsset.balanceOf(address(this));\n if (positionCollateralBalance < borrowedAmount)\n revert RepayFlashLoanFailed(address(collateralAsset), positionCollateralBalance, borrowedAmount);\n } else if (msg.sender == address(stableMarket)) {\n // decreasing the leverage ratio\n uint256 amountToRedeem = abi.decode(data, (uint256));\n _leverDownPostFL(borrowedAmount, amountToRedeem);\n uint256 positionStableBalance = stableAsset.balanceOf(address(this));\n if (positionStableBalance < borrowedAmount)\n revert RepayFlashLoanFailed(address(stableAsset), positionStableBalance, borrowedAmount);\n } else {\n revert(\"!fl not from either markets\");\n }\n\n // repay FL\n IERC20Upgradeable(assetAddress).approve(msg.sender, borrowedAmount);\n }\n\n function withdrawStableLeftovers(address withdrawTo) public returns (uint256) {\n if (msg.sender != positionOwner) revert NotPositionOwner();\n if (!isPositionClosed()) revert OnlyWhenClosed();\n\n uint256 stableLeftovers = stableAsset.balanceOf(address(this));\n stableAsset.safeTransfer(withdrawTo, stableLeftovers);\n return stableLeftovers;\n }\n\n function claimRewards() public {\n claimRewards(msg.sender);\n }\n\n function claimRewards(address withdrawTo) public {\n if (msg.sender != positionOwner && msg.sender != address(factory)) revert NotPositionOwner();\n\n address[] memory flywheels = pool.getRewardsDistributors();\n\n for (uint256 i = 0; i < flywheels.length; i++) {\n IonicFlywheel fw = IonicFlywheel(flywheels[i]);\n fw.accrue(ERC20(address(collateralMarket)), address(this));\n fw.accrue(ERC20(address(stableMarket)), address(this));\n fw.claimRewards(address(this));\n ERC20 rewardToken = fw.rewardToken();\n uint256 rewardsAccrued = rewardToken.balanceOf(address(this));\n if (rewardsAccrued > 0) {\n rewardToken.transfer(withdrawTo, rewardsAccrued);\n }\n }\n }\n\n function rescueTokens(IERC20Upgradeable asset) external {\n if (msg.sender != factory.owner()) revert OnlyFactoryOwner();\n if (asset == stableAsset || asset == collateralAsset) revert AssetNotRescuable();\n\n asset.transfer(positionOwner, asset.balanceOf(address(this)));\n }\n\n function claimRewardsFromRouter(address _flr) external returns (address[] memory, uint256[] memory) {\n IFlywheelLensRouter_LP flr = IFlywheelLensRouter_LP(_flr);\n (address[] memory rewardTokens, uint256[] memory rewards) = flr.claimAllRewardTokens(address(this));\n for (uint256 i = 0; i < rewardTokens.length; i++) {\n IERC20Upgradeable(rewardTokens[i]).safeTransfer(positionOwner, rewards[i]);\n }\n return (rewardTokens, rewards);\n }\n\n fallback() external {\n address extension = factory.getPositionsExtension(msg.sig);\n if (extension == address(0)) revert ExtNotFound(msg.sig);\n // Execute external function from extension using delegatecall and return any value.\n assembly {\n // copy function selector and any arguments\n calldatacopy(0, 0, calldatasize())\n // execute function call using the extension\n let result := delegatecall(gas(), extension, 0, calldatasize(), 0, 0)\n // get any return value\n returndatacopy(0, 0, returndatasize())\n // return any return value or error back to the caller\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /*----------------------------------------------------------------\n View Functions\n ----------------------------------------------------------------*/\n\n /// @notice this is a lens fn, it is not intended to be used on-chain\n function getAccruedRewards()\n external\n returns (\n /*view*/\n ERC20[] memory rewardTokens,\n uint256[] memory amounts\n )\n {\n address[] memory flywheels = pool.getRewardsDistributors();\n\n rewardTokens = new ERC20[](flywheels.length);\n amounts = new uint256[](flywheels.length);\n\n for (uint256 i = 0; i < flywheels.length; i++) {\n IonicFlywheel fw = IonicFlywheel(flywheels[i]);\n fw.accrue(ERC20(address(collateralMarket)), address(this));\n fw.accrue(ERC20(address(stableMarket)), address(this));\n rewardTokens[i] = fw.rewardToken();\n amounts[i] = fw.rewardsAccrued(address(this));\n }\n }\n\n function getCurrentLeverageRatio() public view returns (uint256) {\n uint256 positionSupplyAmount = collateralMarket.balanceOfUnderlying(address(this));\n if (positionSupplyAmount == 0) return 0;\n\n BasePriceOracle oracle = pool.oracle();\n\n uint256 collateralAssetPrice = oracle.getUnderlyingPrice(collateralMarket);\n uint256 positionValue = (collateralAssetPrice * positionSupplyAmount) / 1e18;\n\n uint256 debtValue = 0;\n uint256 debtAmount = stableMarket.borrowBalanceCurrent(address(this));\n if (debtAmount > 0) {\n uint256 borrowedAssetPrice = oracle.getUnderlyingPrice(stableMarket);\n debtValue = (borrowedAssetPrice * debtAmount) / 1e18;\n }\n\n // TODO check if positionValue > debtValue\n // s / ( s - b )\n return (positionValue * 1e18) / (positionValue - debtValue);\n }\n\n function getMinLeverageRatio() public view returns (uint256) {\n uint256 positionSupplyAmount = collateralMarket.balanceOfUnderlying(address(this));\n if (positionSupplyAmount == 0) return 0;\n\n BasePriceOracle oracle = pool.oracle();\n uint256 borrowedAssetPrice = oracle.getUnderlyingPrice(stableMarket);\n uint256 minStableBorrowAmount = (factory.getMinBorrowNative() * 1e18) / borrowedAssetPrice;\n return _getLeverageRatioAfterBorrow(minStableBorrowAmount, positionSupplyAmount, 0);\n }\n\n function getMaxLeverageRatio() public view returns (uint256) {\n uint256 positionSupplyAmount = collateralMarket.balanceOfUnderlying(address(this));\n if (positionSupplyAmount == 0) return 0;\n\n uint256 maxBorrow = pool.getMaxRedeemOrBorrow(address(this), stableMarket, true);\n uint256 positionBorrowAmount = stableMarket.borrowBalanceCurrent(address(this));\n return _getLeverageRatioAfterBorrow(maxBorrow, positionSupplyAmount, positionBorrowAmount);\n }\n\n function _getLeverageRatioAfterBorrow(\n uint256 newBorrowsAmount,\n uint256 positionSupplyAmount,\n uint256 positionBorrowAmount\n ) internal view returns (uint256 r) {\n BasePriceOracle oracle = pool.oracle();\n uint256 stableAssetPrice = oracle.getUnderlyingPrice(stableMarket);\n uint256 collateralAssetPrice = oracle.getUnderlyingPrice(collateralMarket);\n\n uint256 currentBorrowsValue = (positionBorrowAmount * stableAssetPrice) / 1e18;\n uint256 newBorrowsValue = (newBorrowsAmount * stableAssetPrice) / 1e18;\n uint256 positionValue = (positionSupplyAmount * collateralAssetPrice) / 1e18;\n\n // accounting for swaps slippage\n uint256 assumedSlippage = factory.liquidatorsRegistry().getSlippage(stableAsset, collateralAsset);\n {\n // add 10 bps just to not go under the min borrow value\n assumedSlippage += 10;\n }\n uint256 topUpCollateralValue = (newBorrowsValue * 10000) / (10000 + assumedSlippage);\n\n int256 s = int256(positionValue);\n int256 b = int256(currentBorrowsValue);\n int256 x = int256(topUpCollateralValue);\n\n r = uint256(((s + x) * 1e18) / (s + x - b - int256(newBorrowsValue)));\n }\n\n function isPositionClosed() public view returns (bool) {\n return collateralMarket.balanceOfUnderlying(address(this)) == 0;\n }\n\n function getEquityAmount() external view returns (uint256 equityAmount) {\n BasePriceOracle oracle = pool.oracle();\n uint256 borrowedAssetPrice = oracle.getUnderlyingPrice(stableMarket);\n uint256 collateralAssetPrice = oracle.getUnderlyingPrice(collateralMarket);\n uint256 positionSupplyAmount = collateralMarket.balanceOfUnderlying(address(this));\n uint256 positionValue = (collateralAssetPrice * positionSupplyAmount) / 1e18;\n\n uint256 debtAmount = stableMarket.borrowBalanceCurrent(address(this));\n uint256 debtValue = (borrowedAssetPrice * debtAmount) / 1e18;\n\n uint256 equityValue = positionValue - debtValue;\n equityAmount = (equityValue * 1e18) / collateralAssetPrice;\n }\n\n function getSupplyAmountDelta(uint256 targetRatio) public view returns (uint256, uint256) {\n BasePriceOracle oracle = pool.oracle();\n uint256 stableAssetPrice = oracle.getUnderlyingPrice(stableMarket);\n uint256 collateralAssetPrice = oracle.getUnderlyingPrice(collateralMarket);\n\n uint256 currentRatio = getCurrentLeverageRatio();\n bool up = targetRatio > currentRatio;\n return _getSupplyAmountDelta(up, targetRatio, collateralAssetPrice, stableAssetPrice);\n }\n\n function _getSupplyAmountDelta(\n bool up,\n uint256 targetRatio,\n uint256 collateralAssetPrice,\n uint256 borrowedAssetPrice\n ) internal view returns (uint256 supplyDelta, uint256 borrowsDelta) {\n uint256 positionSupplyAmount = collateralMarket.balanceOfUnderlying(address(this));\n uint256 debtAmount = stableMarket.borrowBalanceCurrent(address(this));\n uint256 assumedSlippage;\n if (up) assumedSlippage = factory.liquidatorsRegistry().getSlippage(stableAsset, collateralAsset);\n else assumedSlippage = factory.liquidatorsRegistry().getSlippage(collateralAsset, stableAsset);\n uint256 slippageFactor = (1e18 * (10000 + assumedSlippage)) / 10000;\n\n uint256 supplyValueDeltaAbs;\n {\n // s = supply value before\n // b = borrow value before\n // r = target ratio after\n // c = borrow value coefficient to account for the slippage\n int256 s = int256((collateralAssetPrice * positionSupplyAmount) / 1e18);\n int256 b = int256((borrowedAssetPrice * debtAmount) / 1e18);\n int256 r = int256(targetRatio);\n int256 r1 = r - 1e18;\n int256 c = int256(slippageFactor);\n\n // some math magic here\n // https://www.wolframalpha.com/input?i2d=true&i=r%3D%5C%2840%29Divide%5B%5C%2840%29s%2Bx%5C%2841%29%2C%5C%2840%29s%2Bx-b-c*x%5C%2841%29%5D+%5C%2841%29+solve+for+x\n\n // x = supplyValueDelta\n int256 supplyValueDelta = (((r1 * s) - (b * r)) * 1e18) / ((c * r) - (1e18 * r1));\n supplyValueDeltaAbs = uint256((supplyValueDelta < 0) ? -supplyValueDelta : supplyValueDelta);\n }\n\n supplyDelta = (supplyValueDeltaAbs * 1e18) / collateralAssetPrice;\n borrowsDelta = (supplyValueDeltaAbs * 1e18) / borrowedAssetPrice;\n\n if (up) {\n // stables to borrow = c * x\n borrowsDelta = (borrowsDelta * slippageFactor) / 1e18;\n } else {\n // amount to redeem = c * x\n supplyDelta = (supplyDelta * slippageFactor) / 1e18;\n }\n }\n\n /*----------------------------------------------------------------\n Internal Functions\n ----------------------------------------------------------------*/\n\n function _supplyCollateral(IERC20Upgradeable fundingAsset) internal returns (uint256 amountToSupply) {\n // in case the funding is with a different asset\n if (address(collateralAsset) != address(fundingAsset)) {\n // swap for collateral asset\n convertAllTo(fundingAsset, collateralAsset);\n }\n\n // supply the collateral\n amountToSupply = collateralAsset.balanceOf(address(this));\n collateralAsset.approve(address(collateralMarket), amountToSupply);\n uint256 errorCode = collateralMarket.mint(amountToSupply);\n if (errorCode != 0) revert SupplyCollateralFailed(errorCode);\n }\n\n // @dev flash loan the needed amount, then borrow stables and swap them for the amount needed to repay the FL\n function _leverUp(uint256 targetRatio) internal {\n BasePriceOracle oracle = pool.oracle();\n uint256 stableAssetPrice = oracle.getUnderlyingPrice(stableMarket);\n uint256 collateralAssetPrice = oracle.getUnderlyingPrice(collateralMarket);\n\n (uint256 flashLoanCollateralAmount, uint256 stableToBorrow) = _getSupplyAmountDelta(\n true,\n targetRatio,\n collateralAssetPrice,\n stableAssetPrice\n );\n\n collateralMarket.flash(flashLoanCollateralAmount, abi.encode(stableToBorrow));\n // the execution will first receive a callback to receiveFlashLoan()\n // then it continues from here\n\n // all stables are swapped for collateral to repay the FL\n uint256 collateralLeftovers = collateralAsset.balanceOf(address(this));\n if (collateralLeftovers > 0) {\n collateralAsset.approve(address(collateralMarket), collateralLeftovers);\n collateralMarket.mint(collateralLeftovers);\n }\n }\n\n // @dev supply the flash loaned collateral and then borrow stables with it\n function _leverUpPostFL(uint256 stableToBorrow) internal {\n // supply the flash loaned collateral\n _supplyCollateral(collateralAsset);\n\n // borrow stables that will be swapped to repay the FL\n uint256 errorCode = stableMarket.borrow(stableToBorrow);\n if (errorCode != 0) revert BorrowStableFailed(errorCode);\n\n // swap for the FL asset\n convertAllTo(stableAsset, collateralAsset);\n }\n\n // @dev redeems the supplied collateral by first repaying the debt with which it was levered\n function _leverDown(uint256 targetRatio) internal {\n uint256 amountToRedeem;\n uint256 borrowsToRepay;\n\n BasePriceOracle oracle = pool.oracle();\n uint256 stableAssetPrice = oracle.getUnderlyingPrice(stableMarket);\n uint256 collateralAssetPrice = oracle.getUnderlyingPrice(collateralMarket);\n\n if (targetRatio <= 1e18) {\n // if max levering down, then derive the amount to redeem from the debt to be repaid\n borrowsToRepay = stableMarket.borrowBalanceCurrent(address(this));\n uint256 borrowsToRepayValueScaled = borrowsToRepay * stableAssetPrice;\n // accounting for swaps slippage\n uint256 assumedSlippage = factory.liquidatorsRegistry().getSlippage(collateralAsset, stableAsset);\n uint256 amountToRedeemValueScaled = (borrowsToRepayValueScaled * (10000 + assumedSlippage)) / 10000;\n amountToRedeem = amountToRedeemValueScaled / collateralAssetPrice;\n // round up when dividing in order to redeem enough (otherwise calcs could be exploited)\n if (amountToRedeemValueScaled % collateralAssetPrice > 0) amountToRedeem += 1;\n } else {\n // else derive the debt to be repaid from the amount to redeem\n (amountToRedeem, borrowsToRepay) = _getSupplyAmountDelta(\n false,\n targetRatio,\n collateralAssetPrice,\n stableAssetPrice\n );\n // the slippage is already accounted for in _getSupplyAmountDelta\n }\n\n if (borrowsToRepay > 0) {\n ICErc20(address(stableMarket)).flash(borrowsToRepay, abi.encode(amountToRedeem));\n // the execution will first receive a callback to receiveFlashLoan()\n // then it continues from here\n }\n\n // all the redeemed collateral is swapped for stables to repay the FL\n uint256 stableLeftovers = stableAsset.balanceOf(address(this));\n if (stableLeftovers > 0) {\n uint256 borrowBalance = stableMarket.borrowBalanceCurrent(address(this));\n if (borrowBalance > 0) {\n // whatever is smaller\n uint256 amountToRepay = borrowBalance > stableLeftovers ? stableLeftovers : borrowBalance;\n stableAsset.approve(address(stableMarket), amountToRepay);\n stableMarket.repayBorrow(amountToRepay);\n }\n }\n }\n\n function _leverDownPostFL(uint256 _flashLoanedCollateral, uint256 _amountToRedeem) internal {\n // repay the borrows\n uint256 borrowBalance = stableMarket.borrowBalanceCurrent(address(this));\n uint256 repayAmount = _flashLoanedCollateral < borrowBalance ? _flashLoanedCollateral : borrowBalance;\n stableAsset.approve(address(stableMarket), repayAmount);\n uint256 errorCode = stableMarket.repayBorrow(repayAmount);\n if (errorCode != 0) revert RepayBorrowFailed(errorCode);\n\n // redeem the corresponding amount needed to repay the FL\n errorCode = collateralMarket.redeemUnderlying(_amountToRedeem);\n if (errorCode != 0) revert RedeemCollateralFailed(errorCode);\n\n // swap for the FL asset\n convertAllTo(collateralAsset, stableAsset);\n }\n\n function convertAllTo(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) private returns (uint256 outputAmount) {\n uint256 inputAmount = inputToken.balanceOf(address(this));\n (IRedemptionStrategy[] memory redemptionStrategies, bytes[] memory strategiesData) = factory\n .getRedemptionStrategies(inputToken, outputToken);\n\n if (redemptionStrategies.length == 0) revert ConvertFundsFailed();\n\n for (uint256 i = 0; i < redemptionStrategies.length; i++) {\n IRedemptionStrategy redemptionStrategy = redemptionStrategies[i];\n bytes memory strategyData = strategiesData[i];\n (outputToken, outputAmount) = convertCustomFunds(inputToken, inputAmount, redemptionStrategy, strategyData);\n inputAmount = outputAmount;\n inputToken = outputToken;\n }\n }\n\n function convertCustomFunds(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n IRedemptionStrategy strategy,\n bytes memory strategyData\n ) private returns (IERC20Upgradeable, uint256) {\n bytes memory returndata = _functionDelegateCall(\n address(strategy),\n abi.encodeWithSelector(strategy.redeem.selector, inputToken, inputAmount, strategyData)\n );\n return abi.decode(returndata, (IERC20Upgradeable, uint256));\n }\n\n function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {\n require(AddressUpgradeable.isContract(target), \"Address: delegate call to non-contract\");\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, \"Address: low-level delegate call failed\");\n }\n\n function _verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) private pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n if (returndata.length > 0) {\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" + }, + "contracts/src/ionic/levered/LeveredPositionFactory.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport { IFeeDistributor } from \"../../compound/IFeeDistributor.sol\";\nimport { ILiquidatorsRegistry } from \"../../liquidators/registry/ILiquidatorsRegistry.sol\";\nimport { IonicComptroller } from \"../../compound/ComptrollerInterface.sol\";\nimport { BasePriceOracle } from \"../../oracles/BasePriceOracle.sol\";\nimport { IRedemptionStrategy } from \"../../liquidators/IRedemptionStrategy.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { LeveredPositionFactoryStorage } from \"./LeveredPositionFactoryStorage.sol\";\nimport { DiamondBase, DiamondExtension, LibDiamond } from \"../../ionic/DiamondExtension.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract LeveredPositionFactory is LeveredPositionFactoryStorage, DiamondBase {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n /*----------------------------------------------------------------\n Constructor\n ----------------------------------------------------------------*/\n\n constructor(IFeeDistributor _feeDistributor, ILiquidatorsRegistry _registry, uint256 _blocksPerYear) {\n feeDistributor = _feeDistributor;\n liquidatorsRegistry = _registry;\n blocksPerYear = _blocksPerYear;\n }\n\n /*----------------------------------------------------------------\n Admin Functions\n ----------------------------------------------------------------*/\n\n function _setPairWhitelisted(ICErc20 _collateralMarket, ICErc20 _stableMarket, bool _whitelisted) external onlyOwner {\n require(_collateralMarket.comptroller() == _stableMarket.comptroller(), \"markets not of the same pool\");\n\n if (_whitelisted) {\n collateralMarkets.add(address(_collateralMarket));\n borrowableMarketsByCollateral[_collateralMarket].add(address(_stableMarket));\n } else {\n borrowableMarketsByCollateral[_collateralMarket].remove(address(_stableMarket));\n if (borrowableMarketsByCollateral[_collateralMarket].length() == 0)\n collateralMarkets.remove(address(_collateralMarket));\n }\n }\n\n function _setLiquidatorsRegistry(ILiquidatorsRegistry _liquidatorsRegistry) external onlyOwner {\n liquidatorsRegistry = _liquidatorsRegistry;\n }\n\n function _registerExtension(\n DiamondExtension extensionToAdd,\n DiamondExtension extensionToReplace\n ) public override onlyOwner {\n LibDiamond.registerExtension(extensionToAdd, extensionToReplace);\n }\n}\n" + }, + "contracts/src/ionic/levered/LeveredPositionFactoryFirstExtension.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport \"../../ionic/DiamondExtension.sol\";\nimport { LeveredPositionFactoryStorage } from \"./LeveredPositionFactoryStorage.sol\";\nimport { ILeveredPositionFactoryFirstExtension } from \"./ILeveredPositionFactory.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { IRedemptionStrategy } from \"../../liquidators/IRedemptionStrategy.sol\";\nimport { LeveredPosition } from \"./LeveredPosition.sol\";\nimport { IComptroller, IPriceOracle } from \"../../external/compound/IComptroller.sol\";\nimport { ILiquidatorsRegistry } from \"../../liquidators/registry/ILiquidatorsRegistry.sol\";\nimport { AuthoritiesRegistry } from \"../AuthoritiesRegistry.sol\";\nimport { PoolRolesAuthority } from \"../PoolRolesAuthority.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract LeveredPositionFactoryFirstExtension is\n LeveredPositionFactoryStorage,\n DiamondExtension,\n ILeveredPositionFactoryFirstExtension\n{\n using SafeERC20Upgradeable for IERC20Upgradeable;\n using EnumerableSet for EnumerableSet.AddressSet;\n\n error PairNotWhitelisted();\n error NoSuchPosition();\n error PositionNotClosed();\n\n function _getExtensionFunctions() external pure override returns (bytes4[] memory) {\n uint8 fnsCount = 10;\n bytes4[] memory functionSelectors = new bytes4[](fnsCount);\n functionSelectors[--fnsCount] = this.removeClosedPosition.selector;\n functionSelectors[--fnsCount] = this.closeAndRemoveUserPosition.selector;\n functionSelectors[--fnsCount] = this.getMinBorrowNative.selector;\n functionSelectors[--fnsCount] = this.getRedemptionStrategies.selector;\n functionSelectors[--fnsCount] = this.getBorrowableMarketsByCollateral.selector;\n functionSelectors[--fnsCount] = this.getWhitelistedCollateralMarkets.selector;\n functionSelectors[--fnsCount] = this.getAccountsWithOpenPositions.selector;\n functionSelectors[--fnsCount] = this.getPositionsByAccount.selector;\n functionSelectors[--fnsCount] = this.getPositionsExtension.selector;\n functionSelectors[--fnsCount] = this._setPositionsExtension.selector;\n\n require(fnsCount == 0, \"use the correct array length\");\n return functionSelectors;\n }\n\n /*----------------------------------------------------------------\n Mutable Functions\n ----------------------------------------------------------------*/\n\n // @return true if removed, otherwise false\n function removeClosedPosition(address closedPosition) external returns (bool) {\n return _removeClosedPosition(closedPosition, msg.sender);\n }\n\n function closeAndRemoveUserPosition(LeveredPosition position) external onlyOwner returns (bool) {\n address positionOwner = position.positionOwner();\n position.closePosition(positionOwner);\n return _removeClosedPosition(address(position), positionOwner);\n }\n\n function _removeClosedPosition(address closedPosition, address positionOwner) internal returns (bool removed) {\n EnumerableSet.AddressSet storage userPositions = positionsByAccount[positionOwner];\n if (!userPositions.contains(closedPosition)) revert NoSuchPosition();\n if (!LeveredPosition(closedPosition).isPositionClosed()) revert PositionNotClosed();\n\n removed = userPositions.remove(closedPosition);\n if (userPositions.length() == 0) accountsWithOpenPositions.remove(positionOwner);\n }\n\n function _setPositionsExtension(bytes4 msgSig, address extension) external onlyOwner {\n _positionsExtensions[msgSig] = extension;\n }\n\n /*----------------------------------------------------------------\n View Functions\n ----------------------------------------------------------------*/\n\n function getMinBorrowNative() external view returns (uint256) {\n return feeDistributor.minBorrowEth();\n }\n\n function getRedemptionStrategies(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external view returns (IRedemptionStrategy[] memory strategies, bytes[] memory strategiesData) {\n return liquidatorsRegistry.getRedemptionStrategies(inputToken, outputToken);\n }\n\n function getPositionsByAccount(\n address account\n ) external view returns (address[] memory positions, bool[] memory closed) {\n positions = positionsByAccount[account].values();\n closed = new bool[](positions.length);\n for (uint256 i = 0; i < positions.length; i++) {\n closed[i] = LeveredPosition(positions[i]).isPositionClosed();\n }\n }\n\n function getAccountsWithOpenPositions() external view returns (address[] memory) {\n return accountsWithOpenPositions.values();\n }\n\n function getWhitelistedCollateralMarkets() external view returns (address[] memory) {\n return collateralMarkets.values();\n }\n\n function getBorrowableMarketsByCollateral(ICErc20 _collateralMarket) external view returns (address[] memory) {\n return borrowableMarketsByCollateral[_collateralMarket].values();\n }\n\n function getPositionsExtension(bytes4 msgSig) external view returns (address) {\n return _positionsExtensions[msgSig];\n }\n}\n" + }, + "contracts/src/ionic/levered/LeveredPositionFactorySecondExtension.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport \"../../ionic/DiamondExtension.sol\";\nimport { LeveredPositionFactoryStorage } from \"./LeveredPositionFactoryStorage.sol\";\nimport { ILeveredPositionFactorySecondExtension } from \"./ILeveredPositionFactory.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { IRedemptionStrategy } from \"../../liquidators/IRedemptionStrategy.sol\";\nimport { LeveredPosition } from \"./LeveredPosition.sol\";\nimport { IComptroller, IPriceOracle } from \"../../external/compound/IComptroller.sol\";\nimport { ILiquidatorsRegistry } from \"../../liquidators/registry/ILiquidatorsRegistry.sol\";\nimport { AuthoritiesRegistry } from \"../AuthoritiesRegistry.sol\";\nimport { PoolRolesAuthority } from \"../PoolRolesAuthority.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\ncontract LeveredPositionFactorySecondExtension is\n LeveredPositionFactoryStorage,\n DiamondExtension,\n ILeveredPositionFactorySecondExtension\n{\n using SafeERC20Upgradeable for IERC20Upgradeable;\n using EnumerableSet for EnumerableSet.AddressSet;\n\n error PairNotWhitelisted();\n\n function _getExtensionFunctions() external pure override returns (bytes4[] memory) {\n uint8 fnsCount = 3;\n bytes4[] memory functionSelectors = new bytes4[](fnsCount);\n functionSelectors[--fnsCount] = this.createPosition.selector;\n functionSelectors[--fnsCount] = this.createAndFundPosition.selector;\n functionSelectors[--fnsCount] = this.createAndFundPositionAtRatio.selector;\n require(fnsCount == 0, \"use the correct array length\");\n return functionSelectors;\n }\n\n /*----------------------------------------------------------------\n Mutable Functions\n ----------------------------------------------------------------*/\n\n function createPosition(ICErc20 _collateralMarket, ICErc20 _stableMarket) public returns (LeveredPosition) {\n if (!borrowableMarketsByCollateral[_collateralMarket].contains(address(_stableMarket))) revert PairNotWhitelisted();\n\n LeveredPosition position = new LeveredPosition(msg.sender, _collateralMarket, _stableMarket);\n\n accountsWithOpenPositions.add(msg.sender);\n positionsByAccount[msg.sender].add(address(position));\n\n AuthoritiesRegistry authoritiesRegistry = feeDistributor.authoritiesRegistry();\n address poolAddress = address(_collateralMarket.comptroller());\n PoolRolesAuthority poolAuth = authoritiesRegistry.poolsAuthorities(poolAddress);\n if (address(poolAuth) != address(0)) {\n authoritiesRegistry.setUserRole(poolAddress, address(position), poolAuth.LEVERED_POSITION_ROLE(), true);\n }\n\n return position;\n }\n\n function createAndFundPosition(\n ICErc20 _collateralMarket,\n ICErc20 _stableMarket,\n IERC20Upgradeable _fundingAsset,\n uint256 _fundingAmount\n ) public returns (LeveredPosition) {\n LeveredPosition position = createPosition(_collateralMarket, _stableMarket);\n _fundingAsset.safeTransferFrom(msg.sender, address(this), _fundingAmount);\n _fundingAsset.approve(address(position), _fundingAmount);\n position.fundPosition(_fundingAsset, _fundingAmount);\n return position;\n }\n\n function createAndFundPositionAtRatio(\n ICErc20 _collateralMarket,\n ICErc20 _stableMarket,\n IERC20Upgradeable _fundingAsset,\n uint256 _fundingAmount,\n uint256 _leverageRatio\n ) external returns (LeveredPosition) {\n LeveredPosition position = createAndFundPosition(_collateralMarket, _stableMarket, _fundingAsset, _fundingAmount);\n if (_leverageRatio > 1e18) {\n position.adjustLeverageRatio(_leverageRatio);\n }\n return position;\n }\n}\n" + }, + "contracts/src/ionic/levered/LeveredPositionFactoryStorage.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport { SafeOwnable } from \"../../ionic/SafeOwnable.sol\";\nimport { IFeeDistributor } from \"../../compound/IFeeDistributor.sol\";\nimport { ILiquidatorsRegistry } from \"../../liquidators/registry/ILiquidatorsRegistry.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\nabstract contract LeveredPositionFactoryStorage is SafeOwnable {\n EnumerableSet.AddressSet internal accountsWithOpenPositions;\n mapping(address => EnumerableSet.AddressSet) internal positionsByAccount;\n EnumerableSet.AddressSet internal collateralMarkets;\n mapping(ICErc20 => EnumerableSet.AddressSet) internal borrowableMarketsByCollateral;\n\n mapping(IERC20Upgradeable => mapping(IERC20Upgradeable => uint256)) private __unused;\n\n IFeeDistributor public feeDistributor;\n ILiquidatorsRegistry public liquidatorsRegistry;\n uint256 public blocksPerYear;\n\n mapping(bytes4 => address) internal _positionsExtensions;\n}\n" + }, + "contracts/src/ionic/levered/LeveredPositionsLens.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport { ILeveredPositionFactory } from \"./ILeveredPositionFactory.sol\";\nimport { LeveredPosition } from \"./LeveredPosition.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { IonicComptroller } from \"../../compound/ComptrollerInterface.sol\";\nimport { BasePriceOracle } from \"../../oracles/BasePriceOracle.sol\";\nimport { Initializable } from \"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\ncontract LeveredPositionsLens is Initializable {\n ILeveredPositionFactory public factory;\n\n function initialize(ILeveredPositionFactory _factory) external initializer {\n factory = _factory;\n }\n\n function reinitialize(ILeveredPositionFactory _factory) external reinitializer(2) {\n factory = _factory;\n }\n\n /// @notice this is a lens fn, it is not intended to be used on-chain\n /// @dev returns lists of the market addresses, names and symbols of the underlying assets of those collateral markets that are whitelisted\n function getCollateralMarkets()\n external\n view\n returns (\n address[] memory markets,\n IonicComptroller[] memory poolOfMarket,\n address[] memory underlyings,\n uint256[] memory underlyingPrices,\n string[] memory names,\n string[] memory symbols,\n uint8[] memory decimals,\n uint256[] memory totalUnderlyingSupplied,\n uint256[] memory ratesPerBlock\n )\n {\n markets = factory.getWhitelistedCollateralMarkets();\n poolOfMarket = new IonicComptroller[](markets.length);\n underlyings = new address[](markets.length);\n underlyingPrices = new uint256[](markets.length);\n names = new string[](markets.length);\n symbols = new string[](markets.length);\n totalUnderlyingSupplied = new uint256[](markets.length);\n decimals = new uint8[](markets.length);\n ratesPerBlock = new uint256[](markets.length);\n for (uint256 i = 0; i < markets.length; i++) {\n ICErc20 market = ICErc20(markets[i]);\n poolOfMarket[i] = market.comptroller();\n underlyingPrices[i] = BasePriceOracle(poolOfMarket[i].oracle()).getUnderlyingPrice(market);\n underlyings[i] = market.underlying();\n ERC20Upgradeable underlying = ERC20Upgradeable(underlyings[i]);\n names[i] = underlying.name();\n symbols[i] = underlying.symbol();\n decimals[i] = underlying.decimals();\n totalUnderlyingSupplied[i] = market.getTotalUnderlyingSupplied();\n ratesPerBlock[i] = market.supplyRatePerBlock();\n }\n }\n\n /// @notice this is a lens fn, it is not intended to be used on-chain\n /// @dev returns the Rate for the chosen borrowable at the specified leverage ratio and supply amount\n function getBorrowRateAtRatio(\n ICErc20 _collateralMarket,\n ICErc20 _stableMarket,\n uint256 _equityAmount,\n uint256 _targetLeverageRatio\n ) external view returns (uint256) {\n IonicComptroller pool = IonicComptroller(_stableMarket.comptroller());\n BasePriceOracle oracle = pool.oracle();\n uint256 stableAssetPrice = oracle.getUnderlyingPrice(_stableMarket);\n uint256 collateralAssetPrice = oracle.getUnderlyingPrice(_collateralMarket);\n\n uint256 borrowAmount = ((_targetLeverageRatio - 1e18) * _equityAmount * collateralAssetPrice) /\n (stableAssetPrice * 1e18);\n return _stableMarket.borrowRatePerBlockAfterBorrow(borrowAmount) * factory.blocksPerYear();\n }\n\n /// @notice this is a lens fn, it is not intended to be used on-chain\n /// @dev returns lists of the market addresses, names, symbols and the current Rate for each Borrowable asset\n function getBorrowableMarketsAndRates(\n ICErc20 _collateralMarket\n )\n external\n view\n returns (\n address[] memory markets,\n address[] memory underlyings,\n uint256[] memory underlyingsPrices,\n string[] memory names,\n string[] memory symbols,\n uint256[] memory rates,\n uint8[] memory decimals\n )\n {\n markets = factory.getBorrowableMarketsByCollateral(_collateralMarket);\n underlyings = new address[](markets.length);\n names = new string[](markets.length);\n symbols = new string[](markets.length);\n rates = new uint256[](markets.length);\n decimals = new uint8[](markets.length);\n underlyingsPrices = new uint256[](markets.length);\n for (uint256 i = 0; i < markets.length; i++) {\n ICErc20 market = ICErc20(markets[i]);\n address underlyingAddress = market.underlying();\n underlyings[i] = underlyingAddress;\n ERC20Upgradeable underlying = ERC20Upgradeable(underlyingAddress);\n names[i] = underlying.name();\n symbols[i] = underlying.symbol();\n rates[i] = market.borrowRatePerBlock();\n decimals[i] = underlying.decimals();\n underlyingsPrices[i] = market.comptroller().oracle().getUnderlyingPrice(market);\n }\n }\n\n /// @notice this is a lens fn, it is not intended to be used on-chain\n function getNetAPY(\n uint256 _supplyAPY,\n uint256 _supplyAmount,\n ICErc20 _collateralMarket,\n ICErc20 _stableMarket,\n uint256 _targetLeverageRatio\n ) public view returns (int256 netAPY) {\n if (_supplyAmount == 0 || _targetLeverageRatio <= 1e18) return 0;\n\n IonicComptroller pool = IonicComptroller(_collateralMarket.comptroller());\n BasePriceOracle oracle = pool.oracle();\n // TODO the calcs can be implemented without using collateralAssetPrice\n uint256 collateralAssetPrice = oracle.getUnderlyingPrice(_collateralMarket);\n\n // total collateral = base collateral + levered collateral\n uint256 totalCollateral = (_supplyAmount * _targetLeverageRatio) / 1e18;\n uint256 yieldFromTotalSupplyScaled = _supplyAPY * totalCollateral;\n int256 yieldValueScaled = int256((yieldFromTotalSupplyScaled * collateralAssetPrice) / 1e18);\n\n uint256 borrowedValueScaled = (totalCollateral - _supplyAmount) * collateralAssetPrice;\n uint256 _borrowRate = _stableMarket.borrowRatePerBlock() * factory.blocksPerYear();\n int256 borrowInterestValueScaled = int256((_borrowRate * borrowedValueScaled) / 1e18);\n\n int256 netValueDiffScaled = yieldValueScaled - borrowInterestValueScaled;\n\n netAPY = ((netValueDiffScaled / int256(collateralAssetPrice)) * 1e18) / int256(_supplyAmount);\n }\n\n function getPositionsInfo(\n LeveredPosition[] calldata positions,\n uint256[] calldata supplyApys\n ) external view returns (PositionInfo[] memory infos) {\n infos = new PositionInfo[](positions.length);\n for (uint256 i = 0; i < positions.length; i++) {\n infos[i] = getPositionInfo(positions[i], supplyApys[i]);\n }\n }\n\n function getLeverageRatioAfterFunding(LeveredPosition pos, uint256 newFunding) public view returns (uint256) {\n uint256 equityAmount = pos.getEquityAmount();\n if (equityAmount == 0 && newFunding == 0) return 0;\n\n uint256 suppliedCollateralCurrent = pos.collateralMarket().balanceOfUnderlying(address(pos));\n return ((suppliedCollateralCurrent + newFunding) * 1e18) / (equityAmount + newFunding);\n }\n\n function getNetApyForPositionAfterFunding(\n LeveredPosition pos,\n uint256 supplyAPY,\n uint256 newFunding\n ) public view returns (int256) {\n return\n getNetAPY(\n supplyAPY,\n pos.getEquityAmount() + newFunding,\n pos.collateralMarket(),\n pos.stableMarket(),\n getLeverageRatioAfterFunding(pos, newFunding)\n );\n }\n\n function getNetApyForPosition(LeveredPosition pos, uint256 supplyAPY) public view returns (int256) {\n return getNetApyForPositionAfterFunding(pos, supplyAPY, 0);\n }\n\n struct PositionInfo {\n uint256 collateralAssetPrice;\n uint256 borrowedAssetPrice;\n uint256 positionSupplyAmount;\n uint256 positionValue;\n uint256 debtAmount;\n uint256 debtValue;\n uint256 equityAmount;\n uint256 equityValue;\n int256 currentApy;\n uint256 debtRatio;\n uint256 liquidationThreshold;\n uint256 safetyBuffer;\n }\n\n function getPositionInfo(LeveredPosition pos, uint256 supplyApy) public view returns (PositionInfo memory info) {\n ICErc20 collateralMarket = pos.collateralMarket();\n IonicComptroller pool = pos.pool();\n info.collateralAssetPrice = pool.oracle().getUnderlyingPrice(collateralMarket);\n {\n info.positionSupplyAmount = collateralMarket.balanceOfUnderlying(address(pos));\n info.positionValue = (info.collateralAssetPrice * info.positionSupplyAmount) / 1e18;\n info.currentApy = getNetApyForPosition(pos, supplyApy);\n }\n\n {\n ICErc20 stableMarket = pos.stableMarket();\n info.borrowedAssetPrice = pool.oracle().getUnderlyingPrice(stableMarket);\n info.debtAmount = stableMarket.borrowBalanceCurrent(address(pos));\n info.debtValue = (info.borrowedAssetPrice * info.debtAmount) / 1e18;\n info.equityValue = info.positionValue - info.debtValue;\n info.debtRatio = info.positionValue == 0 ? 0 : (info.debtValue * 1e18) / info.positionValue;\n info.equityAmount = (info.equityValue * 1e18) / info.collateralAssetPrice;\n }\n\n {\n (, uint256 collateralFactor) = pool.markets(address(collateralMarket));\n info.liquidationThreshold = collateralFactor;\n info.safetyBuffer = collateralFactor - info.debtRatio;\n }\n }\n}\n" + }, + "contracts/src/ionic/levered/LeveredPositionStorage.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport { ILeveredPositionFactory } from \"./ILeveredPositionFactory.sol\";\nimport { IonicComptroller } from \"../../compound/ComptrollerInterface.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ncontract LeveredPositionStorage {\n address public immutable positionOwner;\n ILeveredPositionFactory public factory;\n\n ICErc20 public collateralMarket;\n ICErc20 public stableMarket;\n IonicComptroller public pool;\n\n IERC20Upgradeable public collateralAsset;\n IERC20Upgradeable public stableAsset;\n\n constructor(address _positionOwner) {\n positionOwner = _positionOwner;\n }\n}\n" + }, + "contracts/src/ionic/PoolRolesAuthority.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IonicComptroller, ComptrollerInterface } from \"../compound/ComptrollerInterface.sol\";\nimport { ICErc20, CTokenSecondExtensionInterface, CTokenFirstExtensionInterface } from \"../compound/CTokenInterfaces.sol\";\n\nimport { RolesAuthority, Authority } from \"solmate/auth/authorities/RolesAuthority.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\n\ncontract PoolRolesAuthority is RolesAuthority, Initializable {\n constructor() RolesAuthority(address(0), Authority(address(0))) {\n _disableInitializers();\n }\n\n function initialize(address _owner) public initializer {\n owner = _owner;\n authority = this;\n }\n\n // up to 256 roles\n uint8 public constant REGISTRY_ROLE = 0;\n uint8 public constant SUPPLIER_ROLE = 1;\n uint8 public constant BORROWER_ROLE = 2;\n uint8 public constant LIQUIDATOR_ROLE = 3;\n uint8 public constant LEVERED_POSITION_ROLE = 4;\n\n function configureRegistryCapabilities() external requiresAuth {\n setRoleCapability(REGISTRY_ROLE, address(this), PoolRolesAuthority.configureRegistryCapabilities.selector, true);\n setRoleCapability(\n REGISTRY_ROLE,\n address(this),\n PoolRolesAuthority.configurePoolSupplierCapabilities.selector,\n true\n );\n setRoleCapability(\n REGISTRY_ROLE,\n address(this),\n PoolRolesAuthority.configurePoolBorrowerCapabilities.selector,\n true\n );\n setRoleCapability(\n REGISTRY_ROLE,\n address(this),\n PoolRolesAuthority.configureClosedPoolLiquidatorCapabilities.selector,\n true\n );\n setRoleCapability(\n REGISTRY_ROLE,\n address(this),\n PoolRolesAuthority.configureOpenPoolLiquidatorCapabilities.selector,\n true\n );\n setRoleCapability(\n REGISTRY_ROLE,\n address(this),\n PoolRolesAuthority.configureLeveredPositionCapabilities.selector,\n true\n );\n setRoleCapability(REGISTRY_ROLE, address(this), RolesAuthority.setUserRole.selector, true);\n }\n\n function openPoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {\n _setPublicPoolSupplierCapabilities(pool, true);\n }\n\n function closePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {\n _setPublicPoolSupplierCapabilities(pool, false);\n }\n\n function _setPublicPoolSupplierCapabilities(IonicComptroller pool, bool setPublic) internal {\n setPublicCapability(address(pool), pool.enterMarkets.selector, setPublic);\n setPublicCapability(address(pool), pool.exitMarket.selector, setPublic);\n ICErc20[] memory allMarkets = pool.getAllMarkets();\n for (uint256 i = 0; i < allMarkets.length; i++) {\n bytes4[] memory selectors = getSupplierMarketSelectors();\n for (uint256 j = 0; j < selectors.length; j++) {\n setPublicCapability(address(allMarkets[i]), selectors[j], setPublic);\n }\n }\n }\n\n function configurePoolSupplierCapabilities(IonicComptroller pool) external requiresAuth {\n _configurePoolSupplierCapabilities(pool, SUPPLIER_ROLE);\n }\n\n function getSupplierMarketSelectors() internal pure returns (bytes4[] memory selectors) {\n uint8 fnsCount = 6;\n selectors = new bytes4[](fnsCount);\n selectors[--fnsCount] = CTokenSecondExtensionInterface.mint.selector;\n selectors[--fnsCount] = CTokenSecondExtensionInterface.redeem.selector;\n selectors[--fnsCount] = CTokenSecondExtensionInterface.redeemUnderlying.selector;\n selectors[--fnsCount] = CTokenFirstExtensionInterface.transfer.selector;\n selectors[--fnsCount] = CTokenFirstExtensionInterface.transferFrom.selector;\n selectors[--fnsCount] = CTokenFirstExtensionInterface.approve.selector;\n\n require(fnsCount == 0, \"use the correct array length\");\n return selectors;\n }\n\n function _configurePoolSupplierCapabilities(IonicComptroller pool, uint8 role) internal {\n setRoleCapability(role, address(pool), pool.enterMarkets.selector, true);\n setRoleCapability(role, address(pool), pool.exitMarket.selector, true);\n ICErc20[] memory allMarkets = pool.getAllMarkets();\n for (uint256 i = 0; i < allMarkets.length; i++) {\n bytes4[] memory selectors = getSupplierMarketSelectors();\n for (uint256 j = 0; j < selectors.length; j++) {\n setRoleCapability(role, address(allMarkets[i]), selectors[j], true);\n }\n }\n }\n\n function openPoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {\n _setPublicPoolBorrowerCapabilities(pool, true);\n }\n\n function closePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {\n _setPublicPoolBorrowerCapabilities(pool, false);\n }\n\n function _setPublicPoolBorrowerCapabilities(IonicComptroller pool, bool setPublic) internal {\n ICErc20[] memory allMarkets = pool.getAllMarkets();\n for (uint256 i = 0; i < allMarkets.length; i++) {\n setPublicCapability(address(allMarkets[i]), allMarkets[i].borrow.selector, setPublic);\n setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrow.selector, setPublic);\n setPublicCapability(address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, setPublic);\n setPublicCapability(address(allMarkets[i]), allMarkets[i].flash.selector, setPublic);\n }\n }\n\n function configurePoolBorrowerCapabilities(IonicComptroller pool) external requiresAuth {\n // borrowers have the SUPPLIER_ROLE capabilities by default\n _configurePoolSupplierCapabilities(pool, BORROWER_ROLE);\n ICErc20[] memory allMarkets = pool.getAllMarkets();\n for (uint256 i = 0; i < allMarkets.length; i++) {\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true);\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true);\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrowBehalf.selector, true);\n setRoleCapability(BORROWER_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true);\n }\n }\n\n function configureClosedPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth {\n ICErc20[] memory allMarkets = pool.getAllMarkets();\n for (uint256 i = 0; i < allMarkets.length; i++) {\n setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, false);\n setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true);\n setRoleCapability(LIQUIDATOR_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true);\n }\n }\n\n function configureOpenPoolLiquidatorCapabilities(IonicComptroller pool) external requiresAuth {\n ICErc20[] memory allMarkets = pool.getAllMarkets();\n for (uint256 i = 0; i < allMarkets.length; i++) {\n setPublicCapability(address(allMarkets[i]), allMarkets[i].liquidateBorrow.selector, true);\n // TODO this leaves redeeming open for everyone\n setPublicCapability(address(allMarkets[i]), allMarkets[i].redeem.selector, true);\n }\n }\n\n function configureLeveredPositionCapabilities(IonicComptroller pool) external requiresAuth {\n setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.enterMarkets.selector, true);\n setRoleCapability(LEVERED_POSITION_ROLE, address(pool), pool.exitMarket.selector, true);\n ICErc20[] memory allMarkets = pool.getAllMarkets();\n for (uint256 i = 0; i < allMarkets.length; i++) {\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].mint.selector, true);\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeem.selector, true);\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].redeemUnderlying.selector, true);\n\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].borrow.selector, true);\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].repayBorrow.selector, true);\n setRoleCapability(LEVERED_POSITION_ROLE, address(allMarkets[i]), allMarkets[i].flash.selector, true);\n }\n }\n}\n" + }, + "contracts/src/ionic/RewardsClaimer.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity ^0.8.10;\n\nimport { Initializable } from \"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { ERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\ncontract RewardsClaimer is Initializable {\n using SafeERC20Upgradeable for ERC20Upgradeable;\n\n event RewardDestinationUpdate(address indexed newDestination);\n\n event ClaimRewards(address indexed rewardToken, uint256 amount);\n\n /// @notice the address to send rewards\n address public rewardDestination;\n\n /// @notice the array of reward tokens to send to\n ERC20Upgradeable[] public rewardTokens;\n\n function __RewardsClaimer_init(\n address _rewardDestination,\n ERC20Upgradeable[] memory _rewardTokens\n ) internal onlyInitializing {\n rewardDestination = _rewardDestination;\n rewardTokens = _rewardTokens;\n }\n\n /// @notice claim all token rewards\n function claimRewards() public {\n beforeClaim(); // hook to accrue/pull in rewards, if needed\n\n uint256 len = rewardTokens.length;\n // send all tokens to destination\n for (uint256 i = 0; i < len; i++) {\n ERC20Upgradeable token = rewardTokens[i];\n uint256 amount = token.balanceOf(address(this));\n\n token.safeTransfer(rewardDestination, amount);\n\n emit ClaimRewards(address(token), amount);\n }\n }\n\n /// @notice set the address of the new reward destination\n /// @param newDestination the new reward destination\n function setRewardDestination(address newDestination) external {\n require(msg.sender == rewardDestination, \"UNAUTHORIZED\");\n rewardDestination = newDestination;\n emit RewardDestinationUpdate(newDestination);\n }\n\n /// @notice hook to accrue/pull in rewards, if needed\n function beforeClaim() internal virtual {}\n}\n" + }, + "contracts/src/ionic/SafeOwnable.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin/contracts/access/Ownable2Step.sol\";\n\nabstract contract SafeOwnable is Ownable2Step {\n function renounceOwnership() public override onlyOwner {\n revert(\"renounce ownership not allowed\");\n }\n}\n" + }, + "contracts/src/ionic/SafeOwnableUpgradeable.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol\";\n\n/**\n * @dev Ownable extension that requires a two-step process of setting the pending owner and the owner accepting it.\n * @notice Existing OwnableUpgradeable contracts cannot be upgraded due to the extra storage variable\n * that will shift the other.\n */\nabstract contract SafeOwnableUpgradeable is OwnableUpgradeable {\n /**\n * @notice Pending owner of this contract\n */\n address public pendingOwner;\n\n function __SafeOwnable_init(address owner_) internal onlyInitializing {\n __Ownable_init();\n _transferOwnership(owner_);\n }\n\n struct AddressSlot {\n address value;\n }\n\n modifier onlyOwnerOrAdmin() {\n bool isOwner = owner() == _msgSender();\n if (!isOwner) {\n address admin = _getProxyAdmin();\n bool isAdmin = admin == _msgSender();\n require(isAdmin, \"Ownable: caller is neither the owner nor the admin\");\n }\n _;\n }\n\n /**\n * @notice Emitted when pendingOwner is changed\n */\n event NewPendingOwner(address oldPendingOwner, address newPendingOwner);\n\n /**\n * @notice Emitted when pendingOwner is accepted, which means owner is updated\n */\n event NewOwner(address oldOwner, address newOwner);\n\n /**\n * @notice Begins transfer of owner rights. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\n * @dev Owner function to begin change of owner. The newPendingOwner must call `_acceptOwner` to finalize the transfer.\n * @param newPendingOwner New pending owner.\n */\n function _setPendingOwner(address newPendingOwner) public onlyOwner {\n // Save current value, if any, for inclusion in log\n address oldPendingOwner = pendingOwner;\n\n // Store pendingOwner with value newPendingOwner\n pendingOwner = newPendingOwner;\n\n // Emit NewPendingOwner(oldPendingOwner, newPendingOwner)\n emit NewPendingOwner(oldPendingOwner, newPendingOwner);\n }\n\n /**\n * @notice Accepts transfer of owner rights. msg.sender must be pendingOwner\n * @dev Owner function for pending owner to accept role and update owner\n */\n function _acceptOwner() public {\n // Check caller is pendingOwner and pendingOwner ≠ address(0)\n require(msg.sender == pendingOwner, \"not the pending owner\");\n\n // Save current values for inclusion in log\n address oldOwner = owner();\n address oldPendingOwner = pendingOwner;\n\n // Store owner with value pendingOwner\n _transferOwnership(pendingOwner);\n\n // Clear the pending value\n pendingOwner = address(0);\n\n emit NewOwner(oldOwner, pendingOwner);\n emit NewPendingOwner(oldPendingOwner, pendingOwner);\n }\n\n function renounceOwnership() public override onlyOwner {\n // do not remove this overriding fn\n revert(\"not used anymore\");\n }\n\n function transferOwnership(address newOwner) public override onlyOwner {\n emit NewPendingOwner(pendingOwner, newOwner);\n pendingOwner = newOwner;\n }\n\n function _getProxyAdmin() internal view returns (address admin) {\n bytes32 _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n AddressSlot storage adminSlot;\n assembly {\n adminSlot.slot := _ADMIN_SLOT\n }\n admin = adminSlot.value;\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/FlywheelCore.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport {ERC20} from \"solmate/tokens/ERC20.sol\";\nimport {Auth, Authority} from \"solmate/auth/Auth.sol\";\nimport {SafeTransferLib} from \"solmate/utils/SafeTransferLib.sol\";\nimport {SafeCastLib} from \"solmate/utils/SafeCastLib.sol\";\n\nimport {IFlywheelRewards} from \"./rewards/IFlywheelRewards.sol\";\nimport {IFlywheelBooster} from \"./IFlywheelBooster.sol\";\n\n/**\n @title Flywheel Core Incentives Manager\n @notice Flywheel is a general framework for managing token incentives.\n It takes reward streams to various *strategies* such as staking LP tokens and divides them among *users* of those strategies.\n\n The Core contract maintains three important pieces of state:\n * the rewards index which determines how many rewards are owed per token per strategy. User indexes track how far behind the strategy they are to lazily calculate all catch-up rewards.\n * the accrued (unclaimed) rewards per user.\n * references to the booster and rewards module described below.\n\n Core does not manage any tokens directly. The rewards module maintains token balances, and approves core to pull transfer them to users when they claim.\n\n SECURITY NOTE: For maximum accuracy and to avoid exploits, rewards accrual should be notified atomically through the accrue hook. \n Accrue should be called any time tokens are transferred, minted, or burned.\n */\ncontract FlywheelCore is Auth {\n using SafeTransferLib for ERC20;\n using SafeCastLib for uint256;\n\n /// @notice The token to reward\n ERC20 public immutable rewardToken;\n\n /// @notice append-only list of strategies added\n ERC20[] public allStrategies;\n\n /// @notice the rewards contract for managing streams\n IFlywheelRewards public flywheelRewards;\n\n /// @notice optional booster module for calculating virtual balances on strategies\n IFlywheelBooster public flywheelBooster;\n\n constructor(\n ERC20 _rewardToken,\n IFlywheelRewards _flywheelRewards,\n IFlywheelBooster _flywheelBooster,\n address _owner,\n Authority _authority\n ) Auth(_owner, _authority) {\n rewardToken = _rewardToken;\n flywheelRewards = _flywheelRewards;\n flywheelBooster = _flywheelBooster;\n }\n\n /*///////////////////////////////////////////////////////////////\n ACCRUE/CLAIM LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /** \n @notice Emitted when a user's rewards accrue to a given strategy.\n @param strategy the updated rewards strategy\n @param user the user of the rewards\n @param rewardsDelta how many new rewards accrued to the user\n @param rewardsIndex the market index for rewards per token accrued\n */\n event AccrueRewards(ERC20 indexed strategy, address indexed user, uint256 rewardsDelta, uint256 rewardsIndex);\n\n /** \n @notice Emitted when a user claims accrued rewards.\n @param user the user of the rewards\n @param amount the amount of rewards claimed\n */\n event ClaimRewards(address indexed user, uint256 amount);\n\n /// @notice The accrued but not yet transferred rewards for each user\n mapping(address => uint256) public rewardsAccrued;\n\n /** \n @notice accrue rewards for a single user on a strategy\n @param strategy the strategy to accrue a user's rewards on\n @param user the user to be accrued\n @return the cumulative amount of rewards accrued to user (including prior)\n */\n function accrue(ERC20 strategy, address user) public returns (uint256) {\n RewardsState memory state = strategyState[strategy];\n\n if (state.index == 0) return 0;\n\n state = accrueStrategy(strategy, state);\n return accrueUser(strategy, user, state);\n }\n\n /** \n @notice accrue rewards for a two users on a strategy\n @param strategy the strategy to accrue a user's rewards on\n @param user the first user to be accrued\n @param user the second user to be accrued\n @return the cumulative amount of rewards accrued to the first user (including prior)\n @return the cumulative amount of rewards accrued to the second user (including prior)\n */\n function accrue(\n ERC20 strategy,\n address user,\n address secondUser\n ) public returns (uint256, uint256) {\n RewardsState memory state = strategyState[strategy];\n\n if (state.index == 0) return (0, 0);\n\n state = accrueStrategy(strategy, state);\n return (accrueUser(strategy, user, state), accrueUser(strategy, secondUser, state));\n }\n\n /** \n @notice claim rewards for a given user\n @param user the user claiming rewards\n @dev this function is public, and all rewards transfer to the user\n */\n function claimRewards(address user) external {\n uint256 accrued = rewardsAccrued[user];\n\n if (accrued != 0) {\n rewardsAccrued[user] = 0;\n\n rewardToken.safeTransferFrom(address(flywheelRewards), user, accrued);\n\n emit ClaimRewards(user, accrued);\n }\n }\n\n /*///////////////////////////////////////////////////////////////\n ADMIN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n /** \n @notice Emitted when a new strategy is added to flywheel by the admin\n @param newStrategy the new added strategy\n */\n event AddStrategy(address indexed newStrategy);\n\n /// @notice initialize a new strategy\n function addStrategyForRewards(ERC20 strategy) external requiresAuth {\n _addStrategyForRewards(strategy);\n }\n\n function _addStrategyForRewards(ERC20 strategy) internal {\n require(strategyState[strategy].index == 0, \"strategy\");\n strategyState[strategy] = RewardsState({index: ONE, lastUpdatedTimestamp: block.timestamp.safeCastTo32()});\n\n allStrategies.push(strategy);\n emit AddStrategy(address(strategy));\n }\n\n function getAllStrategies() external view returns (ERC20[] memory) {\n return allStrategies;\n }\n\n /** \n @notice Emitted when the rewards module changes\n @param newFlywheelRewards the new rewards module\n */\n event FlywheelRewardsUpdate(address indexed newFlywheelRewards);\n\n /// @notice swap out the flywheel rewards contract\n function setFlywheelRewards(IFlywheelRewards newFlywheelRewards) external requiresAuth {\n uint256 oldRewardBalance = rewardToken.balanceOf(address(flywheelRewards));\n if (oldRewardBalance > 0) {\n rewardToken.safeTransferFrom(address(flywheelRewards), address(newFlywheelRewards), oldRewardBalance);\n }\n\n flywheelRewards = newFlywheelRewards;\n\n emit FlywheelRewardsUpdate(address(newFlywheelRewards));\n }\n\n /** \n @notice Emitted when the booster module changes\n @param newBooster the new booster module\n */\n event FlywheelBoosterUpdate(address indexed newBooster);\n\n /// @notice swap out the flywheel booster contract\n function setBooster(IFlywheelBooster newBooster) external requiresAuth {\n flywheelBooster = newBooster;\n\n emit FlywheelBoosterUpdate(address(newBooster));\n }\n\n /*///////////////////////////////////////////////////////////////\n INTERNAL ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n struct RewardsState {\n /// @notice The strategy's last updated index\n uint224 index;\n /// @notice The timestamp the index was last updated at\n uint32 lastUpdatedTimestamp;\n }\n\n /// @notice the fixed point factor of flywheel\n uint224 public constant ONE = 1e18;\n\n /// @notice The strategy index and last updated per strategy\n mapping(ERC20 => RewardsState) public strategyState;\n\n /// @notice user index per strategy\n mapping(ERC20 => mapping(address => uint224)) public userIndex;\n\n /// @notice accumulate global rewards on a strategy\n function accrueStrategy(ERC20 strategy, RewardsState memory state)\n private\n returns (RewardsState memory rewardsState)\n {\n // calculate accrued rewards through module\n uint256 strategyRewardsAccrued = flywheelRewards.getAccruedRewards(strategy, state.lastUpdatedTimestamp);\n\n rewardsState = state;\n if (strategyRewardsAccrued > 0) {\n // use the booster or token supply to calculate reward index denominator\n uint256 supplyTokens = address(flywheelBooster) != address(0)\n ? flywheelBooster.boostedTotalSupply(strategy)\n : strategy.totalSupply();\n\n uint224 deltaIndex;\n\n if (supplyTokens != 0) deltaIndex = ((strategyRewardsAccrued * ONE) / supplyTokens).safeCastTo224();\n\n // accumulate rewards per token onto the index, multiplied by fixed-point factor\n rewardsState = RewardsState({\n index: state.index + deltaIndex,\n lastUpdatedTimestamp: block.timestamp.safeCastTo32()\n });\n strategyState[strategy] = rewardsState;\n }\n }\n\n /// @notice accumulate rewards on a strategy for a specific user\n function accrueUser(\n ERC20 strategy,\n address user,\n RewardsState memory state\n ) private returns (uint256) {\n // load indices\n uint224 strategyIndex = state.index;\n uint224 supplierIndex = userIndex[strategy][user];\n\n // sync user index to global\n userIndex[strategy][user] = strategyIndex;\n\n // if user hasn't yet accrued rewards, grant them interest from the strategy beginning if they have a balance\n // zero balances will have no effect other than syncing to global index\n if (supplierIndex == 0) {\n supplierIndex = ONE;\n }\n\n uint224 deltaIndex = strategyIndex - supplierIndex;\n // use the booster or token balance to calculate reward balance multiplier\n uint256 supplierTokens = address(flywheelBooster) != address(0)\n ? flywheelBooster.boostedBalanceOf(strategy, user)\n : strategy.balanceOf(user);\n\n // accumulate rewards by multiplying user tokens by rewardsPerToken index and adding on unclaimed\n uint256 supplierDelta = (supplierTokens * deltaIndex) / ONE;\n uint256 supplierAccrued = rewardsAccrued[user] + supplierDelta;\n\n rewardsAccrued[user] = supplierAccrued;\n\n emit AccrueRewards(strategy, user, supplierDelta, strategyIndex);\n\n return supplierAccrued;\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/IFlywheelBooster.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport {ERC20} from \"solmate/tokens/ERC20.sol\";\n\n/**\n @title Balance Booster Module for Flywheel\n @notice Flywheel is a general framework for managing token incentives.\n It takes reward streams to various *strategies* such as staking LP tokens and divides them among *users* of those strategies.\n\n The Booster module is an optional module for virtually boosting or otherwise transforming user balances. \n If a booster is not configured, the strategies ERC-20 balanceOf/totalSupply will be used instead.\n \n Boosting logic can be associated with referrals, vote-escrow, or other strategies.\n\n SECURITY NOTE: similar to how Core needs to be notified any time the strategy user composition changes, the booster would need to be notified of any conditions which change the boosted balances atomically.\n This prevents gaming of the reward calculation function by using manipulated balances when accruing.\n*/\ninterface IFlywheelBooster {\n /**\n @notice calculate the boosted supply of a strategy.\n @param strategy the strategy to calculate boosted supply of\n @return the boosted supply\n */\n function boostedTotalSupply(ERC20 strategy) external view returns (uint256);\n\n /**\n @notice calculate the boosted balance of a user in a given strategy.\n @param strategy the strategy to calculate boosted balance of\n @param user the user to calculate boosted balance of\n @return the boosted balance\n */\n function boostedBalanceOf(ERC20 strategy, address user) external view returns (uint256);\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/IIonicFlywheel.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\n\ninterface IIonicFlywheel {\n function isRewardsDistributor() external returns (bool);\n\n function isFlywheel() external returns (bool);\n\n function flywheelPreSupplierAction(address market, address supplier) external;\n\n function flywheelPostSupplierAction(address market, address supplier) external;\n\n function flywheelPreBorrowerAction(address market, address borrower) external;\n\n function flywheelPostBorrowerAction(address market, address borrower) external;\n\n function flywheelPreTransferAction(address market, address src, address dst) external;\n\n function flywheelPostTransferAction(address market, address src, address dst) external;\n\n function compAccrued(address user) external view returns (uint256);\n\n function addMarketForRewards(ERC20 strategy) external;\n\n function marketState(ERC20 strategy) external view returns (uint224 index, uint32 lastUpdatedTimestamp);\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/IIonicFlywheelBorrowBooster.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { ICErc20 } from \"../../../compound/CTokenInterfaces.sol\";\n\n/**\n @title Balance Booster Module for Flywheel\n @notice Flywheel is a general framework for managing token incentives.\n It takes reward streams to various *strategies* such as staking LP tokens and divides them among *users* of those strategies.\n\n The Booster module is an optional module for virtually boosting or otherwise transforming user balances. \n If a booster is not configured, the strategies ERC-20 balanceOf/totalSupply will be used instead.\n \n Boosting logic can be associated with referrals, vote-escrow, or other strategies.\n\n SECURITY NOTE: similar to how Core needs to be notified any time the strategy user composition changes, the booster would need to be notified of any conditions which change the boosted balances atomically.\n This prevents gaming of the reward calculation function by using manipulated balances when accruing.\n*/\ninterface IIonicFlywheelBorrowBooster {\n /**\n @notice calculate the boosted supply of a strategy.\n @param strategy the strategy to calculate boosted supply of\n @return the boosted supply\n */\n function boostedTotalSupply(ICErc20 strategy) external view returns (uint256);\n\n /**\n @notice calculate the boosted balance of a user in a given strategy.\n @param strategy the strategy to calculate boosted balance of\n @param user the user to calculate boosted balance of\n @return the boosted balance\n */\n function boostedBalanceOf(ICErc20 strategy, address user) external view returns (uint256);\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/IonicFlywheel.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\nimport { IonicFlywheelCore } from \"./IonicFlywheelCore.sol\";\nimport \"./IIonicFlywheel.sol\";\n\ncontract IonicFlywheel is IonicFlywheelCore, IIonicFlywheel {\n bool public constant isRewardsDistributor = true;\n bool public constant isFlywheel = true;\n\n function flywheelPreSupplierAction(address market, address supplier) external {\n accrue(ERC20(market), supplier);\n }\n\n function flywheelPostSupplierAction(address market, address supplier) external {\n _updateBlacklistBalances(ERC20(market), supplier);\n }\n\n function flywheelPreBorrowerAction(address market, address borrower) external {}\n\n function flywheelPostBorrowerAction(address market, address borrower) external {}\n\n function flywheelPreTransferAction(address market, address src, address dst) external {\n accrue(ERC20(market), src, dst);\n }\n\n function flywheelPostTransferAction(address market, address src, address dst) external {\n _updateBlacklistBalances(ERC20(market), src);\n _updateBlacklistBalances(ERC20(market), dst);\n }\n\n function compAccrued(address user) external view returns (uint256) {\n return _rewardsAccrued[user];\n }\n\n function addMarketForRewards(ERC20 strategy) external onlyOwner {\n _addStrategyForRewards(strategy);\n }\n\n function marketState(ERC20 strategy) external view returns (uint224, uint32) {\n return (_strategyState[strategy].index, _strategyState[strategy].lastUpdatedTimestamp);\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/IonicFlywheelBorrow.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\nimport { IonicFlywheelCore } from \"./IonicFlywheelCore.sol\";\nimport \"./IIonicFlywheel.sol\";\n\ncontract IonicFlywheelBorrow is IonicFlywheelCore, IIonicFlywheel {\n bool public constant isRewardsDistributor = true;\n bool public constant isFlywheel = true;\n\n function flywheelPreSupplierAction(address market, address supplier) external {}\n\n function flywheelPostSupplierAction(address market, address supplier) external {}\n\n function flywheelPreBorrowerAction(address market, address borrower) external {\n accrue(ERC20(market), borrower);\n }\n\n function flywheelPostBorrowerAction(address market, address borrower) external {\n _updateBlacklistBalances(ERC20(market), borrower);\n }\n\n function flywheelPreTransferAction(address market, address src, address dst) external {}\n\n function flywheelPostTransferAction(address market, address src, address dst) external {}\n\n function compAccrued(address user) external view returns (uint256) {\n return _rewardsAccrued[user];\n }\n\n function addMarketForRewards(ERC20 strategy) external onlyOwner {\n _addStrategyForRewards(strategy);\n }\n\n function marketState(ERC20 strategy) external view returns (uint224, uint32) {\n return (_strategyState[strategy].index, _strategyState[strategy].lastUpdatedTimestamp);\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/IonicFlywheelBorrowBooster.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { ICErc20 } from \"../../../compound/CTokenInterfaces.sol\";\nimport \"./IIonicFlywheelBorrowBooster.sol\";\n\ncontract IonicFlywheelBorrowBooster is IIonicFlywheelBorrowBooster {\n string public constant BOOSTER_TYPE = \"FlywheelBorrowBooster\";\n\n /**\n @notice calculate the boosted supply of a strategy.\n @param strategy the strategy to calculate boosted supply of\n @return the boosted supply\n */\n function boostedTotalSupply(ICErc20 strategy) external view returns (uint256) {\n return strategy.totalBorrows();\n }\n\n /**\n @notice calculate the boosted balance of a user in a given strategy.\n @param strategy the strategy to calculate boosted balance of\n @param user the user to calculate boosted balance of\n @return the boosted balance\n */\n function boostedBalanceOf(ICErc20 strategy, address user) external view returns (uint256) {\n return strategy.borrowBalanceCurrent(user);\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/IonicFlywheelCore.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\nimport { SafeTransferLib } from \"solmate/utils/SafeTransferLib.sol\";\nimport { SafeCastLib } from \"solmate/utils/SafeCastLib.sol\";\n\nimport { IFlywheelRewards } from \"./rewards/IFlywheelRewards.sol\";\nimport { IFlywheelBooster } from \"./IFlywheelBooster.sol\";\nimport { IEmissionsManager } from \"../../../IEmissionsManager.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol\";\n\ncontract IonicFlywheelCore is Ownable2StepUpgradeable {\n using SafeTransferLib for ERC20;\n using SafeCastLib for uint256;\n\n /// @notice How much rewardsToken will be send to treasury\n uint256 public performanceFee;\n\n /// @notice Address that gets rewardsToken accrued by performanceFee\n address public feeRecipient;\n\n /// @notice The token to reward\n ERC20 public rewardToken;\n\n /// @notice append-only list of strategies added\n ERC20[] public allStrategies;\n\n /// @notice the rewards contract for managing streams\n IFlywheelRewards public flywheelRewards;\n\n /// @notice optional booster module for calculating virtual balances on strategies\n IFlywheelBooster public flywheelBooster;\n\n IEmissionsManager public emissionsManager;\n\n /// @notice The accrued but not yet transferred rewards for each user\n mapping(address => uint256) internal _rewardsAccrued;\n\n /// @notice The strategy index and last updated per strategy\n mapping(ERC20 => RewardsState) internal _strategyState;\n\n /// @notice user index per strategy\n mapping(ERC20 => mapping(address => uint224)) internal _userIndex;\n\n /// @notice user blacklisted supply per strategy\n mapping(ERC20 => mapping(address => uint256)) public userBlacklistedSupply;\n\n /// @notice blacklisted supply per strategy\n mapping(ERC20 => uint256) public blacklistedSupply;\n\n modifier onlyEmissionsManager() {\n require(address(emissionsManager) == msg.sender, \"!emissionsManager\");\n _;\n }\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n function initialize(\n ERC20 _rewardToken,\n IFlywheelRewards _flywheelRewards,\n IFlywheelBooster _flywheelBooster,\n address _owner\n ) public initializer {\n __Ownable2Step_init();\n\n rewardToken = _rewardToken;\n flywheelRewards = _flywheelRewards;\n flywheelBooster = _flywheelBooster;\n\n performanceFee = 10e16; // 10%\n feeRecipient = _owner;\n }\n\n /*----------------------------------------------------------------\n ACCRUE/CLAIM LOGIC\n ----------------------------------------------------------------*/\n\n /** \n @notice Emitted when a user's rewards accrue to a given strategy.\n @param strategy the updated rewards strategy\n @param user the user of the rewards\n @param rewardsDelta how many new rewards accrued to the user\n @param rewardsIndex the market index for rewards per token accrued\n */\n event AccrueRewards(ERC20 indexed strategy, address indexed user, uint256 rewardsDelta, uint256 rewardsIndex);\n\n /** \n @notice Emitted when a user claims accrued rewards.\n @param user the user of the rewards\n @param amount the amount of rewards claimed\n */\n event ClaimRewards(address indexed user, uint256 amount);\n\n /** \n @notice accrue rewards for a single user on a strategy\n @param strategy the strategy to accrue a user's rewards on\n @param user the user to be accrued\n @return the cumulative amount of rewards accrued to user (including prior)\n */\n function accrue(ERC20 strategy, address user) public returns (uint256) {\n (uint224 index, uint32 ts) = strategyState(strategy);\n RewardsState memory state = RewardsState(index, ts);\n\n if (state.index == 0) return 0;\n\n state = accrueStrategy(strategy, state);\n return accrueUser(strategy, user, state);\n }\n\n /** \n @notice accrue rewards for a two users on a strategy\n @param strategy the strategy to accrue a user's rewards on\n @param user the first user to be accrued\n @param user the second user to be accrued\n @return the cumulative amount of rewards accrued to the first user (including prior)\n @return the cumulative amount of rewards accrued to the second user (including prior)\n */\n function accrue(ERC20 strategy, address user, address secondUser) public returns (uint256, uint256) {\n (uint224 index, uint32 ts) = strategyState(strategy);\n RewardsState memory state = RewardsState(index, ts);\n\n if (state.index == 0) return (0, 0);\n\n state = accrueStrategy(strategy, state);\n return (accrueUser(strategy, user, state), accrueUser(strategy, secondUser, state));\n }\n\n /** \n @notice claim rewards for a given user\n @param user the user claiming rewards\n @dev this function is public, and all rewards transfer to the user\n */\n function claimRewards(address user) external {\n require(!emissionsManager.isUserBlacklisted(user), \"blacklisted\");\n require(!emissionsManager.isUserBlacklistable(user), \"blacklistable\");\n uint256 accrued = rewardsAccrued(user);\n\n if (accrued != 0) {\n _rewardsAccrued[user] = 0;\n\n rewardToken.safeTransferFrom(address(flywheelRewards), user, accrued);\n\n emit ClaimRewards(user, accrued);\n }\n }\n\n /** \n @notice take rewards for a given user\n @param user the user claiming rewards\n @param receiver the address that receives the rewards\n @dev this function is public, and all rewards transfer to the receiver\n */\n function takeRewardsFromUser(address user, address receiver) external onlyEmissionsManager {\n uint256 accrued = rewardsAccrued(user);\n\n if (accrued != 0) {\n _rewardsAccrued[user] = 0;\n\n rewardToken.safeTransferFrom(address(flywheelRewards), receiver, accrued);\n\n emit ClaimRewards(user, accrued);\n }\n }\n\n /** \n @notice set user balances to zero\n @param strategy strategy to whitelist user for\n @param user the user to be whitelisted\n @dev this function is public, and all user and strategy blacklisted supplies are reset\n */\n function whitelistUser(ERC20 strategy, address user) external onlyEmissionsManager {\n blacklistedSupply[strategy] -= userBlacklistedSupply[strategy][user];\n userBlacklistedSupply[strategy][user] = 0;\n }\n\n /** \n @notice update user blacklisted balances\n @param strategy strategy to update blacklisted balances\n @param user the user to be blacklisted\n @dev this function is public\n */\n function updateBlacklistBalances(ERC20 strategy, address user) external onlyEmissionsManager {\n _updateBlacklistBalances(strategy, user);\n }\n\n /** \n @notice update user blacklisted balances\n @param strategy strategy to update blacklisted balances\n @param user the user to be blacklisted\n @dev this function is private\n */\n function _updateBlacklistBalances(ERC20 strategy, address user) internal {\n if (emissionsManager.isUserBlacklisted(user)) {\n uint256 _oldUserBlacklistedSupply = userBlacklistedSupply[strategy][user];\n uint256 supplierTokens = address(flywheelBooster) != address(0)\n ? flywheelBooster.boostedBalanceOf(ERC20(strategy), user)\n : ERC20(strategy).balanceOf(user);\n\n if (supplierTokens >= _oldUserBlacklistedSupply) {\n blacklistedSupply[strategy] += supplierTokens - _oldUserBlacklistedSupply;\n userBlacklistedSupply[strategy][user] = supplierTokens;\n } else {\n blacklistedSupply[strategy] -= _oldUserBlacklistedSupply - supplierTokens;\n userBlacklistedSupply[strategy][user] = supplierTokens;\n }\n }\n }\n /*----------------------------------------------------------------\n ADMIN LOGIC\n ----------------------------------------------------------------*/\n\n /** \n @notice Emitted when a new strategy is added to flywheel by the admin\n @param newStrategy the new added strategy\n */\n event AddStrategy(address indexed newStrategy);\n\n /// @notice initialize a new strategy\n function setEmissionsManager(IEmissionsManager _emissionsManager) external onlyOwner {\n emissionsManager = _emissionsManager;\n }\n\n /// @notice initialize a new strategy\n function addStrategyForRewards(ERC20 strategy) external onlyOwner {\n _addStrategyForRewards(strategy);\n }\n\n function _addStrategyForRewards(ERC20 strategy) internal {\n (uint224 index, ) = strategyState(strategy);\n require(index == 0, \"strategy\");\n _strategyState[strategy] = RewardsState({\n index: (10 ** rewardToken.decimals()).safeCastTo224(),\n lastUpdatedTimestamp: block.timestamp.safeCastTo32()\n });\n\n allStrategies.push(strategy);\n emit AddStrategy(address(strategy));\n }\n\n function getAllStrategies() external view returns (ERC20[] memory) {\n return allStrategies;\n }\n\n /** \n @notice Emitted when the rewards module changes\n @param newFlywheelRewards the new rewards module\n */\n event FlywheelRewardsUpdate(address indexed newFlywheelRewards);\n\n /// @notice swap out the flywheel rewards contract\n function setFlywheelRewards(IFlywheelRewards newFlywheelRewards) external onlyOwner {\n if (address(flywheelRewards) != address(0)) {\n uint256 oldRewardBalance = rewardToken.balanceOf(address(flywheelRewards));\n if (oldRewardBalance > 0) {\n rewardToken.safeTransferFrom(address(flywheelRewards), address(newFlywheelRewards), oldRewardBalance);\n }\n }\n\n flywheelRewards = newFlywheelRewards;\n\n emit FlywheelRewardsUpdate(address(newFlywheelRewards));\n }\n\n /** \n @notice Emitted when the booster module changes\n @param newBooster the new booster module\n */\n event FlywheelBoosterUpdate(address indexed newBooster);\n\n /// @notice swap out the flywheel booster contract\n function setBooster(IFlywheelBooster newBooster) external onlyOwner {\n flywheelBooster = newBooster;\n\n emit FlywheelBoosterUpdate(address(newBooster));\n }\n\n event UpdatedFeeSettings(\n uint256 oldPerformanceFee,\n uint256 newPerformanceFee,\n address oldFeeRecipient,\n address newFeeRecipient\n );\n\n /**\n * @notice Update performanceFee and/or feeRecipient\n * @dev Claim rewards first from the previous feeRecipient before changing it\n */\n function updateFeeSettings(uint256 _performanceFee, address _feeRecipient) external onlyOwner {\n _updateFeeSettings(_performanceFee, _feeRecipient);\n }\n\n function _updateFeeSettings(uint256 _performanceFee, address _feeRecipient) internal {\n emit UpdatedFeeSettings(performanceFee, _performanceFee, feeRecipient, _feeRecipient);\n\n if (feeRecipient != _feeRecipient) {\n _rewardsAccrued[_feeRecipient] += rewardsAccrued(feeRecipient);\n _rewardsAccrued[feeRecipient] = 0;\n }\n performanceFee = _performanceFee;\n feeRecipient = _feeRecipient;\n }\n\n /*----------------------------------------------------------------\n INTERNAL ACCOUNTING LOGIC\n ----------------------------------------------------------------*/\n\n struct RewardsState {\n /// @notice The strategy's last updated index\n uint224 index;\n /// @notice The timestamp the index was last updated at\n uint32 lastUpdatedTimestamp;\n }\n\n /// @notice accumulate global rewards on a strategy\n function accrueStrategy(\n ERC20 strategy,\n RewardsState memory state\n ) private returns (RewardsState memory rewardsState) {\n // calculate accrued rewards through module\n uint256 strategyRewardsAccrued = flywheelRewards.getAccruedRewards(strategy, state.lastUpdatedTimestamp);\n\n rewardsState = state;\n\n if (strategyRewardsAccrued > 0) {\n // use the booster or token supply to calculate reward index denominator\n uint256 supplyTokens = address(flywheelBooster) != address(0)\n ? flywheelBooster.boostedTotalSupply(strategy) - blacklistedSupply[strategy]\n : strategy.totalSupply() - blacklistedSupply[strategy];\n\n // 100% = 100e16\n uint256 accruedFees = (strategyRewardsAccrued * performanceFee) / uint224(100e16);\n\n _rewardsAccrued[feeRecipient] += accruedFees;\n strategyRewardsAccrued -= accruedFees;\n\n uint224 deltaIndex;\n\n if (supplyTokens != 0)\n deltaIndex = ((strategyRewardsAccrued * (10 ** strategy.decimals())) / supplyTokens).safeCastTo224();\n\n // accumulate rewards per token onto the index, multiplied by fixed-point factor\n rewardsState = RewardsState({\n index: state.index + deltaIndex,\n lastUpdatedTimestamp: block.timestamp.safeCastTo32()\n });\n _strategyState[strategy] = rewardsState;\n }\n }\n\n /// @notice accumulate rewards on a strategy for a specific user\n function accrueUser(ERC20 strategy, address user, RewardsState memory state) private returns (uint256) {\n // load indices\n uint224 strategyIndex = state.index;\n uint224 supplierIndex = userIndex(strategy, user);\n\n // sync user index to global\n _userIndex[strategy][user] = strategyIndex;\n\n // if user hasn't yet accrued rewards, grant them interest from the strategy beginning if they have a balance\n // zero balances will have no effect other than syncing to global index\n if (supplierIndex == 0) {\n supplierIndex = (10 ** rewardToken.decimals()).safeCastTo224();\n }\n\n uint224 deltaIndex = strategyIndex - supplierIndex;\n // use the booster or token balance to calculate reward balance multiplier\n uint256 supplierTokens = address(flywheelBooster) != address(0)\n ? flywheelBooster.boostedBalanceOf(strategy, user) - userBlacklistedSupply[strategy][user]\n : strategy.balanceOf(user) - userBlacklistedSupply[strategy][user];\n\n // accumulate rewards by multiplying user tokens by rewardsPerToken index and adding on unclaimed\n uint256 supplierDelta = (deltaIndex * supplierTokens) / (10 ** strategy.decimals());\n uint256 supplierAccrued = rewardsAccrued(user) + supplierDelta;\n\n _rewardsAccrued[user] = supplierAccrued;\n\n emit AccrueRewards(strategy, user, supplierDelta, strategyIndex);\n\n return supplierAccrued;\n }\n\n function rewardsAccrued(address user) public virtual returns (uint256) {\n return _rewardsAccrued[user];\n }\n\n function userIndex(ERC20 strategy, address user) public virtual returns (uint224) {\n return _userIndex[strategy][user];\n }\n\n function strategyState(ERC20 strategy) public virtual returns (uint224 index, uint32 lastUpdatedTimestamp) {\n return (_strategyState[strategy].index, _strategyState[strategy].lastUpdatedTimestamp);\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/IonicFlywheelLensRouter.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\n\nimport { IonicFlywheelCore } from \"./IonicFlywheelCore.sol\";\nimport { IonicComptroller } from \"../../../compound/ComptrollerInterface.sol\";\nimport { ICErc20 } from \"../../../compound/CTokenInterfaces.sol\";\nimport { BasePriceOracle } from \"../../../oracles/BasePriceOracle.sol\";\nimport { PoolDirectory } from \"../../../PoolDirectory.sol\";\n\ninterface IPriceOracle_IFLR {\n function getUnderlyingPrice(ERC20 cToken) external view returns (uint256);\n\n function price(address underlying) external view returns (uint256);\n}\n\ncontract IonicFlywheelLensRouter {\n PoolDirectory public fpd;\n\n constructor(PoolDirectory _fpd) {\n fpd = _fpd;\n }\n\n struct MarketRewardsInfo {\n /// @dev comptroller oracle price of market underlying\n uint256 underlyingPrice;\n ICErc20 market;\n RewardsInfo[] rewardsInfo;\n }\n\n struct RewardsInfo {\n /// @dev rewards in `rewardToken` paid per underlying staked token in `market` per second\n uint256 rewardSpeedPerSecondPerToken;\n /// @dev comptroller oracle price of reward token\n uint256 rewardTokenPrice;\n /// @dev APR scaled by 1e18. Calculated as rewardSpeedPerSecondPerToken * rewardTokenPrice * 365.25 days / underlyingPrice * 1e18 / market.exchangeRate\n uint256 formattedAPR;\n address flywheel;\n address rewardToken;\n }\n\n function getPoolMarketRewardsInfo(IonicComptroller comptroller) external returns (MarketRewardsInfo[] memory) {\n ICErc20[] memory markets = comptroller.getAllMarkets();\n return _getMarketRewardsInfo(markets, comptroller);\n }\n\n function getMarketRewardsInfo(ICErc20[] memory markets) external returns (MarketRewardsInfo[] memory) {\n IonicComptroller pool;\n for (uint256 i = 0; i < markets.length; i++) {\n ICErc20 asMarket = ICErc20(address(markets[i]));\n if (address(pool) == address(0)) pool = asMarket.comptroller();\n else require(asMarket.comptroller() == pool);\n }\n return _getMarketRewardsInfo(markets, pool);\n }\n\n function _getMarketRewardsInfo(ICErc20[] memory markets, IonicComptroller comptroller)\n internal\n returns (MarketRewardsInfo[] memory)\n {\n if (address(comptroller) == address(0) || markets.length == 0) return new MarketRewardsInfo[](0);\n\n address[] memory flywheels = comptroller.getAccruingFlywheels();\n address[] memory rewardTokens = new address[](flywheels.length);\n uint256[] memory rewardTokenPrices = new uint256[](flywheels.length);\n uint256[] memory rewardTokenDecimals = new uint256[](flywheels.length);\n BasePriceOracle oracle = comptroller.oracle();\n\n MarketRewardsInfo[] memory infoList = new MarketRewardsInfo[](markets.length);\n for (uint256 i = 0; i < markets.length; i++) {\n RewardsInfo[] memory rewardsInfo = new RewardsInfo[](flywheels.length);\n\n ICErc20 market = ICErc20(address(markets[i]));\n uint256 price = oracle.price(market.underlying()); // scaled to 1e18\n\n if (i == 0) {\n for (uint256 j = 0; j < flywheels.length; j++) {\n ERC20 rewardToken = IonicFlywheelCore(flywheels[j]).rewardToken();\n rewardTokens[j] = address(rewardToken);\n rewardTokenPrices[j] = oracle.price(address(rewardToken)); // scaled to 1e18\n rewardTokenDecimals[j] = uint256(rewardToken.decimals());\n }\n }\n\n for (uint256 j = 0; j < flywheels.length; j++) {\n IonicFlywheelCore flywheel = IonicFlywheelCore(flywheels[j]);\n\n uint256 rewardSpeedPerSecondPerToken = getRewardSpeedPerSecondPerToken(\n flywheel,\n market,\n rewardTokenDecimals[j]\n );\n uint256 apr = getApr(\n rewardSpeedPerSecondPerToken,\n rewardTokenPrices[j],\n price, \n market.exchangeRateCurrent(),\n address(flywheel.flywheelBooster()) != address(0)\n );\n\n rewardsInfo[j] = RewardsInfo({\n rewardSpeedPerSecondPerToken: rewardSpeedPerSecondPerToken, // scaled in 1e18\n rewardTokenPrice: rewardTokenPrices[j],\n formattedAPR: apr, // scaled in 1e18\n flywheel: address(flywheel),\n rewardToken: rewardTokens[j]\n });\n }\n\n infoList[i] = MarketRewardsInfo({ market: market, rewardsInfo: rewardsInfo, underlyingPrice: price });\n }\n\n return infoList;\n }\n\n function scaleIndexDiff(uint256 indexDiff, uint256 decimals) internal pure returns (uint256) {\n return decimals <= 18 ? uint256(indexDiff) * (10**(18 - decimals)) : uint256(indexDiff) / (10**(decimals - 18));\n }\n\n function getRewardSpeedPerSecondPerToken(\n IonicFlywheelCore flywheel,\n ICErc20 market,\n uint256 decimals\n ) internal returns (uint256 rewardSpeedPerSecondPerToken) {\n ERC20 strategy = ERC20(address(market));\n (uint224 indexBefore, uint32 lastUpdatedTimestampBefore) = flywheel.strategyState(strategy);\n flywheel.accrue(strategy, address(0));\n (uint224 indexAfter, uint32 lastUpdatedTimestampAfter) = flywheel.strategyState(strategy);\n if (lastUpdatedTimestampAfter > lastUpdatedTimestampBefore) {\n rewardSpeedPerSecondPerToken =\n scaleIndexDiff((indexAfter - indexBefore), decimals) /\n (lastUpdatedTimestampAfter - lastUpdatedTimestampBefore);\n }\n }\n\n function getApr(\n uint256 rewardSpeedPerSecondPerToken,\n uint256 rewardTokenPrice,\n uint256 underlyingPrice,\n uint256 exchangeRate,\n bool isBorrow\n ) internal pure returns (uint256) {\n if (rewardSpeedPerSecondPerToken == 0) return 0;\n uint256 nativeSpeedPerSecondPerCToken = rewardSpeedPerSecondPerToken * rewardTokenPrice; // scaled to 1e36\n uint256 nativeSpeedPerYearPerCToken = nativeSpeedPerSecondPerCToken * 365.25 days; // scaled to 1e36\n uint256 assetSpeedPerYearPerCToken = nativeSpeedPerYearPerCToken / underlyingPrice; // scaled to 1e18\n uint256 assetSpeedPerYearPerCTokenScaled = assetSpeedPerYearPerCToken * 1e18; // scaled to 1e36\n uint256 apr = assetSpeedPerYearPerCTokenScaled;\n if (!isBorrow) {\n // if not borrowing, use exchange rate to scale\n apr = assetSpeedPerYearPerCTokenScaled / exchangeRate; // scaled to 1e18\n } else {\n apr = assetSpeedPerYearPerCTokenScaled / 1e18; // scaled to 1e18\n }\n return apr;\n }\n\n function getRewardsAprForMarket(ICErc20 market) internal returns (int256 totalMarketRewardsApr) {\n IonicComptroller comptroller = market.comptroller();\n BasePriceOracle oracle = comptroller.oracle();\n uint256 underlyingPrice = oracle.getUnderlyingPrice(market);\n\n address[] memory flywheels = comptroller.getAccruingFlywheels();\n for (uint256 j = 0; j < flywheels.length; j++) {\n IonicFlywheelCore flywheel = IonicFlywheelCore(flywheels[j]);\n ERC20 rewardToken = flywheel.rewardToken();\n\n uint256 rewardSpeedPerSecondPerToken = getRewardSpeedPerSecondPerToken(\n flywheel,\n market,\n uint256(rewardToken.decimals())\n );\n\n uint256 marketApr = getApr(\n rewardSpeedPerSecondPerToken,\n oracle.price(address(rewardToken)),\n underlyingPrice,\n market.exchangeRateCurrent(),\n address(flywheel.flywheelBooster()) != address(0)\n );\n\n totalMarketRewardsApr += int256(marketApr);\n }\n }\n\n function getUserNetValueDeltaForMarket(\n address user,\n ICErc20 market,\n int256 offchainApr,\n int256 blocksPerYear\n ) internal returns (int256) {\n IonicComptroller comptroller = market.comptroller();\n BasePriceOracle oracle = comptroller.oracle();\n int256 netApr = getRewardsAprForMarket(market) +\n getUserInterestAprForMarket(user, market, blocksPerYear) +\n offchainApr;\n return (netApr * int256(market.balanceOfUnderlying(user)) * int256(oracle.getUnderlyingPrice(market))) / 1e36;\n }\n\n function getUserInterestAprForMarket(\n address user,\n ICErc20 market,\n int256 blocksPerYear\n ) internal returns (int256) {\n uint256 borrows = market.borrowBalanceCurrent(user);\n uint256 supplied = market.balanceOfUnderlying(user);\n uint256 supplyRatePerBlock = market.supplyRatePerBlock();\n uint256 borrowRatePerBlock = market.borrowRatePerBlock();\n\n IonicComptroller comptroller = market.comptroller();\n BasePriceOracle oracle = comptroller.oracle();\n uint256 assetPrice = oracle.getUnderlyingPrice(market);\n uint256 collateralValue = (supplied * assetPrice) / 1e18;\n uint256 borrowsValue = (borrows * assetPrice) / 1e18;\n\n uint256 yieldValuePerBlock = collateralValue * supplyRatePerBlock;\n uint256 interestOwedValuePerBlock = borrowsValue * borrowRatePerBlock;\n\n if (collateralValue == 0) return 0;\n return ((int256(yieldValuePerBlock) - int256(interestOwedValuePerBlock)) * blocksPerYear) / int256(collateralValue);\n }\n\n struct AdjustedUserNetAprVars {\n int256 userNetAssetsValue;\n int256 userNetValueDelta;\n BasePriceOracle oracle;\n ICErc20[] markets;\n IonicComptroller pool;\n }\n\n function getAdjustedUserNetApr(\n address user,\n int256 blocksPerYear,\n address[] memory offchainRewardsAprMarkets,\n int256[] memory offchainRewardsAprs\n ) public returns (int256) {\n AdjustedUserNetAprVars memory vars;\n\n (, PoolDirectory.Pool[] memory pools) = fpd.getActivePools();\n for (uint256 i = 0; i < pools.length; i++) {\n IonicComptroller pool = IonicComptroller(pools[i].comptroller);\n vars.oracle = pool.oracle();\n vars.markets = pool.getAllMarkets();\n for (uint256 j = 0; j < vars.markets.length; j++) {\n int256 offchainRewardsApr = 0;\n for (uint256 k = 0; k < offchainRewardsAprMarkets.length; k++) {\n if (offchainRewardsAprMarkets[k] == address(vars.markets[j])) offchainRewardsApr = offchainRewardsAprs[k];\n }\n vars.userNetAssetsValue +=\n int256(vars.markets[j].balanceOfUnderlying(user) * vars.oracle.getUnderlyingPrice(vars.markets[j])) /\n 1e18;\n vars.userNetValueDelta += getUserNetValueDeltaForMarket(\n user,\n vars.markets[j],\n offchainRewardsApr,\n blocksPerYear\n );\n }\n }\n\n if (vars.userNetAssetsValue == 0) return 0;\n else return (vars.userNetValueDelta * 1e18) / vars.userNetAssetsValue;\n }\n\n function getUserNetApr(address user, int256 blocksPerYear) external returns (int256) {\n address[] memory emptyAddrArray = new address[](0);\n int256[] memory emptyIntArray = new int256[](0);\n return getAdjustedUserNetApr(user, blocksPerYear, emptyAddrArray, emptyIntArray);\n }\n\n function getAllRewardTokens() public view returns (address[] memory uniqueRewardTokens) {\n (, PoolDirectory.Pool[] memory pools) = fpd.getActivePools();\n\n uint256 rewardTokensCounter;\n for (uint256 i = 0; i < pools.length; i++) {\n IonicComptroller pool = IonicComptroller(pools[i].comptroller);\n address[] memory fws = pool.getRewardsDistributors();\n\n rewardTokensCounter += fws.length;\n }\n\n address[] memory rewardTokens = new address[](rewardTokensCounter);\n\n uint256 uniqueRewardTokensCounter = 0;\n for (uint256 i = 0; i < pools.length; i++) {\n IonicComptroller pool = IonicComptroller(pools[i].comptroller);\n address[] memory fws = pool.getRewardsDistributors();\n\n for (uint256 j = 0; j < fws.length; j++) {\n address rwToken = address(IonicFlywheelCore(fws[j]).rewardToken());\n if (rwToken == address(0)) break;\n\n bool added;\n for (uint256 k = 0; k < rewardTokens.length; k++) {\n if (rwToken == rewardTokens[k]) {\n added = true;\n break;\n }\n }\n if (!added) rewardTokens[uniqueRewardTokensCounter++] = rwToken;\n }\n }\n\n uniqueRewardTokens = new address[](uniqueRewardTokensCounter);\n for (uint256 i = 0; i < uniqueRewardTokensCounter; i++) {\n uniqueRewardTokens[i] = rewardTokens[i];\n }\n }\n\n function claimAllRewardTokens(address user) external returns (address[] memory, uint256[] memory) {\n address[] memory rewardTokens = getAllRewardTokens();\n uint256[] memory rewardsClaimedForToken = new uint256[](rewardTokens.length);\n\n for (uint256 i = 0; i < rewardTokens.length; i++) {\n rewardsClaimedForToken[i] = claimRewardsOfRewardToken(user, rewardTokens[i]);\n }\n\n return (rewardTokens, rewardsClaimedForToken);\n }\n\n function claimRewardsOfRewardToken(address user, address rewardToken) public returns (uint256 rewardsClaimed) {\n uint256 balanceBefore = ERC20(rewardToken).balanceOf(user);\n (, PoolDirectory.Pool[] memory pools) = fpd.getActivePools();\n for (uint256 i = 0; i < pools.length; i++) {\n IonicComptroller pool = IonicComptroller(pools[i].comptroller);\n ERC20[] memory markets;\n {\n ICErc20[] memory cerc20s = pool.getAllMarkets();\n markets = new ERC20[](cerc20s.length);\n for (uint256 j = 0; j < cerc20s.length; j++) {\n markets[j] = ERC20(address(cerc20s[j]));\n }\n }\n\n address[] memory flywheelAddresses = pool.getAccruingFlywheels();\n for (uint256 k = 0; k < flywheelAddresses.length; k++) {\n IonicFlywheelCore flywheel = IonicFlywheelCore(flywheelAddresses[k]);\n if (address(flywheel.rewardToken()) == rewardToken) {\n for (uint256 m = 0; m < markets.length; m++) {\n flywheel.accrue(markets[m], user);\n }\n flywheel.claimRewards(user);\n }\n }\n }\n\n uint256 balanceAfter = ERC20(rewardToken).balanceOf(user);\n return balanceAfter - balanceBefore;\n }\n\n function claimRewardsForMarket(\n address user,\n ERC20 market,\n IonicFlywheelCore[] calldata flywheels,\n bool[] calldata accrue\n )\n external\n returns (\n IonicFlywheelCore[] memory,\n address[] memory rewardTokens,\n uint256[] memory rewards\n )\n {\n uint256 size = flywheels.length;\n rewards = new uint256[](size);\n rewardTokens = new address[](size);\n\n for (uint256 i = 0; i < size; i++) {\n uint256 newRewards;\n if (accrue[i]) {\n newRewards = flywheels[i].accrue(market, user);\n } else {\n newRewards = flywheels[i].rewardsAccrued(user);\n }\n\n // Take the max, because rewards are cumulative.\n rewards[i] = rewards[i] >= newRewards ? rewards[i] : newRewards;\n\n flywheels[i].claimRewards(user);\n rewardTokens[i] = address(flywheels[i].rewardToken());\n }\n\n return (flywheels, rewardTokens, rewards);\n }\n\n function claimRewardsForPool(address user, IonicComptroller comptroller)\n public\n returns (\n IonicFlywheelCore[] memory,\n address[] memory,\n uint256[] memory\n )\n {\n ICErc20[] memory cerc20s = comptroller.getAllMarkets();\n ERC20[] memory markets = new ERC20[](cerc20s.length);\n address[] memory flywheelAddresses = comptroller.getAccruingFlywheels();\n IonicFlywheelCore[] memory flywheels = new IonicFlywheelCore[](flywheelAddresses.length);\n bool[] memory accrue = new bool[](flywheelAddresses.length);\n\n for (uint256 j = 0; j < flywheelAddresses.length; j++) {\n flywheels[j] = IonicFlywheelCore(flywheelAddresses[j]);\n accrue[j] = true;\n }\n\n for (uint256 j = 0; j < cerc20s.length; j++) {\n markets[j] = ERC20(address(cerc20s[j]));\n }\n\n return claimRewardsForMarkets(user, markets, flywheels, accrue);\n }\n\n function claimRewardsForMarkets(\n address user,\n ERC20[] memory markets,\n IonicFlywheelCore[] memory flywheels,\n bool[] memory accrue\n )\n public\n returns (\n IonicFlywheelCore[] memory,\n address[] memory rewardTokens,\n uint256[] memory rewards\n )\n {\n rewards = new uint256[](flywheels.length);\n rewardTokens = new address[](flywheels.length);\n\n for (uint256 i = 0; i < flywheels.length; i++) {\n for (uint256 j = 0; j < markets.length; j++) {\n ERC20 market = markets[j];\n\n uint256 newRewards;\n if (accrue[i]) {\n newRewards = flywheels[i].accrue(market, user);\n } else {\n newRewards = flywheels[i].rewardsAccrued(user);\n }\n\n // Take the max, because rewards are cumulative.\n rewards[i] = rewards[i] >= newRewards ? rewards[i] : newRewards;\n }\n\n flywheels[i].claimRewards(user);\n rewardTokens[i] = address(flywheels[i].rewardToken());\n }\n\n return (flywheels, rewardTokens, rewards);\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/IonicReplacingFlywheel.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport \"./IonicFlywheel.sol\";\n\nimport { IFlywheelRewards } from \"./rewards/IFlywheelRewards.sol\";\nimport { IFlywheelBooster } from \"./IFlywheelBooster.sol\";\n\ncontract IonicReplacingFlywheel is IonicFlywheel {\n IonicFlywheelCore public flywheelToReplace;\n mapping(address => bool) private rewardsTransferred;\n\n function reinitialize(IonicFlywheelCore _flywheelToReplace) public onlyOwner {\n flywheelToReplace = _flywheelToReplace;\n }\n\n function rewardsAccrued(address user) public override returns (uint256) {\n if (address(flywheelToReplace) != address(0)) {\n if (_rewardsAccrued[user] == 0 && !rewardsTransferred[user]) {\n uint256 oldStateRewardsAccrued = flywheelToReplace.rewardsAccrued(user);\n if (oldStateRewardsAccrued != 0) {\n rewardsTransferred[user] = true;\n _rewardsAccrued[user] = oldStateRewardsAccrued;\n }\n }\n }\n return _rewardsAccrued[user];\n }\n\n function strategyState(ERC20 strategy) public override returns (uint224, uint32) {\n if (address(flywheelToReplace) != address(0)) {\n RewardsState memory newStateStrategyState = _strategyState[strategy];\n if (newStateStrategyState.index == 0) {\n (uint224 index, uint32 ts) = flywheelToReplace.strategyState(strategy);\n if (index != 0) {\n _strategyState[strategy] = RewardsState(index, ts);\n }\n }\n }\n return (_strategyState[strategy].index, _strategyState[strategy].lastUpdatedTimestamp);\n }\n\n function userIndex(ERC20 strategy, address user) public override returns (uint224) {\n if (address(flywheelToReplace) != address(0)) {\n if (_userIndex[strategy][user] == 0) {\n uint224 oldStateUserIndex = flywheelToReplace.userIndex(strategy, user);\n if (oldStateUserIndex != 0) {\n _userIndex[strategy][user] = oldStateUserIndex;\n }\n }\n }\n return _userIndex[strategy][user];\n }\n\n function addInitializedStrategy(ERC20 strategy) public onlyOwner {\n (uint224 index, ) = strategyState(strategy);\n if (index > 0) {\n ERC20[] memory strategies = this.getAllStrategies();\n for (uint8 i = 0; i < strategies.length; i++) {\n require(address(strategy) != address(strategies[i]), \"!added\");\n }\n\n allStrategies.push(strategy);\n emit AddStrategy(address(strategy));\n }\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/LooplessFlywheelBooster.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport \"./IFlywheelBooster.sol\";\nimport { ICErc20 } from \"../../../compound/CTokenInterfaces.sol\";\n\ncontract LooplessFlywheelBooster is IFlywheelBooster {\n string public constant BOOSTER_TYPE = \"LooplessFlywheelBooster\";\n\n /**\n @notice calculate the boosted supply of a strategy.\n @param strategy the strategy to calculate boosted supply of\n @return the boosted supply\n */\n function boostedTotalSupply(ERC20 strategy) external view returns (uint256) {\n return strategy.totalSupply();\n }\n\n /**\n @notice calculate the boosted balance of a user in a given strategy.\n @param strategy the strategy to calculate boosted balance of\n @param user the user to calculate boosted balance of\n @return the boosted balance\n */\n function boostedBalanceOf(ERC20 strategy, address user) external view returns (uint256) {\n uint256 cTokensBalance = strategy.balanceOf(user);\n ICErc20 asMarket = ICErc20(address(strategy));\n uint256 cTokensBorrow = (asMarket.borrowBalanceCurrent(user) * 1e18) / asMarket.exchangeRateCurrent();\n return (cTokensBalance > cTokensBorrow) ? cTokensBalance - cTokensBorrow : 0;\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/rewards/BaseFlywheelRewards.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport {SafeTransferLib, ERC20} from \"solmate/utils/SafeTransferLib.sol\";\nimport {IFlywheelRewards} from \"./IFlywheelRewards.sol\";\nimport {IonicFlywheelCore} from \"../IonicFlywheelCore.sol\";\n\n/** \n @title Flywheel Reward Module\n @notice Determines how many rewards accrue to each strategy globally over a given time period.\n @dev approves the flywheel core for the reward token to allow balances to be managed by the module but claimed from core.\n*/\nabstract contract BaseFlywheelRewards is IFlywheelRewards {\n using SafeTransferLib for ERC20;\n\n /// @notice thrown when caller is not the flywheel\n error FlywheelError();\n\n /// @notice the reward token paid\n ERC20 public immutable override rewardToken;\n\n /// @notice the flywheel core contract\n IonicFlywheelCore public immutable override flywheel;\n\n constructor(IonicFlywheelCore _flywheel) {\n flywheel = _flywheel;\n ERC20 _rewardToken = _flywheel.rewardToken();\n rewardToken = _rewardToken;\n\n _rewardToken.safeApprove(address(_flywheel), type(uint256).max);\n }\n\n modifier onlyFlywheel() {\n if (msg.sender != address(flywheel)) revert FlywheelError();\n _;\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/rewards/FlywheelDynamicRewards.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport {BaseFlywheelRewards} from \"./BaseFlywheelRewards.sol\";\nimport {IonicFlywheelCore} from \"../IonicFlywheelCore.sol\";\nimport {SafeTransferLib, ERC20} from \"solmate/utils/SafeTransferLib.sol\";\nimport {SafeCastLib} from \"solmate/utils/SafeCastLib.sol\";\n\n/** \n @title Flywheel Dynamic Reward Stream\n @notice Determines rewards based on a dynamic reward stream.\n Rewards are transferred linearly over a \"rewards cycle\" to prevent gaming the reward distribution. \n The reward source can be arbitrary logic, but most common is to \"pass through\" rewards from some other source.\n The getNextCycleRewards() hook should also transfer the next cycle's rewards to this contract to ensure proper accounting.\n*/\nabstract contract FlywheelDynamicRewards is BaseFlywheelRewards {\n using SafeTransferLib for ERC20;\n using SafeCastLib for uint256;\n\n event NewRewardsCycle(uint32 indexed start, uint32 indexed end, uint192 reward);\n\n /// @notice the length of a rewards cycle\n uint32 public immutable rewardsCycleLength;\n\n struct RewardsCycle {\n uint32 start;\n uint32 end;\n uint192 reward;\n }\n\n mapping(ERC20 => RewardsCycle) public rewardsCycle;\n\n constructor(IonicFlywheelCore _flywheel, uint32 _rewardsCycleLength) BaseFlywheelRewards(_flywheel) {\n rewardsCycleLength = _rewardsCycleLength;\n }\n\n /**\n @notice calculate and transfer accrued rewards to flywheel core\n @param strategy the strategy to accrue rewards for\n @return amount the amount of tokens accrued and transferred\n */\n function getAccruedRewards(ERC20 strategy, uint32 lastUpdatedTimestamp)\n external\n override\n onlyFlywheel\n returns (uint256 amount)\n {\n RewardsCycle memory cycle = rewardsCycle[strategy];\n\n uint32 timestamp = block.timestamp.safeCastTo32();\n\n uint32 latest = timestamp >= cycle.end ? cycle.end : timestamp;\n uint32 earliest = lastUpdatedTimestamp <= cycle.start ? cycle.start : lastUpdatedTimestamp;\n if (cycle.end != 0) {\n amount = (cycle.reward * (latest - earliest)) / (cycle.end - cycle.start);\n assert(amount <= cycle.reward); // should never happen because latest <= cycle.end and earliest >= cycle.start\n }\n // if cycle has ended, reset cycle and transfer all available\n if (timestamp >= cycle.end) {\n uint32 end = ((timestamp + rewardsCycleLength) / rewardsCycleLength) * rewardsCycleLength;\n uint192 rewards = getNextCycleRewards(strategy);\n\n // reset for next cycle\n rewardsCycle[strategy] = RewardsCycle({start: timestamp, end: end, reward: rewards});\n\n emit NewRewardsCycle(timestamp, end, rewards);\n }\n }\n\n function getNextCycleRewards(ERC20 strategy) internal virtual returns (uint192);\n}" + }, + "contracts/src/ionic/strategies/flywheel/rewards/FlywheelStaticRewards.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport {Auth, Authority} from \"solmate/auth/Auth.sol\";\nimport {BaseFlywheelRewards} from \"./BaseFlywheelRewards.sol\";\nimport {ERC20} from \"solmate/utils/SafeTransferLib.sol\";\nimport {IonicFlywheelCore} from \"../IonicFlywheelCore.sol\";\n\n/** \n @title Flywheel Static Reward Stream\n @notice Determines rewards per strategy based on a fixed reward rate per second\n*/\ncontract FlywheelStaticRewards is Auth, BaseFlywheelRewards {\n event RewardsInfoUpdate(ERC20 indexed strategy, uint224 rewardsPerSecond, uint32 rewardsEndTimestamp);\n\n struct RewardsInfo {\n /// @notice Rewards per second\n uint224 rewardsPerSecond;\n /// @notice The timestamp the rewards end at\n /// @dev use 0 to specify no end\n uint32 rewardsEndTimestamp;\n }\n\n /// @notice rewards info per strategy\n mapping(ERC20 => RewardsInfo) public rewardsInfo;\n\n constructor(\n IonicFlywheelCore _flywheel,\n address _owner,\n Authority _authority\n ) Auth(_owner, _authority) BaseFlywheelRewards(_flywheel) {}\n\n /**\n @notice set rewards per second and rewards end time for Fei Rewards\n @param strategy the strategy to accrue rewards for\n @param rewards the rewards info for the strategy\n */\n function setRewardsInfo(ERC20 strategy, RewardsInfo calldata rewards) external requiresAuth {\n rewardsInfo[strategy] = rewards;\n emit RewardsInfoUpdate(strategy, rewards.rewardsPerSecond, rewards.rewardsEndTimestamp);\n }\n\n /**\n @notice calculate and transfer accrued rewards to flywheel core\n @param strategy the strategy to accrue rewards for\n @param lastUpdatedTimestamp the last updated time for strategy\n @return amount the amount of tokens accrued and transferred\n */\n function getAccruedRewards(ERC20 strategy, uint32 lastUpdatedTimestamp)\n external\n view\n override\n onlyFlywheel\n returns (uint256 amount)\n {\n RewardsInfo memory rewards = rewardsInfo[strategy];\n\n uint256 elapsed;\n if (rewards.rewardsEndTimestamp == 0 || rewards.rewardsEndTimestamp > block.timestamp) {\n elapsed = block.timestamp - lastUpdatedTimestamp;\n } else if (rewards.rewardsEndTimestamp > lastUpdatedTimestamp) {\n elapsed = rewards.rewardsEndTimestamp - lastUpdatedTimestamp;\n }\n\n amount = rewards.rewardsPerSecond * elapsed;\n }\n}" + }, + "contracts/src/ionic/strategies/flywheel/rewards/IFlywheelRewards.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport {ERC20} from \"solmate/tokens/ERC20.sol\";\nimport {IonicFlywheelCore} from \"../IonicFlywheelCore.sol\";\n\n/**\n @title Rewards Module for Flywheel\n @notice Flywheel is a general framework for managing token incentives.\n It takes reward streams to various *strategies* such as staking LP tokens and divides them among *users* of those strategies.\n\n The Rewards module is responsible for:\n * determining the ongoing reward amounts to entire strategies (core handles the logic for dividing among users)\n * actually holding rewards that are yet to be claimed\n\n The reward stream can follow arbitrary logic as long as the amount of rewards passed to flywheel core has been sent to this contract.\n\n Different module strategies include:\n * a static reward rate per second\n * a decaying reward rate\n * a dynamic just-in-time reward stream\n * liquid governance reward delegation (Curve Gauge style)\n\n SECURITY NOTE: The rewards strategy should be smooth and continuous, to prevent gaming the reward distribution by frontrunning.\n */\ninterface IFlywheelRewards {\n /**\n @notice calculate the rewards amount accrued to a strategy since the last update.\n @param strategy the strategy to accrue rewards for.\n @param lastUpdatedTimestamp the last time rewards were accrued for the strategy.\n @return rewards the amount of rewards accrued to the market\n */\n function getAccruedRewards(ERC20 strategy, uint32 lastUpdatedTimestamp) external returns (uint256 rewards);\n\n /// @notice return the flywheel core address\n function flywheel() external view returns (IonicFlywheelCore);\n\n /// @notice return the reward token associated with flywheel core.\n function rewardToken() external view returns (ERC20);\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/rewards/IonicFlywheelDynamicRewards.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { FlywheelDynamicRewards } from \"./FlywheelDynamicRewards.sol\";\nimport { IonicFlywheelCore } from \"../IonicFlywheelCore.sol\";\nimport { SafeTransferLib, ERC20 } from \"solmate/utils/SafeTransferLib.sol\";\n\ncontract IonicFlywheelDynamicRewards is FlywheelDynamicRewards {\n using SafeTransferLib for ERC20;\n\n address public owner;\n mapping(address => address) public rewardAccumulators;\n\n modifier onlyOwner() {\n require(msg.sender == owner, \"You are not the owner\");\n _;\n }\n\n constructor(IonicFlywheelCore _flywheel, uint32 _cycleLength)\n FlywheelDynamicRewards(_flywheel, _cycleLength)\n {\n owner = msg.sender;\n }\n\n function setRewardAccumulators(address[] memory _strategies, address[] memory _rewardAccumulators) external onlyOwner {\n uint256 _length = _strategies.length;\n require(_rewardAccumulators.length == _length, \"parameters\");\n for (uint256 i = 0; i < _length; i++) {\n rewardAccumulators[_strategies[i]] = _rewardAccumulators[i];\n }\n }\n\n function getNextCycleRewards(ERC20 strategy)\n internal\n override\n returns (uint192)\n {\n address rewardAccumulator = rewardAccumulators[address(strategy)];\n uint256 rewardAmount = rewardToken.balanceOf(rewardAccumulator);\n if (rewardAmount != 0) {\n rewardToken.safeTransferFrom(\n rewardAccumulator,\n address(this),\n rewardAmount\n );\n }\n return uint192(rewardAmount);\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/rewards/IonicFlywheelDynamicRewardsPlugin.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport \"./FlywheelDynamicRewards.sol\";\n\ninterface ICERC20 {\n function plugin() external returns (address);\n}\n\ninterface IPlugin_FDR {\n function claimRewards() external;\n}\n\n/** \n @title Ionic Flywheel Dynamic Reward Stream\n @notice Determines rewards based on reward cycle\n Each cycle, claims rewards on the plugin before getting the reward amount\n*/\ncontract IonicFlywheelDynamicRewardsPlugin is FlywheelDynamicRewards {\n using SafeTransferLib for ERC20;\n\n constructor(IonicFlywheelCore _flywheel, uint32 _cycleLength)\n FlywheelDynamicRewards(_flywheel, _cycleLength)\n {}\n\n function getNextCycleRewards(ERC20 strategy)\n internal\n override\n returns (uint192)\n {\n IPlugin_FDR plugin = IPlugin_FDR(ICERC20(address(strategy)).plugin());\n try plugin.claimRewards() {} catch {}\n\n uint256 rewardAmount = rewardToken.balanceOf(address(strategy));\n if (rewardAmount != 0) {\n rewardToken.safeTransferFrom(\n address(strategy),\n address(this),\n rewardAmount\n );\n }\n return uint192(rewardAmount);\n }\n}" + }, + "contracts/src/ionic/strategies/flywheel/rewards/ReplacingFlywheelDynamicRewards.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { FlywheelDynamicRewards } from \"./FlywheelDynamicRewards.sol\";\nimport { IonicFlywheelCore } from \"../IonicFlywheelCore.sol\";\nimport { Auth, Authority } from \"solmate/auth/Auth.sol\";\nimport { SafeTransferLib, ERC20 } from \"solmate/utils/SafeTransferLib.sol\";\n\ninterface ICERC20_RFDR {\n function plugin() external returns (address);\n}\n\ninterface IPlugin_RFDR {\n function claimRewards() external;\n}\n\ncontract ReplacingFlywheelDynamicRewards is FlywheelDynamicRewards {\n using SafeTransferLib for ERC20;\n\n IonicFlywheelCore public replacedFlywheel;\n\n constructor(\n IonicFlywheelCore _replacedFlywheel,\n IonicFlywheelCore _flywheel,\n uint32 _cycleLength\n ) FlywheelDynamicRewards(_flywheel, _cycleLength) {\n replacedFlywheel = _replacedFlywheel;\n // rewardToken.safeApprove(address(_replacedFlywheel), type(uint256).max);\n }\n\n function getNextCycleRewards(ERC20 strategy) internal override returns (uint192) {\n if (msg.sender == address(replacedFlywheel)) {\n return 0;\n } else {\n // make it work for both pulled (claimed) and pushed (transferred some other way) rewards\n try ICERC20_RFDR(address(strategy)).plugin() returns (address plugin) {\n try IPlugin_RFDR(plugin).claimRewards() {} catch {}\n } catch {}\n\n uint256 rewardAmount = rewardToken.balanceOf(address(strategy));\n if (rewardAmount != 0) {\n rewardToken.safeTransferFrom(address(strategy), address(this), rewardAmount);\n }\n return uint192(rewardAmount);\n }\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/rewards/ReplacingFlywheelStaticRewards.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { FlywheelStaticRewards } from \"./FlywheelStaticRewards.sol\";\nimport { IonicFlywheelCore } from \"../IonicFlywheelCore.sol\";\nimport { Auth, Authority } from \"solmate/auth/Auth.sol\";\nimport { SafeTransferLib, ERC20 } from \"solmate/utils/SafeTransferLib.sol\";\n\ncontract ReplacingFlywheelStaticRewards is FlywheelStaticRewards {\n using SafeTransferLib for ERC20;\n\n IonicFlywheelCore public replacedFlywheel;\n\n constructor(\n IonicFlywheelCore _replacedFlywheel,\n IonicFlywheelCore _flywheel,\n address _owner,\n Authority _authority\n ) FlywheelStaticRewards(_flywheel, _owner, _authority) {\n ERC20 _rewardToken = _flywheel.rewardToken();\n _rewardToken.safeApprove(address(_replacedFlywheel), type(uint256).max);\n }\n}\n" + }, + "contracts/src/ionic/strategies/flywheel/rewards/WithdrawableFlywheelStaticRewards.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.10;\n\nimport { FlywheelStaticRewards } from \"./FlywheelStaticRewards.sol\";\nimport { IonicFlywheelCore } from \"../IonicFlywheelCore.sol\";\nimport { Auth, Authority } from \"solmate/auth/Auth.sol\";\nimport { SafeTransferLib, ERC20 } from \"solmate/utils/SafeTransferLib.sol\";\n\ncontract WithdrawableFlywheelStaticRewards is FlywheelStaticRewards {\n using SafeTransferLib for ERC20;\n\n constructor(\n IonicFlywheelCore _flywheel,\n address _owner,\n Authority _authority\n ) FlywheelStaticRewards(_flywheel, _owner, _authority) {}\n\n function withdraw(uint256 amount) external {\n require(msg.sender == flywheel.owner());\n rewardToken.safeTransfer(address(flywheel.owner()), amount);\n }\n}\n" + }, + "contracts/src/ionic/strategies/IonicERC4626.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport { FixedPointMathLib } from \"solmate/utils/FixedPointMathLib.sol\";\n\nimport { PausableUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/security/PausableUpgradeable.sol\";\nimport { ERC4626Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/ERC4626Upgradeable.sol\";\nimport { ERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\nimport { SafeOwnableUpgradeable } from \"../../ionic/SafeOwnableUpgradeable.sol\";\n\nabstract contract IonicERC4626 is SafeOwnableUpgradeable, PausableUpgradeable, ERC4626Upgradeable {\n using FixedPointMathLib for uint256;\n using SafeERC20Upgradeable for ERC20Upgradeable;\n\n /* ========== STATE VARIABLES ========== */\n\n uint256 public vaultShareHWM;\n uint256 public performanceFee;\n address public feeRecipient;\n\n /* ========== EVENTS ========== */\n\n event UpdatedFeeSettings(\n uint256 oldPerformanceFee,\n uint256 newPerformanceFee,\n address oldFeeRecipient,\n address newFeeRecipient\n );\n\n event UpdatedRewardsRecipient(address oldRewardsRecipient, address newRewardsRecipient);\n\n /* ========== INITIALIZER ========== */\n\n function __IonicER4626_init(ERC20Upgradeable asset_) internal onlyInitializing {\n __SafeOwnable_init(msg.sender);\n __Pausable_init();\n __Context_init();\n __ERC20_init(\n string(abi.encodePacked(\"Ionic \", asset_.name(), \" Vault\")),\n string(abi.encodePacked(\"iv\", asset_.symbol()))\n );\n __ERC4626_init(asset_);\n\n vaultShareHWM = 10 ** asset_.decimals();\n feeRecipient = msg.sender;\n }\n\n function _asset() internal view returns (ERC20Upgradeable) {\n return ERC20Upgradeable(super.asset());\n }\n\n /* ========== DEPOSIT/WITHDRAW FUNCTIONS ========== */\n\n function deposit(uint256 assets, address receiver) public override whenNotPaused returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n _asset().safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public override whenNotPaused returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n _asset().safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(uint256 assets, address receiver, address owner) public override returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance(owner, msg.sender); // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) _approve(owner, msg.sender, allowed - shares);\n }\n\n if (!paused()) {\n uint256 balanceBeforeWithdraw = _asset().balanceOf(address(this));\n\n beforeWithdraw(assets, shares);\n\n assets = _asset().balanceOf(address(this)) - balanceBeforeWithdraw;\n }\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n _asset().safeTransfer(receiver, assets);\n }\n\n function redeem(uint256 shares, address receiver, address owner) public override returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance(owner, msg.sender); // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) _approve(owner, msg.sender, allowed - shares);\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n if (!paused()) {\n uint256 balanceBeforeWithdraw = _asset().balanceOf(address(this));\n\n beforeWithdraw(assets, shares);\n\n assets = _asset().balanceOf(address(this)) - balanceBeforeWithdraw;\n }\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n _asset().safeTransfer(receiver, assets);\n }\n\n /* ========== FEE FUNCTIONS ========== */\n\n /**\n * @notice Take the performance fee that has accrued since last fee harvest.\n * @dev Performance fee is based on a vault share high water mark value. If vault share value has increased above the\n * HWM in a fee period, issue fee shares to the vault equal to the performance fee.\n */\n function takePerformanceFee() external onlyOwner {\n require(feeRecipient != address(0), \"fee recipient not initialized\");\n\n uint256 currentAssets = totalAssets();\n uint256 shareValue = convertToAssets(10 ** _asset().decimals());\n\n require(shareValue > vaultShareHWM, \"shareValue !> vaultShareHWM\");\n // cache value\n uint256 supply = totalSupply();\n\n uint256 accruedPerformanceFee = (performanceFee * (shareValue - vaultShareHWM) * supply) / 1e36;\n _mint(feeRecipient, accruedPerformanceFee.mulDivDown(supply, (currentAssets - accruedPerformanceFee)));\n\n vaultShareHWM = convertToAssets(10 ** _asset().decimals());\n }\n\n /**\n * @notice Transfer accrued fees to rewards manager contract. Caller must be a registered keeper.\n * @dev We must make sure that feeRecipient is not address(0) before withdrawing fees\n */\n function withdrawAccruedFees() external onlyOwner {\n redeem(balanceOf(feeRecipient), feeRecipient, feeRecipient);\n }\n\n /**\n * @notice Update performanceFee and/or feeRecipient\n */\n function updateFeeSettings(uint256 newPerformanceFee, address newFeeRecipient) external onlyOwner {\n emit UpdatedFeeSettings(performanceFee, newPerformanceFee, feeRecipient, newFeeRecipient);\n\n performanceFee = newPerformanceFee;\n\n if (newFeeRecipient != feeRecipient) {\n if (feeRecipient != address(0)) {\n uint256 oldFees = balanceOf(feeRecipient);\n\n _burn(feeRecipient, oldFees);\n _approve(feeRecipient, owner(), 0);\n _mint(newFeeRecipient, oldFees);\n }\n\n _approve(newFeeRecipient, owner(), type(uint256).max);\n }\n\n feeRecipient = newFeeRecipient;\n }\n\n /* ========== EMERGENCY FUNCTIONS ========== */\n\n // Should withdraw all funds from the strategy and pause the contract\n function emergencyWithdrawAndPause() external virtual;\n\n function unpause() external virtual;\n\n function shutdown(address market) external onlyOwner whenPaused returns (uint256) {\n ERC20Upgradeable theAsset = _asset();\n uint256 endBalance = theAsset.balanceOf(address(this));\n theAsset.transfer(market, endBalance);\n return endBalance;\n }\n\n /* ========== INTERNAL HOOKS LOGIC ========== */\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual;\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual;\n}\n" + }, + "contracts/src/ionic/strategies/IonicMarketERC4626.sol": { + "content": "// SPDX-License-Identifier: Unlicense\npragma solidity ^0.8.22;\nimport { IonicERC4626, ERC20Upgradeable } from \"./IonicERC4626.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { ComptrollerErrorReporter } from \"../../compound/ErrorReporter.sol\";\n\ninterface IonicFlywheelLensRouter_4626 {\n function claimAllRewardTokens(address user) external returns (address[] memory, uint256[] memory);\n}\n\ncontract IonicMarketERC4626 is IonicERC4626 {\n using SafeERC20Upgradeable for ERC20Upgradeable;\n\n error IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error);\n\n // STATE VARIABLES\n address public rewardsRecipient;\n IonicFlywheelLensRouter_4626 public flywheelLensRouter;\n ICErc20 public cToken;\n\n function initialize(\n ICErc20 cToken_,\n address flywheelLensRouter_,\n address rewardsRecipient_\n ) public initializer {\n __IonicER4626_init(ERC20Upgradeable(cToken_.underlying()));\n cToken = cToken_;\n rewardsRecipient = rewardsRecipient_;\n flywheelLensRouter = IonicFlywheelLensRouter_4626(flywheelLensRouter_);\n }\n\n /* ========== VIEW FUNCTIONS ========== */\n function totalAssets() public view virtual override returns (uint256) {\n return cToken.balanceOfUnderlying(address(this));\n }\n\n /// @notice maximum amount of underlying tokens that can be deposited into the underlying protocol\n function maxDeposit(address) public view override returns (uint256) {\n if (cToken.comptroller().mintGuardianPaused(address(cToken))) {\n return 0;\n }\n\n uint256 supplyCap = cToken.comptroller().supplyCaps(address(cToken));\n if (supplyCap != 0) {\n uint256 currentExchangeRate = cToken.exchangeRateCurrent();\n uint256 _totalSupply = cToken.totalSupply();\n uint256 totalSupplies = (_totalSupply * currentExchangeRate) / 1e18; /// exchange rate is scaled up by 1e18, so needs to be divided off to get accurate total supply\n\n // uint256 totalCash = MToken(address(mToken)).getCash();\n // uint256 totalBorrows = MToken(address(mToken)).totalBorrows();\n // uint256 totalReserves = MToken(address(mToken)).totalReserves();\n\n // // (Pseudocode) totalSupplies = totalCash + totalBorrows - totalReserves\n // uint256 totalSupplies = (totalCash + totalBorrows) - totalReserves;\n\n // supply cap is 3\n // total supplies is 1\n /// no room for additional supplies\n\n // supply cap is 3\n // total supplies is 0\n /// room for 1 additional supplies\n\n // supply cap is 4\n // total supplies is 1\n /// room for 1 additional supplies\n\n /// total supplies could exceed supply cap as interest accrues, need to handle this edge case\n /// going to subtract 2 from supply cap to account for rounding errors\n if (totalSupplies + 2 >= supplyCap) {\n return 0;\n }\n\n return supplyCap - totalSupplies - 2;\n }\n\n return type(uint256).max;\n }\n\n /// @notice Returns the maximum amount of tokens that can be supplied\n /// no way for this function to ever revert unless comptroller or mToken is broken\n /// @dev accrue interest must be called before this function is called, otherwise\n /// an outdated value will be fetched, and the returned value will be incorrect\n /// (greater than actual amount available to be minted will be returned)\n function maxMint(address) public view override returns (uint256) {\n uint256 mintAmount = maxDeposit(address(0));\n\n return mintAmount == type(uint256).max ? mintAmount : convertToShares(mintAmount);\n }\n\n /// @notice maximum amount of underlying tokens that can be withdrawn\n /// @param owner The address that owns the shares\n function maxWithdraw(address owner) public view override returns (uint256) {\n uint256 cash = cToken.getCash();\n uint256 assetsBalance = convertToAssets(balanceOf(owner));\n return cash < assetsBalance ? cash : assetsBalance;\n }\n\n /// @notice maximum amount of shares that can be withdrawn\n /// @param owner The address that owns the shares\n function maxRedeem(address owner) public view override returns (uint256) {\n uint256 cash = cToken.getCash();\n uint256 cashInShares = convertToShares(cash);\n uint256 shareBalance = balanceOf(owner);\n return cashInShares < shareBalance ? cashInShares : shareBalance;\n }\n\n /* ========== REWARDS FUNCTIONS ========== */\n\n function updateRewardsRecipient(address newRewardsRecipient) external onlyOwner {\n emit UpdatedRewardsRecipient(rewardsRecipient, newRewardsRecipient);\n rewardsRecipient = newRewardsRecipient;\n }\n\n function claimRewards() external {\n (address[] memory tokens, uint256[] memory amounts) = flywheelLensRouter.claimAllRewardTokens(address(this));\n for (uint256 i = 0; i < tokens.length; i++) {\n _asset().safeTransfer(rewardsRecipient, amounts[i]);\n }\n }\n\n /* ========== EMERGENCY FUNCTIONS ========== */\n\n // Should withdraw all funds from the strategy and pause the contract\n function emergencyWithdrawAndPause() external override onlyOwner {\n _pause();\n }\n\n function unpause() external override onlyOwner {\n _unpause();\n }\n\n /* ========== INTERNAL HOOKS LOGIC ========== */\n\n function beforeWithdraw(uint256 assets, uint256 /*shares*/) internal override {\n /// -----------------------------------------------------------------------\n /// Withdraw assets from Ionic\n /// -----------------------------------------------------------------------\n\n uint256 errorCode = cToken.redeemUnderlying(assets);\n if (errorCode != uint256(ComptrollerErrorReporter.Error.NO_ERROR)) {\n revert IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error(errorCode));\n }\n }\n\n function afterDeposit(uint256 assets, uint256 /*shares*/) internal override {\n /// -----------------------------------------------------------------------\n /// Deposit assets into Ionic\n /// -----------------------------------------------------------------------\n\n // approve to cToken\n _asset().safeApprove(address(cToken), assets);\n\n // deposit into cToken\n uint256 errorCode = cToken.mint(assets);\n if (errorCode != uint256(ComptrollerErrorReporter.Error.NO_ERROR)) {\n revert IonicMarketERC4626__CompoundError(ComptrollerErrorReporter.Error(errorCode));\n }\n }\n}\n" + }, + "contracts/src/ionic/strategies/MockERC4626.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.0;\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\nimport { SafeTransferLib } from \"solmate/utils/SafeTransferLib.sol\";\n\nimport { ERC4626 } from \"solmate/mixins/ERC4626.sol\";\nimport { FixedPointMathLib } from \"solmate/utils/FixedPointMathLib.sol\";\n\n/**\n * @title Mock ERC4626 Contract\n * @notice ERC4626 wrapper for Tribe Token\n * @author carlomazzaferro\n *\n */\ncontract MockERC4626 is ERC4626 {\n using SafeTransferLib for ERC20;\n using FixedPointMathLib for uint256;\n\n /**\n @notice Creates a new Vault that accepts a specific underlying token.\n @param _asset The ERC20 compliant token the Vault should accept.\n */\n constructor(ERC20 _asset)\n ERC4626(\n _asset,\n string(abi.encodePacked(\"Midas \", _asset.name(), \" Vault\")),\n string(abi.encodePacked(\"mv\", _asset.symbol()))\n )\n {}\n\n /* ========== VIEWS ========== */\n\n /// @notice Calculates the total amount of underlying tokens the Vault holds.\n /// @return The total amount of underlying tokens the Vault holds.\n function totalAssets() public view override returns (uint256) {\n return asset.balanceOf(address(this));\n }\n\n /// @notice Calculates the total amount of underlying tokens the user holds.\n /// @return The total amount of underlying tokens the user holds.\n function balanceOfUnderlying(address account) public view returns (uint256) {\n return convertToAssets(balanceOf[account]);\n }\n\n /* ========== INTERNAL FUNCTIONS ========== */\n\n function afterDeposit(uint256 amount, uint256) internal override {}\n\n function beforeWithdraw(uint256, uint256 shares) internal override {}\n}\n" + }, + "contracts/src/ionic/strategies/MockERC4626Dynamic.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.0;\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\n\nimport { ERC4626 } from \"solmate/mixins/ERC4626.sol\";\nimport { FixedPointMathLib } from \"solmate/utils/FixedPointMathLib.sol\";\nimport { IonicFlywheelCore } from \"./flywheel/IonicFlywheelCore.sol\";\n\n/**\n * @title Mock ERC4626 Contract\n * @notice ERC4626 wrapper for Tribe Token\n * @author carlomazzaferro\n *\n */\ncontract MockERC4626Dynamic is ERC4626 {\n using FixedPointMathLib for uint256;\n\n /* ========== STATE VARIABLES ========== */\n IonicFlywheelCore public immutable flywheel;\n\n /* ========== INITIALIZER ========== */\n\n /**\n @notice Initializes the Vault.\n @param _asset The ERC20 compliant token the Vault should accept.\n @param _flywheel Flywheel to pull in rewardsToken\n */\n constructor(ERC20 _asset, IonicFlywheelCore _flywheel)\n ERC4626(\n _asset,\n string(abi.encodePacked(\"Midas \", _asset.name(), \" Vault\")),\n string(abi.encodePacked(\"mv\", _asset.symbol()))\n )\n {\n flywheel = _flywheel;\n }\n\n /* ========== VIEWS ========== */\n\n /// @notice Calculates the total amount of underlying tokens the Vault holds.\n /// @return The total amount of underlying tokens the Vault holds.\n function totalAssets() public view override returns (uint256) {\n return asset.balanceOf(address(this));\n }\n\n /// @notice Calculates the total amount of underlying tokens the user holds.\n /// @return The total amount of underlying tokens the user holds.\n function balanceOfUnderlying(address account) public view returns (uint256) {\n return convertToAssets(balanceOf[account]);\n }\n\n /* ========== INTERNAL FUNCTIONS ========== */\n\n function afterDeposit(uint256 amount, uint256) internal override {}\n\n function beforeWithdraw(uint256, uint256 shares) internal override {}\n}\n" + }, + "contracts/src/IonicLiquidator.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\nimport \"./liquidators/IRedemptionStrategy.sol\";\nimport \"./liquidators/IFundsConversionStrategy.sol\";\nimport \"./ILiquidator.sol\";\n\nimport \"./utils/IW_NATIVE.sol\";\n\nimport \"./external/uniswap/IUniswapV2Router02.sol\";\nimport \"./external/uniswap/IUniswapV2Pair.sol\";\nimport \"./external/uniswap/IUniswapV2Callee.sol\";\nimport \"./external/uniswap/UniswapV2Library.sol\";\nimport \"./external/pyth/IExpressRelay.sol\";\nimport \"./external/pyth/IExpressRelayFeeReceiver.sol\";\n\nimport { ICErc20 } from \"./compound/CTokenInterfaces.sol\";\n\nimport \"./PoolLens.sol\";\n\n/**\n * @title IonicLiquidator\n * @author David Lucid (https://github.com/davidlucid)\n * @notice IonicLiquidator safely liquidates unhealthy borrowers (with flashloan support).\n * @dev Do not transfer NATIVE or tokens directly to this address. Only send NATIVE here when using a method, and only approve tokens for transfer to here when using a method. Direct NATIVE transfers will be rejected and direct token transfers will be lost.\n */\ncontract IonicLiquidator is OwnableUpgradeable, ILiquidator, IUniswapV2Callee, IExpressRelayFeeReceiver {\n using AddressUpgradeable for address payable;\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n event VaultReceivedETH(address sender, uint256 amount, bytes permissionKey);\n\n /**\n * @dev W_NATIVE contract address.\n */\n address public W_NATIVE_ADDRESS;\n\n /**\n * @dev UniswapV2Router02 contract object. (Is interchangable with any UniV2 forks)\n */\n IUniswapV2Router02 public UNISWAP_V2_ROUTER_02;\n\n /**\n * @dev Cached liquidator profit exchange source.\n * ERC20 token address or the zero address for NATIVE.\n * For use in `safeLiquidateToTokensWithFlashLoan` after it is set by `postFlashLoanTokens`.\n */\n address private _liquidatorProfitExchangeSource;\n\n mapping(address => bool) public redemptionStrategiesWhitelist;\n\n /**\n * @dev Cached flash swap amount.\n * For use in `repayTokenFlashLoan` after it is set by `safeLiquidateToTokensWithFlashLoan`.\n */\n uint256 private _flashSwapAmount;\n\n /**\n * @dev Cached flash swap token.\n * For use in `repayTokenFlashLoan` after it is set by `safeLiquidateToTokensWithFlashLoan`.\n */\n address private _flashSwapToken;\n /**\n * @dev Percentage of the flash swap fee, measured in basis points.\n */\n uint8 public flashSwapFee;\n\n /**\n * @dev Addres of Pyth Express Relay for preventing value leakage in liquidations.\n */\n IExpressRelay public expressRelay;\n /**\n * @dev Pool Lens.\n */\n PoolLens public lens;\n /**\n * @dev Health Factor below which PER permissioning is bypassed.\n */\n uint256 public healthFactorThreshold;\n\n modifier onlyLowHF(address borrower, ICErc20 cToken) {\n uint256 currentHealthFactor = lens.getHealthFactor(borrower, cToken.comptroller());\n require(currentHealthFactor < healthFactorThreshold, \"HF not low enough, reserving for PYTH\");\n _;\n }\n\n function initialize(address _wtoken, address _uniswapV2router, uint8 _flashSwapFee) external initializer {\n __Ownable_init();\n require(_uniswapV2router != address(0), \"_uniswapV2router not defined.\");\n W_NATIVE_ADDRESS = _wtoken;\n UNISWAP_V2_ROUTER_02 = IUniswapV2Router02(_uniswapV2router);\n flashSwapFee = _flashSwapFee;\n }\n\n function _becomeImplementation(bytes calldata data) external {}\n\n /**\n * @dev Internal function to approve unlimited tokens of `erc20Contract` to `to`.\n */\n function safeApprove(IERC20Upgradeable token, address to, uint256 minAmount) private {\n uint256 allowance = token.allowance(address(this), to);\n\n if (allowance < minAmount) {\n if (allowance > 0) token.safeApprove(to, 0);\n token.safeApprove(to, type(uint256).max);\n }\n }\n\n /**\n * @dev Internal function to approve\n */\n function justApprove(IERC20Upgradeable token, address to, uint256 amount) private {\n token.approve(to, amount);\n }\n\n /**\n * @notice Safely liquidate an unhealthy loan (using capital from the sender), confirming that at least `minOutputAmount` in collateral is seized (or outputted by exchange if applicable).\n * @param borrower The borrower's Ethereum address.\n * @param repayAmount The amount to repay to liquidate the unhealthy loan.\n * @param cErc20 The borrowed cErc20 to repay.\n * @param cTokenCollateral The cToken collateral to be liquidated.\n * @param minOutputAmount The minimum amount of collateral to seize (or the minimum exchange output if applicable) required for execution. Reverts if this condition is not met.\n */\n function _safeLiquidate(\n address borrower,\n uint256 repayAmount,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n uint256 minOutputAmount\n ) internal returns (uint256) {\n // Transfer tokens in, approve to cErc20, and liquidate borrow\n require(repayAmount > 0, \"Repay amount (transaction value) must be greater than 0.\");\n IERC20Upgradeable underlying = IERC20Upgradeable(cErc20.underlying());\n underlying.safeTransferFrom(msg.sender, address(this), repayAmount);\n justApprove(underlying, address(cErc20), repayAmount);\n require(cErc20.liquidateBorrow(borrower, repayAmount, address(cTokenCollateral)) == 0, \"Liquidation failed.\");\n\n // Redeem seized cTokens for underlying asset\n uint256 seizedCTokenAmount = cTokenCollateral.balanceOf(address(this));\n require(seizedCTokenAmount > 0, \"No cTokens seized.\");\n uint256 redeemResult = cTokenCollateral.redeem(seizedCTokenAmount);\n require(redeemResult == 0, \"Error calling redeeming seized cToken: error code not equal to 0\");\n\n return transferSeizedFunds(address(cTokenCollateral.underlying()), minOutputAmount);\n }\n\n function safeLiquidate(\n address borrower,\n uint256 repayAmount,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n uint256 minOutputAmount\n ) external onlyLowHF(borrower, cTokenCollateral) returns (uint256) {\n return _safeLiquidate(borrower, repayAmount, cErc20, cTokenCollateral, minOutputAmount);\n }\n\n function safeLiquidatePyth(\n address borrower,\n uint256 repayAmount,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n uint256 minOutputAmount\n ) external returns (uint256) {\n require(expressRelay.isPermissioned(address(this), abi.encode(borrower)), \"invalid liquidation\");\n return _safeLiquidate(borrower, repayAmount, cErc20, cTokenCollateral, minOutputAmount);\n }\n\n /**\n * @dev Transfers seized funds to the sender.\n * @param erc20Contract The address of the token to transfer.\n * @param minOutputAmount The minimum amount to transfer.\n */\n function transferSeizedFunds(address erc20Contract, uint256 minOutputAmount) internal returns (uint256) {\n IERC20Upgradeable token = IERC20Upgradeable(erc20Contract);\n uint256 seizedOutputAmount = token.balanceOf(address(this));\n require(seizedOutputAmount >= minOutputAmount, \"Minimum token output amount not satified.\");\n if (seizedOutputAmount > 0) token.safeTransfer(msg.sender, seizedOutputAmount);\n\n return seizedOutputAmount;\n }\n\n function safeLiquidateWithAggregator(\n address borrower,\n uint256 repayAmount,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n address aggregatorTarget,\n bytes memory aggregatorData\n ) external {\n // Transfer tokens in, approve to cErc20, and liquidate borrow\n require(repayAmount > 0, \"Repay amount (transaction value) must be greater than 0.\");\n cErc20.flash(\n repayAmount,\n abi.encode(borrower, cErc20, cTokenCollateral, aggregatorTarget, aggregatorData, msg.sender)\n );\n }\n\n function receiveFlashLoan(address _underlyingBorrow, uint256 amount, bytes calldata data) external {\n (\n address borrower,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n address aggregatorTarget,\n bytes memory aggregatorData,\n address liquidator\n ) = abi.decode(data, (address, ICErc20, ICErc20, address, bytes, address));\n IERC20Upgradeable underlyingBorrow = IERC20Upgradeable(_underlyingBorrow);\n underlyingBorrow.approve(address(cErc20), amount);\n require(cErc20.liquidateBorrow(borrower, amount, address(cTokenCollateral)) == 0, \"Liquidation failed.\");\n\n // Redeem seized cTokens for underlying asset\n IERC20Upgradeable underlyingCollateral = IERC20Upgradeable(cTokenCollateral.underlying());\n {\n uint256 seizedCTokenAmount = cTokenCollateral.balanceOf(address(this));\n require(seizedCTokenAmount > 0, \"No cTokens seized.\");\n uint256 redeemResult = cTokenCollateral.redeem(seizedCTokenAmount);\n require(redeemResult == 0, \"Error calling redeeming seized cToken: error code not equal to 0\");\n uint256 underlyingCollateralRedeemed = underlyingCollateral.balanceOf(address(this));\n\n // Call the aggregator\n underlyingCollateral.approve(aggregatorTarget, underlyingCollateralRedeemed);\n (bool success, ) = aggregatorTarget.call(aggregatorData);\n require(success, \"Aggregator call failed\");\n }\n\n // receive profits\n {\n uint256 receivedAmount = underlyingBorrow.balanceOf(address(this));\n require(receivedAmount >= amount, \"Not received enough collateral after swap.\");\n uint256 profitBorrow = receivedAmount - amount;\n if (profitBorrow > 0) {\n underlyingBorrow.safeTransfer(liquidator, profitBorrow);\n }\n\n uint256 profitCollateral = underlyingCollateral.balanceOf(address(this));\n if (profitCollateral > 0) {\n underlyingCollateral.safeTransfer(liquidator, profitCollateral);\n }\n }\n\n // pay back flashloan\n underlyingBorrow.approve(address(cErc20), amount);\n }\n\n /**\n * @notice Safely liquidate an unhealthy loan, confirming that at least `minProfitAmount` in NATIVE profit is seized.\n * @param vars @see LiquidateToTokensWithFlashSwapVars.\n */\n function safeLiquidateToTokensWithFlashLoan(\n LiquidateToTokensWithFlashSwapVars calldata vars\n ) external onlyLowHF(vars.borrower, vars.cTokenCollateral) returns (uint256) {\n // Input validation\n require(vars.repayAmount > 0, \"Repay amount must be greater than 0.\");\n\n // we want to calculate the needed flashSwapAmount on-chain to\n // avoid errors due to changing market conditions\n // between the time of calculating and including the tx in a block\n uint256 fundingAmount = vars.repayAmount;\n IERC20Upgradeable fundingToken;\n if (vars.debtFundingStrategies.length > 0) {\n require(\n vars.debtFundingStrategies.length == vars.debtFundingStrategiesData.length,\n \"Funding IFundsConversionStrategy contract array and strategy data bytes array must be the same length.\"\n );\n // estimate the initial (flash-swapped token) input from the expected output (debt token)\n for (uint256 i = 0; i < vars.debtFundingStrategies.length; i++) {\n bytes memory strategyData = vars.debtFundingStrategiesData[i];\n IFundsConversionStrategy fcs = vars.debtFundingStrategies[i];\n (fundingToken, fundingAmount) = fcs.estimateInputAmount(fundingAmount, strategyData);\n }\n } else {\n fundingToken = IERC20Upgradeable(ICErc20(address(vars.cErc20)).underlying());\n }\n\n // the last outputs from estimateInputAmount are the ones to be flash-swapped\n _flashSwapAmount = fundingAmount;\n _flashSwapToken = address(fundingToken);\n\n IUniswapV2Pair flashSwapPair = IUniswapV2Pair(vars.flashSwapContract);\n bool token0IsFlashSwapFundingToken = flashSwapPair.token0() == address(fundingToken);\n flashSwapPair.swap(\n token0IsFlashSwapFundingToken ? fundingAmount : 0,\n !token0IsFlashSwapFundingToken ? fundingAmount : 0,\n address(this),\n msg.data\n );\n\n return transferSeizedFunds(_liquidatorProfitExchangeSource, vars.minProfitAmount);\n }\n\n /**\n * @dev Receives NATIVE from liquidations and flashloans.\n * Requires that `msg.sender` is W_NATIVE, a CToken, or a Uniswap V2 Router, or another contract.\n */\n receive() external payable {\n require(payable(msg.sender).isContract(), \"Sender is not a contract.\");\n }\n\n /**\n * @notice receiveAuctionProceedings function - receives native token from the express relay\n * You can use permission key to distribute the received funds to users who got liquidated, LPs, etc...\n */\n function receiveAuctionProceedings(bytes calldata permissionKey) external payable {\n emit VaultReceivedETH(msg.sender, msg.value, permissionKey);\n }\n\n function withdrawAll() external onlyOwner {\n uint256 balance = address(this).balance;\n require(balance > 0, \"No Ether left to withdraw\");\n\n // Transfer all Ether to the owner\n (bool sent, ) = msg.sender.call{ value: balance }(\"\");\n require(sent, \"Failed to send Ether\");\n }\n\n /**\n * @dev Callback function for Uniswap flashloans.\n */\n function uniswapV2Call(address, uint256, uint256, bytes calldata data) public override {\n // Liquidate unhealthy borrow, exchange seized collateral, return flashloaned funds, and exchange profit\n // Decode params\n LiquidateToTokensWithFlashSwapVars memory vars = abi.decode(data[4:], (LiquidateToTokensWithFlashSwapVars));\n\n // Post token flashloan\n // Cache liquidation profit token (or the zero address for NATIVE) for use as source for exchange later\n _liquidatorProfitExchangeSource = postFlashLoanTokens(vars);\n }\n\n /**\n * @dev Callback function for PCS flashloans.\n */\n function pancakeCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {\n uniswapV2Call(sender, amount0, amount1, data);\n }\n\n function moraswapCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external {\n uniswapV2Call(sender, amount0, amount1, data);\n }\n\n /**\n * @dev Liquidate unhealthy token borrow, exchange seized collateral, return flashloaned funds, and exchange profit.\n */\n function postFlashLoanTokens(LiquidateToTokensWithFlashSwapVars memory vars) private returns (address) {\n IERC20Upgradeable debtRepaymentToken = IERC20Upgradeable(_flashSwapToken);\n uint256 debtRepaymentAmount = _flashSwapAmount;\n\n if (vars.debtFundingStrategies.length > 0) {\n // loop backwards to convert the initial (flash-swapped token) input to the final expected output (debt token)\n for (uint256 i = vars.debtFundingStrategies.length; i > 0; i--) {\n (debtRepaymentToken, debtRepaymentAmount) = convertCustomFunds(\n debtRepaymentToken,\n debtRepaymentAmount,\n vars.debtFundingStrategies[i - 1],\n vars.debtFundingStrategiesData[i - 1]\n );\n }\n }\n\n // Approve the debt repayment transfer, liquidate and redeem the seized collateral\n {\n address underlyingBorrow = vars.cErc20.underlying();\n require(\n address(debtRepaymentToken) == underlyingBorrow,\n \"the debt repayment funds should be converted to the underlying debt token\"\n );\n require(debtRepaymentAmount >= vars.repayAmount, \"debt repayment amount not enough\");\n // Approve repayAmount to cErc20\n justApprove(IERC20Upgradeable(underlyingBorrow), address(vars.cErc20), vars.repayAmount);\n\n // Liquidate borrow\n require(\n vars.cErc20.liquidateBorrow(vars.borrower, vars.repayAmount, address(vars.cTokenCollateral)) == 0,\n \"Liquidation failed.\"\n );\n\n // Redeem seized cTokens for underlying asset\n uint256 seizedCTokenAmount = vars.cTokenCollateral.balanceOf(address(this));\n require(seizedCTokenAmount > 0, \"No cTokens seized.\");\n uint256 redeemResult = vars.cTokenCollateral.redeem(seizedCTokenAmount);\n require(redeemResult == 0, \"Error calling redeeming seized cToken: error code not equal to 0\");\n }\n\n // Repay flashloan\n return repayTokenFlashLoan(vars.cTokenCollateral, vars.redemptionStrategies, vars.strategyData);\n }\n\n /**\n * @dev Repays token flashloans.\n */\n function repayTokenFlashLoan(\n ICErc20 cTokenCollateral,\n IRedemptionStrategy[] memory redemptionStrategies,\n bytes[] memory strategyData\n ) private returns (address) {\n // Calculate flashloan return amount\n uint256 flashSwapReturnAmount = (_flashSwapAmount * 10000) / (10000 - flashSwapFee);\n if ((_flashSwapAmount * 10000) % (10000 - flashSwapFee) > 0) flashSwapReturnAmount++; // Round up if division resulted in a remainder\n\n // Swap cTokenCollateral for cErc20 via Uniswap\n // Check underlying collateral seized\n IERC20Upgradeable underlyingCollateral = IERC20Upgradeable(ICErc20(address(cTokenCollateral)).underlying());\n uint256 underlyingCollateralSeized = underlyingCollateral.balanceOf(address(this));\n\n // Redeem custom collateral if liquidation strategy is set\n if (redemptionStrategies.length > 0) {\n require(\n redemptionStrategies.length == strategyData.length,\n \"IRedemptionStrategy contract array and strategy data bytes array mnust the the same length.\"\n );\n for (uint256 i = 0; i < redemptionStrategies.length; i++)\n (underlyingCollateral, underlyingCollateralSeized) = redeemCustomCollateral(\n underlyingCollateral,\n underlyingCollateralSeized,\n redemptionStrategies[i],\n strategyData[i]\n );\n }\n\n IUniswapV2Pair pair = IUniswapV2Pair(msg.sender);\n\n // Check if we can repay directly one of the sides with collateral\n if (address(underlyingCollateral) == pair.token0() || address(underlyingCollateral) == pair.token1()) {\n // Repay flashloan directly with collateral\n uint256 collateralRequired;\n if (address(underlyingCollateral) == _flashSwapToken) {\n // repay amount for the borrow side\n collateralRequired = flashSwapReturnAmount;\n } else {\n // repay amount for the non-borrow side\n collateralRequired = UniswapV2Library.getAmountsIn(\n UNISWAP_V2_ROUTER_02.factory(),\n _flashSwapAmount, //flashSwapReturnAmount,\n array(address(underlyingCollateral), _flashSwapToken),\n flashSwapFee\n )[0];\n }\n\n // Repay flashloan\n require(\n collateralRequired <= underlyingCollateralSeized,\n \"Token flashloan return amount greater than seized collateral.\"\n );\n require(\n underlyingCollateral.transfer(msg.sender, collateralRequired),\n \"Failed to repay token flashloan on borrow side.\"\n );\n\n return address(underlyingCollateral);\n } else {\n // exchange the collateral to W_NATIVE to repay the borrow side\n uint256 wethRequired;\n if (_flashSwapToken == W_NATIVE_ADDRESS) {\n wethRequired = flashSwapReturnAmount;\n } else {\n // Get W_NATIVE required to repay flashloan\n wethRequired = UniswapV2Library.getAmountsIn(\n UNISWAP_V2_ROUTER_02.factory(),\n flashSwapReturnAmount,\n array(W_NATIVE_ADDRESS, _flashSwapToken),\n flashSwapFee\n )[0];\n }\n\n if (address(underlyingCollateral) != W_NATIVE_ADDRESS) {\n // Approve to Uniswap router\n justApprove(underlyingCollateral, address(UNISWAP_V2_ROUTER_02), underlyingCollateralSeized);\n\n // Swap collateral tokens for W_NATIVE to be repaid via Uniswap router\n UNISWAP_V2_ROUTER_02.swapTokensForExactTokens(\n wethRequired,\n underlyingCollateralSeized,\n array(address(underlyingCollateral), W_NATIVE_ADDRESS),\n address(this),\n block.timestamp\n );\n }\n\n // Repay flashloan\n require(\n wethRequired <= IERC20Upgradeable(W_NATIVE_ADDRESS).balanceOf(address(this)),\n \"Not enough W_NATIVE exchanged from seized collateral to repay flashloan.\"\n );\n require(\n IW_NATIVE(W_NATIVE_ADDRESS).transfer(msg.sender, wethRequired),\n \"Failed to repay Uniswap flashloan with W_NATIVE exchanged from seized collateral.\"\n );\n\n // Return the profited token (underlying collateral if same as exchangeProfitTo; otherwise, W_NATIVE)\n return address(underlyingCollateral);\n }\n }\n\n /**\n * @dev for security reasons only whitelisted redemption strategies may be used.\n * Each whitelisted redemption strategy has to be checked to not be able to\n * call `selfdestruct` with the `delegatecall` call in `redeemCustomCollateral`\n */\n function _whitelistRedemptionStrategy(IRedemptionStrategy strategy, bool whitelisted) external onlyOwner {\n redemptionStrategiesWhitelist[address(strategy)] = whitelisted;\n }\n\n /**\n * @dev for security reasons only whitelisted redemption strategies may be used.\n * Each whitelisted redemption strategy has to be checked to not be able to\n * call `selfdestruct` with the `delegatecall` call in `redeemCustomCollateral`\n */\n function _whitelistRedemptionStrategies(\n IRedemptionStrategy[] calldata strategies,\n bool[] calldata whitelisted\n ) external onlyOwner {\n require(\n strategies.length > 0 && strategies.length == whitelisted.length,\n \"list of strategies empty or whitelist does not match its length\"\n );\n\n for (uint256 i = 0; i < strategies.length; i++) {\n redemptionStrategiesWhitelist[address(strategies[i])] = whitelisted[i];\n }\n }\n\n function setExpressRelay(address _expressRelay) external onlyOwner {\n expressRelay = IExpressRelay(_expressRelay);\n }\n\n function setPoolLens(address _poolLens) external onlyOwner {\n lens = PoolLens(_poolLens);\n }\n\n function setHealthFactorThreshold(uint256 _healthFactorThreshold) external onlyOwner {\n require(_healthFactorThreshold <= 1e18, \"Invalid Health Factor Threshold\");\n healthFactorThreshold = _healthFactorThreshold;\n }\n\n /**\n * @dev Redeem \"special\" collateral tokens (before swapping the output for borrowed tokens to be repaid via Uniswap).\n * Public visibility because we have to call this function externally if called from a payable IonicLiquidator function (for some reason delegatecall fails when called with msg.value > 0).\n */\n function redeemCustomCollateral(\n IERC20Upgradeable underlyingCollateral,\n uint256 underlyingCollateralSeized,\n IRedemptionStrategy strategy,\n bytes memory strategyData\n ) private returns (IERC20Upgradeable, uint256) {\n require(redemptionStrategiesWhitelist[address(strategy)], \"only whitelisted redemption strategies can be used\");\n\n bytes memory returndata = _functionDelegateCall(\n address(strategy),\n abi.encodeWithSelector(strategy.redeem.selector, underlyingCollateral, underlyingCollateralSeized, strategyData)\n );\n return abi.decode(returndata, (IERC20Upgradeable, uint256));\n }\n\n function convertCustomFunds(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n IFundsConversionStrategy strategy,\n bytes memory strategyData\n ) private returns (IERC20Upgradeable, uint256) {\n require(redemptionStrategiesWhitelist[address(strategy)], \"only whitelisted redemption strategies can be used\");\n\n bytes memory returndata = _functionDelegateCall(\n address(strategy),\n abi.encodeWithSelector(strategy.convert.selector, inputToken, inputAmount, strategyData)\n );\n return abi.decode(returndata, (IERC20Upgradeable, uint256));\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but performing a delegate call.\n * Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/contracts/blob/cb4774ace1cb84f2662fa47c573780aab937628b/contracts/utils/MulticallUpgradeable.sol#L37\n */\n function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {\n require(AddressUpgradeable.isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Used by `_functionDelegateCall` to verify the result of a delegate call.\n * Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/contracts/blob/cb4774ace1cb84f2662fa47c573780aab937628b/contracts/utils/MulticallUpgradeable.sol#L45\n */\n function _verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) private pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n\n /**\n * @dev Returns an array containing the parameters supplied.\n */\n function array(address a, address b) private pure returns (address[] memory) {\n address[] memory arr = new address[](2);\n arr[0] = a;\n arr[1] = b;\n return arr;\n }\n}\n" + }, + "contracts/src/IonicUniV3Liquidator.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\nimport \"./liquidators/IRedemptionStrategy.sol\";\nimport \"./liquidators/IFundsConversionStrategy.sol\";\nimport \"./ILiquidator.sol\";\n\nimport \"./external/uniswap/IUniswapV3FlashCallback.sol\";\nimport \"./external/uniswap/IUniswapV3Pool.sol\";\nimport \"./external/pyth/IExpressRelay.sol\";\nimport \"./external/pyth/IExpressRelayFeeReceiver.sol\";\nimport { IUniswapV3Quoter } from \"./external/uniswap/quoter/interfaces/IUniswapV3Quoter.sol\";\nimport { IFlashLoanReceiver } from \"./ionic/IFlashLoanReceiver.sol\";\n\nimport { ICErc20 } from \"./compound/CTokenInterfaces.sol\";\n\nimport \"./PoolLens.sol\";\n\n/**\n * @title IonicUniV3Liquidator\n * @author Veliko Minkov (https://github.com/vminkov)\n * @notice IonicUniV3Liquidator liquidates unhealthy borrowers with flashloan support.\n */\ncontract IonicUniV3Liquidator is\n OwnableUpgradeable,\n ILiquidator,\n IUniswapV3FlashCallback,\n IExpressRelayFeeReceiver,\n IFlashLoanReceiver\n{\n using AddressUpgradeable for address payable;\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n event VaultReceivedETH(address sender, uint256 amount, bytes permissionKey);\n /**\n * @dev Cached liquidator profit exchange source.\n * ERC20 token address or the zero address for NATIVE.\n * For use in `safeLiquidateToTokensWithFlashLoan` after it is set by `postFlashLoanTokens`.\n */\n address private _liquidatorProfitExchangeSource;\n\n /**\n * @dev Cached flash swap amount.\n * For use in `repayTokenFlashLoan` after it is set by `safeLiquidateToTokensWithFlashLoan`.\n */\n uint256 private _flashSwapAmount;\n\n /**\n * @dev Cached flash swap token.\n * For use in `repayTokenFlashLoan` after it is set by `safeLiquidateToTokensWithFlashLoan`.\n */\n address private _flashSwapToken;\n\n address public W_NATIVE_ADDRESS;\n mapping(address => bool) public redemptionStrategiesWhitelist;\n IUniswapV3Quoter public quoter;\n\n /**\n * @dev Addres of Pyth Express Relay for preventing value leakage in liquidations.\n */\n IExpressRelay public expressRelay;\n /**\n * @dev Pool Lens.\n */\n PoolLens public lens;\n /**\n * @dev Health Factor below which PER permissioning is bypassed.\n */\n uint256 public healthFactorThreshold;\n\n modifier onlyLowHF(address borrower, ICErc20 cToken) {\n uint256 currentHealthFactor = lens.getHealthFactor(borrower, cToken.comptroller());\n require(currentHealthFactor < healthFactorThreshold, \"HF not low enough, reserving for PYTH\");\n _;\n }\n\n function initialize(address _wtoken, address _quoter) external initializer {\n __Ownable_init();\n W_NATIVE_ADDRESS = _wtoken;\n quoter = IUniswapV3Quoter(_quoter);\n }\n\n /**\n * @notice Safely liquidate an unhealthy loan (using capital from the sender), confirming that at least `minOutputAmount` in collateral is seized (or outputted by exchange if applicable).\n * @param borrower The borrower's Ethereum address.\n * @param repayAmount The amount to repay to liquidate the unhealthy loan.\n * @param cErc20 The borrowed cErc20 to repay.\n * @param cTokenCollateral The cToken collateral to be liquidated.\n * @param minOutputAmount The minimum amount of collateral to seize (or the minimum exchange output if applicable) required for execution. Reverts if this condition is not met.\n */\n function _safeLiquidate(\n address borrower,\n uint256 repayAmount,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n uint256 minOutputAmount\n ) internal returns (uint256) {\n // Transfer tokens in, approve to cErc20, and liquidate borrow\n require(repayAmount > 0, \"Repay amount (transaction value) must be greater than 0.\");\n IERC20Upgradeable underlying = IERC20Upgradeable(cErc20.underlying());\n underlying.safeTransferFrom(msg.sender, address(this), repayAmount);\n underlying.approve(address(cErc20), repayAmount);\n require(cErc20.liquidateBorrow(borrower, repayAmount, address(cTokenCollateral)) == 0, \"Liquidation failed.\");\n\n // Redeem seized cTokens for underlying asset\n uint256 seizedCTokenAmount = cTokenCollateral.balanceOf(address(this));\n require(seizedCTokenAmount > 0, \"No cTokens seized.\");\n uint256 redeemResult = cTokenCollateral.redeem(seizedCTokenAmount);\n require(redeemResult == 0, \"Error calling redeeming seized cToken: error code not equal to 0\");\n\n return transferSeizedFunds(address(cTokenCollateral.underlying()), minOutputAmount);\n }\n\n function safeLiquidate(\n address borrower,\n uint256 repayAmount,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n uint256 minOutputAmount\n ) external onlyLowHF(borrower, cTokenCollateral) returns (uint256) {\n return _safeLiquidate(borrower, repayAmount, cErc20, cTokenCollateral, minOutputAmount);\n }\n\n function safeLiquidatePyth(\n address borrower,\n uint256 repayAmount,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n uint256 minOutputAmount\n ) external returns (uint256) {\n require(expressRelay.isPermissioned(address(this), abi.encode(borrower)), \"invalid liquidation\");\n return _safeLiquidate(borrower, repayAmount, cErc20, cTokenCollateral, minOutputAmount);\n }\n\n function safeLiquidateWithAggregator(\n address borrower,\n uint256 repayAmount,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n address aggregatorTarget,\n bytes memory aggregatorData\n ) external {\n // Transfer tokens in, approve to cErc20, and liquidate borrow\n require(repayAmount > 0, \"Repay amount (transaction value) must be greater than 0.\");\n cErc20.flash(\n repayAmount,\n abi.encode(borrower, cErc20, cTokenCollateral, aggregatorTarget, aggregatorData, msg.sender)\n );\n }\n\n function receiveFlashLoan(address _underlyingBorrow, uint256 amount, bytes calldata data) external {\n (\n address borrower,\n ICErc20 cErc20,\n ICErc20 cTokenCollateral,\n address aggregatorTarget,\n bytes memory aggregatorData,\n address liquidator\n ) = abi.decode(data, (address, ICErc20, ICErc20, address, bytes, address));\n IERC20Upgradeable underlyingBorrow = IERC20Upgradeable(_underlyingBorrow);\n underlyingBorrow.approve(address(cErc20), amount);\n require(cErc20.liquidateBorrow(borrower, amount, address(cTokenCollateral)) == 0, \"Liquidation failed.\");\n\n // Redeem seized cTokens for underlying asset\n IERC20Upgradeable underlyingCollateral = IERC20Upgradeable(cTokenCollateral.underlying());\n {\n uint256 seizedCTokenAmount = cTokenCollateral.balanceOf(address(this));\n require(seizedCTokenAmount > 0, \"No cTokens seized.\");\n uint256 redeemResult = cTokenCollateral.redeem(seizedCTokenAmount);\n require(redeemResult == 0, \"Error calling redeeming seized cToken: error code not equal to 0\");\n uint256 underlyingCollateralRedeemed = underlyingCollateral.balanceOf(address(this));\n\n // Call the aggregator\n underlyingCollateral.approve(aggregatorTarget, underlyingCollateralRedeemed);\n (bool success, ) = aggregatorTarget.call(aggregatorData);\n require(success, \"Aggregator call failed\");\n }\n\n // receive profits\n {\n uint256 receivedAmount = underlyingBorrow.balanceOf(address(this));\n require(receivedAmount >= amount, \"Not received enough collateral after swap.\");\n uint256 profitBorrow = receivedAmount - amount;\n if (profitBorrow > 0) {\n underlyingBorrow.safeTransfer(liquidator, profitBorrow);\n }\n\n uint256 profitCollateral = underlyingCollateral.balanceOf(address(this));\n if (profitCollateral > 0) {\n underlyingCollateral.safeTransfer(liquidator, profitCollateral);\n }\n }\n\n // pay back flashloan\n underlyingBorrow.approve(address(cErc20), amount);\n }\n\n /**\n * @dev Transfers seized funds to the sender.\n * @param erc20Contract The address of the token to transfer.\n * @param minOutputAmount The minimum amount to transfer.\n */\n function transferSeizedFunds(address erc20Contract, uint256 minOutputAmount) internal returns (uint256) {\n IERC20Upgradeable token = IERC20Upgradeable(erc20Contract);\n uint256 seizedOutputAmount = token.balanceOf(address(this));\n require(seizedOutputAmount >= minOutputAmount, \"Minimum token output amount not satified.\");\n if (seizedOutputAmount > 0) token.safeTransfer(msg.sender, seizedOutputAmount);\n\n return seizedOutputAmount;\n }\n\n function safeLiquidateToTokensWithFlashLoan(\n LiquidateToTokensWithFlashSwapVars calldata vars\n ) external onlyLowHF(vars.borrower, vars.cTokenCollateral) returns (uint256) {\n // Input validation\n require(vars.repayAmount > 0, \"Repay amount must be greater than 0.\");\n\n // we want to calculate the needed flashSwapAmount on-chain to\n // avoid errors due to changing market conditions\n // between the time of calculating and including the tx in a block\n uint256 fundingAmount = vars.repayAmount;\n IERC20Upgradeable fundingToken;\n if (vars.debtFundingStrategies.length > 0) {\n require(\n vars.debtFundingStrategies.length == vars.debtFundingStrategiesData.length,\n \"Funding IFundsConversionStrategy contract array and strategy data bytes array must be the same length.\"\n );\n // estimate the initial (flash-swapped token) input from the expected output (debt token)\n for (uint256 i = 0; i < vars.debtFundingStrategies.length; i++) {\n bytes memory strategyData = vars.debtFundingStrategiesData[i];\n IFundsConversionStrategy fcs = vars.debtFundingStrategies[i];\n (fundingToken, fundingAmount) = fcs.estimateInputAmount(fundingAmount, strategyData);\n }\n } else {\n fundingToken = IERC20Upgradeable(ICErc20(address(vars.cErc20)).underlying());\n }\n\n // the last outputs from estimateInputAmount are the ones to be flash-swapped\n _flashSwapAmount = fundingAmount;\n _flashSwapToken = address(fundingToken);\n\n IUniswapV3Pool flashSwapPool = IUniswapV3Pool(vars.flashSwapContract);\n bool token0IsFlashSwapFundingToken = flashSwapPool.token0() == address(fundingToken);\n flashSwapPool.flash(\n address(this),\n token0IsFlashSwapFundingToken ? fundingAmount : 0,\n !token0IsFlashSwapFundingToken ? fundingAmount : 0,\n msg.data\n );\n\n return transferSeizedFunds(_liquidatorProfitExchangeSource, vars.minProfitAmount);\n }\n\n /**\n * @dev Receives NATIVE from liquidations and flashloans.\n * Requires that `msg.sender` is W_NATIVE, a CToken, or a Uniswap V2 Router, or another contract.\n */\n receive() external payable {\n require(payable(msg.sender).isContract(), \"Sender is not a contract.\");\n }\n\n /**\n * @notice receiveAuctionProceedings function - receives native token from the express relay\n * You can use permission key to distribute the received funds to users who got liquidated, LPs, etc...\n */\n function receiveAuctionProceedings(bytes calldata permissionKey) external payable {\n emit VaultReceivedETH(msg.sender, msg.value, permissionKey);\n }\n\n function withdrawAll() external onlyOwner {\n uint256 balance = address(this).balance;\n require(balance > 0, \"No Ether left to withdraw\");\n\n // Transfer all Ether to the owner\n (bool sent, ) = msg.sender.call{ value: balance }(\"\");\n require(sent, \"Failed to send Ether\");\n }\n\n /**\n * @dev Callback function for Uniswap flashloans.\n */\n\n function supV3FlashCallback(uint256 fee0, uint256 fee1, bytes calldata data) external {\n uniswapV3FlashCallback(fee0, fee1, data);\n }\n\n function algebraFlashCallback(uint256 fee0, uint256 fee1, bytes calldata data) external {\n uniswapV3FlashCallback(fee0, fee1, data);\n }\n\n function uniswapV3FlashCallback(uint256 fee0, uint256 fee1, bytes calldata data) public {\n // Liquidate unhealthy borrow, exchange seized collateral, return flashloaned funds, and exchange profit\n // Decode params\n LiquidateToTokensWithFlashSwapVars memory vars = abi.decode(data[4:], (LiquidateToTokensWithFlashSwapVars));\n\n // Post token flashloan\n // Cache liquidation profit token (or the zero address for NATIVE) for use as source for exchange later\n _liquidatorProfitExchangeSource = postFlashLoanTokens(vars, fee0, fee1);\n }\n\n /**\n * @dev Liquidate unhealthy token borrow, exchange seized collateral, return flashloaned funds, and exchange profit.\n */\n function postFlashLoanTokens(\n LiquidateToTokensWithFlashSwapVars memory vars,\n uint256 fee0,\n uint256 fee1\n ) private returns (address) {\n IERC20Upgradeable debtRepaymentToken = IERC20Upgradeable(_flashSwapToken);\n uint256 debtRepaymentAmount = _flashSwapAmount;\n\n if (vars.debtFundingStrategies.length > 0) {\n // loop backwards to convert the initial (flash-swapped token) input to the final expected output (debt token)\n for (uint256 i = vars.debtFundingStrategies.length; i > 0; i--) {\n (debtRepaymentToken, debtRepaymentAmount) = convertCustomFunds(\n debtRepaymentToken,\n debtRepaymentAmount,\n vars.debtFundingStrategies[i - 1],\n vars.debtFundingStrategiesData[i - 1]\n );\n }\n }\n\n // Approve the debt repayment transfer, liquidate and redeem the seized collateral\n {\n address underlyingBorrow = vars.cErc20.underlying();\n require(\n address(debtRepaymentToken) == underlyingBorrow,\n \"the debt repayment funds should be converted to the underlying debt token\"\n );\n require(debtRepaymentAmount >= vars.repayAmount, \"debt repayment amount not enough\");\n // Approve repayAmount to cErc20\n IERC20Upgradeable(underlyingBorrow).approve(address(vars.cErc20), vars.repayAmount);\n\n // Liquidate borrow\n require(\n vars.cErc20.liquidateBorrow(vars.borrower, vars.repayAmount, address(vars.cTokenCollateral)) == 0,\n \"Liquidation failed.\"\n );\n\n // Redeem seized cTokens for underlying asset\n uint256 seizedCTokenAmount = vars.cTokenCollateral.balanceOf(address(this));\n require(seizedCTokenAmount > 0, \"No cTokens seized.\");\n uint256 redeemResult = vars.cTokenCollateral.redeem(seizedCTokenAmount);\n require(redeemResult == 0, \"Error calling redeeming seized cToken: error code not equal to 0\");\n }\n\n // Repay flashloan\n return repayTokenFlashLoan(vars.cTokenCollateral, vars.redemptionStrategies, vars.strategyData, fee0, fee1);\n }\n\n /**\n * @dev Repays token flashloans.\n */\n function repayTokenFlashLoan(\n ICErc20 cTokenCollateral,\n IRedemptionStrategy[] memory redemptionStrategies,\n bytes[] memory strategyData,\n uint256 fee0,\n uint256 fee1\n ) private returns (address) {\n IUniswapV3Pool pool = IUniswapV3Pool(msg.sender);\n uint256 flashSwapReturnAmount = _flashSwapAmount;\n if (IUniswapV3Pool(msg.sender).token0() == _flashSwapToken) {\n flashSwapReturnAmount += fee0;\n } else if (IUniswapV3Pool(msg.sender).token1() == _flashSwapToken) {\n flashSwapReturnAmount += fee1;\n } else {\n revert(\"wrong pool or _flashSwapToken\");\n }\n\n // Swap cTokenCollateral for cErc20 via Uniswap\n // Check underlying collateral seized\n IERC20Upgradeable underlyingCollateral = IERC20Upgradeable(ICErc20(address(cTokenCollateral)).underlying());\n uint256 underlyingCollateralSeized = underlyingCollateral.balanceOf(address(this));\n\n // Redeem custom collateral if liquidation strategy is set\n if (redemptionStrategies.length > 0) {\n require(\n redemptionStrategies.length == strategyData.length,\n \"IRedemptionStrategy contract array and strategy data bytes array mnust the the same length.\"\n );\n for (uint256 i = 0; i < redemptionStrategies.length; i++)\n (underlyingCollateral, underlyingCollateralSeized) = redeemCustomCollateral(\n underlyingCollateral,\n underlyingCollateralSeized,\n redemptionStrategies[i],\n strategyData[i]\n );\n }\n\n // Check if we can repay directly one of the sides with collateral\n if (address(underlyingCollateral) == pool.token0() || address(underlyingCollateral) == pool.token1()) {\n // Repay flashloan directly with collateral\n uint256 collateralRequired;\n if (address(underlyingCollateral) == _flashSwapToken) {\n // repay the borrowed asset directly\n collateralRequired = flashSwapReturnAmount;\n\n // Repay flashloan\n IERC20Upgradeable(_flashSwapToken).transfer(address(pool), flashSwapReturnAmount);\n } else {\n // TODO swap within the same pool and then repay the FL to the pool\n bool zeroForOne = address(underlyingCollateral) == pool.token0();\n\n {\n collateralRequired = quoter.quoteExactOutputSingle(\n zeroForOne ? pool.token0() : pool.token1(),\n zeroForOne ? pool.token1() : pool.token0(),\n pool.fee(),\n _flashSwapAmount,\n 0 // sqrtPriceLimitX96\n );\n }\n require(\n collateralRequired <= underlyingCollateralSeized,\n \"Token flashloan return amount greater than seized collateral.\"\n );\n\n // Repay flashloan\n pool.swap(\n address(pool),\n zeroForOne,\n int256(collateralRequired),\n 0, // sqrtPriceLimitX96\n \"\"\n );\n }\n\n return address(underlyingCollateral);\n } else {\n revert(\"the redemptions strategy did not swap to the flash swapped pool assets\");\n }\n }\n\n /**\n * @dev for security reasons only whitelisted redemption strategies may be used.\n * Each whitelisted redemption strategy has to be checked to not be able to\n * call `selfdestruct` with the `delegatecall` call in `redeemCustomCollateral`\n */\n function _whitelistRedemptionStrategy(IRedemptionStrategy strategy, bool whitelisted) external onlyOwner {\n redemptionStrategiesWhitelist[address(strategy)] = whitelisted;\n }\n\n /**\n * @dev for security reasons only whitelisted redemption strategies may be used.\n * Each whitelisted redemption strategy has to be checked to not be able to\n * call `selfdestruct` with the `delegatecall` call in `redeemCustomCollateral`\n */\n function _whitelistRedemptionStrategies(\n IRedemptionStrategy[] calldata strategies,\n bool[] calldata whitelisted\n ) external onlyOwner {\n require(\n strategies.length > 0 && strategies.length == whitelisted.length,\n \"list of strategies empty or whitelist does not match its length\"\n );\n\n for (uint256 i = 0; i < strategies.length; i++) {\n redemptionStrategiesWhitelist[address(strategies[i])] = whitelisted[i];\n }\n }\n\n function setExpressRelay(address _expressRelay) external onlyOwner {\n expressRelay = IExpressRelay(_expressRelay);\n }\n\n function setPoolLens(address _poolLens) external onlyOwner {\n lens = PoolLens(_poolLens);\n }\n\n function setHealthFactorThreshold(uint256 _healthFactorThreshold) external onlyOwner {\n require(_healthFactorThreshold <= 1e18, \"Invalid Health Factor Threshold\");\n healthFactorThreshold = _healthFactorThreshold;\n }\n\n /**\n * @dev Redeem \"special\" collateral tokens (before swapping the output for borrowed tokens to be repaid via Uniswap).\n * Public visibility because we have to call this function externally if called from a payable IonicLiquidator function (for some reason delegatecall fails when called with msg.value > 0).\n */\n function redeemCustomCollateral(\n IERC20Upgradeable underlyingCollateral,\n uint256 underlyingCollateralSeized,\n IRedemptionStrategy strategy,\n bytes memory strategyData\n ) private returns (IERC20Upgradeable, uint256) {\n require(redemptionStrategiesWhitelist[address(strategy)], \"only whitelisted redemption strategies can be used\");\n\n bytes memory returndata = _functionDelegateCall(\n address(strategy),\n abi.encodeWithSelector(strategy.redeem.selector, underlyingCollateral, underlyingCollateralSeized, strategyData)\n );\n return abi.decode(returndata, (IERC20Upgradeable, uint256));\n }\n\n function convertCustomFunds(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n IFundsConversionStrategy strategy,\n bytes memory strategyData\n ) private returns (IERC20Upgradeable, uint256) {\n require(redemptionStrategiesWhitelist[address(strategy)], \"only whitelisted redemption strategies can be used\");\n\n bytes memory returndata = _functionDelegateCall(\n address(strategy),\n abi.encodeWithSelector(strategy.convert.selector, inputToken, inputAmount, strategyData)\n );\n return abi.decode(returndata, (IERC20Upgradeable, uint256));\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but performing a delegate call.\n * Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/contracts/blob/cb4774ace1cb84f2662fa47c573780aab937628b/contracts/utils/MulticallUpgradeable.sol#L37\n */\n function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {\n require(AddressUpgradeable.isContract(target), \"Address: delegate call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Used by `_functionDelegateCall` to verify the result of a delegate call.\n * Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/contracts/blob/cb4774ace1cb84f2662fa47c573780aab937628b/contracts/utils/MulticallUpgradeable.sol#L45\n */\n function _verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) private pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" + }, + "contracts/src/liquidators/AerodromeCLLiquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IRedemptionStrategy } from \"./IRedemptionStrategy.sol\";\nimport { ISwapRouter_Aerodrome } from \"../external/aerodrome/IAerodromeSwapRouter.sol\";\n\nimport { IERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport { IERC4626 } from \"../compound/IERC4626.sol\";\n\ncontract AerodromeCLLiquidator is IRedemptionStrategy {\n /**\n * @dev Redeems `inputToken` for `outputToken` where `inputAmount` < `outputAmount`\n * @param inputToken Address of the token\n * @param inputAmount input amount\n * @param strategyData context specific data like input token, pool address and tx expiratio period\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n function _convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) internal returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n (\n ,\n address _outputToken,\n ISwapRouter_Aerodrome swapRouter,\n address _unwrappedInput,\n address _unwrappedOutput,\n int24 _tickSpacing\n ) = abi.decode(strategyData, (address, address, ISwapRouter_Aerodrome, address, address, int24));\n if (_unwrappedOutput != address(0)) {\n outputToken = IERC20Upgradeable(_unwrappedOutput);\n } else {\n outputToken = IERC20Upgradeable(_outputToken);\n }\n\n if (_unwrappedInput != address(0)) {\n inputToken.approve(address(inputToken), inputAmount);\n inputAmount = IERC4626(address(inputToken)).redeem(inputAmount, address(this), address(this));\n inputToken = IERC20Upgradeable(_unwrappedInput);\n }\n\n inputToken.approve(address(swapRouter), inputAmount);\n\n outputAmount = swapRouter.exactInputSingle(\n ISwapRouter_Aerodrome.ExactInputSingleParams(\n address(inputToken),\n address(outputToken),\n _tickSpacing,\n address(this),\n block.timestamp,\n inputAmount,\n 0,\n 0\n )\n );\n\n if (_unwrappedOutput != address(0)) {\n IERC20Upgradeable(_unwrappedOutput).approve(address(_outputToken), outputAmount);\n IERC4626(_outputToken).deposit(outputAmount, address(this));\n outputAmount = IERC4626(_unwrappedOutput).balanceOf(address(this));\n outputToken = IERC20Upgradeable(_outputToken);\n }\n }\n\n function name() public pure virtual override returns (string memory) {\n return \"AerodromeCLLiquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/AerodromeV2Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\nimport { IRouter_Aerodrome } from \"../external/aerodrome/IAerodromeRouter.sol\";\n\n/**\n * @title AerodromeV2Liquidator\n * @notice Exchanges seized token collateral for underlying tokens via a Aerodrome V2 router for use as a step in a liquidation.\n */\ncontract AerodromeV2Liquidator {\n function _swap(IRouter_Aerodrome router, uint256 inputAmount, IRouter_Aerodrome.Route[] memory swapPath) internal {\n router.swapExactTokensForTokens(inputAmount, 0, swapPath, address(this), block.timestamp);\n }\n\n function name() public pure virtual returns (string memory) {\n return \"AerodromeV2Liquidator\";\n }\n\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n function _convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) internal returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n // Get Uniswap router and path\n (IRouter_Aerodrome router, IRouter_Aerodrome.Route[] memory swapPath) = abi.decode(\n strategyData,\n (IRouter_Aerodrome, IRouter_Aerodrome.Route[])\n );\n require(\n swapPath.length >= 1 && swapPath[0].from == address(inputToken),\n \"Invalid AerodromeV2Liquidator swap path.\"\n );\n\n // Swap underlying tokens\n inputToken.approve(address(router), inputAmount);\n\n // call the relevant fn depending on the uni v2 fork specifics\n _swap(router, inputAmount, swapPath);\n\n // Get new collateral\n outputToken = IERC20Upgradeable(swapPath[swapPath.length - 1].to);\n outputAmount = outputToken.balanceOf(address(this));\n }\n}\n" + }, + "contracts/src/liquidators/AlgebraSwapLiquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./IRedemptionStrategy.sol\";\nimport \"../external/algebra/ISwapRouter.sol\";\n\n/**\n * @title AlgebraSwapLiquidator\n * @notice Exchanges seized token collateral for underlying tokens via a Algebra router for use as a step in a liquidation.\n * @author Veliko Minkov (https://github.com/vminkov)\n */\ncontract AlgebraSwapLiquidator is IRedemptionStrategy {\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n (address _outputToken, IAlgebraSwapRouter swapRouter) = abi.decode(strategyData, (address, IAlgebraSwapRouter));\n outputToken = IERC20Upgradeable(_outputToken);\n\n inputToken.approve(address(swapRouter), inputAmount);\n\n IAlgebraSwapRouter.ExactInputSingleParams memory params = IAlgebraSwapRouter.ExactInputSingleParams(\n address(inputToken),\n _outputToken,\n address(this),\n block.timestamp,\n inputAmount,\n 0, // amountOutMinimum\n 0 // limitSqrtPrice\n );\n\n outputAmount = swapRouter.exactInputSingle(params);\n }\n\n function name() public pure returns (string memory) {\n return \"AlgebraSwapLiquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/BaseUniswapV2Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\nimport \"../external/uniswap/IUniswapV2Router02.sol\";\n\nimport \"./IRedemptionStrategy.sol\";\n\nabstract contract BaseUniswapV2Liquidator is IRedemptionStrategy {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n function _convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) internal returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n // Get Uniswap router and path\n (IUniswapV2Router02 uniswapV2Router, address[] memory swapPath) = abi.decode(\n strategyData,\n (IUniswapV2Router02, address[])\n );\n require(swapPath.length >= 2 && swapPath[0] == address(inputToken), \"Invalid UniswapLiquidator swap path.\");\n\n // Swap underlying tokens\n inputToken.approve(address(uniswapV2Router), inputAmount);\n\n // call the relevant fn depending on the uni v2 fork specifics\n _swap(uniswapV2Router, inputAmount, swapPath);\n\n // Get new collateral\n outputToken = IERC20Upgradeable(swapPath[swapPath.length - 1]);\n outputAmount = outputToken.balanceOf(address(this));\n }\n\n function _swap(IUniswapV2Router02 uniswapV2Router, uint256 inputAmount, address[] memory swapPath) internal virtual;\n}\n" + }, + "contracts/src/liquidators/CErc20Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\nimport \"../external/compound/ICErc20.sol\";\n\nimport \"./IRedemptionStrategy.sol\";\n\n/**\n * @title CErc20Liquidator\n * @notice Redeems seized Compound/Cream/Ionic CErc20 cTokens for underlying tokens for use as a step in a liquidation.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract CErc20Liquidator is IRedemptionStrategy {\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n // Redeem cErc20 for underlying ERC20 token (and store output as new collateral)\n ICErc20Compound cErc20 = ICErc20Compound(address(inputToken));\n uint256 redeemResult = cErc20.redeem(inputAmount);\n require(redeemResult == 0, \"Error calling redeeming seized cErc20: error code not equal to 0\");\n outputToken = IERC20Upgradeable(cErc20.underlying());\n outputAmount = outputToken.balanceOf(address(this));\n }\n\n function name() public pure returns (string memory) {\n return \"CErc20Liquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/CurveSwapLiquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\nimport \"../external/curve/ICurvePool.sol\";\nimport { IERC4626 } from \"../compound/IERC4626.sol\";\n\nimport \"./IRedemptionStrategy.sol\";\n\nimport \"../oracles/default/CurveV2LpTokenPriceOracleNoRegistry.sol\";\nimport \"../oracles/default/CurveLpTokenPriceOracleNoRegistry.sol\";\n\n/**\n * @title CurveSwapLiquidator\n * @notice Swaps seized token collateral via Curve as a step in a liquidation.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract CurveSwapLiquidator is IRedemptionStrategy {\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable, uint256) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n function _convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) internal returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n (\n CurveV2LpTokenPriceOracleNoRegistry curveV2Oracle,\n address outputTokenAddress,\n address _unwrappedInput,\n address _unwrappedOutput\n ) = abi.decode(strategyData, (CurveV2LpTokenPriceOracleNoRegistry, address, address, address));\n\n if (_unwrappedOutput != address(0)) {\n outputToken = IERC20Upgradeable(_unwrappedOutput);\n } else {\n outputToken = IERC20Upgradeable(outputTokenAddress);\n }\n\n if (_unwrappedInput != address(0)) {\n inputToken.approve(address(inputToken), inputAmount);\n inputAmount = IERC4626(address(inputToken)).redeem(inputAmount, address(this), address(this));\n inputToken = IERC20Upgradeable(_unwrappedInput);\n }\n\n address inputTokenAddress = address(inputToken);\n\n ICurvePool curvePool;\n int128 i;\n int128 j;\n if (address(curveV2Oracle) != address(0)) {\n (curvePool, i, j) = curveV2Oracle.getPoolForSwap(inputTokenAddress, address(outputToken));\n }\n require(address(curvePool) != address(0), \"!curve pool\");\n\n inputToken.approve(address(curvePool), inputAmount);\n outputAmount = curvePool.exchange(i, j, inputAmount, 0);\n\n if (_unwrappedOutput != address(0)) {\n IERC20Upgradeable(_unwrappedOutput).approve(address(outputTokenAddress), outputAmount);\n IERC4626(outputTokenAddress).deposit(outputAmount, address(this));\n outputToken = IERC20Upgradeable(outputTokenAddress);\n }\n\n outputAmount = outputToken.balanceOf(address(this));\n return (outputToken, outputAmount);\n }\n\n function name() public pure virtual returns (string memory) {\n return \"CurveSwapLiquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/CurveSwapLiquidatorFunder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./CurveSwapLiquidator.sol\";\nimport \"./IFundsConversionStrategy.sol\";\n\nimport { IERC20MetadataUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\n\ncontract CurveSwapLiquidatorFunder is CurveSwapLiquidator, IFundsConversionStrategy {\n function convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n function estimateInputAmount(\n uint256 outputAmount,\n bytes memory strategyData\n ) external view returns (IERC20Upgradeable, uint256) {\n ICurvePool curvePool;\n int128 i;\n int128 j;\n {\n (\n CurveLpTokenPriceOracleNoRegistry curveV1Oracle,\n CurveV2LpTokenPriceOracleNoRegistry curveV2Oracle,\n address inputTokenAddress,\n address outputTokenAddress,\n\n ) = abi.decode(\n strategyData,\n (CurveLpTokenPriceOracleNoRegistry, CurveV2LpTokenPriceOracleNoRegistry, address, address, address)\n );\n\n if (address(curveV2Oracle) != address(0)) {\n (curvePool, i, j) = curveV2Oracle.getPoolForSwap(inputTokenAddress, outputTokenAddress);\n }\n if (address(curvePool) == address(0)) {\n (curvePool, i, j) = curveV1Oracle.getPoolForSwap(inputTokenAddress, outputTokenAddress);\n }\n }\n require(address(curvePool) != address(0), \"!curve pool\");\n\n IERC20MetadataUpgradeable inputMetadataToken = IERC20MetadataUpgradeable(curvePool.coins(uint256(int256(i))));\n uint256 inputAmountGuesstimate = guesstimateInputAmount(curvePool, i, j, inputMetadataToken, outputAmount);\n uint256 inputAmount = binSearch(\n curvePool,\n i,\n j,\n (70 * inputAmountGuesstimate) / 100,\n (130 * inputAmountGuesstimate) / 100,\n outputAmount\n );\n\n return (inputMetadataToken, inputAmount);\n }\n\n function guesstimateInputAmount(\n ICurvePool curvePool,\n int128 i,\n int128 j,\n IERC20MetadataUpgradeable inputMetadataToken,\n uint256 outputAmount\n ) internal view returns (uint256) {\n uint256 oneInputToken = 10 ** inputMetadataToken.decimals();\n uint256 outputTokensForOneInputToken = curvePool.get_dy(i, j, oneInputToken);\n // inputAmount / outputAmount = oneInputToken / outputTokensForOneInputToken\n uint256 inputAmount = (outputAmount * oneInputToken) / outputTokensForOneInputToken;\n return inputAmount;\n }\n\n function binSearch(\n ICurvePool curvePool,\n int128 i,\n int128 j,\n uint256 low,\n uint256 high,\n uint256 value\n ) internal view returns (uint256) {\n if (low >= high) return low;\n\n uint256 mid = (low + high) / 2;\n uint256 outputAmount = curvePool.get_dy(i, j, mid);\n if (outputAmount == 0) revert(\"output amount 0\");\n // output can be up to 10% in excess\n if (outputAmount >= value && outputAmount <= (11 * value) / 10) return mid;\n else if (outputAmount > value) {\n return binSearch(curvePool, i, j, low, mid, value);\n } else {\n return binSearch(curvePool, i, j, mid, high, value);\n }\n }\n\n function name() public pure override(CurveSwapLiquidator, IRedemptionStrategy) returns (string memory) {\n return \"CurveSwapLiquidatorFunder\";\n }\n}\n" + }, + "contracts/src/liquidators/CustomLiquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\nimport \"../utils/IW_NATIVE.sol\";\n\nimport \"./IRedemptionStrategy.sol\";\n\n/**\n * @title CustomLiquidator\n * @notice Redeems seized collateral tokens for the specified output token by calling the specified contract for use as a step in a liquidation.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract CustomLiquidator is IRedemptionStrategy {\n using AddressUpgradeable for address;\n\n /**\n * @dev W_NATIVE contract object.\n */\n IW_NATIVE private constant W_NATIVE = IW_NATIVE(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\n\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n // Call arbitrary contract\n address target;\n bytes memory data;\n (target, data, outputToken) = abi.decode(strategyData, (address, bytes, IERC20Upgradeable));\n target.functionCall(data);\n outputAmount = address(outputToken) == address(0) ? address(this).balance : outputToken.balanceOf(address(this));\n\n // Convert to W_NATIVE if ETH because `IonicLiquidator.repayTokenFlashLoan` only supports tokens (not ETH) as output from redemptions (reverts on line 24 because `underlyingCollateral` is the zero address)\n if (address(outputToken) == address(0)) {\n W_NATIVE.deposit{ value: outputAmount }();\n return (IERC20Upgradeable(address(W_NATIVE)), outputAmount);\n }\n }\n\n function name() public pure returns (string memory) {\n return \"CustomLiquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/ERC4626Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\nimport { IERC4626 } from \"../compound/IERC4626.sol\";\nimport { IUniswapV2Router02 } from \"../external/uniswap/IUniswapV2Router02.sol\";\nimport { IRedemptionStrategy } from \"./IRedemptionStrategy.sol\";\nimport { ISwapRouter } from \"../external/uniswap/ISwapRouter.sol\";\nimport { Quoter } from \"../external/uniswap/quoter/Quoter.sol\";\n\n/**\n * @title ERC4626Liquidator\n * @notice Redeems ERC4626 assets and optionally swaps them via Uniswap V2 router for use as a step in a liquidation.\n * @author Carlo Mazzaferro (https://github.com/carlomazzaferro)\n */\ncontract ERC4626Liquidator is IRedemptionStrategy {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n function _convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) internal returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n // Get Uniswap router and path\n (IERC20Upgradeable _outputToken, uint24 fee, ISwapRouter swapRouter, address[] memory underlyingTokens, ) = abi\n .decode(strategyData, (IERC20Upgradeable, uint24, ISwapRouter, address[], Quoter));\n\n if (underlyingTokens.length == 1) {\n // If there is only one underlying token, we can just redeem it directly\n require(\n address(_outputToken) == underlyingTokens[0],\n \"ERC4626Liquidator: output token does not match underlying token\"\n );\n\n IERC4626(address(inputToken)).redeem(inputAmount, address(this), address(this));\n outputAmount = IERC20Upgradeable(_outputToken).balanceOf(address(this));\n\n return (_outputToken, outputAmount);\n } else {\n // NOTE: for Sommelier, the underlying tokens can be fetched from the Sommelier contract\n // E.g. https://etherscan.io/address/0x6b7f87279982d919bbf85182ddeab179b366d8f2#readContract#F20\n IERC4626(address(inputToken)).redeem(inputAmount, address(this), address(this));\n\n // for each token, we need to swap it for the output token\n for (uint256 i = 0; i < underlyingTokens.length; i++) {\n // do nothing if the token is the output token\n if (underlyingTokens[i] == address(_outputToken)) {\n continue;\n }\n if (IERC20Upgradeable(underlyingTokens[i]).balanceOf(address(this)) == 0) {\n continue;\n }\n _swap(\n underlyingTokens[i],\n IERC20Upgradeable(underlyingTokens[i]).balanceOf(address(this)),\n address(_outputToken),\n swapRouter,\n fee\n );\n }\n outputAmount = _outputToken.balanceOf(address(this));\n return (_outputToken, outputAmount);\n }\n }\n\n function _swap(\n address inputToken,\n uint256 inputAmount,\n address outputToken,\n ISwapRouter swapRouter,\n uint24 fee\n ) internal returns (uint256 outputAmount) {\n IERC20Upgradeable(inputToken).approve(address(swapRouter), inputAmount);\n\n ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams(\n address(inputToken),\n outputToken,\n fee,\n address(this),\n block.timestamp,\n inputAmount,\n 0,\n 0\n );\n outputAmount = swapRouter.exactInputSingle(params);\n }\n\n function name() public pure returns (string memory) {\n return \"ERC4626Liquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/IFundsConversionStrategy.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./IRedemptionStrategy.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ninterface IFundsConversionStrategy is IRedemptionStrategy {\n function convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount);\n\n function estimateInputAmount(\n uint256 outputAmount,\n bytes memory strategyData\n ) external view returns (IERC20Upgradeable inputToken, uint256 inputAmount);\n}\n" + }, + "contracts/src/liquidators/IRedemptionStrategy.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\n/**\n * @title IRedemptionStrategy\n * @notice Redeems seized wrapped token collateral for an underlying token for use as a step in a liquidation.\n * @author David Lucid (https://github.com/davidlucid)\n */\ninterface IRedemptionStrategy {\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount);\n\n function name() external view returns (string memory);\n}\n" + }, + "contracts/src/liquidators/KimUniV2Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./BaseUniswapV2Liquidator.sol\";\n\ncontract KimUniV2Liquidator is BaseUniswapV2Liquidator {\n function _swap(\n IUniswapV2Router02 uniswapV2Router,\n uint256 inputAmount,\n address[] memory swapPath\n ) internal override {\n uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(\n inputAmount,\n 0,\n swapPath,\n address(this),\n address(0), // referrer\n block.timestamp\n );\n }\n\n function name() public pure virtual returns (string memory) {\n return \"KimUniV2Liquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/registry/ILiquidatorsRegistry.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IRedemptionStrategy } from \"../../liquidators/IRedemptionStrategy.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ninterface ILiquidatorsRegistryStorage {\n function redemptionStrategiesByName(string memory name) external view returns (IRedemptionStrategy);\n\n function redemptionStrategiesByTokens(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external view returns (IRedemptionStrategy);\n\n function defaultOutputToken(IERC20Upgradeable inputToken) external view returns (IERC20Upgradeable);\n\n function owner() external view returns (address);\n\n function uniswapV3Fees(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken) external view returns (uint24);\n\n function customUniV3Router(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external view returns (address);\n}\n\ninterface ILiquidatorsRegistryExtension {\n function getInputTokensByOutputToken(IERC20Upgradeable outputToken) external view returns (address[] memory);\n\n function getRedemptionStrategies(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external view returns (IRedemptionStrategy[] memory strategies, bytes[] memory strategiesData);\n\n function getRedemptionStrategy(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external view returns (IRedemptionStrategy strategy, bytes memory strategyData);\n\n function getAllRedemptionStrategies() external view returns (address[] memory);\n\n function getSlippage(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external view returns (uint256 slippage);\n\n function swap(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n IERC20Upgradeable outputToken\n ) external returns (uint256);\n\n function amountOutAndSlippageOfSwap(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n IERC20Upgradeable outputToken\n ) external returns (uint256 outputAmount, uint256 slippage);\n}\n\ninterface ILiquidatorsRegistrySecondExtension {\n function getAllPairsStrategies()\n external\n view\n returns (\n IRedemptionStrategy[] memory strategies,\n IERC20Upgradeable[] memory inputTokens,\n IERC20Upgradeable[] memory outputTokens\n );\n\n function pairsStrategiesMatch(\n IRedemptionStrategy[] calldata configStrategies,\n IERC20Upgradeable[] calldata configInputTokens,\n IERC20Upgradeable[] calldata configOutputTokens\n ) external view returns (bool);\n\n function uniswapPairsFeesMatch(\n IERC20Upgradeable[] calldata configInputTokens,\n IERC20Upgradeable[] calldata configOutputTokens,\n uint256[] calldata configFees\n ) external view returns (bool);\n\n function uniswapPairsRoutersMatch(\n IERC20Upgradeable[] calldata configInputTokens,\n IERC20Upgradeable[] calldata configOutputTokens,\n address[] calldata configRouters\n ) external view returns (bool);\n\n function _setRedemptionStrategy(\n IRedemptionStrategy strategy,\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external;\n\n function _setRedemptionStrategies(\n IRedemptionStrategy[] calldata strategies,\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens\n ) external;\n\n function _resetRedemptionStrategies(\n IRedemptionStrategy[] calldata strategies,\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens\n ) external;\n\n function _removeRedemptionStrategy(IRedemptionStrategy strategyToRemove) external;\n\n function _setDefaultOutputToken(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken) external;\n\n function _setUniswapV3Fees(\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens,\n uint24[] calldata fees\n ) external;\n\n function _setUniswapV3Routers(\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens,\n address[] calldata routers\n ) external;\n\n function _setSlippages(\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens,\n uint256[] calldata slippages\n ) external;\n\n function optimalSwapPath(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external view returns (IERC20Upgradeable[] memory);\n\n function _setOptimalSwapPath(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken,\n IERC20Upgradeable[] calldata optimalPath\n ) external;\n\n function wrappedToUnwrapped4626(address wrapped) external view returns (address);\n\n function _setWrappedToUnwrapped4626(address wrapped, address unwrapped) external;\n\n function aeroCLTickSpacings(address inputToken, address outputToken) external view returns (int24);\n\n function _setAeroCLTickSpacings(address inputToken, address outputToken, int24 tickSpacing) external;\n\n function aeroV2IsStable(address inputToken, address outputToken) external view returns (bool);\n\n function _setAeroV2IsStable(address inputToken, address outputToken, bool isStable) external;\n}\n\ninterface ILiquidatorsRegistry is\n ILiquidatorsRegistryExtension,\n ILiquidatorsRegistrySecondExtension,\n ILiquidatorsRegistryStorage\n{}\n" + }, + "contracts/src/liquidators/registry/LiquidatorsRegistry.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport \"../../ionic/DiamondExtension.sol\";\nimport \"./LiquidatorsRegistryStorage.sol\";\nimport \"./LiquidatorsRegistryExtension.sol\";\n\ncontract LiquidatorsRegistry is LiquidatorsRegistryStorage, DiamondBase {\n using EnumerableSet for EnumerableSet.AddressSet;\n\n constructor(AddressesProvider _ap) SafeOwnable() {\n ap = _ap;\n }\n\n /**\n * @dev register a logic extension\n * @param extensionToAdd the extension whose functions are to be added\n * @param extensionToReplace the extension whose functions are to be removed/replaced\n */\n function _registerExtension(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace)\n public\n override\n onlyOwner\n {\n LibDiamond.registerExtension(extensionToAdd, extensionToReplace);\n }\n\n function asExtension() public view returns (LiquidatorsRegistryExtension) {\n return LiquidatorsRegistryExtension(address(this));\n }\n}\n" + }, + "contracts/src/liquidators/registry/LiquidatorsRegistryExtension.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport \"./ILiquidatorsRegistry.sol\";\nimport \"./LiquidatorsRegistryStorage.sol\";\n\nimport \"../IRedemptionStrategy.sol\";\nimport \"../../ionic/DiamondExtension.sol\";\nimport { MasterPriceOracle } from \"../../oracles/MasterPriceOracle.sol\";\n\nimport { IRouter_Aerodrome as IAerodromeV2Router } from \"../../external/aerodrome/IAerodromeRouter.sol\";\nimport { IRouter_Velodrome as IVelodromeV2Router } from \"../../external/velodrome/IVelodromeRouter.sol\";\nimport { IUniswapV2Pair } from \"../../external/uniswap/IUniswapV2Pair.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\ncontract LiquidatorsRegistryExtension is LiquidatorsRegistryStorage, DiamondExtension, ILiquidatorsRegistryExtension {\n using EnumerableSet for EnumerableSet.AddressSet;\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n error NoRedemptionPath();\n error OutputTokenMismatch();\n\n event SlippageUpdated(\n IERC20Upgradeable indexed from,\n IERC20Upgradeable indexed to,\n uint256 prevValue,\n uint256 newValue\n );\n\n // @notice maximum slippage in swaps, in bps\n uint256 public constant MAX_SLIPPAGE = 900; // 9%\n\n function _getExtensionFunctions() external pure override returns (bytes4[] memory) {\n uint8 fnsCount = 7;\n bytes4[] memory functionSelectors = new bytes4[](fnsCount);\n functionSelectors[--fnsCount] = this.getRedemptionStrategies.selector;\n functionSelectors[--fnsCount] = this.getRedemptionStrategy.selector;\n functionSelectors[--fnsCount] = this.getInputTokensByOutputToken.selector;\n functionSelectors[--fnsCount] = this.swap.selector;\n functionSelectors[--fnsCount] = this.getAllRedemptionStrategies.selector;\n functionSelectors[--fnsCount] = this.amountOutAndSlippageOfSwap.selector;\n functionSelectors[--fnsCount] = this.getSlippage.selector;\n require(fnsCount == 0, \"use the correct array length\");\n return functionSelectors;\n }\n\n function getSlippage(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) external view returns (uint256 slippage) {\n slippage = conversionSlippage[inputToken][outputToken];\n // TODO slippage == 0 should be allowed\n if (slippage == 0) return MAX_SLIPPAGE;\n }\n\n function getAllRedemptionStrategies() public view returns (address[] memory) {\n return redemptionStrategies.values();\n }\n\n function amountOutAndSlippageOfSwap(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n IERC20Upgradeable outputToken\n ) external returns (uint256 outputAmount, uint256 slippage) {\n if (inputAmount == 0) return (0, 0);\n\n outputAmount = swap(inputToken, inputAmount, outputToken);\n if (outputAmount == 0) return (0, 0);\n\n MasterPriceOracle mpo = MasterPriceOracle(ap.getAddress(\"MasterPriceOracle\"));\n uint256 inputTokenPrice = mpo.price(address(inputToken));\n uint256 outputTokenPrice = mpo.price(address(outputToken));\n\n uint256 inputTokensValue = inputAmount * toScaledPrice(inputTokenPrice, inputToken);\n uint256 outputTokensValue = outputAmount * toScaledPrice(outputTokenPrice, outputToken);\n\n if (outputTokensValue < inputTokensValue) {\n slippage = ((inputTokensValue - outputTokensValue) * 10000) / inputTokensValue;\n }\n // min slippage should be non-zero\n // just in case of rounding errors\n slippage += 1;\n\n // cache the slippage\n uint256 prevValue = conversionSlippage[inputToken][outputToken];\n if (prevValue == 0 || block.timestamp - conversionSlippageUpdated[inputToken][outputToken] > 5000) {\n emit SlippageUpdated(inputToken, outputToken, prevValue, slippage);\n\n conversionSlippage[inputToken][outputToken] = slippage;\n conversionSlippageUpdated[inputToken][outputToken] = block.timestamp;\n }\n }\n\n /// @dev returns price scaled to 1e36 - decimals\n function toScaledPrice(uint256 unscaledPrice, IERC20Upgradeable token) internal view returns (uint256) {\n uint256 tokenDecimals = uint256(ERC20Upgradeable(address(token)).decimals());\n return\n tokenDecimals <= 18\n ? uint256(unscaledPrice) * (10 ** (18 - tokenDecimals))\n : uint256(unscaledPrice) / (10 ** (tokenDecimals - 18));\n }\n\n function swap(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n IERC20Upgradeable outputToken\n ) public returns (uint256 outputAmount) {\n inputToken.safeTransferFrom(msg.sender, address(this), inputAmount);\n outputAmount = convertAllTo(inputToken, outputToken);\n outputToken.safeTransfer(msg.sender, outputAmount);\n }\n\n function convertAllTo(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken) private returns (uint256) {\n uint256 inputAmount = inputToken.balanceOf(address(this));\n (IRedemptionStrategy[] memory redemptionStrategies, bytes[] memory strategiesData) = getRedemptionStrategies(\n inputToken,\n outputToken\n );\n\n if (redemptionStrategies.length == 0) revert NoRedemptionPath();\n\n IERC20Upgradeable swapInputToken = inputToken;\n uint256 swapInputAmount = inputAmount;\n for (uint256 i = 0; i < redemptionStrategies.length; i++) {\n IRedemptionStrategy redemptionStrategy = redemptionStrategies[i];\n bytes memory strategyData = strategiesData[i];\n (IERC20Upgradeable swapOutputToken, uint256 swapOutputAmount) = convertCustomFunds(\n swapInputToken,\n swapInputAmount,\n redemptionStrategy,\n strategyData\n );\n swapInputAmount = swapOutputAmount;\n swapInputToken = swapOutputToken;\n }\n\n if (swapInputToken != outputToken) revert OutputTokenMismatch();\n return outputToken.balanceOf(address(this));\n }\n\n function convertCustomFunds(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n IRedemptionStrategy strategy,\n bytes memory strategyData\n ) private returns (IERC20Upgradeable, uint256) {\n bytes memory returndata = _functionDelegateCall(\n address(strategy),\n abi.encodeWithSelector(strategy.redeem.selector, inputToken, inputAmount, strategyData)\n );\n return abi.decode(returndata, (IERC20Upgradeable, uint256));\n }\n\n function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {\n require(AddressUpgradeable.isContract(target), \"Address: delegate call to non-contract\");\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return _verifyCallResult(success, returndata, \"Address: low-level delegate call failed\");\n }\n\n function _verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) private pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n if (returndata.length > 0) {\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n\n function getInputTokensByOutputToken(IERC20Upgradeable outputToken) external view returns (address[] memory) {\n return inputTokensByOutputToken[outputToken].values();\n }\n\n function getRedemptionStrategies(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) public view returns (IRedemptionStrategy[] memory strategies, bytes[] memory strategiesData) {\n IERC20Upgradeable tokenToRedeem = inputToken;\n IERC20Upgradeable targetOutputToken = outputToken;\n IRedemptionStrategy[] memory strategiesTemp = new IRedemptionStrategy[](10);\n bytes[] memory strategiesDataTemp = new bytes[](10);\n IERC20Upgradeable[] memory tokenPath = new IERC20Upgradeable[](10);\n IERC20Upgradeable[] memory optimalPath = new IERC20Upgradeable[](0);\n uint256 optimalPathIterator = 0;\n\n uint256 k = 0;\n while (tokenToRedeem != targetOutputToken) {\n IERC20Upgradeable nextRedeemedToken;\n IRedemptionStrategy directStrategy = redemptionStrategiesByTokens[tokenToRedeem][targetOutputToken];\n if (address(directStrategy) != address(0)) {\n nextRedeemedToken = targetOutputToken;\n } else {\n // check if an optimal path is preconfigured\n if (optimalPath.length == 0 && _optimalSwapPath[tokenToRedeem][targetOutputToken].length != 0) {\n optimalPath = _optimalSwapPath[tokenToRedeem][targetOutputToken];\n }\n if (optimalPath.length != 0 && optimalPathIterator < optimalPath.length) {\n nextRedeemedToken = optimalPath[optimalPathIterator++];\n } else {\n // else if no optimal path is available, use the default\n nextRedeemedToken = defaultOutputToken[tokenToRedeem];\n }\n }\n\n // check if going in an endless loop\n for (uint256 i = 0; i < tokenPath.length; i++) {\n if (nextRedeemedToken == tokenPath[i]) break;\n }\n\n (IRedemptionStrategy strategy, bytes memory strategyData) = getRedemptionStrategy(\n tokenToRedeem,\n nextRedeemedToken\n );\n if (address(strategy) == address(0)) break;\n\n strategiesTemp[k] = strategy;\n strategiesDataTemp[k] = strategyData;\n tokenPath[k] = nextRedeemedToken;\n tokenToRedeem = nextRedeemedToken;\n\n k++;\n if (k == 10) break;\n }\n\n strategies = new IRedemptionStrategy[](k);\n strategiesData = new bytes[](k);\n\n for (uint8 i = 0; i < k; i++) {\n strategies[i] = strategiesTemp[i];\n strategiesData[i] = strategiesDataTemp[i];\n }\n }\n\n function getRedemptionStrategy(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) public view returns (IRedemptionStrategy strategy, bytes memory strategyData) {\n strategy = redemptionStrategiesByTokens[inputToken][outputToken];\n\n if (isStrategy(strategy, \"UniswapV2LiquidatorFunder\") || isStrategy(strategy, \"KimUniV2Liquidator\")) {\n strategyData = uniswapV2LiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"UniswapV3LiquidatorFunder\")) {\n strategyData = uniswapV3LiquidatorFunderData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"AlgebraSwapLiquidator\")) {\n strategyData = algebraSwapLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"AerodromeV2Liquidator\")) {\n strategyData = aerodromeV2LiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"AerodromeCLLiquidator\")) {\n strategyData = aerodromeCLLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"CurveSwapLiquidator\")) {\n strategyData = curveSwapLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"VelodromeV2Liquidator\")) {\n strategyData = velodromeV2LiquidatorData(inputToken, outputToken);\n } else {\n revert(\"no strategy data\");\n }\n }\n\n function isStrategy(IRedemptionStrategy strategy, string memory name) internal view returns (bool) {\n return address(strategy) != address(0) && address(strategy) == address(redemptionStrategiesByName[name]);\n }\n\n function pickPreferredToken(address[] memory tokens, address strategyOutputToken) internal view returns (address) {\n for (uint256 i = 0; i < tokens.length; i++) {\n if (tokens[i] == strategyOutputToken) return strategyOutputToken;\n }\n address wnative = ap.getAddress(\"wtoken\");\n for (uint256 i = 0; i < tokens.length; i++) {\n if (tokens[i] == wnative) return wnative;\n }\n address stableToken = ap.getAddress(\"stableToken\");\n for (uint256 i = 0; i < tokens.length; i++) {\n if (tokens[i] == stableToken) return stableToken;\n }\n address wbtc = ap.getAddress(\"wBTCToken\");\n for (uint256 i = 0; i < tokens.length; i++) {\n if (tokens[i] == wbtc) return wbtc;\n }\n return tokens[0];\n }\n\n function getUniswapV3Router(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) internal view returns (address) {\n address customRouter = customUniV3Router[inputToken][outputToken];\n if (customRouter == address(0)) {\n customRouter = customUniV3Router[outputToken][inputToken];\n }\n\n if (customRouter != address(0)) {\n return customRouter;\n } else {\n // get asset specific router or default\n return ap.getAddress(\"UNISWAP_V3_ROUTER\");\n }\n }\n\n function getUniswapV2Router(IERC20Upgradeable inputToken) internal view returns (address) {\n // get asset specific router or default\n return ap.getAddress(\"IUniswapV2Router02\");\n }\n\n function getAerodromeV2Router(IERC20Upgradeable inputToken) internal view returns (address) {\n // get asset specific router or default\n return ap.getAddress(\"AERODROME_V2_ROUTER\");\n }\n\n function getAerodromeCLRouter(IERC20Upgradeable inputToken) internal view returns (address) {\n // get asset specific router or default\n return ap.getAddress(\"AERODROME_CL_ROUTER\");\n }\n\n function uniswapV3LiquidatorFunderData(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) internal view returns (bytes memory strategyData) {\n uint24 fee = uniswapV3Fees[inputToken][outputToken];\n if (fee == 0) fee = uniswapV3Fees[outputToken][inputToken];\n if (fee == 0) fee = 500;\n\n address router = getUniswapV3Router(inputToken, outputToken);\n strategyData = abi.encode(inputToken, outputToken, fee, router, ap.getAddress(\"Quoter\"));\n }\n\n function getWrappedToUnwrapped4626(IERC20Upgradeable inputToken) internal view returns (address) {\n return _wrappedToUnwrapped4626[address(inputToken)];\n }\n\n function getAeroCLTickSpacing(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) internal view returns (int24) {\n int24 tickSpacing = _aeroCLTickSpacings[address(inputToken)][address(outputToken)];\n if (tickSpacing == 0) {\n tickSpacing = 1;\n }\n return tickSpacing;\n }\n\n function aeroV2IsStable(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken) internal view returns (bool) {\n return _aeroV2IsStable[address(inputToken)][address(outputToken)];\n }\n\n function uniswapV2LiquidatorData(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) internal view returns (bytes memory strategyData) {\n IERC20Upgradeable[] memory swapPath = new IERC20Upgradeable[](2);\n swapPath[0] = inputToken;\n swapPath[1] = outputToken;\n strategyData = abi.encode(getUniswapV2Router(inputToken), swapPath);\n }\n\n function aerodromeV2LiquidatorData(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) internal view returns (bytes memory strategyData) {\n IAerodromeV2Router.Route[] memory swapPath = new IAerodromeV2Router.Route[](1);\n swapPath[0] = IAerodromeV2Router.Route({\n from: address(inputToken),\n to: address(outputToken),\n stable: aeroV2IsStable(inputToken, outputToken),\n factory: ap.getAddress(\"AERODROME_V2_FACTORY\")\n });\n strategyData = abi.encode(getAerodromeV2Router(inputToken), swapPath);\n }\n\n function aerodromeCLLiquidatorData(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) internal view returns (bytes memory strategyData) {\n strategyData = abi.encode(\n inputToken,\n outputToken,\n getAerodromeCLRouter(inputToken),\n getWrappedToUnwrapped4626(inputToken),\n getWrappedToUnwrapped4626(outputToken),\n getAeroCLTickSpacing(inputToken, outputToken)\n );\n }\n\n function algebraSwapLiquidatorData(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) internal view returns (bytes memory strategyData) {\n strategyData = abi.encode(outputToken, ap.getAddress(\"ALGEBRA_SWAP_ROUTER\"));\n }\n\n function curveSwapLiquidatorData(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) internal view returns (bytes memory strategyData) {\n strategyData = abi.encode(\n ap.getAddress(\"CURVE_V2_ORACLE_NO_REGISTRY\"),\n outputToken,\n getWrappedToUnwrapped4626(inputToken),\n getWrappedToUnwrapped4626(outputToken)\n );\n }\n\n function velodromeV2LiquidatorData(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) internal view returns (bytes memory strategyData) {\n IVelodromeV2Router.Route[] memory swapPath = new IVelodromeV2Router.Route[](1);\n swapPath[0] = IVelodromeV2Router.Route({\n from: address(inputToken),\n to: address(outputToken),\n stable: aeroV2IsStable(inputToken, outputToken)\n });\n strategyData = abi.encode(getAerodromeV2Router(inputToken), swapPath);\n }\n}" + }, + "contracts/src/liquidators/registry/LiquidatorsRegistrySecondExtension.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport \"./ILiquidatorsRegistry.sol\";\nimport \"./LiquidatorsRegistryStorage.sol\";\n\nimport \"../../ionic/DiamondExtension.sol\";\n\ncontract LiquidatorsRegistrySecondExtension is\n LiquidatorsRegistryStorage,\n DiamondExtension,\n ILiquidatorsRegistrySecondExtension\n{\n using EnumerableSet for EnumerableSet.AddressSet;\n\n function _getExtensionFunctions() external pure override returns (bytes4[] memory) {\n uint8 fnsCount = 20;\n bytes4[] memory functionSelectors = new bytes4[](fnsCount);\n functionSelectors[--fnsCount] = this.getAllPairsStrategies.selector;\n functionSelectors[--fnsCount] = this.pairsStrategiesMatch.selector;\n functionSelectors[--fnsCount] = this.uniswapPairsFeesMatch.selector;\n functionSelectors[--fnsCount] = this.uniswapPairsRoutersMatch.selector;\n functionSelectors[--fnsCount] = this._setSlippages.selector;\n functionSelectors[--fnsCount] = this._setUniswapV3Fees.selector;\n functionSelectors[--fnsCount] = this._setUniswapV3Routers.selector;\n functionSelectors[--fnsCount] = this._setDefaultOutputToken.selector;\n functionSelectors[--fnsCount] = this._setRedemptionStrategy.selector;\n functionSelectors[--fnsCount] = this._setRedemptionStrategies.selector;\n functionSelectors[--fnsCount] = this._removeRedemptionStrategy.selector;\n functionSelectors[--fnsCount] = this._resetRedemptionStrategies.selector;\n functionSelectors[--fnsCount] = this.optimalSwapPath.selector;\n functionSelectors[--fnsCount] = this._setOptimalSwapPath.selector;\n functionSelectors[--fnsCount] = this.wrappedToUnwrapped4626.selector;\n functionSelectors[--fnsCount] = this.aeroCLTickSpacings.selector;\n functionSelectors[--fnsCount] = this.aeroV2IsStable.selector;\n functionSelectors[--fnsCount] = this._setWrappedToUnwrapped4626.selector;\n functionSelectors[--fnsCount] = this._setAeroCLTickSpacings.selector;\n functionSelectors[--fnsCount] = this._setAeroV2IsStable.selector;\n require(fnsCount == 0, \"use the correct array length\");\n return functionSelectors;\n }\n\n function _setSlippages(\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens,\n uint256[] calldata slippages\n ) external onlyOwner {\n require(slippages.length == inputTokens.length && inputTokens.length == outputTokens.length, \"!arrays len\");\n\n for (uint256 i = 0; i < slippages.length; i++) {\n conversionSlippage[inputTokens[i]][outputTokens[i]] = slippages[i];\n }\n }\n\n function _setUniswapV3Fees(\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens,\n uint24[] calldata fees\n ) external onlyOwner {\n require(fees.length == inputTokens.length && inputTokens.length == outputTokens.length, \"!arrays len\");\n\n for (uint256 i = 0; i < fees.length; i++) {\n uniswapV3Fees[inputTokens[i]][outputTokens[i]] = fees[i];\n }\n }\n\n function _setUniswapV3Routers(\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens,\n address[] calldata routers\n ) external onlyOwner {\n require(routers.length == inputTokens.length && inputTokens.length == outputTokens.length, \"!arrays len\");\n\n for (uint256 i = 0; i < routers.length; i++) {\n customUniV3Router[inputTokens[i]][outputTokens[i]] = routers[i];\n }\n }\n\n function _setDefaultOutputToken(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken) external onlyOwner {\n defaultOutputToken[inputToken] = outputToken;\n }\n\n function _setRedemptionStrategy(\n IRedemptionStrategy strategy,\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken\n ) public onlyOwner {\n string memory name = strategy.name();\n IRedemptionStrategy oldStrategy = redemptionStrategiesByName[name];\n\n redemptionStrategiesByTokens[inputToken][outputToken] = strategy;\n redemptionStrategiesByName[name] = strategy;\n\n redemptionStrategies.remove(address(oldStrategy));\n redemptionStrategies.add(address(strategy));\n\n if (defaultOutputToken[inputToken] == IERC20Upgradeable(address(0))) {\n defaultOutputToken[inputToken] = outputToken;\n }\n inputTokensByOutputToken[outputToken].add(address(inputToken));\n outputTokensSet.add(address(outputToken));\n }\n\n function _setRedemptionStrategies(\n IRedemptionStrategy[] calldata strategies,\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens\n ) external onlyOwner {\n require(strategies.length == inputTokens.length && inputTokens.length == outputTokens.length, \"!arrays len\");\n for (uint256 i = 0; i < strategies.length; i++) {\n _setRedemptionStrategy(strategies[i], inputTokens[i], outputTokens[i]);\n }\n }\n\n function _resetRedemptionStrategies(\n IRedemptionStrategy[] calldata strategies,\n IERC20Upgradeable[] calldata inputTokens,\n IERC20Upgradeable[] calldata outputTokens\n ) external onlyOwner {\n require(strategies.length == inputTokens.length && inputTokens.length == outputTokens.length, \"!arrays len\");\n\n // empty the input/output token mappings/sets\n address[] memory _outputTokens = outputTokensSet.values();\n for (uint256 i = 0; i < _outputTokens.length; i++) {\n IERC20Upgradeable _outputToken = IERC20Upgradeable(_outputTokens[i]);\n address[] memory _inputTokens = inputTokensByOutputToken[_outputToken].values();\n for (uint256 j = 0; j < _inputTokens.length; j++) {\n IERC20Upgradeable _inputToken = IERC20Upgradeable(_inputTokens[j]);\n redemptionStrategiesByTokens[_inputToken][_outputToken] = IRedemptionStrategy(address(0));\n inputTokensByOutputToken[_outputToken].remove(_inputTokens[j]);\n defaultOutputToken[_inputToken] = IERC20Upgradeable(address(0));\n }\n outputTokensSet.remove(_outputTokens[i]);\n }\n\n // empty the strategies mappings/sets\n address[] memory _currentStrategies = redemptionStrategies.values();\n for (uint256 i = 0; i < _currentStrategies.length; i++) {\n IRedemptionStrategy _currentStrategy = IRedemptionStrategy(_currentStrategies[i]);\n string memory _name = _currentStrategy.name();\n redemptionStrategiesByName[_name] = IRedemptionStrategy(address(0));\n redemptionStrategies.remove(_currentStrategies[i]);\n }\n\n // write the new strategies and their tokens configs\n for (uint256 i = 0; i < strategies.length; i++) {\n _setRedemptionStrategy(strategies[i], inputTokens[i], outputTokens[i]);\n }\n }\n\n function _removeRedemptionStrategy(IRedemptionStrategy strategyToRemove) external onlyOwner {\n // check all the input/output tokens if they match the strategy to remove\n address[] memory _outputTokens = outputTokensSet.values();\n for (uint256 i = 0; i < _outputTokens.length; i++) {\n IERC20Upgradeable _outputToken = IERC20Upgradeable(_outputTokens[i]);\n address[] memory _inputTokens = inputTokensByOutputToken[_outputToken].values();\n for (uint256 j = 0; j < _inputTokens.length; j++) {\n IERC20Upgradeable _inputToken = IERC20Upgradeable(_inputTokens[j]);\n IRedemptionStrategy _currentStrategy = redemptionStrategiesByTokens[_inputToken][_outputToken];\n\n // only nullify the input/output tokens config if the strategy matches\n if (_currentStrategy == strategyToRemove) {\n redemptionStrategiesByTokens[_inputToken][_outputToken] = IRedemptionStrategy(address(0));\n inputTokensByOutputToken[_outputToken].remove(_inputTokens[j]);\n if (defaultOutputToken[_inputToken] == _outputToken) {\n defaultOutputToken[_inputToken] = IERC20Upgradeable(address(0));\n }\n }\n }\n if (inputTokensByOutputToken[_outputToken].length() == 0) {\n outputTokensSet.remove(address(_outputToken));\n }\n }\n\n redemptionStrategiesByName[strategyToRemove.name()] = IRedemptionStrategy(address(0));\n redemptionStrategies.remove(address(strategyToRemove));\n }\n\n function uniswapPairsFeesMatch(\n IERC20Upgradeable[] calldata configInputTokens,\n IERC20Upgradeable[] calldata configOutputTokens,\n uint256[] calldata configFees\n ) external view returns (bool) {\n // find a match for each config fee\n for (uint256 i = 0; i < configFees.length; i++) {\n if (uniswapV3Fees[configInputTokens[i]][configOutputTokens[i]] != configFees[i]) return false;\n }\n\n return true;\n }\n\n function uniswapPairsRoutersMatch(\n IERC20Upgradeable[] calldata configInputTokens,\n IERC20Upgradeable[] calldata configOutputTokens,\n address[] calldata configRouters\n ) external view returns (bool) {\n // find a match for each config router\n for (uint256 i = 0; i < configRouters.length; i++) {\n if (customUniV3Router[configInputTokens[i]][configOutputTokens[i]] != configRouters[i]) return false;\n }\n\n return true;\n }\n\n function pairsStrategiesMatch(\n IRedemptionStrategy[] calldata configStrategies,\n IERC20Upgradeable[] calldata configInputTokens,\n IERC20Upgradeable[] calldata configOutputTokens\n ) external view returns (bool) {\n (\n IRedemptionStrategy[] memory onChainStrategies,\n IERC20Upgradeable[] memory onChainInputTokens,\n IERC20Upgradeable[] memory onChainOutputTokens\n ) = getAllPairsStrategies();\n // find a match for each config strategy\n for (uint256 i = 0; i < configStrategies.length; i++) {\n bool foundMatch = false;\n for (uint256 j = 0; j < onChainStrategies.length; j++) {\n if (\n onChainStrategies[j] == configStrategies[i] &&\n onChainInputTokens[j] == configInputTokens[i] &&\n onChainOutputTokens[j] == configOutputTokens[i]\n ) {\n foundMatch = true;\n break;\n }\n }\n if (!foundMatch) return false;\n }\n\n // find a match for each on-chain strategy\n for (uint256 i = 0; i < onChainStrategies.length; i++) {\n bool foundMatch = false;\n for (uint256 j = 0; j < configStrategies.length; j++) {\n if (\n onChainStrategies[i] == configStrategies[j] &&\n onChainInputTokens[i] == configInputTokens[j] &&\n onChainOutputTokens[i] == configOutputTokens[j]\n ) {\n foundMatch = true;\n break;\n }\n }\n if (!foundMatch) return false;\n }\n\n return true;\n }\n\n function getAllPairsStrategies()\n public\n view\n returns (\n IRedemptionStrategy[] memory strategies,\n IERC20Upgradeable[] memory inputTokens,\n IERC20Upgradeable[] memory outputTokens\n )\n {\n address[] memory _outputTokens = outputTokensSet.values();\n uint256 pairsCounter = 0;\n\n {\n for (uint256 i = 0; i < _outputTokens.length; i++) {\n IERC20Upgradeable _outputToken = IERC20Upgradeable(_outputTokens[i]);\n address[] memory _inputTokens = inputTokensByOutputToken[_outputToken].values();\n pairsCounter += _inputTokens.length;\n }\n\n strategies = new IRedemptionStrategy[](pairsCounter);\n inputTokens = new IERC20Upgradeable[](pairsCounter);\n outputTokens = new IERC20Upgradeable[](pairsCounter);\n }\n\n pairsCounter = 0;\n for (uint256 i = 0; i < _outputTokens.length; i++) {\n IERC20Upgradeable _outputToken = IERC20Upgradeable(_outputTokens[i]);\n address[] memory _inputTokens = inputTokensByOutputToken[_outputToken].values();\n for (uint256 j = 0; j < _inputTokens.length; j++) {\n IERC20Upgradeable _inputToken = IERC20Upgradeable(_inputTokens[j]);\n strategies[pairsCounter] = redemptionStrategiesByTokens[_inputToken][_outputToken];\n inputTokens[pairsCounter] = _inputToken;\n outputTokens[pairsCounter] = _outputToken;\n pairsCounter++;\n }\n }\n }\n\n function optimalSwapPath(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n external\n view\n returns (IERC20Upgradeable[] memory)\n {\n return _optimalSwapPath[inputToken][outputToken];\n }\n\n function _setOptimalSwapPath(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken,\n IERC20Upgradeable[] calldata optimalPath\n ) external onlyOwner {\n _optimalSwapPath[inputToken][outputToken] = optimalPath;\n }\n\n function wrappedToUnwrapped4626(address wrapped) external view returns (address) {\n return _wrappedToUnwrapped4626[wrapped];\n }\n\n function aeroCLTickSpacings(address inputToken, address outputToken) external view returns (int24) {\n return _aeroCLTickSpacings[inputToken][outputToken];\n }\n\n function aeroV2IsStable(address inputToken, address outputToken) external view returns (bool) {\n return _aeroV2IsStable[inputToken][outputToken];\n }\n\n function _setWrappedToUnwrapped4626(address wrapped, address unwrapped) external onlyOwner {\n _wrappedToUnwrapped4626[wrapped] = unwrapped;\n }\n\n function _setAeroCLTickSpacings(address inputToken, address outputToken, int24 tickSpacing) external onlyOwner {\n _aeroCLTickSpacings[inputToken][outputToken] = tickSpacing;\n }\n\n function _setAeroV2IsStable(address inputToken, address outputToken, bool isStable) external onlyOwner {\n _aeroV2IsStable[inputToken][outputToken] = isStable;\n }\n}" + }, + "contracts/src/liquidators/registry/LiquidatorsRegistryStorage.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.10;\n\nimport \"../IRedemptionStrategy.sol\";\nimport { SafeOwnable } from \"../../ionic/SafeOwnable.sol\";\nimport { AddressesProvider } from \"../../ionic/AddressesProvider.sol\";\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\n\nabstract contract LiquidatorsRegistryStorage is SafeOwnable {\n AddressesProvider public ap;\n\n EnumerableSet.AddressSet internal redemptionStrategies;\n mapping(string => IRedemptionStrategy) public redemptionStrategiesByName;\n mapping(IERC20Upgradeable => mapping(IERC20Upgradeable => IRedemptionStrategy)) public redemptionStrategiesByTokens;\n mapping(IERC20Upgradeable => IERC20Upgradeable) public defaultOutputToken;\n mapping(IERC20Upgradeable => EnumerableSet.AddressSet) internal inputTokensByOutputToken;\n EnumerableSet.AddressSet internal outputTokensSet;\n\n mapping(IERC20Upgradeable => mapping(IERC20Upgradeable => uint256)) internal conversionSlippage;\n mapping(IERC20Upgradeable => mapping(IERC20Upgradeable => uint256)) internal conversionSlippageUpdated;\n\n mapping(IERC20Upgradeable => mapping(IERC20Upgradeable => uint24)) public uniswapV3Fees;\n mapping(IERC20Upgradeable => mapping(IERC20Upgradeable => address)) public customUniV3Router;\n\n mapping(IERC20Upgradeable => mapping(IERC20Upgradeable => IERC20Upgradeable[])) internal _optimalSwapPath;\n mapping(address => address) internal _wrappedToUnwrapped4626;\n mapping(address => mapping(address => int24)) internal _aeroCLTickSpacings;\n mapping(address => mapping(address => bool)) internal _aeroV2IsStable;\n}" + }, + "contracts/src/liquidators/UniswapV1Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\n\nimport \"../external/uniswap/IUniswapV1Exchange.sol\";\nimport \"../external/uniswap/IUniswapV1Factory.sol\";\n\nimport \"../utils/IW_NATIVE.sol\";\n\nimport \"./IRedemptionStrategy.sol\";\n\n/**\n * @title UniswapV1Liquidator\n * @notice Exchanges seized token collateral for underlying tokens via a Uniswap V1 pool for use as a step in a liquidation.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract UniswapV1Liquidator is IRedemptionStrategy {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /**\n * @dev The V1 Uniswap factory contract.\n */\n IUniswapV1Factory private constant UNISWAP_V1_FACTORY = IUniswapV1Factory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95);\n\n /**\n * @dev W_NATIVE contract object.\n */\n IW_NATIVE private constant W_NATIVE = IW_NATIVE(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\n\n /**\n * @dev Internal function to approve unlimited tokens of `erc20Contract` to `to`.\n */\n function safeApprove(IERC20Upgradeable token, address to, uint256 minAmount) private {\n uint256 allowance = token.allowance(address(this), to);\n\n if (allowance < minAmount) {\n if (allowance > 0) token.safeApprove(to, 0);\n token.safeApprove(to, type(uint256).max);\n }\n }\n\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n // Get Uniswap exchange\n IUniswapV1Exchange uniswapV1Exchange = IUniswapV1Exchange(UNISWAP_V1_FACTORY.getExchange(address(inputToken)));\n\n // Swap underlying tokens\n safeApprove(inputToken, address(uniswapV1Exchange), inputAmount);\n uniswapV1Exchange.tokenToEthSwapInput(inputAmount, 1, block.timestamp);\n\n // Get new collateral\n outputAmount = address(this).balance;\n W_NATIVE.deposit{ value: outputAmount }();\n return (IERC20Upgradeable(address(W_NATIVE)), outputAmount);\n }\n\n function name() public pure returns (string memory) {\n return \"UniswapV1Liquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/UniswapV2Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./BaseUniswapV2Liquidator.sol\";\n\n/**\n * @title UniswapV2Liquidator\n * @notice Exchanges seized token collateral for underlying tokens via a Uniswap V2 router for use as a step in a liquidation.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract UniswapV2Liquidator is BaseUniswapV2Liquidator {\n function _swap(\n IUniswapV2Router02 uniswapV2Router,\n uint256 inputAmount,\n address[] memory swapPath\n ) internal override {\n uniswapV2Router.swapExactTokensForTokens(inputAmount, 0, swapPath, address(this), block.timestamp);\n }\n\n function name() public pure virtual returns (string memory) {\n return \"UniswapV2Liquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/UniswapV2LiquidatorFunder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { UniswapV2Liquidator } from \"./UniswapV2Liquidator.sol\";\nimport \"./IFundsConversionStrategy.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"../external/uniswap/IUniswapV2Router02.sol\";\n\ncontract UniswapV2LiquidatorFunder is UniswapV2Liquidator, IFundsConversionStrategy {\n function convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n function estimateInputAmount(\n uint256 outputAmount,\n bytes memory strategyData\n ) external view returns (IERC20Upgradeable inputToken, uint256 inputAmount) {\n (IUniswapV2Router02 uniswapV2Router, address[] memory swapPath) = abi.decode(\n strategyData,\n (IUniswapV2Router02, address[])\n );\n require(swapPath.length >= 2, \"Invalid UniswapLiquidator swap path.\");\n\n uint256[] memory amounts = uniswapV2Router.getAmountsIn(outputAmount, swapPath);\n\n inputAmount = amounts[0];\n inputToken = IERC20Upgradeable(swapPath[0]);\n }\n\n function name() public pure override(UniswapV2Liquidator, IRedemptionStrategy) returns (string memory) {\n return \"UniswapV2LiquidatorFunder\";\n }\n}\n" + }, + "contracts/src/liquidators/UniswapV3Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IRedemptionStrategy } from \"./IRedemptionStrategy.sol\";\nimport { IV3SwapRouter } from \"../external/uniswap/IV3SwapRouter.sol\";\n\nimport { IERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ncontract UniswapV3Liquidator is IRedemptionStrategy {\n /**\n * @dev Redeems `inputToken` for `outputToken` where `inputAmount` < `outputAmount`\n * @param inputToken Address of the token\n * @param inputAmount input amount\n * @param strategyData context specific data like input token, pool address and tx expiratio period\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n function _convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) internal returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n (, address _outputToken, uint24 fee, IV3SwapRouter swapRouter, ) = abi.decode(\n strategyData,\n (address, address, uint24, IV3SwapRouter, address)\n );\n outputToken = IERC20Upgradeable(_outputToken);\n\n inputToken.approve(address(swapRouter), inputAmount);\n\n outputAmount = swapRouter.exactInputSingle(\n IV3SwapRouter.ExactInputSingleParams(\n address(inputToken),\n _outputToken,\n fee,\n address(this),\n inputAmount,\n 0,\n 0\n )\n );\n }\n\n function name() public pure virtual override returns (string memory) {\n return \"UniswapV3Liquidator\";\n }\n}\n" + }, + "contracts/src/liquidators/UniswapV3LiquidatorFunder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { FixedPointMathLib } from \"solmate/utils/FixedPointMathLib.sol\";\nimport { IFundsConversionStrategy } from \"./IFundsConversionStrategy.sol\";\nimport { IRedemptionStrategy } from \"./IRedemptionStrategy.sol\";\nimport \"./UniswapV3Liquidator.sol\";\n\nimport { Quoter } from \"../external/uniswap/quoter/Quoter.sol\";\n\ncontract UniswapV3LiquidatorFunder is UniswapV3Liquidator, IFundsConversionStrategy {\n using FixedPointMathLib for uint256;\n\n function convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n /**\n * @dev Estimates the needed input amount of the input token for the conversion to return the desired output amount.\n * @param outputAmount the desired output amount\n * @param strategyData the input token\n */\n function estimateInputAmount(uint256 outputAmount, bytes memory strategyData)\n external\n view\n returns (IERC20Upgradeable inputToken, uint256 inputAmount)\n {\n (address _inputToken, address _outputToken, uint24 fee, , Quoter quoter) = abi.decode(\n strategyData,\n (address, address, uint24, IV3SwapRouter, Quoter)\n );\n\n inputAmount = quoter.estimateMinSwapUniswapV3(_inputToken, _outputToken, outputAmount, fee);\n inputToken = IERC20Upgradeable(_inputToken);\n }\n\n function name() public pure override(UniswapV3Liquidator, IRedemptionStrategy) returns (string memory) {\n return \"UniswapV3LiquidatorFunder\";\n }\n}\n" + }, + "contracts/src/liquidators/VelodromeV2Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\nimport { IRouter_Velodrome } from \"../external/velodrome/IVelodromeRouter.sol\";\n\n/**\n * @title VelodromeV2Liquidator\n * @notice Exchanges seized token collateral for underlying tokens via a Velodrome V2 router for use as a step in a liquidation.\n */\ncontract VelodromeV2Liquidator {\n function _swap(IRouter_Velodrome router, uint256 inputAmount, IRouter_Velodrome.Route[] memory swapPath) internal {\n router.swapExactTokensForTokens(inputAmount, 0, swapPath, address(this), block.timestamp);\n }\n\n function name() public pure virtual returns (string memory) {\n return \"VelodromeV2Liquidator\";\n }\n\n /**\n * @notice Redeems custom collateral `token` for an underlying token.\n * @param inputToken The input wrapped token to be redeemed for an underlying token.\n * @param inputAmount The amount of the input wrapped token to be redeemed for an underlying token.\n * @param strategyData The ABI-encoded data to be used in the redemption strategy logic.\n * @return outputToken The underlying ERC20 token outputted.\n * @return outputAmount The quantity of underlying tokens outputted.\n */\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n return _convert(inputToken, inputAmount, strategyData);\n }\n\n function _convert(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) internal returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n // Get Uniswap router and path\n (IRouter_Velodrome router, IRouter_Velodrome.Route[] memory swapPath) = abi.decode(\n strategyData,\n (IRouter_Velodrome, IRouter_Velodrome.Route[])\n );\n require(\n swapPath.length >= 1 && swapPath[0].from == address(inputToken),\n \"Invalid VelodromeV2Liquidator swap path.\"\n );\n\n // Swap underlying tokens\n inputToken.approve(address(router), inputAmount);\n\n // call the relevant fn depending on the uni v2 fork specifics\n _swap(router, inputAmount, swapPath);\n\n // Get new collateral\n outputToken = IERC20Upgradeable(swapPath[swapPath.length - 1].to);\n outputAmount = outputToken.balanceOf(address(this));\n }\n}\n" + }, + "contracts/src/oracles/1337/MockPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../../external/chainlink/AggregatorV3Interface.sol\";\n\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title MockPriceOracle\n * @notice Returns mocked prices from a Chainlink-like oracle. Used for local dev only\n * @dev Implements `PriceOracle`.\n * @author Carlo Mazzaferro (https://github.com/carlomazzaferro)\n */\ncontract MockPriceOracle is BasePriceOracle {\n /**\n * @notice The maximum number of seconds elapsed since the round was last updated before the price is considered stale. If set to 0, no limit is enforced.\n */\n uint256 public maxSecondsBeforePriceIsStale;\n\n /**\n * @dev Constructor to set `maxSecondsBeforePriceIsStale` as well as all Chainlink price feeds.\n */\n constructor(uint256 _maxSecondsBeforePriceIsStale) {\n // Set maxSecondsBeforePriceIsStale\n maxSecondsBeforePriceIsStale = _maxSecondsBeforePriceIsStale;\n }\n\n /**\n * @dev Returns a boolean indicating if a price feed exists for the underlying asset.\n */\n\n function hasPriceFeed(address underlying) external pure returns (bool) {\n return true;\n }\n\n /**\n * @dev Internal function returning the price in ETH of `underlying`.\n */\n\n function random() private view returns (uint256) {\n uint256 r = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender))) % 99;\n r = r + 1;\n return r;\n }\n\n function _price(address underlying) internal view returns (uint256) {\n // Return 1e18 for WETH\n if (underlying == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2) return 1e18;\n\n int256 tokenEthPrice = 1;\n uint256 r = random();\n\n return ((uint256(tokenEthPrice) * 1e18) / r) / 1e18;\n }\n\n /**\n * @dev Returns the price in ETH of `underlying` (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n return 1e18;\n }\n}\n" + }, + "contracts/src/oracles/1337/MockRevertPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title MockRevertPriceOracle\n * @notice Mocks a failing price oracle. Used for testing purposes only\n * @author Jourdan Dunkley (https://github.com/jourdanDunkley)\n */\ncontract MockRevertPriceOracle is BasePriceOracle {\n constructor() {}\n\n /**\n * @dev Returns the price in ETH of `underlying` (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n revert(\"MockPriceOracle: price function is failing.\");\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n revert(\"MockPriceOracle: getUnderlyingPrice function is failing.\");\n }\n}\n" + }, + "contracts/src/oracles/BasePriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../compound/CTokenInterfaces.sol\";\n\n/**\n * @title BasePriceOracle\n * @notice Returns prices of underlying tokens directly without the caller having to specify a cToken address.\n * @dev Implements the `PriceOracle` interface.\n * @author David Lucid (https://github.com/davidlucid)\n */\ninterface BasePriceOracle {\n /**\n * @notice Get the price of an underlying asset.\n * @param underlying The underlying asset to get the price of.\n * @return The underlying asset price in ETH as a mantissa (scaled by 1e18).\n * Zero means the price is unavailable.\n */\n function price(address underlying) external view returns (uint256);\n\n /**\n * @notice Get the underlying price of a cToken asset\n * @param cToken The cToken to get the underlying price of\n * @return The underlying asset price mantissa (scaled by 1e18).\n * Zero means the price is unavailable.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view returns (uint256);\n}\n" + }, + "contracts/src/oracles/default/AerodromePriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../BasePriceOracle.sol\";\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\ninterface BasePrices {\n function getManyRatesWithConnectors(\n uint8 src_len,\n address[] memory connectors\n ) external view returns (uint256[] memory rates);\n}\n\ncontract AerodromePriceOracle is BasePriceOracle {\n BasePrices immutable prices;\n address constant WETH = 0x4200000000000000000000000000000000000006;\n\n constructor(address _prices) {\n prices = BasePrices(_prices);\n }\n\n /**\n * @notice Fetches the token/ETH price, with 18 decimals of precision.\n * @param underlying The underlying token address for which to get the price.\n * @return Price denominated in ETH (scaled by 1e18)\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying));\n }\n\n /**\n * @notice Fetches the token/ETH price, with 18 decimals of precision.\n */\n function _price(address token) internal view returns (uint256) {\n address[] memory connectors = new address[](2);\n connectors[0] = token;\n connectors[1] = WETH;\n return prices.getManyRatesWithConnectors(1, connectors)[0];\n }\n}\n" + }, + "contracts/src/oracles/default/API3PriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport { IProxy } from \"../../external/api3/IProxy.sol\";\n\nimport \"../BasePriceOracle.sol\";\nimport { SafeOwnableUpgradeable } from \"../../ionic/SafeOwnableUpgradeable.sol\";\n\n/**\n * @title API3PriceOracle\n * @notice Returns prices from Api3.\n * @dev Implements `PriceOracle`.\n * @author Carlo Mazzaferro (https://github.com/carlomazzaferro)\n */\ncontract API3PriceOracle is SafeOwnableUpgradeable, BasePriceOracle {\n /**\n * @notice Maps ERC20 token addresses to ETH-based Chainlink price feed contracts.\n */\n mapping(address => IProxy) public proxies;\n\n /**\n * @notice Chainlink NATIVE/USD price feed contracts.\n */\n address public NATIVE_TOKEN_USD_PRICE_FEED;\n\n /**\n * @notice The USD Token of the chain\n */\n address public USD_TOKEN;\n\n /**\n * @dev Constructor to set wtoken address and native token USD price feed address\n * @param _usdToken The Wrapped native asset address\n * @param nativeTokenUsd Will this oracle return prices denominated in USD or in the native token.\n */\n function initialize(address _usdToken, address nativeTokenUsd) public initializer {\n __SafeOwnable_init(msg.sender);\n USD_TOKEN = _usdToken;\n NATIVE_TOKEN_USD_PRICE_FEED = nativeTokenUsd;\n }\n\n /**\n * @dev Constructor to set wtoken address and native token USD price feed address\n * @param _usdToken The Wrapped native asset address\n * @param nativeTokenUsd Will this oracle return prices denominated in USD or in the native token.\n */\n function reinitialize(address _usdToken, address nativeTokenUsd) public onlyOwnerOrAdmin {\n USD_TOKEN = _usdToken;\n NATIVE_TOKEN_USD_PRICE_FEED = nativeTokenUsd;\n }\n\n /**\n * @dev Admin-only function to set price feeds.\n * @param underlyings Underlying token addresses for which to set price feeds.\n * @param feeds The Chainlink price feed contract addresses for each of `underlyings`.\n */\n function setPriceFeeds(address[] memory underlyings, address[] memory feeds) external onlyOwner {\n // Input validation\n require(\n underlyings.length > 0 && underlyings.length == feeds.length,\n \"Lengths of both arrays must be equal and greater than 0.\"\n );\n\n // For each token/feed\n for (uint256 i = 0; i < underlyings.length; i++) {\n address underlying = underlyings[i];\n // Set feed and base currency\n proxies[underlying] = IProxy(feeds[i]);\n }\n }\n\n /**\n * @notice Internal function returning the price in of `underlying`.\n * @dev If the oracle got constructed with `nativeTokenUsd` = TRUE this will return a price denominated in USD otherwise in the native token\n */\n function _price(address underlying) internal view returns (uint256) {\n IProxy proxy = proxies[underlying];\n require(address(proxy) != address(0), \"No API3 price feed found for this underlying ERC20 token.\");\n\n uint256 nativeTokenUsdPrice;\n\n if (NATIVE_TOKEN_USD_PRICE_FEED == address(0)) {\n // get the USDX/USD price from the MPO\n uint256 usdNativeTokenPrice = BasePriceOracle(msg.sender).price(USD_TOKEN);\n nativeTokenUsdPrice = 1e36 / usdNativeTokenPrice; // 18 decimals\n } else {\n (int224 nativeTokenUsdPrice224, ) = IProxy(NATIVE_TOKEN_USD_PRICE_FEED).read();\n if (nativeTokenUsdPrice224 <= 0) {\n revert(\"API3PriceOracle: native token price <= 0\");\n }\n nativeTokenUsdPrice = uint256(uint224(nativeTokenUsdPrice224));\n }\n (int224 tokenUsdPrice, ) = proxy.read();\n\n if (tokenUsdPrice <= 0) {\n revert(\"API3PriceOracle: token price <= 0\");\n }\n\n return (uint256(uint224(tokenUsdPrice)) * 1e18) / nativeTokenUsdPrice;\n }\n\n /**\n * @notice Returns the price in of `underlying` either in USD or the native token (implements `BasePriceOracle`).\n * @dev If the oracle got constructed with `nativeTokenUsd` = TRUE this will return a price denominated in USD otherwise in the native token\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying token address\n address underlying = cToken.underlying();\n\n uint256 oraclePrice = _price(underlying);\n\n uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals());\n return\n underlyingDecimals <= 18\n ? uint256(oraclePrice) * (10 ** (18 - underlyingDecimals))\n : uint256(oraclePrice) / (10 ** (underlyingDecimals - 18));\n }\n}\n" + }, + "contracts/src/oracles/default/ChainlinkPriceOracleV2.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../../external/chainlink/AggregatorV3Interface.sol\";\n\nimport \"../BasePriceOracle.sol\";\nimport { SafeOwnableUpgradeable } from \"../../ionic/SafeOwnableUpgradeable.sol\";\n\n/**\n * @title ChainlinkPriceOracleV2\n * @notice Returns prices from Chainlink.\n * @dev Implements `PriceOracle`.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract ChainlinkPriceOracleV2 is SafeOwnableUpgradeable, BasePriceOracle {\n /**\n * @notice Maps ERC20 token addresses to ETH-based Chainlink price feed contracts.\n */\n mapping(address => AggregatorV3Interface) public priceFeeds;\n\n /**\n * @notice Maps ERC20 token addresses to enums indicating the base currency of the feed.\n */\n mapping(address => FeedBaseCurrency) public feedBaseCurrencies;\n\n /**\n * @notice Enum indicating the base currency of a Chainlink price feed.\n * @dev ETH is interchangeable with the nativeToken of the current chain.\n */\n enum FeedBaseCurrency {\n ETH,\n USD\n }\n\n /**\n * @notice Chainlink NATIVE/USD price feed contracts.\n */\n address public NATIVE_TOKEN_USD_PRICE_FEED;\n\n /**\n * @notice The USD Token of the chain\n */\n address public USD_TOKEN;\n\n /**\n * @dev Constructor to set admin and canAdminOverwrite, wtoken address and native token USD price feed address\n * @param _usdToken The Wrapped native asset address\n * @param nativeTokenUsd Will this oracle return prices denominated in USD or in the native token.\n */\n function initialize(address _usdToken, address nativeTokenUsd) public initializer {\n __SafeOwnable_init(msg.sender);\n USD_TOKEN = _usdToken;\n NATIVE_TOKEN_USD_PRICE_FEED = nativeTokenUsd;\n }\n\n /**\n * @dev Admin-only function to set price feeds.\n * @param underlyings Underlying token addresses for which to set price feeds.\n * @param feeds The Chainlink price feed contract addresses for each of `underlyings`.\n * @param baseCurrency The currency in which `feeds` are based.\n */\n function setPriceFeeds(\n address[] memory underlyings,\n address[] memory feeds,\n FeedBaseCurrency baseCurrency\n ) external onlyOwner {\n // Input validation\n require(\n underlyings.length > 0 && underlyings.length == feeds.length,\n \"Lengths of both arrays must be equal and greater than 0.\"\n );\n\n // For each token/feed\n for (uint256 i = 0; i < underlyings.length; i++) {\n address underlying = underlyings[i];\n // Set feed and base currency\n priceFeeds[underlying] = AggregatorV3Interface(feeds[i]);\n feedBaseCurrencies[underlying] = baseCurrency;\n }\n }\n\n /**\n * @notice Internal function returning the price in of `underlying`.\n * @dev If the oracle got constructed with `nativeTokenUsd` = TRUE this will return a price denominated in USD otherwise in the native token\n */\n function _price(address underlying) internal view returns (uint256) {\n // Get token/ETH price from Chainlink\n AggregatorV3Interface feed = priceFeeds[underlying];\n require(address(feed) != address(0), \"No Chainlink price feed found for this underlying ERC20 token.\");\n FeedBaseCurrency baseCurrency = feedBaseCurrencies[underlying];\n\n if (baseCurrency == FeedBaseCurrency.ETH) {\n (, int256 tokenEthPrice, , , ) = feed.latestRoundData();\n return tokenEthPrice >= 0 ? (uint256(tokenEthPrice) * 1e18) / (10 ** uint256(feed.decimals())) : 0;\n } else if (baseCurrency == FeedBaseCurrency.USD) {\n int256 nativeTokenUsdPrice;\n uint8 usdPriceDecimals;\n\n if (NATIVE_TOKEN_USD_PRICE_FEED == address(0)) {\n uint256 usdNativeTokenPrice = BasePriceOracle(msg.sender).price(USD_TOKEN);\n nativeTokenUsdPrice = int256(1e36 / usdNativeTokenPrice); // 18 decimals\n usdPriceDecimals = 18;\n } else {\n (, nativeTokenUsdPrice, , , ) = AggregatorV3Interface(NATIVE_TOKEN_USD_PRICE_FEED).latestRoundData();\n if (nativeTokenUsdPrice <= 0) return 0;\n usdPriceDecimals = AggregatorV3Interface(NATIVE_TOKEN_USD_PRICE_FEED).decimals();\n }\n (, int256 tokenUsdPrice, , , ) = feed.latestRoundData();\n\n return\n tokenUsdPrice >= 0\n ? ((uint256(tokenUsdPrice) * 1e18 * (10 ** uint256(usdPriceDecimals))) / (10 ** uint256(feed.decimals()))) /\n uint256(nativeTokenUsdPrice)\n : 0;\n } else {\n revert(\"unknown base currency\");\n }\n }\n\n /**\n * @notice Returns the price in of `underlying` either in USD or the native token (implements `BasePriceOracle`).\n * @dev If the oracle got constructed with `nativeTokenUsd` = TRUE this will return a price denominated in USD otherwise in the native token\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying token address\n address underlying = cToken.underlying();\n\n uint256 oraclePrice = _price(underlying);\n\n uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals());\n return\n underlyingDecimals <= 18\n ? uint256(oraclePrice) * (10 ** (18 - underlyingDecimals))\n : uint256(oraclePrice) / (10 ** (underlyingDecimals - 18));\n }\n}\n" + }, + "contracts/src/oracles/default/ConcentratedLiquidityBasePriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { EIP20Interface } from \"../../compound/EIP20Interface.sol\";\nimport { ERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\nimport { BasePriceOracle } from \"../../oracles/BasePriceOracle.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\n\nimport \"../../external/uniswap/FullMath.sol\";\nimport \"../../ionic/SafeOwnableUpgradeable.sol\";\n\n/**\n * @title ConcentratedLiquidityBasePriceOracle\n * @author Carlo Mazzaferro (https://github.com/carlomazzaferro)\n * @notice ConcentratedLiquidityBasePriceOracle is an abstract price oracle for concentrated liquidty (UniV3-like) pairs.\n * @dev Implements the `PriceOracle` interface used by Ionic pools (and Compound v2).\n */\nabstract contract ConcentratedLiquidityBasePriceOracle is BasePriceOracle, SafeOwnableUpgradeable {\n /**\n * @notice Maps ERC20 token addresses to asset configs.\n */\n mapping(address => AssetConfig) public poolFeeds;\n\n /**\n * @dev Controls if `admin` can overwrite existing assignments of oracles to underlying tokens.\n */\n bool public canAdminOverwrite;\n\n struct AssetConfig {\n address poolAddress;\n uint256 twapWindow;\n address baseToken;\n }\n\n address public WTOKEN;\n address[] public SUPPORTED_BASE_TOKENS;\n\n function initialize(address _wtoken, address[] memory _supportedBaseTokens) public initializer {\n __SafeOwnable_init(msg.sender);\n WTOKEN = _wtoken;\n SUPPORTED_BASE_TOKENS = _supportedBaseTokens;\n }\n\n /**\n * @dev Admin-only function to set price feeds.\n * @param underlyings Underlying token addresses for which to set price feeds.\n * @param assetConfig The asset configuration which includes pool address and twap window.\n */\n function setPoolFeeds(address[] memory underlyings, AssetConfig[] memory assetConfig) external onlyOwner {\n // Input validation\n require(\n underlyings.length > 0 && underlyings.length == assetConfig.length,\n \"Lengths of both arrays must be equal and greater than 0.\"\n );\n\n // For each token/config\n for (uint256 i = 0; i < underlyings.length; i++) {\n address underlying = underlyings[i];\n // Set asset config for underlying\n require(\n assetConfig[i].baseToken == WTOKEN || _isBaseTokenSupported(assetConfig[i].baseToken),\n \"Base token must be supported\"\n );\n poolFeeds[underlying] = assetConfig[i];\n }\n }\n\n /**\n * @notice Get the token price price for an underlying token address.\n * @param underlying The underlying token address for which to get the price (set to zero address for WTOKEN)\n * @return Price denominated in NATIVE (scaled by 1e18)\n */\n function price(address underlying) external view returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in NATIVE of the token underlying `cToken`.\n * @dev Implements the `BasePriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in NATIVE of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) public view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying) * 1e18) / (10 ** uint256(EIP20Interface(underlying).decimals()));\n }\n\n /**\n * @dev Fetches the price for a token from Uniswap v3\n */\n function _price(address token) internal view virtual returns (uint256);\n\n function getPriceX96FromSqrtPriceX96(\n address token0,\n address priceToken,\n uint160 sqrtPriceX96\n ) public pure returns (uint256 price_) {\n price_ = FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, uint256(2 ** (96 * 2)) / 1e18);\n if (token0 != priceToken) price_ = 1e36 / price_;\n }\n\n function _isBaseTokenSupported(address token) internal view returns (bool) {\n for (uint256 i = 0; i < SUPPORTED_BASE_TOKENS.length; i++) {\n if (SUPPORTED_BASE_TOKENS[i] == token) {\n return true;\n }\n }\n return false;\n }\n\n function _setSupportedBaseTokens(address[] memory _supportedBaseTokens) external onlyOwner {\n SUPPORTED_BASE_TOKENS = _supportedBaseTokens;\n }\n\n function getSupportedBaseTokens() external view returns (address[] memory) {\n return SUPPORTED_BASE_TOKENS;\n }\n\n function scalePrices(address baseToken, address token, uint256 tokenPrice) internal view returns (uint256) {\n uint256 baseTokenDecimals;\n uint256 tokenPriceScaled;\n\n if (baseToken == address(0) || baseToken == WTOKEN) {\n baseTokenDecimals = 18;\n } else {\n baseTokenDecimals = uint256(ERC20Upgradeable(baseToken).decimals());\n }\n\n uint256 baseNativePrice = BasePriceOracle(msg.sender).price(baseToken);\n\n // scale tokenPrice by 1e18\n uint256 tokenDecimals = uint256(ERC20Upgradeable(token).decimals());\n if (baseTokenDecimals > tokenDecimals) {\n tokenPriceScaled = tokenPrice / (10 ** (baseTokenDecimals - tokenDecimals));\n } else if (baseTokenDecimals < tokenDecimals) {\n tokenPriceScaled = tokenPrice * (10 ** (tokenDecimals - baseTokenDecimals));\n } else {\n tokenPriceScaled = tokenPrice;\n }\n return (tokenPriceScaled * baseNativePrice) / 1e18;\n }\n}\n" + }, + "contracts/src/oracles/default/CurveLpTokenPriceOracleNoRegistry.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { EIP20Interface } from \"../../compound/EIP20Interface.sol\";\n\nimport \"../../external/curve/ICurvePool.sol\";\nimport \"../../ionic/SafeOwnableUpgradeable.sol\";\n\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title CurveLpTokenPriceOracleNoRegistry\n * @author David Lucid (https://github.com/davidlucid)\n * @notice CurveLpTokenPriceOracleNoRegistry is a price oracle for Curve LP tokens (using the sender as a root oracle).\n * @dev Implements the `PriceOracle` interface used by Ionic pools (and Compound v2).\n */\ncontract CurveLpTokenPriceOracleNoRegistry is SafeOwnableUpgradeable, BasePriceOracle {\n /**\n * @dev Maps Curve LP token addresses to underlying token addresses.\n */\n mapping(address => address[]) public underlyingTokens;\n\n /**\n * @dev Maps Curve LP token addresses to pool addresses.\n */\n mapping(address => address) public poolOf;\n\n address[] public lpTokens;\n\n /**\n * @dev Initializes an array of LP tokens and pools if desired.\n * @param _lpTokens Array of LP token addresses.\n * @param _pools Array of pool addresses.\n * @param _poolUnderlyings The underlying token addresses of a pool\n */\n function initialize(\n address[] memory _lpTokens,\n address[] memory _pools,\n address[][] memory _poolUnderlyings\n ) public initializer {\n require(\n _lpTokens.length == _pools.length && _lpTokens.length == _poolUnderlyings.length,\n \"No LP tokens supplied or array lengths not equal.\"\n );\n\n __SafeOwnable_init(msg.sender);\n for (uint256 i = 0; i < _lpTokens.length; i++) {\n poolOf[_lpTokens[i]] = _pools[i];\n underlyingTokens[_lpTokens[i]] = _poolUnderlyings[i];\n }\n }\n\n function getAllLPTokens() public view returns (address[] memory) {\n return lpTokens;\n }\n\n function getPoolForSwap(address inputToken, address outputToken)\n public\n view\n returns (\n ICurvePool,\n int128,\n int128\n )\n {\n for (uint256 i = 0; i < lpTokens.length; i++) {\n ICurvePool pool = ICurvePool(poolOf[lpTokens[i]]);\n int128 inputIndex = -1;\n int128 outputIndex = -1;\n int128 j = 0;\n while (true) {\n try pool.coins(uint256(uint128(j))) returns (address coin) {\n if (coin == inputToken) inputIndex = j;\n else if (coin == outputToken) outputIndex = j;\n j++;\n } catch {\n break;\n }\n\n if (outputIndex > -1 && inputIndex > -1) {\n return (pool, inputIndex, outputIndex);\n }\n }\n }\n\n return (ICurvePool(address(0)), 0, 0);\n }\n\n /**\n * @notice Get the LP token price price for an underlying token address.\n * @param underlying The underlying token address for which to get the price (set to zero address for ETH).\n * @return Price denominated in ETH (scaled by 1e18).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying) * 1e18) / (10**uint256(EIP20Interface(underlying).decimals()));\n }\n\n /**\n * @dev Fetches the fair LP token/ETH price from Curve, with 18 decimals of precision.\n * Source: https://github.com/AlphaFinanceLab/homora-v2/blob/master/contracts/oracle/CurveOracle.sol\n * @param lpToken The LP token contract address for price retrieval.\n */\n function _price(address lpToken) internal view returns (uint256) {\n address pool = poolOf[lpToken];\n require(pool != address(0), \"LP token is not registered.\");\n address[] memory tokens = underlyingTokens[lpToken];\n uint256 minPx = type(uint256).max;\n uint256 n = tokens.length;\n\n for (uint256 i = 0; i < n; i++) {\n address ulToken = tokens[i];\n uint256 tokenPx = BasePriceOracle(msg.sender).price(ulToken);\n if (tokenPx < minPx) minPx = tokenPx;\n }\n\n require(minPx != type(uint256).max, \"No minimum underlying token price found.\");\n return (minPx * ICurvePool(pool).get_virtual_price()) / 1e18; // Use min underlying token prices\n }\n\n /**\n * @dev Register the pool given LP token address and set the pool info.\n * @param _lpToken LP token to find the corresponding pool.\n * @param _pool Pool address.\n * @param _underlyings Underlying addresses.\n */\n function registerPool(\n address _lpToken,\n address _pool,\n address[] memory _underlyings\n ) external onlyOwner {\n poolOf[_lpToken] = _pool;\n underlyingTokens[_lpToken] = _underlyings;\n\n bool skip = false;\n for (uint256 j = 0; j < lpTokens.length; j++) {\n if (lpTokens[j] == _lpToken) {\n skip = true;\n break;\n }\n }\n if (!skip) lpTokens.push(_lpToken);\n }\n\n /**\n * @dev getter for the underlying tokens\n * @param lpToken the LP token address.\n * @return _underlyings Underlying addresses.\n */\n function getUnderlyingTokens(address lpToken) public view returns (address[] memory) {\n return underlyingTokens[lpToken];\n }\n}\n" + }, + "contracts/src/oracles/default/CurveV2LpTokenPriceOracleNoRegistry.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { EIP20Interface } from \"../../compound/EIP20Interface.sol\";\nimport { MasterPriceOracle } from \"../MasterPriceOracle.sol\";\n\nimport \"../../external/curve/ICurveV2Pool.sol\";\nimport \"../../ionic/SafeOwnableUpgradeable.sol\";\n\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title CurveLpTokenPriceOracle\n * @author Carlo Mazzaferro (https://github.com/carlomazzaferro)\n * @notice CurveLpTokenPriceOracleNoRegistry is a price oracle for Curve V2 LP tokens (using the sender as a root oracle).\n * @dev Implements the `PriceOracle` interface used by Midas pools (and Compound v2).\n */\ncontract CurveV2LpTokenPriceOracleNoRegistry is SafeOwnableUpgradeable, BasePriceOracle {\n address public usdToken;\n MasterPriceOracle public masterPriceOracle;\n /**\n * @dev Maps Curve LP token addresses to pool addresses.\n */\n mapping(address => address) public poolOf;\n\n address[] public lpTokens;\n\n /**\n * @dev Initializes an array of LP tokens and pools if desired.\n * @param _lpTokens Array of LP token addresses.\n * @param _pools Array of pool addresses.\n */\n function initialize(address[] memory _lpTokens, address[] memory _pools) public initializer {\n require(_lpTokens.length == _pools.length, \"No LP tokens supplied or array lengths not equal.\");\n __SafeOwnable_init(msg.sender);\n\n for (uint256 i = 0; i < _pools.length; i++) {\n poolOf[_lpTokens[i]] = _pools[i];\n }\n }\n\n function getAllLPTokens() public view returns (address[] memory) {\n return lpTokens;\n }\n\n function getPoolForSwap(address inputToken, address outputToken)\n public\n view\n returns (\n ICurvePool,\n int128,\n int128\n )\n {\n for (uint256 i = 0; i < lpTokens.length; i++) {\n ICurvePool pool = ICurvePool(poolOf[lpTokens[i]]);\n int128 inputIndex = -1;\n int128 outputIndex = -1;\n int128 j = 0;\n while (true) {\n try pool.coins(uint256(uint128(j))) returns (address coin) {\n if (coin == inputToken) inputIndex = j;\n else if (coin == outputToken) outputIndex = j;\n j++;\n } catch {\n break;\n }\n\n if (outputIndex > -1 && inputIndex > -1) {\n return (pool, inputIndex, outputIndex);\n }\n }\n }\n\n return (ICurvePool(address(0)), int128(0), int128(0));\n }\n\n /**\n * @notice Get the LP token price price for an underlying token address.\n * @param underlying The underlying token address for which to get the price (set to zero address for ETH).\n * @return Price denominated in ETH (scaled by 1e18).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying) * 1e18) / (10**uint256(EIP20Interface(underlying).decimals()));\n }\n\n /**\n * @dev Fetches the fair LP token price from Curve, with 18 decimals of precision.\n * @param lpToken The LP token contract address for price retrieval.\n */\n function _price(address lpToken) internal view returns (uint256) {\n address pool = poolOf[lpToken];\n require(address(pool) != address(0), \"LP token is not registered.\");\n\n address baseToken = ICurvePool(pool).coins(0);\n uint256 lpPrice = ICurveV2Pool(pool).lp_price();\n uint256 baseTokenPrice = BasePriceOracle(msg.sender).price(baseToken);\n return (lpPrice * baseTokenPrice) / 10**18;\n }\n\n /**\n * @dev Register the pool given LP token address and set the pool info.\n * @param _lpToken LP token to find the corresponding pool.\n * @param _pool Pool address.\n */\n function registerPool(address _lpToken, address _pool) external onlyOwner {\n address pool = poolOf[_lpToken];\n require(pool == address(0), \"This LP token is already registered.\");\n poolOf[_lpToken] = _pool;\n\n bool skip = false;\n for (uint256 j = 0; j < lpTokens.length; j++) {\n if (lpTokens[j] == _lpToken) {\n skip = true;\n break;\n }\n }\n if (!skip) lpTokens.push(_lpToken);\n }\n}\n" + }, + "contracts/src/oracles/default/CurveV2PriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { EIP20Interface } from \"../../compound/EIP20Interface.sol\";\n\nimport \"../../external/curve/ICurveV2Pool.sol\";\n\nimport \"../../ionic/SafeOwnableUpgradeable.sol\";\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title CurveLpTokenPriceOracle\n * @author Carlo Mazzaferro (https://github.com/carlomazzaferro)\n * @notice CurveLpTokenPriceOracleNoRegistry is a price oracle for Curve V2 LP tokens (using the sender as a root oracle).\n * @dev Implements the `PriceOracle` interface used by Midas pools (and Compound v2).\n */\ncontract CurveV2PriceOracle is SafeOwnableUpgradeable, BasePriceOracle {\n /**\n * @dev Maps Curve LP token addresses to pool addresses.\n */\n mapping(address => address) public poolFor;\n\n address[] public tokens;\n\n /**\n * @dev Initializes an array of tokens and pools if desired.\n * @param _tokens Array of token addresses.\n * @param _pools Array of pool addresses.\n */\n function initialize(address[] memory _tokens, address[] memory _pools) public initializer {\n require(_tokens.length == _pools.length, \"No LP tokens supplied or array lengths not equal.\");\n __SafeOwnable_init(msg.sender);\n\n for (uint256 i = 0; i < _pools.length; i++) {\n try ICurvePool(_pools[i]).coins(2) returns (address) {\n revert(\"!only two token pools\");\n } catch {\n // ignore error\n }\n\n poolFor[_tokens[i]] = _pools[i];\n }\n }\n\n function getAllSupportedTokens() public view returns (address[] memory) {\n return tokens;\n }\n\n function getPoolForSwap(address inputToken, address outputToken)\n public\n view\n returns (\n ICurvePool,\n int128,\n int128\n )\n {\n for (uint256 i = 0; i < tokens.length; i++) {\n ICurvePool pool = ICurvePool(poolFor[tokens[i]]);\n int128 inputIndex = -1;\n int128 outputIndex = -1;\n int128 j = 0;\n while (true) {\n try pool.coins(uint256(uint128(j))) returns (address coin) {\n if (coin == inputToken) inputIndex = j;\n else if (coin == outputToken) outputIndex = j;\n j++;\n } catch {\n break;\n }\n\n if (outputIndex > -1 && inputIndex > -1) {\n return (pool, inputIndex, outputIndex);\n }\n }\n }\n\n return (ICurvePool(address(0)), int128(0), int128(0));\n }\n\n /**\n * @notice Get the LP token price price for an underlying token address.\n * @param underlying The underlying token address for which to get the price (set to zero address for ETH).\n * @return Price denominated in ETH (scaled by 1e18).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying) * 1e18) / (10**uint256(EIP20Interface(underlying).decimals()));\n }\n\n /**\n * @dev Fetches the fair LP token price from Curve, with 18 decimals of precision.\n * @param token The LP token contract address for price retrieval.\n */\n function _price(address token) internal view returns (uint256) {\n address pool = poolFor[token];\n require(address(pool) != address(0), \"Token is not registered.\");\n\n address baseToken;\n // Returns always coin(1) / coin(0) [ e.g. USDC (1) / eUSDC (1) ]\n uint256 exchangeRate = ICurveV2Pool(pool).price_oracle();\n\n if (ICurvePool(pool).coins(0) == token) {\n baseToken = ICurvePool(pool).coins(1);\n // USDC / ETH\n uint256 baseTokenPrice = BasePriceOracle(msg.sender).price(baseToken);\n // USDC / ETH * eUSDC / USDC = eUSDC / ETH\n return (baseTokenPrice * 10**18) / exchangeRate;\n } else {\n // if coin(1) is eUSDC, exchangeRate is USDC / eUSDC\n baseToken = ICurvePool(pool).coins(0);\n // USDC / ETH\n uint256 baseTokenPrice = BasePriceOracle(msg.sender).price(baseToken);\n // (USDC / ETH) * (1 / (USDC / eUSDC)) = eUSDC / ETH\n return (baseTokenPrice * exchangeRate) / 10**18;\n }\n }\n\n /**\n * @dev Register the pool given token address and set the pool info.\n * @param _token token to find the corresponding pool.\n * @param _pool Pool address.\n */\n function registerPool(address _token, address _pool) external onlyOwner {\n try ICurvePool(_pool).coins(2) returns (address) {\n revert(\"!only two token pools\");\n } catch {\n // ignore error\n }\n\n address pool = poolFor[_token];\n require(pool == address(0), \"This LP token is already registered.\");\n poolFor[_token] = _pool;\n\n bool skip = false;\n for (uint256 j = 0; j < tokens.length; j++) {\n if (tokens[j] == _token) {\n skip = true;\n break;\n }\n }\n if (!skip) tokens.push(_token);\n }\n}\n" + }, + "contracts/src/oracles/default/DiaPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { ERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport { IPriceOracle } from \"../../external/compound/IPriceOracle.sol\";\nimport { MasterPriceOracle } from \"../MasterPriceOracle.sol\";\nimport { BasePriceOracle, ICErc20 } from \"../BasePriceOracle.sol\";\n\ninterface DIAOracleV2 {\n function getValue(string memory key) external view returns (uint128, uint128);\n}\n\n/**\n * @title DiaPriceOracle\n * @notice Returns prices from DIA.\n * @dev Implements `PriceOracle`.\n * @author Rahul Sethuram (https://github.com/rhlsthrm)\n */\ncontract DiaPriceOracle is BasePriceOracle {\n struct DiaOracle {\n DIAOracleV2 feed;\n string key;\n }\n\n /**\n * @notice Maps ERC20 token addresses to ETH-based Chainlink price feed contracts.\n */\n mapping(address => DiaOracle) public priceFeeds;\n\n /**\n * @dev The administrator of this `MasterPriceOracle`.\n */\n address public admin;\n\n /**\n * @dev Controls if `admin` can overwrite existing assignments of oracles to underlying tokens.\n */\n bool public immutable CAN_ADMIN_OVERWRITE;\n\n /**\n * @dev The Wrapped native asset address.\n */\n address public immutable WTOKEN;\n\n /**\n * @notice DIA NATIVE/USD price feed contracts.\n */\n DIAOracleV2 public immutable NATIVE_TOKEN_USD_PRICE_FEED;\n string public NATIVE_TOKEN_USD_KEY;\n\n /**\n * @notice MasterPriceOracle for backup for USD price.\n */\n MasterPriceOracle public immutable MASTER_PRICE_ORACLE;\n address public immutable USD_TOKEN; // token to use as USD price (i.e. USDC)\n\n /**\n * @dev Constructor to set admin and canAdminOverwrite, wtoken address and native token USD price feed address\n */\n constructor(\n address _admin,\n bool canAdminOverwrite,\n address wtoken,\n DIAOracleV2 nativeTokenUsd,\n string memory nativeTokenUsdKey,\n MasterPriceOracle masterPriceOracle,\n address usdToken\n ) {\n admin = _admin;\n CAN_ADMIN_OVERWRITE = canAdminOverwrite;\n WTOKEN = wtoken;\n NATIVE_TOKEN_USD_PRICE_FEED = nativeTokenUsd;\n NATIVE_TOKEN_USD_KEY = nativeTokenUsdKey;\n MASTER_PRICE_ORACLE = masterPriceOracle;\n USD_TOKEN = usdToken;\n }\n\n /**\n * @dev Changes the admin and emits an event.\n */\n function changeAdmin(address newAdmin) external onlyAdmin {\n address oldAdmin = admin;\n admin = newAdmin;\n emit NewAdmin(oldAdmin, newAdmin);\n }\n\n /**\n * @dev Event emitted when `admin` is changed.\n */\n event NewAdmin(address oldAdmin, address newAdmin);\n\n /**\n * @dev Modifier that checks if `msg.sender == admin`.\n */\n modifier onlyAdmin() {\n require(msg.sender == admin, \"Sender is not the admin.\");\n _;\n }\n\n /**\n * @dev Admin-only function to set price feeds.\n * @param underlyings Underlying token addresses for which to set price feeds.\n * @param feeds The DIA price feed contract addresses for each of `underlyings`.\n * @param keys The keys for each of `underlyings`, in the format \"ETH/USD\" for example\n */\n function setPriceFeeds(\n address[] memory underlyings,\n DIAOracleV2[] memory feeds,\n string[] memory keys\n ) external onlyAdmin {\n // Input validation\n require(\n underlyings.length > 0 && underlyings.length == feeds.length && underlyings.length == keys.length,\n \"Lengths of both arrays must be equal and greater than 0.\"\n );\n\n // For each token/feed\n for (uint256 i = 0; i < underlyings.length; i++) {\n address underlying = underlyings[i];\n\n // Check for existing oracle if !canAdminOverwrite\n if (!CAN_ADMIN_OVERWRITE)\n require(\n address(priceFeeds[underlying].feed) == address(0),\n \"Admin cannot overwrite existing assignments of price feeds to underlying tokens.\"\n );\n\n // Set feed and base currency\n priceFeeds[underlying] = DiaOracle({ feed: feeds[i], key: keys[i] });\n }\n }\n\n /**\n * @dev Internal function returning the price in ETH of `underlying`.\n * Assumes price feeds are 8 decimals!\n */\n function _price(address underlying) internal view returns (uint256) {\n // Return 1e18 for WTOKEN\n if (underlying == WTOKEN || underlying == address(0)) return 1e18;\n\n // Get token/Native price from Oracle\n DiaOracle memory feed = priceFeeds[underlying];\n require(address(feed.feed) != address(0), \"No oracle price feed found for this underlying ERC20 token.\");\n\n if (address(NATIVE_TOKEN_USD_PRICE_FEED) == address(0)) {\n // Get price from MasterPriceOracle\n uint256 usdNativeTokenPrice = MASTER_PRICE_ORACLE.price(USD_TOKEN);\n uint256 nativeTokenUsdPrice = 1e36 / usdNativeTokenPrice; // 18 decimals\n (uint128 tokenUsdPrice, ) = feed.feed.getValue(feed.key); // 8 decimals\n return tokenUsdPrice >= 0 ? (uint256(tokenUsdPrice) * 1e28) / uint256(nativeTokenUsdPrice) : 0;\n } else {\n (uint128 nativeTokenUsdPrice, ) = NATIVE_TOKEN_USD_PRICE_FEED.getValue(NATIVE_TOKEN_USD_KEY);\n if (nativeTokenUsdPrice <= 0) return 0;\n (uint128 tokenUsdPrice, ) = feed.feed.getValue(feed.key); // 8 decimals\n return tokenUsdPrice >= 0 ? (uint256(tokenUsdPrice) * 1e18) / uint256(nativeTokenUsdPrice) : 0;\n }\n }\n\n /**\n * @dev Returns the price in ETH of `underlying` (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying token address\n address underlying = cToken.underlying();\n\n // Get price\n uint256 oraclePrice = _price(underlying);\n\n // Format and return price\n uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals());\n return\n underlyingDecimals <= 18\n ? uint256(oraclePrice) * (10 ** (18 - underlyingDecimals))\n : uint256(oraclePrice) / (10 ** (underlyingDecimals - 18));\n }\n}\n" + }, + "contracts/src/oracles/default/ERC4626Oracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { ERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport { IERC4626 } from \"../../compound/IERC4626.sol\";\nimport { BasePriceOracle, ICErc20 } from \"../BasePriceOracle.sol\";\nimport { SafeOwnableUpgradeable } from \"../../ionic/SafeOwnableUpgradeable.sol\";\n\ncontract ERC4626Oracle is SafeOwnableUpgradeable, BasePriceOracle {\n function initialize() public initializer {\n __SafeOwnable_init(msg.sender);\n }\n\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying) * 1e18) / (10 ** uint256(ERC20Upgradeable(underlying).decimals()));\n }\n\n /**\n * @dev Fetches the fair LP token/ETH price from Balancer, with 18 decimals of precision.\n */\n function _price(address underlying) internal view virtual returns (uint256) {\n IERC4626 vault = IERC4626(underlying);\n address asset = vault.asset();\n uint256 redeemAmount = vault.previewRedeem(10 ** vault.decimals());\n uint256 underlyingPrice = BasePriceOracle(msg.sender).price(asset);\n return (redeemAmount * underlyingPrice) / 10 ** ERC20Upgradeable(asset).decimals();\n }\n}\n" + }, + "contracts/src/oracles/default/FixedNativePriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title FixedEthPriceOracle\n * @notice Returns fixed prices of 1 denominated in the chain's native token for all tokens (expected to be used under a `MasterPriceOracle`).\n * @dev Implements `PriceOracle` and `BasePriceOracle`.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract FixedNativePriceOracle is BasePriceOracle {\n /**\n * @dev Returns the price in native token of `underlying` (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n return 1e18;\n }\n\n /**\n * @notice Returns the price in native token of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in native token of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n return 1e18;\n }\n}\n" + }, + "contracts/src/oracles/default/FixedTokenPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title FixedTokenPriceOracle\n * @notice Returns token prices using the prices for another token.\n * @dev Implements `PriceOracle` and `BasePriceOracle`.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract FixedTokenPriceOracle is BasePriceOracle {\n /**\n * @dev The token to base prices on.\n */\n address public immutable baseToken;\n\n /**\n * @dev Sets the token to base prices on.\n */\n constructor(address _baseToken) {\n baseToken = _baseToken;\n }\n\n /**\n * @notice Fetches the token/ETH price, with 18 decimals of precision.\n * @param underlying The underlying token address for which to get the price.\n * @return Price denominated in ETH (scaled by 1e18)\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying) * 1e18) / (10 ** uint256(ERC20Upgradeable(underlying).decimals()));\n }\n\n /**\n * @notice Fetches the token/ETH price, with 18 decimals of precision.\n */\n function _price(address token) internal view returns (uint256) {\n return BasePriceOracle(msg.sender).price(baseToken);\n }\n}\n" + }, + "contracts/src/oracles/default/PreferredPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../BasePriceOracle.sol\";\nimport \"../MasterPriceOracle.sol\";\nimport \"../default/ChainlinkPriceOracleV2.sol\";\n\n/**\n * @title PreferredPriceOracle\n * @notice Returns prices from MasterPriceOracle, ChainlinkPriceOracleV2, or prices from a tertiary oracle (in order of preference).\n * @dev Implements `PriceOracle` and `BasePriceOracle`.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract PreferredPriceOracle is BasePriceOracle {\n /**\n * @dev The primary `MasterPriceOracle`.\n */\n MasterPriceOracle public masterOracle;\n\n /**\n * @dev The secondary `ChainlinkPriceOracleV2`.\n */\n ChainlinkPriceOracleV2 public chainlinkOracleV2;\n\n /**\n * @dev The tertiary `PriceOracle`.\n */\n BasePriceOracle public tertiaryOracle;\n\n /**\n * @dev The Wrapped native asset address.\n */\n address public wtoken;\n\n /**\n * @dev Constructor to set the primary `MasterPriceOracle`, the secondary `ChainlinkPriceOracleV2`, and the tertiary `PriceOracle`.\n */\n constructor(\n MasterPriceOracle _masterOracle,\n ChainlinkPriceOracleV2 _chainlinkOracleV2,\n BasePriceOracle _tertiaryOracle,\n address _wtoken\n ) {\n require(address(_masterOracle) != address(0), \"MasterPriceOracle not set.\");\n require(address(_chainlinkOracleV2) != address(0), \"ChainlinkPriceOracleV2 not set.\");\n require(address(_tertiaryOracle) != address(0), \"Tertiary price oracle not set.\");\n masterOracle = _masterOracle;\n chainlinkOracleV2 = _chainlinkOracleV2;\n tertiaryOracle = _tertiaryOracle;\n wtoken = _wtoken;\n }\n\n /**\n * @notice Fetches the token/ETH price, with 18 decimals of precision.\n * @param underlying The underlying token address for which to get the price.\n * @return Price denominated in ETH (scaled by 1e18)\n */\n function price(address underlying) external view override returns (uint256) {\n // Return 1e18 for wtoken\n if (underlying == wtoken) return 1e18;\n\n // Try to get MasterPriceOracle price\n if (address(masterOracle.oracles(underlying)) != address(0)) return masterOracle.price(underlying);\n\n // Try to get ChainlinkPriceOracleV2 price\n if (address(chainlinkOracleV2.priceFeeds(underlying)) != address(0)) return chainlinkOracleV2.price(underlying);\n\n // Otherwise, get price from tertiary oracle\n return BasePriceOracle(address(tertiaryOracle)).price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying ERC20 token address\n address underlying = cToken.underlying();\n\n // Return 1e18 for wtoken\n if (underlying == wtoken) return 1e18;\n\n // Try to get MasterPriceOracle price\n if (address(masterOracle.oracles(underlying)) != address(0)) return masterOracle.getUnderlyingPrice(cToken);\n\n // Try to get ChainlinkPriceOracleV2 price\n if (address(chainlinkOracleV2.priceFeeds(underlying)) != address(0))\n return chainlinkOracleV2.getUnderlyingPrice(cToken);\n\n // Otherwise, get price from tertiary oracle\n return tertiaryOracle.getUnderlyingPrice(cToken);\n }\n}\n" + }, + "contracts/src/oracles/default/PythPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { ERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport { MasterPriceOracle } from \"../MasterPriceOracle.sol\";\nimport { BasePriceOracle, ICErc20 } from \"../BasePriceOracle.sol\";\nimport { IPyth } from \"@pythnetwork/pyth-sdk-solidity/IPyth.sol\";\nimport { PythStructs } from \"@pythnetwork/pyth-sdk-solidity/PythStructs.sol\";\nimport { SafeOwnableUpgradeable } from \"../../ionic/SafeOwnableUpgradeable.sol\";\n\n/**\n * @title PythPriceOracle\n * @notice Returns prices from Pyth.\n * @dev Implements `PriceOracle`.\n * @author Rahul Sethuram (https://github.com/rhlsthrm)\n */\ncontract PythPriceOracle is BasePriceOracle, SafeOwnableUpgradeable {\n /**\n * @notice Maps ERC20 token addresses to Pyth price IDs.\n */\n mapping(address => bytes32) public priceFeedIds;\n\n /**\n * @notice DIA NATIVE/USD price feed contracts.\n */\n bytes32 public NATIVE_TOKEN_USD_FEED;\n\n /**\n * @notice MasterPriceOracle for backup for USD price.\n */\n address public USD_TOKEN; // token to use as USD price (i.e. USDC)\n\n /**\n * @dev Constructor to set admin and canAdminOverwrite, wtoken address and native token USD price feed address\n */\n\n IPyth public PYTH;\n\n function initialize(address pythAddress, bytes32 nativeTokenUsdFeed, address usdToken) public initializer {\n __SafeOwnable_init(msg.sender);\n NATIVE_TOKEN_USD_FEED = nativeTokenUsdFeed;\n USD_TOKEN = usdToken;\n PYTH = IPyth(pythAddress);\n }\n\n function reinitialize(address pythAddress, bytes32 nativeTokenUsdFeed, address usdToken) public onlyOwnerOrAdmin {\n NATIVE_TOKEN_USD_FEED = nativeTokenUsdFeed;\n USD_TOKEN = usdToken;\n PYTH = IPyth(pythAddress);\n }\n\n /**\n * @dev Admin-only function to set price feeds.\n * @param underlyings Underlying token addresses for which to set price feeds.\n * @param feedIds The Pyth Network feed IDs`.\n */\n function setPriceFeeds(address[] memory underlyings, bytes32[] memory feedIds) external onlyOwner {\n // Input validation\n require(\n underlyings.length > 0 && underlyings.length == feedIds.length,\n \"Lengths of both arrays must be equal and greater than 0.\"\n );\n\n // For each token/feed\n for (uint256 i = 0; i < underlyings.length; i++) {\n address underlying = underlyings[i];\n // Set feed and base currency\n priceFeedIds[underlying] = feedIds[i];\n }\n }\n\n /**\n * @dev Internal function returning the price in ETH of `underlying`.\n * Assumes price feeds are 8 decimals (TODO: doublecheck)\n */\n function _price(address underlying) internal view returns (uint256) {\n // Get token/native price from Oracle\n bytes32 feed = priceFeedIds[underlying];\n require(feed != \"\", \"No oracle price feed found for this underlying ERC20 token.\");\n\n if (NATIVE_TOKEN_USD_FEED == \"\") {\n // Get price from MasterPriceOracle\n uint256 usdNativeTokenPrice = BasePriceOracle(msg.sender).price(USD_TOKEN);\n uint256 nativeTokenUsdPrice = 1e36 / usdNativeTokenPrice; // 18 decimals -- TODO: doublecheck\n PythStructs.Price memory tokenUsdPrice = PYTH.getPriceUnsafe(feed); // 8 decimals --- TODO: doublecheck\n return\n tokenUsdPrice.price >= 0 ? (uint256(uint64(tokenUsdPrice.price)) * 1e28) / uint256(nativeTokenUsdPrice) : 0;\n } else {\n uint128 nativeTokenUsdPrice = uint128(uint64(PYTH.getPriceUnsafe(NATIVE_TOKEN_USD_FEED).price));\n if (nativeTokenUsdPrice <= 0) return 0;\n uint128 tokenUsdPrice = uint128(uint64(PYTH.getPriceUnsafe(feed).price));\n return tokenUsdPrice >= 0 ? (uint256(tokenUsdPrice) * 1e18) / uint256(nativeTokenUsdPrice) : 0;\n }\n }\n\n /**\n * @dev Returns the price in ETH of `underlying` (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying token address\n address underlying = cToken.underlying();\n\n // Get price\n uint256 oraclePrice = _price(underlying);\n\n // Format and return price\n uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals());\n return\n underlyingDecimals <= 18\n ? uint256(oraclePrice) * (10 ** (18 - underlyingDecimals))\n : uint256(oraclePrice) / (10 ** (underlyingDecimals - 18));\n }\n}\n" + }, + "contracts/src/oracles/default/PythPriceOracleDmBTC.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { ERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport { MasterPriceOracle } from \"../MasterPriceOracle.sol\";\nimport { BasePriceOracle, ICErc20 } from \"../BasePriceOracle.sol\";\nimport { IPyth } from \"@pythnetwork/pyth-sdk-solidity/IPyth.sol\";\nimport { PythStructs } from \"@pythnetwork/pyth-sdk-solidity/PythStructs.sol\";\nimport { SafeOwnableUpgradeable } from \"../../ionic/SafeOwnableUpgradeable.sol\";\n\n/**\n * @title PythPriceOracle\n * @notice Returns prices from Pyth.\n * @dev Implements `PriceOracle`.\n * @author Rahul Sethuram (https://github.com/rhlsthrm)\n */\ncontract PythPriceOracleDmBTC is BasePriceOracle, SafeOwnableUpgradeable {\n /**\n * @notice Maps ERC20 token addresses to Pyth price IDs.\n */\n mapping(address => bytes32) public priceFeedIds;\n\n /**\n * @notice DIA NATIVE/USD price feed contracts.\n */\n bytes32 public NATIVE_TOKEN_USD_FEED;\n\n /**\n * @notice MasterPriceOracle for backup for USD price.\n */\n address public USD_TOKEN; // token to use as USD price (i.e. USDC)\n\n /**\n * @dev Constructor to set admin and canAdminOverwrite, wtoken address and native token USD price feed address\n */\n\n IPyth public PYTH;\n\n address public DMBTC;\n\n function initialize(\n address pythAddress,\n bytes32 nativeTokenUsdFeed,\n address usdToken,\n address dmBTC\n ) public initializer {\n __SafeOwnable_init(msg.sender);\n NATIVE_TOKEN_USD_FEED = nativeTokenUsdFeed;\n USD_TOKEN = usdToken;\n PYTH = IPyth(pythAddress);\n DMBTC = dmBTC;\n }\n\n function reinitialize(\n address pythAddress,\n bytes32 nativeTokenUsdFeed,\n address usdToken,\n address dmBTC\n ) public onlyOwnerOrAdmin {\n NATIVE_TOKEN_USD_FEED = nativeTokenUsdFeed;\n USD_TOKEN = usdToken;\n PYTH = IPyth(pythAddress);\n DMBTC = dmBTC;\n }\n\n /**\n * @dev Admin-only function to set price feeds.\n * @param underlyings Underlying token addresses for which to set price feeds.\n * @param feedIds The Pyth Network feed IDs`.\n */\n function setPriceFeeds(address[] memory underlyings, bytes32[] memory feedIds) external onlyOwner {\n // Input validation\n require(\n underlyings.length > 0 && underlyings.length == feedIds.length,\n \"Lengths of both arrays must be equal and greater than 0.\"\n );\n\n // For each token/feed\n for (uint256 i = 0; i < underlyings.length; i++) {\n address underlying = underlyings[i];\n // Set feed and base currency\n priceFeedIds[underlying] = feedIds[i];\n }\n }\n\n /**\n * @dev Internal function returning the price in ETH of `underlying`.\n * Assumes price feeds are 8 decimals (TODO: doublecheck)\n */\n function _price(address underlying) internal view returns (uint256) {\n // Get token/native price from Oracle\n bytes32 feed = priceFeedIds[underlying];\n require(feed != \"\", \"No oracle price feed found for this underlying ERC20 token.\");\n uint256 normalizedPrice;\n if (NATIVE_TOKEN_USD_FEED == \"\") {\n // Get price from MasterPriceOracle\n uint256 usdNativeTokenPrice = BasePriceOracle(msg.sender).price(USD_TOKEN);\n uint256 nativeTokenUsdPrice = 1e36 / usdNativeTokenPrice; // 18 decimals -- TODO: doublecheck\n PythStructs.Price memory tokenUsdPrice = PYTH.getPriceUnsafe(feed); // 8 decimals --- TODO: doublecheck\n normalizedPrice = tokenUsdPrice.price >= 0\n ? (uint256(uint64(tokenUsdPrice.price)) * 1e28) / uint256(nativeTokenUsdPrice)\n : 0;\n } else {\n uint128 nativeTokenUsdPrice = uint128(uint64(PYTH.getPriceUnsafe(NATIVE_TOKEN_USD_FEED).price));\n if (nativeTokenUsdPrice <= 0) return 0;\n uint128 tokenUsdPrice = uint128(uint64(PYTH.getPriceUnsafe(feed).price));\n normalizedPrice = tokenUsdPrice >= 0 ? (uint256(tokenUsdPrice) * 1e18) / uint256(nativeTokenUsdPrice) : 0;\n }\n if (underlying == DMBTC) {\n return normalizedPrice / 100000;\n }\n return normalizedPrice;\n }\n\n /**\n * @dev Returns the price in ETH of `underlying` (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying token address\n address underlying = cToken.underlying();\n\n // Get price\n uint256 oraclePrice = _price(underlying);\n\n // Format and return price\n uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals());\n return\n underlyingDecimals <= 18\n ? uint256(oraclePrice) * (10 ** (18 - underlyingDecimals))\n : uint256(oraclePrice) / (10 ** (underlyingDecimals - 18));\n }\n}\n" + }, + "contracts/src/oracles/default/RecursivePriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../../external/compound/IPriceOracle.sol\";\nimport \"../../external/compound/ICToken.sol\";\nimport \"../../external/compound/ICErc20.sol\";\nimport \"../../external/compound/IComptroller.sol\";\n\n/**\n * @title RecursivePriceOracle\n * @notice Returns prices from other cTokens (from Ionic).\n * @dev Implements `PriceOracle`.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract RecursivePriceOracle is IPriceOracle {\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICToken cToken) external view override returns (uint256) {\n // Get cToken's underlying cToken\n ICToken underlying = ICToken(ICErc20Compound(address(cToken)).underlying());\n\n // Get Comptroller\n IComptroller comptroller = IComptroller(underlying.comptroller());\n\n // If cETH, return cETH/ETH exchange rate\n if (underlying.isCEther()) {\n return underlying.exchangeRateStored();\n }\n\n // Ionic cTokens: cToken/token price * token/ETH price = cToken/ETH price\n return (underlying.exchangeRateStored() * comptroller.oracle().getUnderlyingPrice(underlying)) / 1e18;\n }\n}\n" + }, + "contracts/src/oracles/default/RedstoneAdapterPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../../external/redstone/IRedstoneOracle.sol\";\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title RedstoneAdapterPriceOracle\n * @notice Returns prices from Redstone.\n * @dev Implements `BasePriceOracle`.\n * @author Veliko Minkov (https://github.com/vminkov)\n */\ncontract RedstoneAdapterPriceOracle is BasePriceOracle {\n /**\n * @notice The Redstone oracle contract\n */\n IRedstoneOracle public REDSTONE_ORACLE;\n\n /**\n * @dev Constructor to set admin, wtoken address and native token USD price feed address\n * @param redstoneOracle The Redstone oracle contract address\n */\n constructor(address redstoneOracle) {\n REDSTONE_ORACLE = IRedstoneOracle(redstoneOracle);\n }\n\n /**\n * @notice Internal function returning the price in of `underlying`.\n * @dev will return a price denominated in the native token\n */\n function _price(address underlying) internal view returns (uint256) {\n uint256 priceInUsd = REDSTONE_ORACLE.priceOf(underlying);\n uint256 priceOfNativeInUsd = REDSTONE_ORACLE.priceOfETH();\n return (priceInUsd * 1e18) / priceOfNativeInUsd;\n }\n\n /**\n * @notice Returns the price in of `underlying` either in the\n * native token (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in WNATIVE of the token underlying `cToken`.\n * @dev Implements the `BasePriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in WNATIVE of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying token address\n address underlying = cToken.underlying();\n\n uint256 oraclePrice = _price(underlying);\n\n uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals());\n return\n underlyingDecimals <= 18\n ? uint256(oraclePrice) * (10 ** (18 - underlyingDecimals))\n : uint256(oraclePrice) / (10 ** (underlyingDecimals - 18));\n }\n}\n" + }, + "contracts/src/oracles/default/RedstoneAdapterPriceOracleWeETH.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../../external/redstone/IRedstoneOracle.sol\";\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title RedstoneAdapterPriceOracle\n * @notice Returns prices from Redstone.\n * @dev Implements `BasePriceOracle`.\n * @author Veliko Minkov (https://github.com/vminkov)\n */\ncontract RedstoneAdapterPriceOracleWeETH is BasePriceOracle {\n /**\n * @notice The Redstone oracle contract\n */\n IRedstoneOracle public REDSTONE_ORACLE;\n\n /**\n * @dev Constructor to set admin, wtoken address and native token USD price feed address\n * @param redstoneOracle The Redstone oracle contract address\n */\n constructor(address redstoneOracle) {\n REDSTONE_ORACLE = IRedstoneOracle(redstoneOracle);\n }\n\n /**\n * @notice Internal function returning the price in of `underlying`.\n * @dev will return a price denominated in the native token\n */\n function _price(address underlying) internal view returns (uint256) {\n // special case for wrsETH\n // if input is wrsETH, we need to get the price of rsETH\n if (underlying == 0x04C0599Ae5A44757c0af6F9eC3b93da8976c150A) {\n underlying = 0x028227c4dd1e5419d11Bb6fa6e661920c519D4F5;\n }\n uint256 priceInUsd = REDSTONE_ORACLE.priceOf(underlying);\n uint256 priceOfNativeInUsd = REDSTONE_ORACLE.priceOfETH();\n return (priceInUsd * 1e18) / priceOfNativeInUsd;\n }\n\n /**\n * @notice Returns the price in of `underlying` either in the\n * native token (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in WNATIVE of the token underlying `cToken`.\n * @dev Implements the `BasePriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in WNATIVE of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying token address\n address underlying = cToken.underlying();\n\n uint256 oraclePrice = _price(underlying);\n\n uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals());\n return\n underlyingDecimals <= 18\n ? uint256(oraclePrice) * (10 ** (18 - underlyingDecimals))\n : uint256(oraclePrice) / (10 ** (underlyingDecimals - 18));\n }\n}\n" + }, + "contracts/src/oracles/default/RedstoneAdapterPriceOracleWrsETH.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../../external/redstone/IRedstoneOracle.sol\";\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title RedstoneAdapterPriceOracle\n * @notice Returns prices from Redstone.\n * @dev Implements `BasePriceOracle`.\n * @author Veliko Minkov (https://github.com/vminkov)\n */\ncontract RedstoneAdapterPriceOracleWrsETH is BasePriceOracle {\n /**\n * @notice The Redstone oracle contract\n */\n IRedstoneOracle public REDSTONE_ORACLE;\n\n /**\n * @dev Constructor to set admin, wtoken address and native token USD price feed address\n * @param redstoneOracle The Redstone oracle contract address\n */\n constructor(address redstoneOracle) {\n REDSTONE_ORACLE = IRedstoneOracle(redstoneOracle);\n }\n\n /**\n * @notice Internal function returning the price in of `underlying`.\n * @dev will return a price denominated in the native token\n */\n function _price(address underlying) internal view returns (uint256) {\n // special case for wrsETH\n // if input is wrsETH, we need to get the price of rsETH\n if (underlying == 0xe7903B1F75C534Dd8159b313d92cDCfbC62cB3Cd) {\n underlying = 0x4186BFC76E2E237523CBC30FD220FE055156b41F;\n }\n uint256 priceInUsd = REDSTONE_ORACLE.priceOf(underlying);\n uint256 priceOfNativeInUsd = REDSTONE_ORACLE.priceOfETH();\n return (priceInUsd * 1e18) / priceOfNativeInUsd;\n }\n\n /**\n * @notice Returns the price in of `underlying` either in the\n * native token (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in WNATIVE of the token underlying `cToken`.\n * @dev Implements the `BasePriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in WNATIVE of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying token address\n address underlying = cToken.underlying();\n\n uint256 oraclePrice = _price(underlying);\n\n uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals());\n return\n underlyingDecimals <= 18\n ? uint256(oraclePrice) * (10 ** (18 - underlyingDecimals))\n : uint256(oraclePrice) / (10 ** (underlyingDecimals - 18));\n }\n}\n" + }, + "contracts/src/oracles/default/SimplePriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../BasePriceOracle.sol\";\nimport { ERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\nimport \"../../ionic/SafeOwnableUpgradeable.sol\";\n\ncontract SimplePriceOracle is BasePriceOracle, SafeOwnableUpgradeable {\n mapping(address => uint256) prices;\n event PricePosted(\n address asset,\n uint256 previousPriceMantissa,\n uint256 requestedPriceMantissa,\n uint256 newPriceMantissa\n );\n\n function initialize() public initializer {\n __SafeOwnable_init(msg.sender);\n }\n\n function getUnderlyingPrice(ICErc20 cToken) public view override returns (uint256) {\n if (compareStrings(cToken.symbol(), \"cETH\")) {\n return 1e18;\n } else {\n address underlying = ICErc20(address(cToken)).underlying();\n uint256 oraclePrice = prices[underlying];\n\n uint256 underlyingDecimals = uint256(ERC20Upgradeable(underlying).decimals());\n return\n underlyingDecimals <= 18\n ? uint256(oraclePrice) * (10 ** (18 - underlyingDecimals))\n : uint256(oraclePrice) / (10 ** (underlyingDecimals - 18));\n }\n }\n\n function setUnderlyingPrice(ICErc20 cToken, uint256 underlyingPriceMantissa) public onlyOwner {\n address asset = ICErc20(address(cToken)).underlying();\n emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa);\n prices[asset] = underlyingPriceMantissa;\n }\n\n function setDirectPrice(address asset, uint256 _price) public onlyOwner {\n emit PricePosted(asset, prices[asset], _price, _price);\n prices[asset] = _price;\n }\n\n function price(address underlying) external view returns (uint256) {\n return prices[address(underlying)];\n }\n\n // v1 price oracle interface for use as backing of proxy\n function assetPrices(address asset) external view returns (uint256) {\n return prices[asset];\n }\n\n function compareStrings(string memory a, string memory b) internal pure returns (bool) {\n return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));\n }\n}\n" + }, + "contracts/src/oracles/default/UniswapLikeLpTokenPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../../external/uniswap/IUniswapV2Pair.sol\";\n\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title UniswapLpTokenPriceOracle\n * @author David Lucid (https://github.com/davidlucid)\n * @notice UniswapLpTokenPriceOracle is a price oracle for Uniswap (and SushiSwap) LP tokens.\n * @dev Implements the `PriceOracle` interface used by Ionic pools (and Compound v2).\n */\nabstract contract UniswapLikeLpTokenPriceOracle is BasePriceOracle {\n /**\n * @dev wtoken contract address.\n */\n address public immutable wtoken;\n\n /**\n * @dev Constructor to set admin and canAdminOverwrite, wtoken address and native token USD price feed address\n */\n constructor(address _wtoken) {\n wtoken = _wtoken;\n }\n\n function _price(address token) internal view virtual returns (uint256);\n\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying) * 1e18) / (10 ** uint256(ERC20Upgradeable(underlying).decimals()));\n }\n\n /**\n * @dev Fast square root function.\n * Implementation from: https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0\n * Original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687\n */\n function sqrt(uint256 x) internal pure returns (uint256) {\n if (x == 0) return 0;\n uint256 xx = x;\n uint256 r = 1;\n\n if (xx >= 0x100000000000000000000000000000000) {\n xx >>= 128;\n r <<= 64;\n }\n if (xx >= 0x10000000000000000) {\n xx >>= 64;\n r <<= 32;\n }\n if (xx >= 0x100000000) {\n xx >>= 32;\n r <<= 16;\n }\n if (xx >= 0x10000) {\n xx >>= 16;\n r <<= 8;\n }\n if (xx >= 0x100) {\n xx >>= 8;\n r <<= 4;\n }\n if (xx >= 0x10) {\n xx >>= 4;\n r <<= 2;\n }\n if (xx >= 0x8) {\n r <<= 1;\n }\n\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1;\n r = (r + x / r) >> 1; // Seven iterations should be enough\n uint256 r1 = x / r;\n return (r < r1 ? r : r1);\n }\n}\n" + }, + "contracts/src/oracles/default/UniswapLpTokenPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../../external/uniswap/IUniswapV2Pair.sol\";\n\nimport \"../BasePriceOracle.sol\";\nimport { UniswapLikeLpTokenPriceOracle } from \"./UniswapLikeLpTokenPriceOracle.sol\";\n\n/**\n * @title UniswapLpTokenPriceOracle\n * @author David Lucid (https://github.com/davidlucid)\n * @notice UniswapLpTokenPriceOracle is a price oracle for Uniswap (and SushiSwap) LP tokens.\n * @dev Implements the `PriceOracle` interface used by Ionic pools (and Compound v2).\n */\ncontract UniswapLpTokenPriceOracle is UniswapLikeLpTokenPriceOracle {\n /**\n * @dev Fetches the fair LP token/ETH price from Uniswap, with 18 decimals of precision.\n */\n constructor(address _wtoken) UniswapLikeLpTokenPriceOracle(_wtoken) {}\n\n function _price(address token) internal view virtual override returns (uint256) {\n IUniswapV2Pair pair = IUniswapV2Pair(token);\n uint256 totalSupply = pair.totalSupply();\n if (totalSupply == 0) return 0;\n (uint256 r0, uint256 r1, ) = pair.getReserves();\n\n r0 = r0 * 10 ** (18 - uint256(ERC20Upgradeable(pair.token0()).decimals()));\n r1 = r1 * 10 ** (18 - uint256(ERC20Upgradeable(pair.token1()).decimals()));\n\n address token0 = pair.token0();\n address token1 = pair.token1();\n\n // Get fair price of non-WETH token (underlying the pair) in terms of ETH\n uint256 token0FairPrice = token0 == wtoken ? 1e18 : BasePriceOracle(msg.sender).price(token0);\n uint256 token1FairPrice = token1 == wtoken ? 1e18 : BasePriceOracle(msg.sender).price(token1);\n\n // Implementation from https://github.com/AlphaFinanceLab/homora-v2/blob/e643392d582c81f6695136971cff4b685dcd2859/contracts/oracle/UniswapV2Oracle.sol#L18\n uint256 sqrtK = (sqrt(r0 * r1) * (2 ** 112)) / totalSupply;\n return (((sqrtK * 2 * sqrt(token0FairPrice)) / (2 ** 56)) * sqrt(token1FairPrice)) / (2 ** 56);\n }\n}\n" + }, + "contracts/src/oracles/default/UniswapTwapPriceOracleV2.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../BasePriceOracle.sol\";\nimport \"./UniswapTwapPriceOracleV2Root.sol\";\n\n/**\n * @title UniswapTwapPriceOracleV2\n * @notice Stores cumulative prices and returns TWAPs for assets on Uniswap V2 pairs.\n * @dev Implements `PriceOracle` and `BasePriceOracle`.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract UniswapTwapPriceOracleV2 is Initializable, BasePriceOracle {\n /**\n * @dev wtoken token contract address.\n */\n address public wtoken;\n\n /**\n * @dev UniswapTwapPriceOracleV2Root contract address.\n */\n UniswapTwapPriceOracleV2Root public rootOracle;\n\n /**\n * @dev UniswapV2Factory contract address.\n */\n address public uniswapV2Factory;\n\n /**\n * @dev The token on which to base TWAPs (its price must be available via `msg.sender`).\n */\n address public baseToken;\n\n /**\n * @dev Initalize that sets the UniswapTwapPriceOracleV2Root, UniswapV2Factory, and base token.\n * @param _rootOracle Sets `UniswapTwapPriceOracleV2Root`\n * @param _uniswapV2Factory Sets `UniswapV2Factory`\n * @param _baseToken The token on which to base TWAPs (its price must be available via `msg.sender`).\n * @param _wtoken The Wrapped native asset address\n */\n function initialize(\n address _rootOracle,\n address _uniswapV2Factory,\n address _baseToken,\n address _wtoken\n ) external initializer {\n require(_rootOracle != address(0), \"UniswapTwapPriceOracleV2Root not defined.\");\n require(_uniswapV2Factory != address(0), \"UniswapV2Factory not defined.\");\n rootOracle = UniswapTwapPriceOracleV2Root(_rootOracle);\n uniswapV2Factory = _uniswapV2Factory;\n wtoken = _wtoken;\n baseToken = _baseToken == address(0) ? address(wtoken) : _baseToken;\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying ERC20 token address\n address underlying = cToken.underlying();\n\n // Get price, format, and return\n uint256 baseUnit = 10 ** uint256(ERC20Upgradeable(underlying).decimals());\n return (_price(underlying) * 1e18) / baseUnit;\n }\n\n /**\n * @dev Internal function returning the price in ETH of `underlying`.\n */\n function _price(address underlying) internal view returns (uint256) {\n // Return 1e18 for wtoken\n if (underlying == wtoken) return 1e18;\n\n // Return root oracle ERC20/ETH TWAP\n uint256 twap = rootOracle.price(underlying, baseToken, uniswapV2Factory);\n return\n baseToken == address(wtoken)\n ? twap\n : (twap * BasePriceOracle(msg.sender).price(baseToken)) /\n (10 ** uint256(ERC20Upgradeable(baseToken).decimals()));\n }\n\n /**\n * @dev Returns the price in ETH of `underlying` (implements `BasePriceOracle`).\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n}\n" + }, + "contracts/src/oracles/default/UniswapTwapPriceOracleV2Factory.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/proxy/ClonesUpgradeable.sol\";\n\nimport \"./UniswapTwapPriceOracleV2.sol\";\n\n/**\n * @title UniswapTwapPriceOracleV2Factory\n * @notice Deploys and catalogs UniswapTwapPriceOracleV2 contracts.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract UniswapTwapPriceOracleV2Factory {\n /**\n * @dev WETH token contract address.\n */\n address public immutable wtoken;\n\n /**\n * @dev `UniswapTwapPriceOracleV2Root` contract address.\n */\n address public immutable rootOracle;\n\n /**\n * @dev Implementation address for the `UniswapV3TwapPriceOracleV2`.\n */\n address public immutable logic;\n\n /**\n * @notice Maps `UniswapV2Factory` contracts to base tokens to `UniswapTwapPriceOracleV2` contract addresses.\n */\n mapping(address => mapping(address => UniswapTwapPriceOracleV2)) public oracles;\n\n /**\n * @dev Constructor that sets the `UniswapTwapPriceOracleV2Root` and `UniswapTwapPriceOracleV2` implementation contract.\n */\n constructor(address _rootOracle, address _logic, address _wtoken) {\n require(_rootOracle != address(0), \"UniswapTwapPriceOracleV2Root not defined.\");\n require(_logic != address(0), \"UniswapTwapPriceOracleV2 implementation/logic contract not defined.\");\n rootOracle = _rootOracle;\n logic = _logic;\n wtoken = _wtoken;\n }\n\n /**\n * @notice Deploys a `UniswapTwapPriceOracleV2`.\n * @param uniswapV2Factory The `UniswapV2Factory` contract of the pairs for which this oracle will be used.\n * @param baseToken The base token of the pairs for which this oracle will be used.\n */\n function deploy(address uniswapV2Factory, address baseToken) external returns (address) {\n // Input validation\n if (baseToken == address(0)) baseToken = address(wtoken);\n\n // Return existing oracle if present\n address currentOracle = address(oracles[uniswapV2Factory][baseToken]);\n if (currentOracle != address(0)) return currentOracle;\n\n // Deploy oracle\n bytes32 salt = keccak256(abi.encodePacked(uniswapV2Factory, baseToken));\n address oracle = ClonesUpgradeable.cloneDeterministic(logic, salt);\n UniswapTwapPriceOracleV2(oracle).initialize(rootOracle, uniswapV2Factory, baseToken, wtoken);\n\n // Set oracle in state\n oracles[uniswapV2Factory][baseToken] = UniswapTwapPriceOracleV2(oracle);\n\n // Return oracle address\n return oracle;\n }\n}\n" + }, + "contracts/src/oracles/default/UniswapTwapPriceOracleV2Resolver.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IResolver } from \"ops/interfaces/IResolver.sol\";\nimport { UniswapTwapPriceOracleV2Root } from \"./UniswapTwapPriceOracleV2Root.sol\";\nimport { Ownable } from \"@openzeppelin/contracts/access/Ownable.sol\";\n\ncontract UniswapTwapPriceOracleV2Resolver is IResolver, Ownable {\n struct PairConfig {\n address pair;\n address baseToken;\n uint256 minPeriod;\n uint256 deviationThreshold;\n }\n\n // need to store as arrays for the UniswapTwapPriceOracleV2Root workable functions\n address[] pairs;\n address[] baseTokens;\n uint256[] minPeriods;\n uint256[] deviationThresholds;\n\n UniswapTwapPriceOracleV2Root public root;\n uint256 public lastUpdate;\n\n constructor(PairConfig[] memory _pairConfigs, UniswapTwapPriceOracleV2Root _root) {\n for (uint256 i = 0; i < _pairConfigs.length; i++) {\n pairs[i] = _pairConfigs[i].pair;\n baseTokens[i] = _pairConfigs[i].baseToken;\n minPeriods[i] = _pairConfigs[i].minPeriod;\n deviationThresholds[i] = _pairConfigs[i].deviationThreshold;\n }\n root = _root;\n }\n\n function getPairs() external view returns (PairConfig[] memory) {\n PairConfig[] memory pairConfigs = new PairConfig[](pairs.length);\n for (uint256 i = 0; i < pairs.length; i++) {\n PairConfig memory pairConfig = PairConfig({\n pair: pairs[i],\n baseToken: baseTokens[i],\n minPeriod: minPeriods[i],\n deviationThreshold: deviationThresholds[i]\n });\n pairConfigs[i] = pairConfig;\n }\n return pairConfigs;\n }\n\n function changeRoot(UniswapTwapPriceOracleV2Root _root) external onlyOwner {\n root = _root;\n }\n\n function removeFromPairs(uint256 index) external onlyOwner {\n if (index >= pairs.length) return;\n\n for (uint256 i = index; i < pairs.length - 1; i++) {\n pairs[i] = pairs[i + 1];\n baseTokens[i] = baseTokens[i + 1];\n minPeriods[i] = minPeriods[i + 1];\n deviationThresholds[i] = deviationThresholds[i + 1];\n }\n pairs.pop();\n baseTokens.pop();\n minPeriods.pop();\n deviationThresholds.pop();\n }\n\n function addPair(PairConfig calldata pair) external onlyOwner {\n pairs.push(pair.pair);\n baseTokens.push(pair.baseToken);\n minPeriods.push(pair.minPeriod);\n deviationThresholds.push(pair.deviationThreshold);\n }\n\n function getWorkablePairs() public view returns (address[] memory) {\n bool[] memory workable = root.workable(pairs, baseTokens, minPeriods, deviationThresholds);\n uint256 workableCount = 0;\n for (uint256 i = 0; i < workable.length; i += 1) {\n if (workable[i]) {\n workableCount += 1;\n }\n }\n\n address[] memory workablePairs = new address[](workableCount);\n uint256 j = 0;\n\n for (uint256 i = 0; i < workable.length; i++) {\n if (workable[i]) {\n workablePairs[j++] = pairs[i];\n }\n }\n return workablePairs;\n }\n\n function updatePairs(address[] calldata workablePairs) external {\n if (workablePairs.length == 0) return;\n root.update(workablePairs);\n }\n\n function checker() external view override returns (bool canExec, bytes memory execPayload) {\n address[] memory workablePairs = getWorkablePairs();\n if (workablePairs.length == 0) {\n return (false, bytes(\"No workable pairs\"));\n }\n\n canExec = true;\n execPayload = abi.encodeWithSelector(this.updatePairs.selector, workablePairs);\n }\n}\n" + }, + "contracts/src/oracles/default/UniswapTwapPriceOracleV2Root.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport \"../../external/uniswap/IUniswapV2Pair.sol\";\nimport \"../../external/uniswap/IUniswapV2Factory.sol\";\n\n/**\n * @title UniswapTwapPriceOracleV2Root\n * @notice Stores cumulative prices and returns TWAPs for assets on Uniswap V2 pairs.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract UniswapTwapPriceOracleV2Root {\n /**\n * @dev wtoken token contract address.\n */\n address public immutable wtoken;\n\n /**\n * @dev Minimum TWAP interval.\n */\n uint256 public constant MIN_TWAP_TIME = 15 minutes;\n\n /**\n * @dev Constructor to set wtoken address\n */\n constructor(address _wtoken) {\n wtoken = _wtoken;\n }\n\n /**\n * @dev Return the TWAP value price0. Revert if TWAP time range is not within the threshold.\n * Copied from: https://github.com/AlphaFinanceLab/homora-v2/blob/master/contracts/oracle/BaseKP3ROracle.sol\n * @param pair The pair to query for price0.\n */\n function price0TWAP(address pair) internal view returns (uint256) {\n uint256 length = observationCount[pair];\n require(length > 0, \"No length-1 TWAP observation.\");\n Observation memory lastObservation = observations[pair][(length - 1) % OBSERVATION_BUFFER];\n if (lastObservation.timestamp > block.timestamp - MIN_TWAP_TIME) {\n require(length > 1, \"No length-2 TWAP observation.\");\n lastObservation = observations[pair][(length - 2) % OBSERVATION_BUFFER];\n }\n uint256 elapsedTime = block.timestamp - lastObservation.timestamp;\n require(elapsedTime >= MIN_TWAP_TIME, \"Bad TWAP time.\");\n uint256 currPx0Cumu = currentPx0Cumu(pair);\n unchecked {\n return (currPx0Cumu - lastObservation.price0Cumulative) / (block.timestamp - lastObservation.timestamp); // overflow is desired\n }\n }\n\n /**\n * @dev Return the TWAP value price1. Revert if TWAP time range is not within the threshold.\n * Copied from: https://github.com/AlphaFinanceLab/homora-v2/blob/master/contracts/oracle/BaseKP3ROracle.sol\n * @param pair The pair to query for price1.\n */\n function price1TWAP(address pair) internal view returns (uint256) {\n uint256 length = observationCount[pair];\n require(length > 0, \"No length-1 TWAP observation.\");\n Observation memory lastObservation = observations[pair][(length - 1) % OBSERVATION_BUFFER];\n if (lastObservation.timestamp > block.timestamp - MIN_TWAP_TIME) {\n require(length > 1, \"No length-2 TWAP observation.\");\n lastObservation = observations[pair][(length - 2) % OBSERVATION_BUFFER];\n }\n uint256 elapsedTime = block.timestamp - lastObservation.timestamp;\n require(elapsedTime >= MIN_TWAP_TIME, \"Bad TWAP time.\");\n uint256 currPx1Cumu = currentPx1Cumu(pair);\n unchecked {\n return (currPx1Cumu - lastObservation.price1Cumulative) / (block.timestamp - lastObservation.timestamp); // overflow is desired\n }\n }\n\n /**\n * @dev Return the current price0 cumulative value on Uniswap.\n * Copied from: https://github.com/AlphaFinanceLab/homora-v2/blob/master/contracts/oracle/BaseKP3ROracle.sol\n * @param pair The uniswap pair to query for price0 cumulative value.\n */\n function currentPx0Cumu(address pair) internal view returns (uint256 px0Cumu) {\n uint32 currTime = uint32(block.timestamp);\n px0Cumu = IUniswapV2Pair(pair).price0CumulativeLast();\n (uint256 reserve0, uint256 reserve1, uint32 lastTime) = IUniswapV2Pair(pair).getReserves();\n if (lastTime != block.timestamp) {\n unchecked {\n uint32 timeElapsed = currTime - lastTime; // overflow is desired\n px0Cumu += uint256((reserve1 << 112) / reserve0) * timeElapsed; // overflow is desired\n }\n }\n }\n\n /**\n * @dev Return the current price1 cumulative value on Uniswap.\n * Copied from: https://github.com/AlphaFinanceLab/homora-v2/blob/master/contracts/oracle/BaseKP3ROracle.sol\n * @param pair The uniswap pair to query for price1 cumulative value.\n */\n function currentPx1Cumu(address pair) internal view returns (uint256 px1Cumu) {\n uint32 currTime = uint32(block.timestamp);\n px1Cumu = IUniswapV2Pair(pair).price1CumulativeLast();\n (uint256 reserve0, uint256 reserve1, uint32 lastTime) = IUniswapV2Pair(pair).getReserves();\n if (lastTime != currTime) {\n unchecked {\n uint32 timeElapsed = currTime - lastTime; // overflow is desired\n px1Cumu += uint256((reserve0 << 112) / reserve1) * timeElapsed; // overflow is desired\n }\n }\n }\n\n /**\n * @dev Returns the price of `underlying` in terms of `baseToken` given `factory`.\n */\n function price(address underlying, address baseToken, address factory) external view returns (uint256) {\n // Return ERC20/ETH TWAP\n address pair = IUniswapV2Factory(factory).getPair(underlying, baseToken);\n uint256 baseUnit = 10 ** uint256(ERC20Upgradeable(underlying).decimals());\n return (((underlying < baseToken ? price0TWAP(pair) : price1TWAP(pair)) / (2 ** 56)) * baseUnit) / (2 ** 56); // Scaled by 1e18, not 2 ** 112\n }\n\n /**\n * @dev Struct for cumulative price observations.\n */\n struct Observation {\n uint32 timestamp;\n uint256 price0Cumulative;\n uint256 price1Cumulative;\n }\n\n /**\n * @dev Length after which observations roll over to index 0.\n */\n uint8 public constant OBSERVATION_BUFFER = 4;\n\n /**\n * @dev Total observation count for each pair.\n */\n mapping(address => uint256) public observationCount;\n\n /**\n * @dev Array of cumulative price observations for each pair.\n */\n mapping(address => Observation[OBSERVATION_BUFFER]) public observations;\n\n /// @notice Get pairs for token combinations.\n function pairsFor(\n address[] calldata tokenA,\n address[] calldata tokenB,\n address factory\n ) external view returns (address[] memory) {\n require(\n tokenA.length > 0 && tokenA.length == tokenB.length,\n \"Token array lengths must be equal and greater than 0.\"\n );\n address[] memory pairs = new address[](tokenA.length);\n for (uint256 i = 0; i < tokenA.length; i++) pairs[i] = IUniswapV2Factory(factory).getPair(tokenA[i], tokenB[i]);\n return pairs;\n }\n\n /// @notice Check which of multiple pairs are workable/updatable.\n function workable(\n address[] calldata pairs,\n address[] calldata baseTokens,\n uint256[] calldata minPeriods,\n uint256[] calldata deviationThresholds\n ) external view returns (bool[] memory) {\n require(\n pairs.length > 0 &&\n pairs.length == baseTokens.length &&\n pairs.length == minPeriods.length &&\n pairs.length == deviationThresholds.length,\n \"Array lengths must be equal and greater than 0.\"\n );\n bool[] memory answers = new bool[](pairs.length);\n for (uint256 i = 0; i < pairs.length; i++)\n answers[i] = _workable(pairs[i], baseTokens[i], minPeriods[i], deviationThresholds[i]);\n return answers;\n }\n\n /// @dev Internal function to check if a pair is workable (updateable AND reserves have changed AND deviation threshold is satisfied).\n function _workable(\n address pair,\n address baseToken,\n uint256 minPeriod,\n uint256 deviationThreshold\n ) internal view returns (bool) {\n // Workable if:\n // 1) We have no observations\n // 2) The elapsed time since the last observation is > minPeriod AND reserves have changed AND deviation threshold is satisfied\n // Note that we loop observationCount[pair] around OBSERVATION_BUFFER so we don't waste gas on new storage slots\n if (observationCount[pair] <= 0) return true;\n (, , uint32 lastTime) = IUniswapV2Pair(pair).getReserves();\n return\n (block.timestamp - observations[pair][(observationCount[pair] - 1) % OBSERVATION_BUFFER].timestamp) >\n (minPeriod >= MIN_TWAP_TIME ? minPeriod : MIN_TWAP_TIME) &&\n lastTime != observations[pair][(observationCount[pair] - 1) % OBSERVATION_BUFFER].timestamp &&\n _deviation(pair, baseToken) >= deviationThreshold;\n }\n\n /// @dev Internal function to check if a pair's spot price's deviation from its TWAP price as a ratio scaled by 1e18\n function _deviation(address pair, address baseToken) internal view returns (uint256) {\n // Get token base unit\n address token0 = IUniswapV2Pair(pair).token0();\n bool useToken0Price = token0 != baseToken;\n address underlying = useToken0Price ? token0 : IUniswapV2Pair(pair).token1();\n uint256 baseUnit = 10 ** uint256(ERC20Upgradeable(underlying).decimals());\n\n // Get TWAP price\n uint256 twapPrice = (((useToken0Price ? price0TWAP(pair) : price1TWAP(pair)) / (2 ** 56)) * baseUnit) / (2 ** 56); // Scaled by 1e18, not 2 ** 112\n\n // Get spot price\n (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves();\n uint256 spotPrice = useToken0Price ? (reserve1 * baseUnit) / reserve0 : (reserve0 * baseUnit) / reserve1;\n\n // Get ratio and return deviation\n uint256 ratio = (spotPrice * 1e18) / twapPrice;\n return ratio >= 1e18 ? ratio - 1e18 : 1e18 - ratio;\n }\n\n /// @dev Internal function to check if a pair is updatable at all.\n function _updateable(address pair) internal view returns (bool) {\n // Updateable if:\n // 1) We have no observations\n // 2) The elapsed time since the last observation is > MIN_TWAP_TIME\n // Note that we loop observationCount[pair] around OBSERVATION_BUFFER so we don't waste gas on new storage slots\n return\n observationCount[pair] <= 0 ||\n (block.timestamp - observations[pair][(observationCount[pair] - 1) % OBSERVATION_BUFFER].timestamp) >\n MIN_TWAP_TIME;\n }\n\n /// @notice Update one pair.\n function update(address pair) external {\n require(_update(pair), \"Failed to update pair.\");\n }\n\n /// @notice Update multiple pairs at once.\n function update(address[] calldata pairs) external {\n bool worked = false;\n for (uint256 i = 0; i < pairs.length; i++) if (_update(pairs[i])) worked = true;\n require(worked, \"No pairs can be updated (yet).\");\n }\n\n /// @dev Internal function to update a single pair.\n function _update(address pair) internal returns (bool) {\n // Check if workable\n if (!_updateable(pair)) return false;\n\n // Get cumulative price(s)\n uint256 price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();\n uint256 price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();\n\n // Loop observationCount[pair] around OBSERVATION_BUFFER so we don't waste gas on new storage slots\n (, , uint32 lastTime) = IUniswapV2Pair(pair).getReserves();\n observations[pair][observationCount[pair] % OBSERVATION_BUFFER] = Observation(\n lastTime,\n price0Cumulative,\n price1Cumulative\n );\n observationCount[pair]++;\n return true;\n }\n}\n" + }, + "contracts/src/oracles/default/UniswapV3PriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { BasePriceOracle } from \"../BasePriceOracle.sol\";\nimport { ERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\nimport { ConcentratedLiquidityBasePriceOracle } from \"./ConcentratedLiquidityBasePriceOracle.sol\";\n\nimport \"../../external/uniswap/TickMath.sol\";\nimport \"../../external/uniswap/FullMath.sol\";\nimport \"../../external/uniswap/IUniswapV3Pool.sol\";\n\n/**\n * @title UniswapV3PriceOracle\n * @author Carlo Mazzaferro (https://github.com/carlomazzaferro)\n * @notice UniswapV3PriceOracle is a price oracle for Uniswap V3 pairs.\n * @dev Implements the `PriceOracle` interface used by Ionic pools (and Compound v2).\n */\ncontract UniswapV3PriceOracle is ConcentratedLiquidityBasePriceOracle {\n /**\n * @dev Fetches the price for a token from Algebra pools.\n */\n\n function _price(address token) internal view override returns (uint256) {\n uint32[] memory secondsAgos = new uint32[](2);\n uint256 twapWindow = poolFeeds[token].twapWindow;\n address baseToken = poolFeeds[token].baseToken;\n\n secondsAgos[0] = uint32(twapWindow);\n secondsAgos[1] = 0;\n\n IUniswapV3Pool pool = IUniswapV3Pool(poolFeeds[token].poolAddress);\n (int56[] memory tickCumulatives, ) = pool.observe(secondsAgos);\n\n int24 tick = int24((tickCumulatives[1] - tickCumulatives[0]) / int56(int256(twapWindow)));\n uint160 sqrtPriceX96 = TickMath.getSqrtRatioAtTick(tick);\n\n uint256 tokenPrice = getPriceX96FromSqrtPriceX96(pool.token0(), token, sqrtPriceX96);\n return scalePrices(baseToken, token, tokenPrice);\n }\n}\n" + }, + "contracts/src/oracles/default/VelodromePriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../BasePriceOracle.sol\";\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\ninterface Prices {\n function getRateToEth(address srcToken, bool useSrcWrappers) external view returns (uint256 weightedRate);\n}\n\ncontract VelodromePriceOracle is BasePriceOracle {\n Prices immutable prices;\n\n constructor(address _prices) {\n prices = Prices(_prices);\n }\n /**\n * @notice Fetches the token/ETH price, with 18 decimals of precision.\n * @param underlying The underlying token address for which to get the price.\n * @return Price denominated in ETH (scaled by 1e18)\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying));\n }\n\n /**\n * @notice Fetches the token/ETH price, with 18 decimals of precision.\n */\n function _price(address token) internal view returns (uint256) {\n return prices.getRateToEth(token, false);\n }\n}\n" + }, + "contracts/src/oracles/default/VelodromePriceOracleFraxtal.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../BasePriceOracle.sol\";\n\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\ninterface Prices_Fraxtal {\n function getRate(address srcToken, address dstToken, bool useSrcWrappers) external view returns (uint256 weightedRate);\n}\n\ncontract VelodromePriceOracleFraxtal is BasePriceOracle {\n Prices_Fraxtal immutable prices;\n\n constructor(address _prices) {\n prices = Prices_Fraxtal(_prices);\n }\n /**\n * @notice Fetches the token/ETH price, with 18 decimals of precision.\n * @param underlying The underlying token address for which to get the price.\n * @return Price denominated in ETH (scaled by 1e18)\n */\n function price(address underlying) external view override returns (uint256) {\n return _price(underlying);\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n address underlying = cToken.underlying();\n // Comptroller needs prices to be scaled by 1e(36 - decimals)\n // Since `_price` returns prices scaled by 18 decimals, we must scale them by 1e(36 - 18 - decimals)\n return (_price(underlying));\n }\n\n /**\n * @notice Fetches the token/ETH price, with 18 decimals of precision.\n */\n function _price(address token) internal view returns (uint256) {\n return prices.getRate(token, 0xFC00000000000000000000000000000000000006, false);\n }\n}\n" + }, + "contracts/src/oracles/MasterPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\n\nimport { ICErc20 } from \"../compound/CTokenInterfaces.sol\";\n\nimport { BasePriceOracle } from \"./BasePriceOracle.sol\";\n\n/**\n * @title MasterPriceOracle\n * @notice Use a combination of price oracles.\n * @dev Implements `PriceOracle`.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract MasterPriceOracle is Initializable, BasePriceOracle {\n /**\n * @dev Maps underlying token addresses to `PriceOracle` contracts (can be `BasePriceOracle` contracts too).\n */\n mapping(address => BasePriceOracle) public oracles;\n\n /**\n * @dev Default/fallback `PriceOracle`.\n */\n BasePriceOracle public defaultOracle;\n\n /**\n * @dev The administrator of this `MasterPriceOracle`.\n */\n address public admin;\n\n /**\n * @dev Controls if `admin` can overwrite existing assignments of oracles to underlying tokens.\n */\n bool internal noAdminOverwrite;\n\n /**\n * @dev The Wrapped native asset address.\n */\n address public wtoken;\n\n /**\n * @dev Maps underlying token addresses to `PriceOracle` contracts (can be `BasePriceOracle` contracts too).\n */\n mapping(address => BasePriceOracle) public fallbackOracles;\n\n /**\n * @dev Returns a boolean indicating if `admin` can overwrite existing assignments of oracles to underlying tokens.\n */\n function canAdminOverwrite() external view returns (bool) {\n return !noAdminOverwrite;\n }\n\n /**\n * @dev Event emitted when `admin` is changed.\n */\n event NewAdmin(address oldAdmin, address newAdmin);\n\n /**\n * @dev Event emitted when the default oracle is changed.\n */\n event NewDefaultOracle(address oldOracle, address newOracle);\n\n /**\n * @dev Event emitted when an underlying token's oracle is changed.\n */\n event NewOracle(address underlying, address oldOracle, address newOracle);\n\n /**\n * @dev Initialize state variables.\n * @param underlyings The underlying ERC20 token addresses to link to `_oracles`.\n * @param _oracles The `PriceOracle` contracts to be assigned to `underlyings`.\n * @param _defaultOracle The default `PriceOracle` contract to use.\n * @param _admin The admin who can assign oracles to underlying tokens.\n * @param _canAdminOverwrite Controls if `admin` can overwrite existing assignments of oracles to underlying tokens.\n * @param _wtoken The Wrapped native asset address\n */\n function initialize(\n address[] memory underlyings,\n BasePriceOracle[] memory _oracles,\n BasePriceOracle _defaultOracle,\n address _admin,\n bool _canAdminOverwrite,\n address _wtoken\n ) external initializer {\n // Input validation\n require(underlyings.length == _oracles.length, \"Lengths of both arrays must be equal.\");\n\n // Initialize state variables\n for (uint256 i = 0; i < underlyings.length; i++) {\n address underlying = underlyings[i];\n BasePriceOracle newOracle = _oracles[i];\n oracles[underlying] = newOracle;\n emit NewOracle(underlying, address(0), address(newOracle));\n }\n\n defaultOracle = _defaultOracle;\n admin = _admin;\n noAdminOverwrite = !_canAdminOverwrite;\n wtoken = _wtoken;\n }\n\n /**\n * @dev Sets `_oracles` for `underlyings`.\n */\n function add(address[] calldata underlyings, BasePriceOracle[] calldata _oracles) external onlyAdmin {\n // Input validation\n require(\n underlyings.length > 0 && underlyings.length == _oracles.length,\n \"Lengths of both arrays must be equal and greater than 0.\"\n );\n\n // Assign oracles to underlying tokens\n for (uint256 i = 0; i < underlyings.length; i++) {\n address underlying = underlyings[i];\n address oldOracle = address(oracles[underlying]);\n if (noAdminOverwrite)\n require(\n oldOracle == address(0),\n \"Admin cannot overwrite existing assignments of oracles to underlying tokens.\"\n );\n BasePriceOracle newOracle = _oracles[i];\n oracles[underlying] = newOracle;\n emit NewOracle(underlying, oldOracle, address(newOracle));\n }\n }\n\n /**\n * @dev Sets `_oracles` for `underlyings`.\n */\n function addFallbacks(address[] calldata underlyings, BasePriceOracle[] calldata _oracles) external onlyAdmin {\n // Input validation\n require(\n underlyings.length > 0 && underlyings.length == _oracles.length,\n \"Lengths of both arrays must be equal and greater than 0.\"\n );\n\n // Assign oracles to underlying tokens\n for (uint256 i = 0; i < underlyings.length; i++) {\n address underlying = underlyings[i];\n address oldOracle = address(fallbackOracles[underlying]);\n if (noAdminOverwrite)\n require(\n oldOracle == address(0),\n \"Admin cannot overwrite existing assignments of oracles to underlying tokens.\"\n );\n BasePriceOracle newOracle = _oracles[i];\n fallbackOracles[underlying] = newOracle;\n emit NewOracle(underlying, oldOracle, address(newOracle));\n }\n }\n\n /**\n * @dev Changes the default price oracle\n */\n function setDefaultOracle(BasePriceOracle newOracle) external onlyAdmin {\n BasePriceOracle oldOracle = defaultOracle;\n defaultOracle = newOracle;\n emit NewDefaultOracle(address(oldOracle), address(newOracle));\n }\n\n /**\n * @dev Changes the admin and emits an event.\n */\n function changeAdmin(address newAdmin) external onlyAdmin {\n address oldAdmin = admin;\n admin = newAdmin;\n emit NewAdmin(oldAdmin, newAdmin);\n }\n\n /**\n * @dev Modifier that checks if `msg.sender == admin`.\n */\n modifier onlyAdmin() {\n require(msg.sender == admin, \"Sender is not the admin.\");\n _;\n }\n\n /**\n * @notice Returns the price in ETH of the token underlying `cToken`.\n * @dev Implements the `PriceOracle` interface for Ionic pools (and Compound v2).\n * @return Price in ETH of the token underlying `cToken`, scaled by `10 ** (36 - underlyingDecimals)`.\n */\n function getUnderlyingPrice(ICErc20 cToken) external view override returns (uint256) {\n // Get underlying ERC20 token address\n address underlying = address(ICErc20(address(cToken)).underlying());\n\n if (underlying == wtoken) return 1e18;\n\n BasePriceOracle oracle = oracles[underlying];\n BasePriceOracle fallbackOracle = fallbackOracles[underlying];\n\n if (address(oracle) != address(0)) {\n try oracle.getUnderlyingPrice(cToken) returns (uint256 underlyingPrice) {\n if (underlyingPrice == 0) {\n if (address(fallbackOracle) != address(0)) return fallbackOracle.getUnderlyingPrice(cToken);\n } else {\n return underlyingPrice;\n }\n } catch {\n if (address(fallbackOracle) != address(0)) return fallbackOracle.getUnderlyingPrice(cToken);\n }\n } else {\n if (address(fallbackOracle) != address(0)) return fallbackOracle.getUnderlyingPrice(cToken);\n }\n revert(\"Price oracle not found for this underlying token address.\");\n }\n\n /**\n * @dev Attempts to return the price in ETH of `underlying` (implements `BasePriceOracle`).\n */\n function price(address underlying) public view override returns (uint256) {\n // Return 1e18 for WETH\n if (underlying == wtoken) return 1e18;\n\n // Get underlying price from assigned oracle\n BasePriceOracle oracle = oracles[underlying];\n BasePriceOracle fallbackOracle = fallbackOracles[underlying];\n\n if (address(oracle) != address(0)) {\n try oracle.price(underlying) returns (uint256 underlyingPrice) {\n if (underlyingPrice == 0) {\n if (address(fallbackOracle) != address(0)) return fallbackOracle.price(underlying);\n } else {\n return underlyingPrice;\n }\n } catch {\n if (address(fallbackOracle) != address(0)) return fallbackOracle.price(underlying);\n }\n } else {\n if (address(fallbackOracle) != address(0)) return fallbackOracle.price(underlying);\n }\n revert(\"Price oracle not found for this underlying token address.\");\n }\n}\n" + }, + "contracts/src/PoolDirectory.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/utils/Create2Upgradeable.sol\";\n\nimport { IonicComptroller } from \"./compound/ComptrollerInterface.sol\";\nimport { BasePriceOracle } from \"./oracles/BasePriceOracle.sol\";\nimport { Unitroller } from \"./compound/Unitroller.sol\";\nimport \"./ionic/SafeOwnableUpgradeable.sol\";\nimport \"./ionic/DiamondExtension.sol\";\n\n/**\n * @title PoolDirectory\n * @author David Lucid (https://github.com/davidlucid)\n * @notice PoolDirectory is a directory for Ionic interest rate pools.\n */\ncontract PoolDirectory is SafeOwnableUpgradeable {\n /**\n * @dev Initializes a deployer whitelist if desired.\n * @param _enforceDeployerWhitelist Boolean indicating if the deployer whitelist is to be enforced.\n * @param _deployerWhitelist Array of Ethereum accounts to be whitelisted.\n */\n function initialize(bool _enforceDeployerWhitelist, address[] memory _deployerWhitelist) public initializer {\n __SafeOwnable_init(msg.sender);\n enforceDeployerWhitelist = _enforceDeployerWhitelist;\n for (uint256 i = 0; i < _deployerWhitelist.length; i++) deployerWhitelist[_deployerWhitelist[i]] = true;\n }\n\n /**\n * @dev Struct for a Ionic interest rate pool.\n */\n struct Pool {\n string name;\n address creator;\n address comptroller;\n uint256 blockPosted;\n uint256 timestampPosted;\n }\n\n /**\n * @dev Array of Ionic interest rate pools.\n */\n Pool[] public pools;\n\n /**\n * @dev Maps Ethereum accounts to arrays of Ionic pool indexes.\n */\n mapping(address => uint256[]) private _poolsByAccount;\n\n /**\n * @dev Maps Ionic pool Comptroller addresses to bools indicating if they have been registered via the directory.\n */\n mapping(address => bool) public poolExists;\n\n /**\n * @dev Emitted when a new Ionic pool is added to the directory.\n */\n event PoolRegistered(uint256 index, Pool pool);\n\n /**\n * @dev Booleans indicating if the deployer whitelist is enforced.\n */\n bool public enforceDeployerWhitelist;\n\n /**\n * @dev Maps Ethereum accounts to booleans indicating if they are allowed to deploy pools.\n */\n mapping(address => bool) public deployerWhitelist;\n\n /**\n * @dev Controls if the deployer whitelist is to be enforced.\n * @param enforce Boolean indicating if the deployer whitelist is to be enforced.\n */\n function _setDeployerWhitelistEnforcement(bool enforce) external onlyOwner {\n enforceDeployerWhitelist = enforce;\n }\n\n /**\n * @dev Adds/removes Ethereum accounts to the deployer whitelist.\n * @param deployers Array of Ethereum accounts to be whitelisted.\n * @param status Whether to add or remove the accounts.\n */\n function _editDeployerWhitelist(address[] calldata deployers, bool status) external onlyOwner {\n require(deployers.length > 0, \"No deployers supplied.\");\n for (uint256 i = 0; i < deployers.length; i++) deployerWhitelist[deployers[i]] = status;\n }\n\n /**\n * @dev Adds a new Ionic pool to the directory (without checking msg.sender).\n * @param name The name of the pool.\n * @param comptroller The pool's Comptroller proxy contract address.\n * @return The index of the registered Ionic pool.\n */\n function _registerPool(string memory name, address comptroller) internal returns (uint256) {\n require(!poolExists[comptroller], \"Pool already exists in the directory.\");\n require(!enforceDeployerWhitelist || deployerWhitelist[msg.sender], \"Sender is not on deployer whitelist.\");\n require(bytes(name).length <= 100, \"No pool name supplied.\");\n Pool memory pool = Pool(name, msg.sender, comptroller, block.number, block.timestamp);\n pools.push(pool);\n _poolsByAccount[msg.sender].push(pools.length - 1);\n poolExists[comptroller] = true;\n emit PoolRegistered(pools.length - 1, pool);\n return pools.length - 1;\n }\n\n function _deprecatePool(address comptroller) external onlyOwner {\n for (uint256 i = 0; i < pools.length; i++) {\n if (pools[i].comptroller == comptroller) {\n _deprecatePool(i);\n break;\n }\n }\n }\n\n function _deprecatePool(uint256 index) public onlyOwner {\n Pool storage ionicPool = pools[index];\n\n require(ionicPool.comptroller != address(0), \"pool already deprecated\");\n\n // swap with the last pool of the creator and delete\n uint256[] storage creatorPools = _poolsByAccount[ionicPool.creator];\n for (uint256 i = 0; i < creatorPools.length; i++) {\n if (creatorPools[i] == index) {\n creatorPools[i] = creatorPools[creatorPools.length - 1];\n creatorPools.pop();\n break;\n }\n }\n\n // leave it to true to deny the re-registering of the same pool\n poolExists[ionicPool.comptroller] = true;\n\n // nullify the storage\n ionicPool.comptroller = address(0);\n ionicPool.creator = address(0);\n ionicPool.name = \"\";\n ionicPool.blockPosted = 0;\n ionicPool.timestampPosted = 0;\n }\n\n /**\n * @dev Deploys a new Ionic pool and adds to the directory.\n * @param name The name of the pool.\n * @param implementation The Comptroller implementation contract address.\n * @param constructorData Encoded construction data for `Unitroller constructor()`\n * @param enforceWhitelist Boolean indicating if the pool's supplier/borrower whitelist is to be enforced.\n * @param closeFactor The pool's close factor (scaled by 1e18).\n * @param liquidationIncentive The pool's liquidation incentive (scaled by 1e18).\n * @param priceOracle The pool's PriceOracle contract address.\n * @return Index of the registered Ionic pool and the Unitroller proxy address.\n */\n function deployPool(\n string memory name,\n address implementation,\n bytes calldata constructorData,\n bool enforceWhitelist,\n uint256 closeFactor,\n uint256 liquidationIncentive,\n address priceOracle\n ) external returns (uint256, address) {\n // Input validation\n require(implementation != address(0), \"No Comptroller implementation contract address specified.\");\n require(priceOracle != address(0), \"No PriceOracle contract address specified.\");\n\n // Deploy Unitroller using msg.sender, name, and block.number as a salt\n bytes memory unitrollerCreationCode = abi.encodePacked(type(Unitroller).creationCode, constructorData);\n address proxy = Create2Upgradeable.deploy(\n 0,\n keccak256(abi.encodePacked(msg.sender, name, ++poolsCounter)),\n unitrollerCreationCode\n );\n\n // Setup the pool\n IonicComptroller comptrollerProxy = IonicComptroller(proxy);\n // Set up the extensions\n comptrollerProxy._upgrade();\n\n // Set pool parameters\n require(comptrollerProxy._setCloseFactor(closeFactor) == 0, \"Failed to set pool close factor.\");\n require(\n comptrollerProxy._setLiquidationIncentive(liquidationIncentive) == 0,\n \"Failed to set pool liquidation incentive.\"\n );\n require(comptrollerProxy._setPriceOracle(BasePriceOracle(priceOracle)) == 0, \"Failed to set pool price oracle.\");\n\n // Whitelist\n if (enforceWhitelist)\n require(comptrollerProxy._setWhitelistEnforcement(true) == 0, \"Failed to enforce supplier/borrower whitelist.\");\n\n // Make msg.sender the admin\n require(comptrollerProxy._setPendingAdmin(msg.sender) == 0, \"Failed to set pending admin on Unitroller.\");\n\n // Register the pool with this PoolDirectory\n return (_registerPool(name, proxy), proxy);\n }\n\n /**\n * @notice Returns `ids` and directory information of all non-deprecated Ionic pools.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getActivePools() public view returns (uint256[] memory, Pool[] memory) {\n uint256 count = 0;\n for (uint256 i = 0; i < pools.length; i++) {\n if (pools[i].comptroller != address(0)) count++;\n }\n\n Pool[] memory activePools = new Pool[](count);\n uint256[] memory poolIds = new uint256[](count);\n\n uint256 index = 0;\n for (uint256 i = 0; i < pools.length; i++) {\n if (pools[i].comptroller != address(0)) {\n poolIds[index] = i;\n activePools[index] = pools[i];\n index++;\n }\n }\n\n return (poolIds, activePools);\n }\n\n /**\n * @notice Returns arrays of all Ionic pools' data.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getAllPools() public view returns (Pool[] memory) {\n uint256 count = 0;\n for (uint256 i = 0; i < pools.length; i++) {\n if (pools[i].comptroller != address(0)) count++;\n }\n\n Pool[] memory result = new Pool[](count);\n\n uint256 index = 0;\n for (uint256 i = 0; i < pools.length; i++) {\n if (pools[i].comptroller != address(0)) {\n result[index++] = pools[i];\n }\n }\n\n return result;\n }\n\n /**\n * @notice Returns arrays of all public Ionic pool indexes and data.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getPublicPools() external view returns (uint256[] memory, Pool[] memory) {\n uint256 arrayLength = 0;\n\n (, Pool[] memory activePools) = getActivePools();\n for (uint256 i = 0; i < activePools.length; i++) {\n try IonicComptroller(activePools[i].comptroller).enforceWhitelist() returns (bool enforceWhitelist) {\n if (enforceWhitelist) continue;\n } catch {}\n\n arrayLength++;\n }\n\n uint256[] memory indexes = new uint256[](arrayLength);\n Pool[] memory publicPools = new Pool[](arrayLength);\n uint256 index = 0;\n\n for (uint256 i = 0; i < activePools.length; i++) {\n try IonicComptroller(activePools[i].comptroller).enforceWhitelist() returns (bool enforceWhitelist) {\n if (enforceWhitelist) continue;\n } catch {}\n\n indexes[index] = i;\n publicPools[index] = activePools[i];\n index++;\n }\n\n return (indexes, publicPools);\n }\n\n /**\n * @notice Returns arrays of all public Ionic pool indexes and data.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getPoolsOfUser(address user) external view returns (uint256[] memory, Pool[] memory) {\n uint256 arrayLength = 0;\n\n (, Pool[] memory activePools) = getActivePools();\n for (uint256 i = 0; i < activePools.length; i++) {\n try IonicComptroller(activePools[i].comptroller).isUserOfPool(user) returns (bool isUsing) {\n if (!isUsing) continue;\n } catch {}\n\n arrayLength++;\n }\n\n uint256[] memory indexes = new uint256[](arrayLength);\n Pool[] memory poolsOfUser = new Pool[](arrayLength);\n uint256 index = 0;\n\n for (uint256 i = 0; i < activePools.length; i++) {\n try IonicComptroller(activePools[i].comptroller).isUserOfPool(user) returns (bool isUsing) {\n if (!isUsing) continue;\n } catch {}\n\n indexes[index] = i;\n poolsOfUser[index] = activePools[i];\n index++;\n }\n\n return (indexes, poolsOfUser);\n }\n\n /**\n * @notice Returns arrays of Ionic pool indexes and data created by `account`.\n */\n function getPoolsByAccount(address account) external view returns (uint256[] memory, Pool[] memory) {\n uint256[] memory indexes = new uint256[](_poolsByAccount[account].length);\n Pool[] memory accountPools = new Pool[](_poolsByAccount[account].length);\n (, Pool[] memory activePools) = getActivePools();\n\n for (uint256 i = 0; i < _poolsByAccount[account].length; i++) {\n indexes[i] = _poolsByAccount[account][i];\n accountPools[i] = activePools[_poolsByAccount[account][i]];\n }\n\n return (indexes, accountPools);\n }\n\n /**\n * @notice Modify existing Ionic pool name.\n */\n function setPoolName(uint256 index, string calldata name) external {\n IonicComptroller _comptroller = IonicComptroller(pools[index].comptroller);\n require(\n (msg.sender == _comptroller.admin() && _comptroller.adminHasRights()) || msg.sender == owner(),\n \"!permission\"\n );\n pools[index].name = name;\n }\n\n /**\n * @dev Maps Ethereum accounts to booleans indicating if they are a whitelisted admin.\n */\n mapping(address => bool) public adminWhitelist;\n\n /**\n * @dev used as salt for the creation of new pools\n */\n uint256 public poolsCounter;\n\n /**\n * @dev Event emitted when the admin whitelist is updated.\n */\n event AdminWhitelistUpdated(address[] admins, bool status);\n\n /**\n * @dev Adds/removes Ethereum accounts to the admin whitelist.\n * @param admins Array of Ethereum accounts to be whitelisted.\n * @param status Whether to add or remove the accounts.\n */\n function _editAdminWhitelist(address[] calldata admins, bool status) external onlyOwner {\n require(admins.length > 0, \"No admins supplied.\");\n for (uint256 i = 0; i < admins.length; i++) adminWhitelist[admins[i]] = status;\n emit AdminWhitelistUpdated(admins, status);\n }\n\n /**\n * @notice Returns arrays of all Ionic pool indexes and data with whitelisted admins.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getPublicPoolsByVerification(bool whitelistedAdmin) external view returns (uint256[] memory, Pool[] memory) {\n uint256 arrayLength = 0;\n\n (, Pool[] memory activePools) = getActivePools();\n for (uint256 i = 0; i < activePools.length; i++) {\n IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller);\n\n try comptroller.admin() returns (address admin) {\n if (whitelistedAdmin != adminWhitelist[admin]) continue;\n } catch {}\n\n arrayLength++;\n }\n\n uint256[] memory indexes = new uint256[](arrayLength);\n Pool[] memory publicPools = new Pool[](arrayLength);\n uint256 index = 0;\n\n for (uint256 i = 0; i < activePools.length; i++) {\n IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller);\n\n try comptroller.admin() returns (address admin) {\n if (whitelistedAdmin != adminWhitelist[admin]) continue;\n } catch {}\n\n indexes[index] = i;\n publicPools[index] = activePools[i];\n index++;\n }\n\n return (indexes, publicPools);\n }\n\n /**\n * @notice Returns arrays of all verified Ionic pool indexes and data for which the account is whitelisted\n * @param account who is whitelisted in the returned verified whitelist-enabled pools.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getVerifiedPoolsOfWhitelistedAccount(\n address account\n ) external view returns (uint256[] memory, Pool[] memory) {\n uint256 arrayLength = 0;\n (, Pool[] memory activePools) = getActivePools();\n for (uint256 i = 0; i < activePools.length; i++) {\n IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller);\n\n try comptroller.enforceWhitelist() returns (bool enforceWhitelist) {\n if (!enforceWhitelist || !comptroller.whitelist(account)) continue;\n } catch {}\n\n arrayLength++;\n }\n\n uint256[] memory indexes = new uint256[](arrayLength);\n Pool[] memory accountWhitelistedPools = new Pool[](arrayLength);\n uint256 index = 0;\n\n for (uint256 i = 0; i < activePools.length; i++) {\n IonicComptroller comptroller = IonicComptroller(activePools[i].comptroller);\n try comptroller.enforceWhitelist() returns (bool enforceWhitelist) {\n if (!enforceWhitelist || !comptroller.whitelist(account)) continue;\n } catch {}\n\n indexes[index] = i;\n accountWhitelistedPools[index] = activePools[i];\n index++;\n }\n\n return (indexes, accountWhitelistedPools);\n }\n}\n" + }, + "contracts/src/PoolLens.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport { IonicComptroller } from \"./compound/ComptrollerInterface.sol\";\nimport { BasePriceOracle } from \"./oracles/BasePriceOracle.sol\";\nimport { ICErc20 } from \"./compound/CTokenInterfaces.sol\";\n\nimport { PoolDirectory } from \"./PoolDirectory.sol\";\nimport { MasterPriceOracle } from \"./oracles/MasterPriceOracle.sol\";\n\n/**\n * @title PoolLens\n * @author David Lucid (https://github.com/davidlucid)\n * @notice PoolLens returns data on Ionic interest rate pools in mass for viewing by dApps, bots, etc.\n */\ncontract PoolLens is Initializable {\n error ComptrollerError(uint256 errCode);\n\n /**\n * @notice Initialize the `PoolDirectory` contract object.\n * @param _directory The PoolDirectory\n * @param _name Name for the nativeToken\n * @param _symbol Symbol for the nativeToken\n * @param _hardcodedAddresses Underlying token addresses for a token like maker which are DSToken and/or use bytes32 for `symbol`\n * @param _hardcodedNames Harcoded name for these tokens\n * @param _hardcodedSymbols Harcoded symbol for these tokens\n * @param _uniswapLPTokenNames Harcoded names for underlying uniswap LpToken\n * @param _uniswapLPTokenSymbols Harcoded symbols for underlying uniswap LpToken\n * @param _uniswapLPTokenDisplayNames Harcoded display names for underlying uniswap LpToken\n */\n function initialize(\n PoolDirectory _directory,\n string memory _name,\n string memory _symbol,\n address[] memory _hardcodedAddresses,\n string[] memory _hardcodedNames,\n string[] memory _hardcodedSymbols,\n string[] memory _uniswapLPTokenNames,\n string[] memory _uniswapLPTokenSymbols,\n string[] memory _uniswapLPTokenDisplayNames\n ) public initializer {\n require(address(_directory) != address(0), \"PoolDirectory instance cannot be the zero address.\");\n require(\n _hardcodedAddresses.length == _hardcodedNames.length && _hardcodedAddresses.length == _hardcodedSymbols.length,\n \"Hardcoded addresses lengths not equal.\"\n );\n require(\n _uniswapLPTokenNames.length == _uniswapLPTokenSymbols.length &&\n _uniswapLPTokenNames.length == _uniswapLPTokenDisplayNames.length,\n \"Uniswap LP token names lengths not equal.\"\n );\n\n directory = _directory;\n name = _name;\n symbol = _symbol;\n for (uint256 i = 0; i < _hardcodedAddresses.length; i++) {\n hardcoded[_hardcodedAddresses[i]] = TokenData({ name: _hardcodedNames[i], symbol: _hardcodedSymbols[i] });\n }\n\n for (uint256 i = 0; i < _uniswapLPTokenNames.length; i++) {\n uniswapData.push(\n UniswapData({\n name: _uniswapLPTokenNames[i],\n symbol: _uniswapLPTokenSymbols[i],\n displayName: _uniswapLPTokenDisplayNames[i]\n })\n );\n }\n }\n\n string public name;\n string public symbol;\n\n struct TokenData {\n string name;\n string symbol;\n }\n mapping(address => TokenData) hardcoded;\n\n struct UniswapData {\n string name; // ie \"Uniswap V2\" or \"SushiSwap LP Token\"\n string symbol; // ie \"UNI-V2\" or \"SLP\"\n string displayName; // ie \"SushiSwap\" or \"Uniswap\"\n }\n UniswapData[] uniswapData;\n\n /**\n * @notice `PoolDirectory` contract object.\n */\n PoolDirectory public directory;\n\n /**\n * @dev Struct for Ionic pool summary data.\n */\n struct IonicPoolData {\n uint256 totalSupply;\n uint256 totalBorrow;\n address[] underlyingTokens;\n string[] underlyingSymbols;\n bool whitelistedAdmin;\n }\n\n /**\n * @notice Returns arrays of all public Ionic pool indexes, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state.\n */\n function getPublicPoolsWithData()\n external\n returns (uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory)\n {\n (uint256[] memory indexes, PoolDirectory.Pool[] memory publicPools) = directory.getPublicPools();\n (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(publicPools);\n return (indexes, publicPools, data, errored);\n }\n\n /**\n * @notice Returns arrays of all whitelisted public Ionic pool indexes, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state.\n */\n function getPublicPoolsByVerificationWithData(\n bool whitelistedAdmin\n ) external returns (uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory) {\n (uint256[] memory indexes, PoolDirectory.Pool[] memory publicPools) = directory.getPublicPoolsByVerification(\n whitelistedAdmin\n );\n (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(publicPools);\n return (indexes, publicPools, data, errored);\n }\n\n /**\n * @notice Returns arrays of the indexes of Ionic pools created by `account`, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state.\n */\n function getPoolsByAccountWithData(\n address account\n ) external returns (uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory) {\n (uint256[] memory indexes, PoolDirectory.Pool[] memory accountPools) = directory.getPoolsByAccount(account);\n (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(accountPools);\n return (indexes, accountPools, data, errored);\n }\n\n /**\n * @notice Returns arrays of the indexes of Ionic pools used by `user`, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state.\n */\n function getPoolsOIonicrWithData(\n address user\n ) external returns (uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory) {\n (uint256[] memory indexes, PoolDirectory.Pool[] memory userPools) = directory.getPoolsOfUser(user);\n (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(userPools);\n return (indexes, userPools, data, errored);\n }\n\n /**\n * @notice Internal function returning arrays of requested Ionic pool indexes, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state.\n */\n function getPoolsData(PoolDirectory.Pool[] memory pools) internal returns (IonicPoolData[] memory, bool[] memory) {\n IonicPoolData[] memory data = new IonicPoolData[](pools.length);\n bool[] memory errored = new bool[](pools.length);\n\n for (uint256 i = 0; i < pools.length; i++) {\n try this.getPoolSummary(IonicComptroller(pools[i].comptroller)) returns (\n uint256 _totalSupply,\n uint256 _totalBorrow,\n address[] memory _underlyingTokens,\n string[] memory _underlyingSymbols,\n bool _whitelistedAdmin\n ) {\n data[i] = IonicPoolData(_totalSupply, _totalBorrow, _underlyingTokens, _underlyingSymbols, _whitelistedAdmin);\n } catch {\n errored[i] = true;\n }\n }\n\n return (data, errored);\n }\n\n /**\n * @notice Returns total supply balance (in ETH), total borrow balance (in ETH), underlying token addresses, and underlying token symbols of a Ionic pool.\n */\n function getPoolSummary(\n IonicComptroller comptroller\n ) external returns (uint256, uint256, address[] memory, string[] memory, bool) {\n uint256 totalBorrow = 0;\n uint256 totalSupply = 0;\n ICErc20[] memory cTokens = comptroller.getAllMarkets();\n address[] memory underlyingTokens = new address[](cTokens.length);\n string[] memory underlyingSymbols = new string[](cTokens.length);\n BasePriceOracle oracle = comptroller.oracle();\n\n for (uint256 i = 0; i < cTokens.length; i++) {\n ICErc20 cToken = cTokens[i];\n (bool isListed, ) = comptroller.markets(address(cToken));\n if (!isListed) continue;\n cToken.accrueInterest();\n uint256 assetTotalBorrow = cToken.totalBorrowsCurrent();\n uint256 assetTotalSupply = cToken.getCash() +\n assetTotalBorrow -\n (cToken.totalReserves() + cToken.totalAdminFees() + cToken.totalIonicFees());\n uint256 underlyingPrice = oracle.getUnderlyingPrice(cToken);\n totalBorrow = totalBorrow + (assetTotalBorrow * underlyingPrice) / 1e18;\n totalSupply = totalSupply + (assetTotalSupply * underlyingPrice) / 1e18;\n\n underlyingTokens[i] = ICErc20(address(cToken)).underlying();\n (, underlyingSymbols[i]) = getTokenNameAndSymbol(underlyingTokens[i]);\n }\n\n bool whitelistedAdmin = directory.adminWhitelist(comptroller.admin());\n return (totalSupply, totalBorrow, underlyingTokens, underlyingSymbols, whitelistedAdmin);\n }\n\n /**\n * @dev Struct for a Ionic pool asset.\n */\n struct PoolAsset {\n address cToken;\n address underlyingToken;\n string underlyingName;\n string underlyingSymbol;\n uint256 underlyingDecimals;\n uint256 underlyingBalance;\n uint256 supplyRatePerBlock;\n uint256 borrowRatePerBlock;\n uint256 totalSupply;\n uint256 totalBorrow;\n uint256 supplyBalance;\n uint256 borrowBalance;\n uint256 liquidity;\n bool membership;\n uint256 exchangeRate; // Price of cTokens in terms of underlying tokens\n uint256 underlyingPrice; // Price of underlying tokens in ETH (scaled by 1e18)\n address oracle;\n uint256 collateralFactor;\n uint256 reserveFactor;\n uint256 adminFee;\n uint256 ionicFee;\n bool borrowGuardianPaused;\n bool mintGuardianPaused;\n }\n\n /**\n * @notice Returns data on the specified assets of the specified Ionic pool.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state.\n * @param comptroller The Comptroller proxy contract address of the Ionic pool.\n * @param cTokens The cToken contract addresses of the assets to query.\n * @param user The user for which to get account data.\n * @return An array of Ionic pool assets.\n */\n function getPoolAssetsWithData(\n IonicComptroller comptroller,\n ICErc20[] memory cTokens,\n address user\n ) internal returns (PoolAsset[] memory) {\n uint256 arrayLength = 0;\n\n for (uint256 i = 0; i < cTokens.length; i++) {\n (bool isListed, ) = comptroller.markets(address(cTokens[i]));\n if (isListed) arrayLength++;\n }\n\n PoolAsset[] memory detailedAssets = new PoolAsset[](arrayLength);\n uint256 index = 0;\n BasePriceOracle oracle = BasePriceOracle(address(comptroller.oracle()));\n\n for (uint256 i = 0; i < cTokens.length; i++) {\n // Check if market is listed and get collateral factor\n (bool isListed, uint256 collateralFactorMantissa) = comptroller.markets(address(cTokens[i]));\n if (!isListed) continue;\n\n // Start adding data to PoolAsset\n PoolAsset memory asset;\n ICErc20 cToken = cTokens[i];\n asset.cToken = address(cToken);\n\n cToken.accrueInterest();\n\n // Get underlying asset data\n asset.underlyingToken = ICErc20(address(cToken)).underlying();\n ERC20Upgradeable underlying = ERC20Upgradeable(asset.underlyingToken);\n (asset.underlyingName, asset.underlyingSymbol) = getTokenNameAndSymbol(asset.underlyingToken);\n asset.underlyingDecimals = underlying.decimals();\n asset.underlyingBalance = underlying.balanceOf(user);\n\n // Get cToken data\n asset.supplyRatePerBlock = cToken.supplyRatePerBlock();\n asset.borrowRatePerBlock = cToken.borrowRatePerBlock();\n asset.liquidity = cToken.getCash();\n asset.totalBorrow = cToken.totalBorrowsCurrent();\n asset.totalSupply =\n asset.liquidity +\n asset.totalBorrow -\n (cToken.totalReserves() + cToken.totalAdminFees() + cToken.totalIonicFees());\n asset.supplyBalance = cToken.balanceOfUnderlying(user);\n asset.borrowBalance = cToken.borrowBalanceCurrent(user);\n asset.membership = comptroller.checkMembership(user, cToken);\n asset.exchangeRate = cToken.exchangeRateCurrent(); // We would use exchangeRateCurrent but we already accrue interest above\n asset.underlyingPrice = oracle.price(asset.underlyingToken);\n\n // Get oracle for this cToken\n asset.oracle = address(oracle);\n\n try MasterPriceOracle(asset.oracle).oracles(asset.underlyingToken) returns (BasePriceOracle _oracle) {\n asset.oracle = address(_oracle);\n } catch {}\n\n // More cToken data\n asset.collateralFactor = collateralFactorMantissa;\n asset.reserveFactor = cToken.reserveFactorMantissa();\n asset.adminFee = cToken.adminFeeMantissa();\n asset.ionicFee = cToken.ionicFeeMantissa();\n asset.borrowGuardianPaused = comptroller.borrowGuardianPaused(address(cToken));\n asset.mintGuardianPaused = comptroller.mintGuardianPaused(address(cToken));\n\n // Add to assets array and increment index\n detailedAssets[index] = asset;\n index++;\n }\n\n return (detailedAssets);\n }\n\n function getBorrowCapsPerCollateral(\n ICErc20 borrowedAsset,\n IonicComptroller comptroller\n )\n internal\n view\n returns (\n address[] memory collateral,\n uint256[] memory borrowCapsAgainstCollateral,\n bool[] memory borrowingBlacklistedAgainstCollateral\n )\n {\n ICErc20[] memory poolMarkets = comptroller.getAllMarkets();\n\n collateral = new address[](poolMarkets.length);\n borrowCapsAgainstCollateral = new uint256[](poolMarkets.length);\n borrowingBlacklistedAgainstCollateral = new bool[](poolMarkets.length);\n\n for (uint256 i = 0; i < poolMarkets.length; i++) {\n address collateralAddress = address(poolMarkets[i]);\n if (collateralAddress != address(borrowedAsset)) {\n collateral[i] = collateralAddress;\n borrowCapsAgainstCollateral[i] = comptroller.borrowCapForCollateral(address(borrowedAsset), collateralAddress);\n borrowingBlacklistedAgainstCollateral[i] = comptroller.borrowingAgainstCollateralBlacklist(\n address(borrowedAsset),\n collateralAddress\n );\n }\n }\n }\n\n /**\n * @notice Returns the `name` and `symbol` of `token`.\n * Supports Uniswap V2 and SushiSwap LP tokens as well as MKR.\n * @param token An ERC20 token contract object.\n * @return The `name` and `symbol`.\n */\n function getTokenNameAndSymbol(address token) internal view returns (string memory, string memory) {\n // i.e. MKR is a DSToken and uses bytes32\n if (bytes(hardcoded[token].symbol).length != 0) {\n return (hardcoded[token].name, hardcoded[token].symbol);\n }\n\n // Get name and symbol from token contract\n ERC20Upgradeable tokenContract = ERC20Upgradeable(token);\n string memory _name = tokenContract.name();\n string memory _symbol = tokenContract.symbol();\n\n return (_name, _symbol);\n }\n\n /**\n * @notice Returns the assets of the specified Ionic pool.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state.\n * @param comptroller The Comptroller proxy contract of the Ionic pool.\n * @return An array of Ionic pool assets.\n */\n function getPoolAssetsWithData(IonicComptroller comptroller) external returns (PoolAsset[] memory) {\n return getPoolAssetsWithData(comptroller, comptroller.getAllMarkets(), msg.sender);\n }\n\n /**\n * @dev Struct for a Ionic pool user.\n */\n struct IonicPoolUser {\n address account;\n uint256 totalBorrow;\n uint256 totalCollateral;\n uint256 health;\n }\n\n /**\n * @notice Returns arrays of PoolAsset for a specific user\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getPoolAssetsByUser(IonicComptroller comptroller, address user) public returns (PoolAsset[] memory) {\n PoolAsset[] memory assets = getPoolAssetsWithData(comptroller, comptroller.getAssetsIn(user), user);\n return assets;\n }\n\n /**\n * @notice returns the total supply cap for each asset in the pool\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getSupplyCapsForPool(IonicComptroller comptroller) public view returns (address[] memory, uint256[] memory) {\n ICErc20[] memory poolMarkets = comptroller.getAllMarkets();\n\n address[] memory assets = new address[](poolMarkets.length);\n uint256[] memory supplyCapsPerAsset = new uint256[](poolMarkets.length);\n for (uint256 i = 0; i < poolMarkets.length; i++) {\n assets[i] = address(poolMarkets[i]);\n supplyCapsPerAsset[i] = comptroller.effectiveSupplyCaps(assets[i]);\n }\n\n return (assets, supplyCapsPerAsset);\n }\n\n /**\n * @notice returns the total supply cap for each asset in the pool and the total non-whitelist supplied assets\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getSupplyCapsDataForPool(\n IonicComptroller comptroller\n ) public view returns (address[] memory, uint256[] memory, uint256[] memory) {\n ICErc20[] memory poolMarkets = comptroller.getAllMarkets();\n\n address[] memory assets = new address[](poolMarkets.length);\n uint256[] memory supplyCapsPerAsset = new uint256[](poolMarkets.length);\n uint256[] memory nonWhitelistedTotalSupply = new uint256[](poolMarkets.length);\n for (uint256 i = 0; i < poolMarkets.length; i++) {\n assets[i] = address(poolMarkets[i]);\n supplyCapsPerAsset[i] = comptroller.effectiveSupplyCaps(assets[i]);\n uint256 assetTotalSupplied = poolMarkets[i].getTotalUnderlyingSupplied();\n uint256 whitelistedSuppliersSupply = comptroller.getWhitelistedSuppliersSupply(assets[i]);\n if (whitelistedSuppliersSupply >= assetTotalSupplied) nonWhitelistedTotalSupply[i] = 0;\n else nonWhitelistedTotalSupply[i] = assetTotalSupplied - whitelistedSuppliersSupply;\n }\n\n return (assets, supplyCapsPerAsset, nonWhitelistedTotalSupply);\n }\n\n /**\n * @notice returns the total borrow cap and the per collateral borrowing cap/blacklist for the asset\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getBorrowCapsForAsset(\n ICErc20 asset\n )\n public\n view\n returns (\n address[] memory collateral,\n uint256[] memory borrowCapsPerCollateral,\n bool[] memory collateralBlacklisted,\n uint256 totalBorrowCap\n )\n {\n IonicComptroller comptroller = IonicComptroller(asset.comptroller());\n (collateral, borrowCapsPerCollateral, collateralBlacklisted) = getBorrowCapsPerCollateral(asset, comptroller);\n totalBorrowCap = comptroller.effectiveBorrowCaps(address(asset));\n }\n\n /**\n * @notice returns the total borrow cap, the per collateral borrowing cap/blacklist for the asset and the total non-whitelist borrows\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getBorrowCapsDataForAsset(\n ICErc20 asset\n )\n public\n view\n returns (\n address[] memory collateral,\n uint256[] memory borrowCapsPerCollateral,\n bool[] memory collateralBlacklisted,\n uint256 totalBorrowCap,\n uint256 nonWhitelistedTotalBorrows\n )\n {\n IonicComptroller comptroller = IonicComptroller(asset.comptroller());\n (collateral, borrowCapsPerCollateral, collateralBlacklisted) = getBorrowCapsPerCollateral(asset, comptroller);\n totalBorrowCap = comptroller.effectiveBorrowCaps(address(asset));\n uint256 totalBorrows = asset.totalBorrowsCurrent();\n uint256 whitelistedBorrowersBorrows = comptroller.getWhitelistedBorrowersBorrows(address(asset));\n if (whitelistedBorrowersBorrows >= totalBorrows) nonWhitelistedTotalBorrows = 0;\n else nonWhitelistedTotalBorrows = totalBorrows - whitelistedBorrowersBorrows;\n }\n\n /**\n * @notice Returns arrays of Ionic pool indexes and data with a whitelist containing `account`.\n * Note that the whitelist does not have to be enforced.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getWhitelistedPoolsByAccount(\n address account\n ) public view returns (uint256[] memory, PoolDirectory.Pool[] memory) {\n (, PoolDirectory.Pool[] memory pools) = directory.getActivePools();\n uint256 arrayLength = 0;\n\n for (uint256 i = 0; i < pools.length; i++) {\n IonicComptroller comptroller = IonicComptroller(pools[i].comptroller);\n\n if (comptroller.whitelist(account)) arrayLength++;\n }\n\n uint256[] memory indexes = new uint256[](arrayLength);\n PoolDirectory.Pool[] memory accountPools = new PoolDirectory.Pool[](arrayLength);\n uint256 index = 0;\n\n for (uint256 i = 0; i < pools.length; i++) {\n IonicComptroller comptroller = IonicComptroller(pools[i].comptroller);\n\n if (comptroller.whitelist(account)) {\n indexes[index] = i;\n accountPools[index] = pools[i];\n index++;\n break;\n }\n }\n\n return (indexes, accountPools);\n }\n\n /**\n * @notice Returns arrays of the indexes of Ionic pools with a whitelist containing `account`, data, total supply balances (in ETH), total borrow balances (in ETH), arrays of underlying token addresses, arrays of underlying asset symbols, and booleans indicating if retrieving each pool's data failed.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state.\n */\n function getWhitelistedPoolsByAccountWithData(\n address account\n ) external returns (uint256[] memory, PoolDirectory.Pool[] memory, IonicPoolData[] memory, bool[] memory) {\n (uint256[] memory indexes, PoolDirectory.Pool[] memory accountPools) = getWhitelistedPoolsByAccount(account);\n (IonicPoolData[] memory data, bool[] memory errored) = getPoolsData(accountPools);\n return (indexes, accountPools, data, errored);\n }\n\n function getHealthFactor(address user, IonicComptroller pool) external view returns (uint256) {\n return getHealthFactorHypothetical(pool, user, address(0), 0, 0, 0);\n }\n\n function getHealthFactorHypothetical(\n IonicComptroller pool,\n address account,\n address cTokenModify,\n uint256 redeemTokens,\n uint256 borrowAmount,\n uint256 repayAmount\n ) public view returns (uint256) {\n (uint256 err, uint256 collateralValue, uint256 liquidity, uint256 shortfall) = pool.getHypotheticalAccountLiquidity(\n account,\n cTokenModify,\n redeemTokens,\n borrowAmount,\n repayAmount\n );\n\n if (err != 0) revert ComptrollerError(err);\n\n if (shortfall > 0) {\n // HF < 1.0\n return (collateralValue * 1e18) / (collateralValue + shortfall);\n } else {\n // HF >= 1.0\n if (collateralValue <= liquidity) return type(uint256).max;\n else return (collateralValue * 1e18) / (collateralValue - liquidity);\n }\n }\n}\n" + }, + "contracts/src/PoolLensSecondary.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nimport \"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/ERC20Upgradeable.sol\";\n\nimport { IonicComptroller } from \"./compound/ComptrollerInterface.sol\";\nimport { ICErc20 } from \"./compound/CTokenInterfaces.sol\";\nimport { IUniswapV2Pair } from \"./external/uniswap/IUniswapV2Pair.sol\";\n\nimport { PoolDirectory } from \"./PoolDirectory.sol\";\n\ninterface IRewardsDistributor_PLS {\n function rewardToken() external view returns (address);\n\n function compSupplySpeeds(address) external view returns (uint256);\n\n function compBorrowSpeeds(address) external view returns (uint256);\n\n function compAccrued(address) external view returns (uint256);\n\n function flywheelPreSupplierAction(address cToken, address supplier) external;\n\n function flywheelPreBorrowerAction(address cToken, address borrower) external;\n\n function getAllMarkets() external view returns (ICErc20[] memory);\n}\n\n/**\n * @title PoolLensSecondary\n * @author David Lucid (https://github.com/davidlucid)\n * @notice PoolLensSecondary returns data on Ionic interest rate pools in mass for viewing by dApps, bots, etc.\n */\ncontract PoolLensSecondary is Initializable {\n /**\n * @notice Constructor to set the `PoolDirectory` contract object.\n */\n function initialize(PoolDirectory _directory) public initializer {\n require(address(_directory) != address(0), \"PoolDirectory instance cannot be the zero address.\");\n directory = _directory;\n }\n\n /**\n * @notice `PoolDirectory` contract object.\n */\n PoolDirectory public directory;\n\n /**\n * @notice Struct for ownership over a CToken.\n */\n struct CTokenOwnership {\n address cToken;\n address admin;\n bool adminHasRights;\n bool ionicAdminHasRights;\n }\n\n /**\n * @notice Returns the admin, admin rights, Ionic admin (constant), Ionic admin rights, and an array of cTokens with differing properties.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n * Ideally, we can add the `view` modifier, but many cToken functions potentially modify the state.\n */\n function getPoolOwnership(\n IonicComptroller comptroller\n ) external view returns (address, bool, bool, CTokenOwnership[] memory) {\n // Get pool ownership\n address comptrollerAdmin = comptroller.admin();\n bool comptrollerAdminHasRights = comptroller.adminHasRights();\n bool comptrollerIonicAdminHasRights = comptroller.ionicAdminHasRights();\n\n // Get cToken ownership\n ICErc20[] memory cTokens = comptroller.getAllMarkets();\n uint256 arrayLength = 0;\n\n for (uint256 i = 0; i < cTokens.length; i++) {\n ICErc20 cToken = cTokens[i];\n (bool isListed, ) = comptroller.markets(address(cToken));\n if (!isListed) continue;\n\n address cTokenAdmin;\n try cToken.admin() returns (address _cTokenAdmin) {\n cTokenAdmin = _cTokenAdmin;\n } catch {\n continue;\n }\n bool cTokenAdminHasRights = cToken.adminHasRights();\n bool cTokenIonicAdminHasRights = cToken.ionicAdminHasRights();\n\n // If outlier, push to array\n if (\n cTokenAdmin != comptrollerAdmin ||\n cTokenAdminHasRights != comptrollerAdminHasRights ||\n cTokenIonicAdminHasRights != comptrollerIonicAdminHasRights\n ) arrayLength++;\n }\n\n CTokenOwnership[] memory outliers = new CTokenOwnership[](arrayLength);\n uint256 arrayIndex = 0;\n\n for (uint256 i = 0; i < cTokens.length; i++) {\n ICErc20 cToken = cTokens[i];\n (bool isListed, ) = comptroller.markets(address(cToken));\n if (!isListed) continue;\n\n address cTokenAdmin;\n try cToken.admin() returns (address _cTokenAdmin) {\n cTokenAdmin = _cTokenAdmin;\n } catch {\n continue;\n }\n bool cTokenAdminHasRights = cToken.adminHasRights();\n bool cTokenIonicAdminHasRights = cToken.ionicAdminHasRights();\n\n // If outlier, push to array and increment array index\n if (\n cTokenAdmin != comptrollerAdmin ||\n cTokenAdminHasRights != comptrollerAdminHasRights ||\n cTokenIonicAdminHasRights != comptrollerIonicAdminHasRights\n ) {\n outliers[arrayIndex] = CTokenOwnership(\n address(cToken),\n cTokenAdmin,\n cTokenAdminHasRights,\n cTokenIonicAdminHasRights\n );\n arrayIndex++;\n }\n }\n\n return (comptrollerAdmin, comptrollerAdminHasRights, comptrollerIonicAdminHasRights, outliers);\n }\n\n /**\n * @notice Determine the maximum redeem amount of a cToken.\n * @param cTokenModify The market to hypothetically redeem in.\n * @param account The account to determine liquidity for.\n * @return Maximum redeem amount.\n */\n function getMaxRedeem(address account, ICErc20 cTokenModify) external returns (uint256) {\n return getMaxRedeemOrBorrow(account, cTokenModify, false);\n }\n\n /**\n * @notice Determine the maximum borrow amount of a cToken.\n * @param cTokenModify The market to hypothetically borrow in.\n * @param account The account to determine liquidity for.\n * @return Maximum borrow amount.\n */\n function getMaxBorrow(address account, ICErc20 cTokenModify) external returns (uint256) {\n return getMaxRedeemOrBorrow(account, cTokenModify, true);\n }\n\n /**\n * @dev Internal function to determine the maximum borrow/redeem amount of a cToken.\n * @param cTokenModify The market to hypothetically borrow/redeem in.\n * @param account The account to determine liquidity for.\n * @return Maximum borrow/redeem amount.\n */\n function getMaxRedeemOrBorrow(address account, ICErc20 cTokenModify, bool isBorrow) internal returns (uint256) {\n IonicComptroller comptroller = IonicComptroller(cTokenModify.comptroller());\n return comptroller.getMaxRedeemOrBorrow(account, cTokenModify, isBorrow);\n }\n\n /**\n * @notice Returns an array of all markets, an array of all `RewardsDistributor` contracts, an array of reward token addresses for each `RewardsDistributor`, an array of supply speeds for each distributor for each, and their borrow speeds.\n * @param comptroller The Ionic pool Comptroller to check.\n */\n function getRewardSpeedsByPool(\n IonicComptroller comptroller\n ) public view returns (ICErc20[] memory, address[] memory, address[] memory, uint256[][] memory, uint256[][] memory) {\n ICErc20[] memory allMarkets = comptroller.getAllMarkets();\n address[] memory distributors;\n\n try comptroller.getRewardsDistributors() returns (address[] memory _distributors) {\n distributors = _distributors;\n } catch {\n distributors = new address[](0);\n }\n\n address[] memory rewardTokens = new address[](distributors.length);\n uint256[][] memory supplySpeeds = new uint256[][](allMarkets.length);\n uint256[][] memory borrowSpeeds = new uint256[][](allMarkets.length);\n\n // Get reward tokens for each distributor\n for (uint256 i = 0; i < distributors.length; i++) {\n rewardTokens[i] = IRewardsDistributor_PLS(distributors[i]).rewardToken();\n }\n\n // Get reward speeds for each market for each distributor\n for (uint256 i = 0; i < allMarkets.length; i++) {\n address cToken = address(allMarkets[i]);\n supplySpeeds[i] = new uint256[](distributors.length);\n borrowSpeeds[i] = new uint256[](distributors.length);\n\n for (uint256 j = 0; j < distributors.length; j++) {\n IRewardsDistributor_PLS distributor = IRewardsDistributor_PLS(distributors[j]);\n supplySpeeds[i][j] = distributor.compSupplySpeeds(cToken);\n borrowSpeeds[i][j] = distributor.compBorrowSpeeds(cToken);\n }\n }\n\n return (allMarkets, distributors, rewardTokens, supplySpeeds, borrowSpeeds);\n }\n\n /**\n * @notice For each `Comptroller`, returns an array of all markets, an array of all `RewardsDistributor` contracts, an array of reward token addresses for each `RewardsDistributor`, an array of supply speeds for each distributor for each, and their borrow speeds.\n * @param comptrollers The Ionic pool Comptrollers to check.\n */\n function getRewardSpeedsByPools(\n IonicComptroller[] memory comptrollers\n )\n external\n view\n returns (ICErc20[][] memory, address[][] memory, address[][] memory, uint256[][][] memory, uint256[][][] memory)\n {\n ICErc20[][] memory allMarkets = new ICErc20[][](comptrollers.length);\n address[][] memory distributors = new address[][](comptrollers.length);\n address[][] memory rewardTokens = new address[][](comptrollers.length);\n uint256[][][] memory supplySpeeds = new uint256[][][](comptrollers.length);\n uint256[][][] memory borrowSpeeds = new uint256[][][](comptrollers.length);\n for (uint256 i = 0; i < comptrollers.length; i++)\n (allMarkets[i], distributors[i], rewardTokens[i], supplySpeeds[i], borrowSpeeds[i]) = getRewardSpeedsByPool(\n comptrollers[i]\n );\n return (allMarkets, distributors, rewardTokens, supplySpeeds, borrowSpeeds);\n }\n\n /**\n * @notice Returns unaccrued rewards by `holder` from `cToken` on `distributor`.\n * @param holder The address to check.\n * @param distributor The RewardsDistributor to check.\n * @param cToken The CToken to check.\n * @return Unaccrued (unclaimed) supply-side rewards and unaccrued (unclaimed) borrow-side rewards.\n */\n function getUnaccruedRewards(\n address holder,\n IRewardsDistributor_PLS distributor,\n ICErc20 cToken\n ) internal returns (uint256, uint256) {\n // Get unaccrued supply rewards\n uint256 compAccruedPrior = distributor.compAccrued(holder);\n distributor.flywheelPreSupplierAction(address(cToken), holder);\n uint256 supplyRewardsUnaccrued = distributor.compAccrued(holder) - compAccruedPrior;\n\n // Get unaccrued borrow rewards\n compAccruedPrior = distributor.compAccrued(holder);\n distributor.flywheelPreBorrowerAction(address(cToken), holder);\n uint256 borrowRewardsUnaccrued = distributor.compAccrued(holder) - compAccruedPrior;\n\n // Return both\n return (supplyRewardsUnaccrued, borrowRewardsUnaccrued);\n }\n\n /**\n * @notice Returns all unclaimed rewards accrued by the `holder` on `distributors`.\n * @param holder The address to check.\n * @param distributors The `RewardsDistributor` contracts to check.\n * @return For each of `distributors`: total quantity of unclaimed rewards, array of cTokens, array of unaccrued (unclaimed) supply-side and borrow-side rewards per cToken, and quantity of funds available in the distributor.\n */\n function getUnclaimedRewardsByDistributors(\n address holder,\n IRewardsDistributor_PLS[] memory distributors\n ) external returns (address[] memory, uint256[] memory, ICErc20[][] memory, uint256[2][][] memory, uint256[] memory) {\n address[] memory rewardTokens = new address[](distributors.length);\n uint256[] memory compUnclaimedTotal = new uint256[](distributors.length);\n ICErc20[][] memory allMarkets = new ICErc20[][](distributors.length);\n uint256[2][][] memory rewardsUnaccrued = new uint256[2][][](distributors.length);\n uint256[] memory distributorFunds = new uint256[](distributors.length);\n\n for (uint256 i = 0; i < distributors.length; i++) {\n IRewardsDistributor_PLS distributor = distributors[i];\n rewardTokens[i] = distributor.rewardToken();\n allMarkets[i] = distributor.getAllMarkets();\n rewardsUnaccrued[i] = new uint256[2][](allMarkets[i].length);\n for (uint256 j = 0; j < allMarkets[i].length; j++)\n (rewardsUnaccrued[i][j][0], rewardsUnaccrued[i][j][1]) = getUnaccruedRewards(\n holder,\n distributor,\n allMarkets[i][j]\n );\n compUnclaimedTotal[i] = distributor.compAccrued(holder);\n distributorFunds[i] = IERC20Upgradeable(rewardTokens[i]).balanceOf(address(distributor));\n }\n\n return (rewardTokens, compUnclaimedTotal, allMarkets, rewardsUnaccrued, distributorFunds);\n }\n\n /**\n * @notice Returns arrays of indexes, `Comptroller` proxy contracts, and `RewardsDistributor` contracts for Ionic pools supplied to by `account`.\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getRewardsDistributorsBySupplier(\n address supplier\n ) external view returns (uint256[] memory, IonicComptroller[] memory, address[][] memory) {\n // Get array length\n (, PoolDirectory.Pool[] memory pools) = directory.getActivePools();\n uint256 arrayLength = 0;\n\n for (uint256 i = 0; i < pools.length; i++) {\n try IonicComptroller(pools[i].comptroller).suppliers(supplier) returns (bool isSupplier) {\n if (isSupplier) arrayLength++;\n } catch {}\n }\n\n // Build array\n uint256[] memory indexes = new uint256[](arrayLength);\n IonicComptroller[] memory comptrollers = new IonicComptroller[](arrayLength);\n address[][] memory distributors = new address[][](arrayLength);\n uint256 index = 0;\n\n for (uint256 i = 0; i < pools.length; i++) {\n IonicComptroller comptroller = IonicComptroller(pools[i].comptroller);\n\n try comptroller.suppliers(supplier) returns (bool isSupplier) {\n if (isSupplier) {\n indexes[index] = i;\n comptrollers[index] = comptroller;\n\n try comptroller.getRewardsDistributors() returns (address[] memory _distributors) {\n distributors[index] = _distributors;\n } catch {}\n\n index++;\n }\n } catch {}\n }\n\n // Return distributors\n return (indexes, comptrollers, distributors);\n }\n\n /**\n * @notice The returned list of flywheels contains address(0) for flywheels for which the user has no rewards to claim\n * @dev This function is not designed to be called in a transaction: it is too gas-intensive.\n */\n function getFlywheelsToClaim(\n address user\n ) external view returns (uint256[] memory, IonicComptroller[] memory, address[][] memory) {\n (uint256[] memory poolIds, PoolDirectory.Pool[] memory pools) = directory.getActivePools();\n\n IonicComptroller[] memory comptrollers = new IonicComptroller[](pools.length);\n address[][] memory distributors = new address[][](pools.length);\n\n for (uint256 i = 0; i < pools.length; i++) {\n IonicComptroller comptroller = IonicComptroller(pools[i].comptroller);\n try comptroller.getRewardsDistributors() returns (address[] memory _distributors) {\n comptrollers[i] = comptroller;\n distributors[i] = flywheelsWithRewardsForPoolUser(user, _distributors);\n } catch {}\n }\n\n return (poolIds, comptrollers, distributors);\n }\n\n function flywheelsWithRewardsForPoolUser(\n address user,\n address[] memory _distributors\n ) internal view returns (address[] memory) {\n address[] memory distributors = new address[](_distributors.length);\n for (uint256 j = 0; j < _distributors.length; j++) {\n if (IRewardsDistributor_PLS(_distributors[j]).compAccrued(user) > 0) {\n distributors[j] = _distributors[j];\n }\n }\n\n return distributors;\n }\n}\n" + }, + "contracts/src/security/OracleRegistry.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.22;\n\nimport { IHypernativeOracle } from \"../external/hypernative/interfaces/IHypernativeOracle.sol\";\nimport { Ownable2Step } from \"@openzeppelin/contracts/access/Ownable2Step.sol\";\n\ncontract OracleRegistry is Ownable2Step {\n bytes32 private constant HYPERNATIVE_ORACLE_STORAGE_SLOT =\n bytes32(uint256(keccak256(\"eip1967.hypernative.oracle\")) - 1);\n bytes32 private constant HYPERNATIVE_MODE_STORAGE_SLOT =\n bytes32(uint256(keccak256(\"eip1967.hypernative.is_strict_mode\")) - 1);\n\n event OracleAdminChanged(address indexed previousAdmin, address indexed newAdmin);\n event OracleAddressChanged(address indexed previousOracle, address indexed newOracle);\n\n constructor() Ownable2Step() {}\n\n function oracleRegister(address _account) public {\n address oracleAddress = hypernativeOracle();\n bool isStrictMode = hypernativeOracleIsStrictMode();\n IHypernativeOracle oracle = IHypernativeOracle(oracleAddress);\n oracle.register(_account, isStrictMode);\n }\n\n function setOracle(address _oracle) public onlyOwner {\n _setOracle(_oracle);\n }\n\n function setIsStrictMode(bool _mode) public onlyOwner {\n _setIsStrictMode(_mode);\n }\n\n function hypernativeOracleIsStrictMode() public view returns (bool) {\n return _getValueBySlot(HYPERNATIVE_MODE_STORAGE_SLOT) == 1;\n }\n\n function hypernativeOracle() public view returns (address) {\n return _getAddressBySlot(HYPERNATIVE_ORACLE_STORAGE_SLOT);\n }\n\n /**\n * @dev Admin only function, sets new oracle admin. set to address(0) to revoke oracle\n */\n function _setOracle(address _oracle) internal {\n address oldOracle = hypernativeOracle();\n _setAddressBySlot(HYPERNATIVE_ORACLE_STORAGE_SLOT, _oracle);\n emit OracleAddressChanged(oldOracle, _oracle);\n }\n\n function _setIsStrictMode(bool _mode) internal {\n _setValueBySlot(HYPERNATIVE_MODE_STORAGE_SLOT, _mode ? 1 : 0);\n }\n\n function _setAddressBySlot(bytes32 slot, address newAddress) internal {\n assembly {\n sstore(slot, newAddress)\n }\n }\n\n function _setValueBySlot(bytes32 _slot, uint256 _value) internal {\n assembly {\n sstore(_slot, _value)\n }\n }\n\n function _getAddressBySlot(bytes32 slot) internal view returns (address addr) {\n assembly {\n addr := sload(slot)\n }\n }\n\n function _getValueBySlot(bytes32 _slot) internal view returns (uint256 _value) {\n assembly {\n _value := sload(_slot)\n }\n }\n}\n" + }, + "contracts/src/utils/IMulticall.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\n/// @title Multicall interface\n/// @notice Enables calling multiple methods in a single call to the contract\ninterface IMulticall {\n /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed\n /// @dev The `msg.value` should not be trusted for any method callable from multicall.\n /// @param data The encoded function data for each of the calls to make to this contract\n /// @return results The results from each of the calls passed in via data\n function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);\n}\n" + }, + "contracts/src/utils/IW_NATIVE.sol": { + "content": "// SPDX-License-Identifier: agpl-3.0\npragma solidity >=0.8.0;\n\ninterface IW_NATIVE {\n function deposit() external payable;\n\n function withdraw(uint256 amount) external;\n\n function approve(address spender, uint256 amount) external returns (bool);\n\n function transfer(address to, uint256 amount) external returns (bool);\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n\n function balanceOf(address) external view returns (uint256);\n}\n" + }, + "contracts/src/utils/Multicall.sol": { + "content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.8.0;\n\nimport \"./IMulticall.sol\";\n\n/// @title Multicall\n/// @notice Enables calling multiple methods in a single call to the contract\nabstract contract Multicall is IMulticall {\n /// @inheritdoc IMulticall\n function multicall(bytes[] calldata data) public payable virtual override returns (bytes[] memory results) {\n results = new bytes[](data.length);\n for (uint256 i = 0; i < data.length; i++) {\n (bool success, bytes memory result) = address(this).delegatecall(data[i]);\n\n if (!success) {\n // Next 5 lines from https://ethereum.stackexchange.com/a/83577\n if (result.length < 68) revert();\n assembly {\n result := add(result, 0x04)\n }\n revert(abi.decode(result, (string)));\n }\n\n results[i] = result;\n }\n }\n}\n" + }, + "contracts/src/utils/TOUCHToken.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: UNLICENSED\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\n\ncontract TOUCHToken is ERC20 {\n constructor(uint256 initialSupply, address tokenOwner) ERC20(\"Midas TOUCH Token\", \"TOUCH\", 18) {\n _mint(tokenOwner, initialSupply);\n }\n}\n" + }, + "contracts/src/utils/TRIBEToken.sol": { + "content": "pragma solidity ^0.8.0;\n\n// SPDX-License-Identifier: UNLICENSED\n\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\n\ncontract TRIBEToken is ERC20 {\n constructor(uint256 initialSupply, address tokenOwner) ERC20(\"TRIBE Governance Token\", \"TRIBE\", 18) {\n _mint(tokenOwner, initialSupply);\n }\n}\n" + }, + "contracts/src/veION/BribeRewards.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport { Math } from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport { IBribeRewards } from \"./interfaces/IBribeRewards.sol\";\nimport { IVoter } from \"./interfaces/IVoter.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol\";\nimport { IonicTimeLibrary } from \"./libraries/IonicTimeLibrary.sol\";\nimport { ERC721Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol\";\n\n/**\n * @title BribeRewards Contract\n * @notice This contract allows veION to benefit from bribes when voting for various markets\n * @author Jourdan Dunkley (https://github.com/jourdanDunkley)\n */\ncontract BribeRewards is IBribeRewards, ReentrancyGuardUpgradeable, Ownable2StepUpgradeable {\n using SafeERC20 for IERC20;\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ State Variables ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n /// @notice Duration of the reward period in seconds\n uint256 public constant DURATION = 7 days;\n /// @notice Address of the voter contract\n address public voter;\n /// @notice Address of the veION contract\n address public ve;\n /// @notice List of reward tokens\n address[] public rewards;\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Mappings ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n /// @notice Mapping to check if an address is a reward token\n mapping(address => bool) public isReward;\n /// @notice Total supply of LP tokens for each reward token\n mapping(address => uint256) public totalSupply;\n /// @notice Balance of LP tokens for each tokenId and reward token\n mapping(uint256 => mapping(address => uint256)) public balanceOf;\n /// @notice Rewards per epoch for each reward token\n mapping(address => mapping(uint256 => uint256)) public tokenRewardsPerEpoch;\n /// @notice Last earned timestamp for each reward token and tokenId\n mapping(address => mapping(uint256 => uint256)) public lastEarn;\n /// @notice A record of balance checkpoints for each account, by index\n mapping(uint256 => mapping(address => mapping(uint256 => Checkpoint))) public checkpoints;\n /// @notice The number of checkpoints for each account\n mapping(uint256 => mapping(address => uint256)) public numCheckpoints;\n /// @notice A record of balance checkpoints for each token, by index\n mapping(uint256 => mapping(address => SupplyCheckpoint)) public supplyCheckpoints;\n /// @notice The number of supply checkpoints for each token\n mapping(address => uint256) public supplyNumCheckpoints;\n /// @notice Historical prices for each reward token and epoch\n mapping(address => mapping(uint256 => uint256)) public historicalPrices;\n\n /**\n * @notice Modifier to restrict access to only the voter contract\n * @dev Ensures that the caller is the voter contract\n */\n modifier onlyVoter() {\n require(msg.sender == voter, \"Caller is not the voter\");\n _;\n }\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n /**\n * @notice Initializes the BribeRewards contract with the voter and veION addresses\n * @dev This function is called only once during contract deployment\n * @param _voter The address of the voter contract\n * @param _ve The address of the veION contract\n */\n function initialize(address _voter, address _ve) public initializer {\n __ReentrancyGuard_init();\n __Ownable2Step_init();\n voter = _voter;\n ve = _ve;\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ External Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IBribeRewards\n function deposit(address lpToken, uint256 amount, uint256 tokenId) external onlyVoter {\n address sender = msg.sender;\n\n totalSupply[lpToken] += amount;\n balanceOf[tokenId][lpToken] += amount;\n\n _writeCheckpoint(tokenId, lpToken, balanceOf[tokenId][lpToken]);\n _writeSupplyCheckpoint(lpToken);\n\n emit Deposit(sender, tokenId, amount);\n }\n\n /// @inheritdoc IBribeRewards\n function withdraw(address lpToken, uint256 amount, uint256 tokenId) external onlyVoter {\n address sender = msg.sender;\n\n totalSupply[lpToken] -= amount;\n balanceOf[tokenId][lpToken] -= amount;\n\n _writeCheckpoint(tokenId, lpToken, balanceOf[tokenId][lpToken]);\n _writeSupplyCheckpoint(lpToken);\n\n emit Withdraw(sender, tokenId, amount);\n }\n\n /**\n * @inheritdoc IBribeRewards\n * @notice This function can accept any token, regardless of its whitelisting status.\n * @dev If we were to check the whitelisting status, it could prevent tokens that were initially whitelisted and later de-whitelisted from having their rewards claimed, leading to unclaimable rewards.\n */\n function getReward(uint256 tokenId, address[] memory tokens) external nonReentrant onlyVoter {\n address sender = msg.sender;\n if (ERC721Upgradeable(ve).ownerOf(tokenId) != sender && sender != voter) revert Unauthorized();\n\n address _owner = ERC721Upgradeable(ve).ownerOf(tokenId);\n _getReward(_owner, tokenId, tokens);\n }\n\n /// @inheritdoc IBribeRewards\n function notifyRewardAmount(address token, uint256 amount) external override nonReentrant {\n address sender = msg.sender;\n\n if (!isReward[token]) {\n if (!IVoter(voter).isWhitelistedToken(token)) revert TokenNotWhitelisted();\n isReward[token] = true;\n rewards.push(token);\n }\n\n _notifyRewardAmount(sender, token, amount);\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Internal Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @dev used with all getReward implementations\n function _getReward(address recipient, uint256 tokenId, address[] memory tokens) internal {\n // check if token whitelisted\n uint256 _length = tokens.length;\n for (uint256 i = 0; i < _length; i++) {\n uint256 _reward = earned(tokens[i], tokenId);\n lastEarn[tokens[i]][tokenId] = block.timestamp;\n if (_reward > 0) IERC20(tokens[i]).safeTransfer(recipient, _reward);\n\n emit RewardsClaimed(recipient, tokens[i], _reward);\n }\n }\n\n /**\n * @notice Writes a new checkpoint for a token's balance\n * @param tokenId The ID of the veION token\n * @param lpToken The LP token address\n * @param balance The balance to record\n */\n function _writeCheckpoint(uint256 tokenId, address lpToken, uint256 balance) internal {\n uint256 _nCheckPoints = numCheckpoints[tokenId][lpToken];\n uint256 _timestamp = block.timestamp;\n\n if (\n _nCheckPoints > 0 &&\n IonicTimeLibrary.epochStart(checkpoints[tokenId][lpToken][_nCheckPoints - 1].timestamp) ==\n IonicTimeLibrary.epochStart(_timestamp)\n ) {\n checkpoints[tokenId][lpToken][_nCheckPoints - 1] = Checkpoint(_timestamp, balance);\n } else {\n checkpoints[tokenId][lpToken][_nCheckPoints] = Checkpoint(_timestamp, balance);\n numCheckpoints[tokenId][lpToken] = _nCheckPoints + 1;\n }\n }\n\n /// @notice Writes a new checkpoint for total supply\n /// @param lpToken The LP token address\n function _writeSupplyCheckpoint(address lpToken) internal {\n uint256 _nCheckPoints = supplyNumCheckpoints[lpToken];\n uint256 _timestamp = block.timestamp;\n\n if (\n _nCheckPoints > 0 &&\n IonicTimeLibrary.epochStart(supplyCheckpoints[_nCheckPoints - 1][lpToken].timestamp) ==\n IonicTimeLibrary.epochStart(_timestamp)\n ) {\n supplyCheckpoints[_nCheckPoints - 1][lpToken] = SupplyCheckpoint(_timestamp, totalSupply[lpToken]);\n } else {\n supplyCheckpoints[_nCheckPoints][lpToken] = SupplyCheckpoint(_timestamp, totalSupply[lpToken]);\n supplyNumCheckpoints[lpToken] = _nCheckPoints + 1;\n }\n }\n\n /// @dev used within all notifyRewardAmount implementations\n function _notifyRewardAmount(address sender, address token, uint256 amount) internal {\n if (amount == 0) revert AmountCannotBeZero();\n IERC20(token).safeTransferFrom(sender, address(this), amount);\n\n uint256 epochStart = IonicTimeLibrary.epochStart(block.timestamp);\n tokenRewardsPerEpoch[token][epochStart] += amount;\n\n emit RewardNotification(sender, token, epochStart, amount);\n }\n\n /**\n * @notice Calculates the ETH value of a token amount at a specific epoch\n * @param amount The amount of tokens\n * @param lpToken The LP token address\n * @param epochTimestamp The timestamp of the epoch\n * @return The ETH value of the tokens\n */\n function _getTokenEthValueAt(\n uint256 amount,\n address lpToken,\n uint256 epochTimestamp\n ) internal view returns (uint256) {\n uint256 epochStart = IonicTimeLibrary.epochStart(epochTimestamp);\n if (historicalPrices[lpToken][epochStart] == 0) revert HistoricalPriceNotSet(lpToken, epochStart);\n uint256 _priceAtTimestamp = historicalPrices[lpToken][epochStart];\n uint256 ethValue = (amount * _priceAtTimestamp) / 1e18;\n return ethValue;\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Pure/View Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @notice Returns the total number of reward tokens\n /// @return The length of the rewards array\n function rewardsListLength() external view returns (uint256) {\n return rewards.length;\n }\n\n /// @inheritdoc IBribeRewards\n function earned(address token, uint256 tokenId) public view returns (uint256) {\n EarnedVars memory vars;\n vars.totalReward = 0;\n address[] memory lpTokens = getAllLpRewardTokens();\n uint256 lpTokensLength = lpTokens.length;\n for (uint256 j = 0; j < lpTokensLength; j++) {\n address lpToken = lpTokens[j];\n\n if (numCheckpoints[tokenId][lpToken] == 0) {\n continue;\n }\n\n vars.currTs = IonicTimeLibrary.epochStart(lastEarn[token][tokenId]);\n vars.index = getPriorBalanceIndex(tokenId, lpToken, vars.currTs);\n Checkpoint memory cp0 = checkpoints[tokenId][lpToken][vars.index];\n\n vars.currTs = Math.max(vars.currTs, IonicTimeLibrary.epochStart(cp0.timestamp));\n vars.numEpochs = (IonicTimeLibrary.epochStart(block.timestamp) - vars.currTs) / DURATION;\n\n if (vars.numEpochs > 0) {\n for (uint256 i = 0; i < vars.numEpochs; i++) {\n vars.index = getPriorBalanceIndex(tokenId, lpToken, vars.currTs + DURATION - 1);\n cp0 = checkpoints[tokenId][lpToken][vars.index];\n vars.epochBalanceValue = _getTokenEthValueAt(cp0.balanceOf, lpToken, vars.currTs);\n\n vars.supplyValue = 0;\n for (uint256 k = 0; k < lpTokensLength; k++) {\n address currentLpToken = lpTokens[k];\n uint256 supplyAmount = Math.max(\n supplyCheckpoints[getPriorSupplyIndex(vars.currTs + DURATION - 1, currentLpToken)][currentLpToken].supply,\n 1\n );\n vars.supplyValue += _getTokenEthValueAt(supplyAmount, currentLpToken, vars.currTs);\n }\n if (vars.supplyValue > 0) {\n vars.totalReward += (vars.epochBalanceValue * tokenRewardsPerEpoch[token][vars.currTs]) / vars.supplyValue;\n }\n vars.currTs += DURATION;\n }\n }\n }\n\n return vars.totalReward;\n }\n\n /// @notice Gets all LP tokens that can receive rewards\n /// @return Array of LP token addresses\n function getAllLpRewardTokens() public view returns (address[] memory) {\n return IVoter(voter).getAllLpRewardTokens();\n }\n\n /**\n * @notice Sets historical prices for LP tokens at specific epochs\n * @param epochTimestamp The timestamp of the epoch\n * @param lpToken The LP token address\n * @param price The price to set\n */\n function setHistoricalPrices(uint256 epochTimestamp, address lpToken, uint256 price) external onlyOwner {\n uint256 epochStart = IonicTimeLibrary.epochStart(epochTimestamp);\n historicalPrices[lpToken][epochStart] = price;\n emit HistoricalPriceSet(epochTimestamp, lpToken, price);\n }\n\n /**\n * @notice Gets a specific checkpoint for a token\n * @param tokenId The ID of the veION token\n * @param lpToken The LP token address\n * @param index The index of the checkpoint to retrieve\n * @return The checkpoint data\n */\n function getCheckpoint(uint256 tokenId, address lpToken, uint256 index) external view returns (Checkpoint memory) {\n return checkpoints[tokenId][lpToken][index];\n }\n\n /// @inheritdoc IBribeRewards\n function getPriorBalanceIndex(uint256 tokenId, address lpToken, uint256 timestamp) public view returns (uint256) {\n uint256 nCheckpoints = numCheckpoints[tokenId][lpToken];\n if (nCheckpoints == 0) {\n return 0;\n }\n\n // First check most recent balance\n if (checkpoints[tokenId][lpToken][nCheckpoints - 1].timestamp <= timestamp) {\n return (nCheckpoints - 1);\n }\n\n // Next check implicit zero balance\n if (checkpoints[tokenId][lpToken][0].timestamp > timestamp) {\n return 0;\n }\n\n uint256 lower = 0;\n uint256 upper = nCheckpoints - 1;\n while (upper > lower) {\n uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\n Checkpoint memory cp = checkpoints[tokenId][lpToken][center];\n if (cp.timestamp == timestamp) {\n return center;\n } else if (cp.timestamp < timestamp) {\n lower = center;\n } else {\n upper = center - 1;\n }\n }\n return lower;\n }\n\n /// @inheritdoc IBribeRewards\n function getPriorSupplyIndex(uint256 timestamp, address lpToken) public view returns (uint256) {\n uint256 nCheckpoints = supplyNumCheckpoints[lpToken];\n if (nCheckpoints == 0) {\n return 0;\n }\n\n // First check most recent balance\n if (supplyCheckpoints[nCheckpoints - 1][lpToken].timestamp <= timestamp) {\n return (nCheckpoints - 1);\n }\n\n // Next check implicit zero balance\n if (supplyCheckpoints[0][lpToken].timestamp > timestamp) {\n return 0;\n }\n\n uint256 lower = 0;\n uint256 upper = nCheckpoints - 1;\n while (upper > lower) {\n uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\n SupplyCheckpoint memory cp = supplyCheckpoints[center][lpToken];\n if (cp.timestamp == timestamp) {\n return center;\n } else if (cp.timestamp < timestamp) {\n lower = center;\n } else {\n upper = center - 1;\n }\n }\n return lower;\n }\n}\n" + }, + "contracts/src/veION/interfaces/IBribeRewards.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\ninterface IBribeRewards {\n /// @notice A checkpoint for marking balance\n struct Checkpoint {\n uint256 timestamp;\n uint256 balanceOf;\n }\n\n /// @notice A checkpoint for marking supply\n struct SupplyCheckpoint {\n uint256 timestamp;\n uint256 supply;\n }\n\n struct EarnedVars {\n uint256 totalReward;\n uint256 reward;\n uint256 supplyValue;\n uint256 epochBalanceValue;\n uint256 currTs;\n uint256 index;\n uint256 numEpochs;\n uint256 overallBalance;\n uint256 overallSupply;\n uint256 historicalPrice;\n }\n\n error InvalidReward();\n error Unauthorized();\n error InvalidGauge();\n error InvalidEscrowToken();\n error SingleTokenExpected();\n error InvalidVotingEscrow();\n error TokenNotWhitelisted();\n error AmountCannotBeZero();\n error HistoricalPriceNotSet(address lpToken, uint256 epochStart);\n\n event Deposit(address indexed user, uint256 indexed tokenId, uint256 amount);\n event Withdraw(address indexed user, uint256 indexed tokenId, uint256 amount);\n event RewardNotification(address indexed user, address indexed rewardToken, uint256 indexed epoch, uint256 amount);\n event RewardsClaimed(address indexed user, address indexed rewardToken, uint256 amount);\n event HistoricalPriceSet(uint256 indexed epochTimestamp, address indexed lpToken, uint256 price);\n\n /// @notice Deposit an amount into the bribe rewards contract for a specific veNFT\n /// @dev Can only be called internally by authorized entities.\n /// @param lpToken Address of the liquidity pool token\n /// @param amount Amount to be deposited for the veNFT\n /// @param tokenId Unique identifier of the veNFT\n function deposit(address lpToken, uint256 amount, uint256 tokenId) external;\n\n /// @notice Withdraw an amount from the bribe rewards contract for a specific veNFT\n /// @dev Can only be called internally by authorized entities.\n /// @param lpToken Address of the liquidity pool token\n /// @param amount Amount to be withdrawn for the veNFT\n /// @param tokenId Unique identifier of the veNFT\n function withdraw(address lpToken, uint256 amount, uint256 tokenId) external;\n\n /// @notice Claim the rewards earned by a veNFT holder\n /// @param tokenId Unique identifier of the veNFT\n /// @param tokens Array of tokens to claim rewards for\n function getReward(uint256 tokenId, address[] memory tokens) external;\n\n /// @notice Notify the contract about new rewards for stakers\n /// @param token Address of the reward token\n /// @param amount Amount of the reward token to be added\n function notifyRewardAmount(address token, uint256 amount) external;\n\n /// @notice Get the prior balance index for a veNFT at a specific timestamp\n /// @dev Timestamp must be in the past or present.\n /// @param tokenId The veNFT token ID to check\n /// @param lpToken Address of the liquidity pool token\n /// @param timestamp The timestamp to get the balance at\n /// @return The balance index at the given timestamp\n function getPriorBalanceIndex(uint256 tokenId, address lpToken, uint256 timestamp) external view returns (uint256);\n\n /// @notice Get the prior supply index at a specific timestamp\n /// @dev Timestamp must be in the past or present.\n /// @param timestamp The timestamp to get the supply index at\n /// @return The supply index at the given timestamp\n function getPriorSupplyIndex(uint256 timestamp, address lpToken) external view returns (uint256);\n\n /// @notice Calculate the rewards earned for a specific token and veNFT\n /// @param token Address of the reward token\n /// @param tokenId Unique identifier of the veNFT\n /// @return Amount of the reward token earned\n function earned(address token, uint256 tokenId) external view returns (uint256);\n}\n" + }, + "contracts/src/veION/interfaces/IveION.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport \"../stake/IStakeStrategy.sol\";\nimport \"./IveIONCore.sol\";\nimport \"./IveIONFirstExtension.sol\";\nimport \"./IveIONSecondExtension.sol\";\n\n/// @title IveION Interface\n/// @notice Interface for veION contract\ninterface IveION is IveIONStructsEnumsErrorsEvents, IveIONCore, IveIONFirstExtension, IveIONSecondExtension {\n // Constants\n function PRECISION() external view returns (uint256);\n\n // State Variables\n function s_tokenId() external view returns (uint256);\n function s_limitedBoost() external view returns (uint256);\n function s_limitedBoostActive() external view returns (bool);\n function s_veAERO() external view returns (address);\n function s_aeroVoting() external view returns (address);\n function s_ionicPool() external view returns (address);\n function s_voter() external view returns (address);\n function s_aeroVoterBoost() external view returns (uint256);\n function s_minimumLockDuration() external view returns (uint256);\n function s_maxEarlyWithdrawFee() external view returns (uint256);\n function ap() external view returns (address);\n function implementation() external view returns (address);\n\n // Mappings\n function s_minimumLockAmount(LpTokenType lpTokenType) external view returns (uint256);\n function s_whitelistedToken(address token) external view returns (bool);\n function s_lpType(address token) external view returns (LpTokenType);\n function s_canSplit(address user) external view returns (bool);\n function s_locked(uint256 tokenId, LpTokenType lpTokenType) external view returns (LockedBalance memory);\n function s_userPointEpoch(uint256 tokenId, LpTokenType lpTokenType) external view returns (uint256);\n function s_userPointHistory(\n uint256 tokenId,\n LpTokenType lpTokenType,\n uint256 epoch\n ) external view returns (UserPoint memory);\n function s_voted(uint256 tokenId) external view returns (bool);\n function s_supply(LpTokenType lpTokenType) external view returns (uint256);\n function s_permanentLockBalance(LpTokenType lpTokenType) external view returns (uint256);\n function s_stakeStrategy(LpTokenType lpTokenType) external view returns (address);\n function s_underlyingStake(uint256 tokenId, address token) external view returns (uint256);\n function s_protocolFees(LpTokenType lpTokenType) external view returns (uint256);\n function s_distributedFees(LpTokenType lpTokenType) external view returns (uint256);\n function s_delegations(\n uint256 delegatorTokenId,\n uint256 delegateeTokenId,\n LpTokenType lpTokenType\n ) external view returns (uint256);\n function s_userCumulativeAssetValues(address user, address token) external view returns (uint256);\n function s_delegatorsBlocked(uint256 tokenId, address token) external view returns (bool);\n\n // Openzeppelin functions\n function transferFrom(address from, address to, uint256 tokenId) external;\n function ownerOf(uint256 tokenId) external returns (address);\n function owner() external returns (address);\n function balanceOf(address owner) external returns (uint256);\n}\n" + }, + "contracts/src/veION/interfaces/IveIONCore.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport \"../stake/IStakeStrategy.sol\";\n\n/// @title IveION Interface\n/// @notice Interface for veION contract\ninterface IveIONCore {\n /**\n * @notice Creates a new lock for multiple tokens and assigns it to a specified address\n * @param _tokenAddress Array of token addresses to lock\n * @param _tokenAmount Array of token amounts to lock\n * @param _duration Array of lock durations\n * @param _stakeUnderlying Array of booleans indicating whether to stake underlying tokens\n * @param _to Address to assign the lock to\n * @return The ID of the newly created veNFT\n */\n function createLockFor(\n address[] memory _tokenAddress,\n uint256[] memory _tokenAmount,\n uint256[] memory _duration,\n bool[] memory _stakeUnderlying,\n address _to\n ) external returns (uint256);\n\n /**\n * @notice Creates a new lock for multiple tokens\n * @param _tokenAddress Array of token addresses to lock\n * @param _tokenAmount Array of token amounts to lock\n * @param _duration Array of lock durations\n * @param _stakeUnderlying Array of booleans indicating whether to stake underlying tokens\n * @return The ID of the newly created veNFT\n */\n function createLock(\n address[] calldata _tokenAddress,\n uint256[] calldata _tokenAmount,\n uint256[] calldata _duration,\n bool[] memory _stakeUnderlying\n ) external returns (uint256);\n\n /**\n * @notice Increases the amount of tokens locked for a specific veNFT\n * @param _tokenAddress Address of the token to increase lock amount for\n * @param _tokenId ID of the veNFT\n * @param _tokenAmount Amount of tokens to add to the lock\n * @param _stakeUnderlying Whether to stake the underlying tokens\n */\n function increaseAmount(\n address _tokenAddress,\n uint256 _tokenId,\n uint256 _tokenAmount,\n bool _stakeUnderlying\n ) external;\n\n /**\n * @notice Locks additional asset type for an existing veNFT\n * @param _tokenAddress Address of the new token to lock\n * @param _tokenAmount Amount of tokens to lock\n * @param _tokenId ID of the veNFT\n * @param _duration Duration of the lock\n * @param _stakeUnderlying Whether to stake the underlying tokens\n */\n function lockAdditionalAsset(\n address _tokenAddress,\n uint256 _tokenAmount,\n uint256 _tokenId,\n uint256 _duration,\n bool _stakeUnderlying\n ) external;\n\n /**\n * @notice Increases the lock duration for a specific token in a veNFT\n * @param _tokenAddress Address of the token\n * @param _tokenId ID of the veNFT\n * @param _lockDuration New lock duration to extend to\n */\n function increaseUnlockTime(address _tokenAddress, uint256 _tokenId, uint256 _lockDuration) external;\n\n /**\n * @notice Delegates voting power from one veNFT to another.\n * @param fromTokenId The ID of the veNFT from which voting power is delegated.\n * @param toTokenId The ID of the veNFT to which voting power is delegated.\n * @param lpToken The address of the LP token associated with the delegation.\n * @param amount The amount of voting power to delegate.\n */\n function delegate(uint256 fromTokenId, uint256 toTokenId, address lpToken, uint256 amount) external;\n\n /**\n * @notice Removes delegatees from a specific veNFT\n * @param fromTokenId ID of the veNFT from which delegatees are removed\n * @param toTokenIds Array of veNFT IDs that are delegatees to be removed\n * @param lpToken Address of the LP token associated with the delegation\n * @param amounts Array of amounts of voting power to remove from each delegatee\n */\n function removeDelegatees(\n uint256 fromTokenId,\n uint256[] memory toTokenIds,\n address lpToken,\n uint256[] memory amounts\n ) external;\n\n /**\n * @notice Removes delegators from a specific veNFT\n * @param fromTokenIds Array of veNFT IDs that are delegators to be removed\n * @param toTokenId ID of the veNFT from which delegators are removed\n * @param lpToken Address of the LP token associated with the delegation\n * @param amounts Array of amounts of voting power to remove from each delegator\n */\n function removeDelegators(\n uint256[] memory fromTokenIds,\n uint256 toTokenId,\n address lpToken,\n uint256[] memory amounts\n ) external;\n\n /**\n * @notice Locks a token permanently.\n * @param _tokenAddress The address of the token to lock.\n * @param _tokenId The ID of the token to lock.\n */\n function lockPermanent(address _tokenAddress, uint256 _tokenId) external;\n\n /**\n * @notice Unlocks a permanently locked token.\n * @param _tokenAddress The address of the token to unlock.\n * @param _tokenId The ID of the token to unlock.\n */\n function unlockPermanent(address _tokenAddress, uint256 _tokenId) external;\n\n /**\n * @notice Updates voting status for a veNFT\n * @param _tokenId ID of the veNFT\n * @param _voting Voting status\n */\n function voting(uint256 _tokenId, bool _voting) external;\n\n /**\n * @notice Sets the implementation addresses for the veION contract extensions.\n * @dev This function can only be called by authorized entities.\n * @param _veIONFirstExtension The address of the first extension contract.\n * @param _veIONSecondExtension The address of the second extension contract.\n */\n function setExtensions(address _veIONFirstExtension, address _veIONSecondExtension) external;\n}\n\n/// @title IAeroVotingEscrow Interface\n/// @notice Interface for Aero Voting Escrow contract\ninterface IAeroVotingEscrow {\n /**\n * @notice Returns the balance of the specified owner.\n * @param _owner The address of the owner.\n * @return The balance of the owner.\n */\n function balanceOf(address _owner) external view returns (uint256);\n\n /**\n * @notice Retrieves the token ID at a specific index for a given owner.\n * @param _owner The address of the owner.\n * @param _index The index of the token ID in the owner's list.\n * @return The token ID at the specified index.\n */\n function ownerToNFTokenIdList(address _owner, uint256 _index) external view returns (uint256);\n}\n\n/// @title IAeroVoter Interface\n/// @notice Interface for Aero Voter contract\ninterface IAeroVoter {\n /**\n * @notice Returns the list of pools voted for by a specific token ID.\n * @param tokenId The ID of the token.\n * @return An array of addresses representing the pools voted for.\n */\n function poolVote(uint256 tokenId) external view returns (address[] memory);\n\n /**\n * @notice Retrieves the weight of a specific pool.\n * @param pool The address of the pool.\n * @return The weight of the pool.\n */\n function weights(address pool) external view returns (uint256);\n\n /**\n * @notice Returns the number of votes a specific token ID has for a given pool.\n * @param tokenId The ID of the token.\n * @param pool The address of the pool.\n * @return The number of votes for the pool.\n */\n function votes(uint256 tokenId, address pool) external view returns (uint256);\n}\n\ninterface IAddressesProvider {\n function getAddress(string calldata id) external view returns (address);\n}\n\ninterface IMasterPriceOracle {\n function price(address underlying) external view returns (uint256);\n}\n" + }, + "contracts/src/veION/interfaces/IveIONFirstExtension.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport \"../stake/IStakeStrategy.sol\";\nimport { IveIONStructsEnumsErrorsEvents } from \"./IveIONStructsEnumsErrorsEvents.sol\";\n\n/// @title IveION Interface First Extensions\n/// @notice Interface for veION contract\ninterface IveIONFirstExtension is IveIONStructsEnumsErrorsEvents {\n /**\n * @notice Withdraws tokens associated with a specific token ID.\n * @param _tokenAddress The address of the token to withdraw.\n * @param _tokenId The ID of the token to withdraw.\n */\n function withdraw(address _tokenAddress, uint256 _tokenId) external;\n\n /**\n * @notice Merges two token IDs into one.\n * @param _from The ID of the token to merge from.\n * @param _to The ID of the token to merge into.\n */\n function merge(uint256 _from, uint256 _to) external;\n\n /**\n * @notice Splits a token into two separate tokens.\n * @param _tokenAddress The address of the token to split.\n * @param _from The ID of the token to split.\n * @param _splitAmount The amount to split from the original token.\n * @return _tokenId1 The ID of the first resulting token.\n * @return _tokenId2 The ID of the second resulting token.\n */\n function split(\n address _tokenAddress,\n uint256 _from,\n uint256 _splitAmount\n ) external returns (uint256 _tokenId1, uint256 _tokenId2);\n\n /**\n * @notice Claims emissions for a specific token.\n * @param _tokenAddress The address of the token for which to claim emissions.\n */\n function claimEmissions(address _tokenAddress) external;\n\n /**\n * @notice Allows or blocks delegators for a specific token ID.\n * @param _tokenId The ID of the token.\n * @param _tokenAddress The address of the token.\n * @param _blocked Boolean indicating if delegators are blocked.\n */\n function allowDelegators(uint256 _tokenId, address _tokenAddress, bool _blocked) external;\n\n /**\n * @notice Retrieves the balance of a specific NFT.\n * @param _tokenId The ID of the NFT.\n * @return _assets An array of asset addresses.\n * @return _balances An array of balances for each asset.\n * @return _boosts An array of boost values for each asset.\n */\n function balanceOfNFT(\n uint256 _tokenId\n ) external view returns (address[] memory _assets, uint256[] memory _balances, uint256[] memory _boosts);\n\n /**\n * @notice Retrieves the total ETH value of tokens owned by a specific address.\n * @param _owner The address of the owner.\n * @return totalValue The total ETH value of the tokens.\n */\n function getTotalEthValueOfTokens(address _owner) external view returns (uint256 totalValue);\n}\n" + }, + "contracts/src/veION/interfaces/IveIONSecondExtension.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport \"../stake/IStakeStrategy.sol\";\nimport { IveIONStructsEnumsErrorsEvents } from \"./IveIONStructsEnumsErrorsEvents.sol\";\n\n/// @title IveION Interface Second Extension\n/// @notice Interface for veION contract\ninterface IveIONSecondExtension is IveIONStructsEnumsErrorsEvents {\n /**\n * @notice Whitelists or removes tokens from the whitelist.\n * @param _tokens An array of token addresses to be whitelisted or removed.\n * @param _isWhitelisted An array of booleans indicating the whitelist status for each token.\n */\n function whitelistTokens(address[] memory _tokens, bool[] memory _isWhitelisted) external;\n\n /**\n * @notice Withdraws protocol fees for a specific token to a recipient address.\n * @param _tokenAddress The address of the token for which protocol fees are to be withdrawn.\n * @param _recipient The address to which the protocol fees will be sent.\n */\n function withdrawProtocolFees(address _tokenAddress, address _recipient) external;\n\n /**\n * @notice Withdraws distributed fees for a specific token to a recipient address.\n * @param _tokenAddress The address of the token for which distributed fees are to be withdrawn.\n * @param _recipient The address to which the distributed fees will be sent.\n */\n function withdrawDistributedFees(address _tokenAddress, address _recipient) external;\n\n /**\n * @notice Toggles the ability to split tokens for a specific account.\n * @param _account The address of the account.\n * @param _isAllowed Boolean indicating if splitting is allowed.\n */\n function toggleSplit(address _account, bool _isAllowed) external;\n\n /**\n * @notice Toggles the limited boost feature.\n * @param _isBoosted Boolean indicating if the boost is active.\n */\n function toggleLimitedBoost(bool _isBoosted) external;\n\n /**\n * @notice Sets the amount for a limited time boost.\n * @param _boostAmount The amount of the boost.\n */\n function setLimitedTimeBoost(uint256 _boostAmount) external;\n\n /**\n * @notice Sets the address of the voter.\n * @param _voter The address of the voter.\n */\n function setVoter(address _voter) external;\n\n /**\n * @notice Sets the minimum lock amount for a specific token.\n * @param _tokenAddress The address of the token.\n * @param _minimumAmount The minimum amount to lock.\n */\n function setMinimumLockAmount(address _tokenAddress, uint256 _minimumAmount) external;\n\n /**\n * @notice Sets the minimum lock duration.\n * @param _minimumLockDuration The minimum duration for locking.\n */\n function setMinimumLockDuration(uint256 _minimumLockDuration) external;\n\n /**\n * @notice Sets the address of the Ionic Pool.\n * @param _ionicPool The address of the Ionic Pool.\n */\n function setIonicPool(address _ionicPool) external;\n\n /**\n * @notice Sets the address of the Aero Voting contract.\n * @param _aeroVoting The address of the Aero Voting contract.\n */\n function setAeroVoting(address _aeroVoting) external;\n\n /**\n * @notice Sets the boost amount for Aero Voter.\n * @param _aeroVoterBoost The boost amount for Aero Voter.\n */\n function setAeroVoterBoost(uint256 _aeroVoterBoost) external;\n\n /**\n * @notice Sets the maximum early withdrawal fee.\n * @param _maxEarlyWithdrawFee The maximum fee for early withdrawal.\n */\n function setMaxEarlyWithdrawFee(uint256 _maxEarlyWithdrawFee) external;\n\n /**\n * @notice Sets the LP token type for a specific token.\n * @param _token The address of the token.\n * @param _type The LP token type.\n */\n function setLpTokenType(address _token, LpTokenType _type) external;\n\n /**\n * @notice Sets the stake strategy for a specific LP token type.\n * @param _lpType The LP token type.\n * @param _strategy The stake strategy.\n */\n function setStakeStrategy(LpTokenType _lpType, IStakeStrategy _strategy) external;\n\n /**\n * @notice Sets the address of the veAERO contract.\n * @param _veAERO The address of the veAERO contract.\n */\n function setVeAERO(address _veAERO) external;\n\n /**\n * @notice Retrieves the lock information for a specific user.\n * @param _tokenId The ID of the token.\n * @param _lpType The LP token type.\n * @return A LockedBalance struct containing lock details.\n */\n function getUserLock(uint256 _tokenId, LpTokenType _lpType) external view returns (LockedBalance memory);\n\n /**\n * @notice Retrieves the token IDs owned by a specific address.\n * @param _owner The address of the owner.\n * @return An array of token IDs owned by the address.\n */\n function getOwnedTokenIds(address _owner) external view returns (uint256[] memory);\n\n /**\n * @notice Retrieves the assets locked for a specific token ID.\n * @param _tokenId The ID of the token.\n * @return An array of addresses representing the locked assets.\n */\n function getAssetsLocked(uint256 _tokenId) external view returns (address[] memory);\n\n /**\n * @notice Retrieves the delegatees for a specific token ID and LP token type.\n * @param _tokenId The ID of the token.\n * @param _lpType The LP token type.\n * @return An array of delegatee IDs.\n */\n function getDelegatees(uint256 _tokenId, LpTokenType _lpType) external view returns (uint256[] memory);\n\n /**\n * @notice Retrieves the delegators for a specific token ID and LP token type.\n * @param _tokenId The ID of the token.\n * @param _lpType The LP token type.\n * @return An array of delegator IDs.\n */\n function getDelegators(uint256 _tokenId, LpTokenType _lpType) external view returns (uint256[] memory);\n\n /**\n * @notice Retrieves the user point for a specific token ID, LP token type, and epoch.\n * @param _tokenId The ID of the token.\n * @param _lpType The LP token type.\n * @param _epoch The epoch number.\n * @return A UserPoint struct containing user point details.\n */\n function getUserPoint(uint256 _tokenId, LpTokenType _lpType, uint256 _epoch) external view returns (UserPoint memory);\n}\n" + }, + "contracts/src/veION/interfaces/IveIONStructsEnumsErrorsEvents.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\ninterface IveIONStructsEnumsErrorsEvents {\n /**\n * @notice Structure representing a locked balance\n * @param tokenAddress Address of the token\n * @param amount Amount of tokens locked\n * @param delegateAmount Amount of tokens delegated\n * @param start Start time of the lock\n * @param end End time of the lock\n * @param isPermanent Indicates if the lock is permanent\n * @param boost Boost value for the lock\n */\n struct LockedBalance {\n address tokenAddress;\n uint256 amount;\n uint256 delegateAmount;\n uint256 start;\n uint256 end;\n bool isPermanent;\n uint256 boost;\n }\n\n /**\n * @notice Structure representing a delegation\n * @param amount Amount of tokens delegated\n * @param delegatee ID of the delegatee\n */\n struct Delegation {\n uint256 amount;\n uint256 delegatee;\n }\n\n /**\n * @notice Structure representing a user point\n * @param bias Bias value\n * @param slope Slope value, representing -dweight / dt\n * @param ts Timestamp of the point\n * @param blk Block number of the point\n * @param permanent Permanent value\n * @param permanentDelegate Permanent delegate value\n */\n struct UserPoint {\n uint256 bias;\n uint256 slope;\n uint256 ts;\n uint256 blk;\n uint256 permanent;\n uint256 permanentDelegate;\n }\n\n /**\n * @notice Structure representing a global point\n * @param bias Bias value\n * @param slope Slope value, representing -dweight / dt\n * @param ts Timestamp of the point\n * @param blk Block number of the point\n * @param permanentLockBalance Permanent lock balance\n */\n struct GlobalPoint {\n int128 bias;\n int128 slope;\n uint256 ts;\n uint256 blk;\n uint256 permanentLockBalance;\n }\n\n /**\n * @notice Structure representing a checkpoint\n * @param fromTimestamp Timestamp from which the checkpoint is valid\n * @param owner Address of the owner\n * @param delegatedBalance Balance that has been delegated\n * @param delegatee ID of the delegatee\n */\n struct Checkpoint {\n uint256 fromTimestamp;\n address owner;\n uint256 delegatedBalance;\n uint256 delegatee;\n }\n\n /**\n * @notice Enum representing deposit types\n */\n enum DepositType {\n DEPOSIT_FOR_TYPE,\n CREATE_LOCK_TYPE,\n INCREASE_LOCK_AMOUNT,\n INCREASE_UNLOCK_TIME,\n LOCK_ADDITIONAL\n }\n\n /**\n * @notice Enum representing LP token types\n */\n enum LpTokenType {\n Mode_Velodrome_5050_ION_MODE,\n Mode_Balancer_8020_ION_ETH,\n Base_Aerodrome_5050_ION_wstETH,\n Base_Balancer_8020_ION_ETH,\n Optimism_Velodrome_5050_ION_OP,\n Optimism_Balancer_8020_ION_ETH\n }\n\n error LockDurationNotInFuture();\n error ZeroAmount();\n error LockDurationTooLong();\n error TokenNotWhitelisted();\n error NotOwner();\n error AlreadyVoted();\n error PermanentLock();\n error NoLockFound();\n error LockExpired();\n error SameNFT();\n error SplitNotAllowed();\n error AmountTooBig();\n error NotPermanentLock();\n error TokenHasDelegatees();\n error TokenHasDelegators();\n error NotVoter();\n error MinimumNotMet();\n error ArrayMismatch();\n error LockDurationTooShort();\n error DuplicateAsset();\n error SplitTooSmall();\n error NotEnoughRemainingAfterSplit();\n error NoDelegationBetweenTokens(uint256 _tokenId1, uint256 _tokenId2);\n error NoUnderlyingStake();\n error NotAcceptingDelegators();\n error BoostAmountMustBeGreaterThanZero();\n error InvalidAddress();\n error MinimumAmountMustBeGreaterThanZero();\n error MinimumLockDurationMustBeGreaterThanZero();\n error AeroBoostAmountMustBeGreaterThanZero();\n error MaxEarlyWithdrawFeeMustBeGreaterThanZero();\n error InvalidTokenAddress();\n error InvalidStrategyAddress();\n error InvalidVeAEROAddress();\n\n event Deposit(\n address indexed provider,\n uint256 indexed tokenId,\n DepositType indexed depositType,\n uint256 value,\n uint256 locktime,\n uint256 ts\n );\n event Withdraw(address indexed provider, uint256 indexed tokenId, uint256 value, uint256 ts);\n event Supply(uint256 prevSupply, uint256 supply);\n event Delegated(uint256 indexed fromTokenId, uint256 indexed toTokenId, address lpToken, uint256 amount);\n event DelegationRemoved(uint256 indexed fromTokenId, uint256 indexed toTokenId, address lpToken, uint256 amount);\n event ProtocolFeesWithdrawn(address indexed tokenAddress, address indexed recipient, uint256 amount);\n event DistributedFeesWithdrawn(address indexed tokenAddress, address indexed recipient, uint256 amount);\n event SplitToggle(address indexed account, bool isAllowed);\n event LimitedBoostToggled(bool isBoosted);\n event LimitedTimeBoostSet(uint256 boostAmount);\n event VoterSet(address indexed newVoter);\n event AeroVotingSet(address indexed newAeroVoting);\n event AeroVoterBoostSet(uint256 newAeroVoterBoost);\n event TokensWhitelisted(address[] token, bool[] isWhitelisted);\n event LpTokenTypeSet(address indexed token, LpTokenType lpTokenType);\n event VeAEROSet(address indexed veAERO);\n event StakeStrategySet(LpTokenType indexed lpTokenType, address indexed strategy);\n event MinimumLockAmountSet(address indexed tokenAddress, uint256 minimumAmount);\n event MinimumLockDurationSet(uint256 minimumDuration);\n event IonicPoolSet(address indexed newIonicPool);\n event SplitCompleted(\n uint256 indexed fromTokenId,\n uint256 indexed tokenId1,\n uint256 indexed tokenId2,\n uint256 splitAmount,\n address tokenAddress\n );\n event MergeCompleted(\n uint256 indexed fromTokenId,\n uint256 indexed toTokenId,\n address[] assetsLocked,\n uint256 lengthOfAssets\n );\n event EmissionsClaimed(address indexed claimant, address indexed tokenAddress);\n event MaxEarlyWithdrawFeeSet(uint256 maxEarlyWithdrawFee);\n event PermanentLockCreated(address indexed tokenAddress, uint256 indexed tokenId, uint256 amount);\n event PermanentLockRemoved(address indexed tokenAddress, uint256 indexed tokenId, uint256 amount);\n event Voted(uint256 _tokenId, bool _voting);\n event DelegatorsBlocked(uint256 indexed _tokenId, address indexed _lpToken, bool _blocked);\n event Initialized(address indexed addressesProvider);\n event ExtensionsSet(address indexed _firstExtension, address indexed _secondExtension);\n}\n" + }, + "contracts/src/veION/interfaces/IVoter.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\n/**\n * @title IVoter\n * @notice Interface for the Voter contract, which manages voting and reward distribution.\n */\ninterface IVoter {\n /// @notice Error thrown when a user has already voted or deposited.\n error AlreadyVotedOrDeposited();\n\n /// @notice Error thrown when an action is attempted outside the distribution window.\n error DistributeWindow();\n\n /// @notice Error thrown when a reward accumulator does not exist for a given pool.\n error RewardAccumulatorDoesNotExist(address _pool);\n\n /// @notice Error thrown when a reward accumulator is not alive.\n error RewardAccumulatorNotAlive(address _rewardAccumulator);\n\n /// @notice Error thrown when a market already exists.\n error MarketAlreadyExists();\n\n /// @notice Error thrown when the maximum voting number is too low.\n error MaximumVotingNumberTooLow();\n\n /// @notice Error thrown when array lengths do not match.\n error MismatchedArrayLengths();\n\n /// @notice Error thrown when there are non-zero votes.\n error NonZeroVotes();\n\n /// @notice Error thrown when the caller is not the owner.\n error NotOwner();\n\n /// @notice Error thrown when an action is attempted outside the distribution window.\n error NotDistributeWindow();\n\n /// @notice Error thrown when the caller is not the governor.\n error NotGovernor();\n\n /// @notice Error thrown when an NFT is not whitelisted.\n error NotWhitelistedNFT();\n\n /// @notice Error thrown when the same value is provided.\n error SameValue();\n\n /// @notice Error thrown when there are too many pools.\n error TooManyPools();\n\n /// @notice Error thrown when array lengths are unequal.\n error UnequalLengths();\n\n /// @notice Error thrown when an address is zero.\n error ZeroAddress();\n\n /// @notice Error thrown when the tokens array is empty.\n error TokensArrayEmpty();\n\n /// @notice Error thrown when the weight is zero.\n error ZeroWeight();\n\n /**\n * @notice Struct to store vote details.\n * @param marketVotes Array of market addresses voted for.\n * @param marketVoteSides Array of market sides voted for.\n * @param votes Array of vote weights.\n * @param usedWeight Total weight used in voting.\n */\n struct VoteDetails {\n address[] marketVotes;\n MarketSide[] marketVoteSides;\n uint256[] votes;\n uint256 usedWeight;\n }\n\n /**\n * @notice Struct to store market information.\n * @param marketAddress Address of the market.\n * @param side Side of the market (Supply or Borrow).\n */\n struct Market {\n address marketAddress;\n MarketSide side;\n }\n\n /**\n * @notice Struct to store variables used in voting.\n * @param totalWeight Total weight available for voting.\n * @param usedWeight Weight used in voting.\n * @param market Address of the market.\n * @param marketSide Side of the market.\n * @param rewardAccumulator Address of the reward accumulator.\n * @param marketWeight Weight of the market.\n * @param bribes Address of the bribes.\n */\n struct VoteVars {\n uint256 totalWeight;\n uint256 usedWeight;\n address market;\n MarketSide marketSide;\n address rewardAccumulator;\n uint256 marketWeight;\n address bribes;\n }\n\n /**\n * @notice Struct to store local variables used in voting.\n * @param sender Address of the sender.\n * @param timestamp Timestamp of the vote.\n * @param votingLPs Array of voting LP addresses.\n * @param votingLPBalances Array of voting LP balances.\n * @param boosts Array of boosts.\n */\n struct VoteLocalVars {\n address sender;\n uint256 timestamp;\n address[] votingLPs;\n uint256[] votingLPBalances;\n uint256[] boosts;\n }\n\n /**\n * @notice Enum to represent the side of a market.\n */\n enum MarketSide {\n Supply,\n Borrow\n }\n\n /**\n * @notice Event emitted when a vote is cast.\n * @param voter Address of the voter.\n * @param pool Address of the pool.\n * @param tokenId ID of the token.\n * @param weight Weight of the vote.\n * @param totalWeight Total weight of the vote.\n * @param timestamp Timestamp of the vote.\n */\n event Voted(\n address indexed voter,\n address indexed pool,\n uint256 indexed tokenId,\n uint256 weight,\n uint256 totalWeight,\n uint256 timestamp\n );\n\n /**\n * @notice Event emitted when a vote is abstained.\n * @param voter Address of the voter.\n * @param pool Address of the pool.\n * @param tokenId ID of the token.\n * @param weight Weight of the vote.\n * @param totalWeight Total weight of the vote.\n * @param timestamp Timestamp of the vote.\n */\n event Abstained(\n address indexed voter,\n address indexed pool,\n uint256 indexed tokenId,\n uint256 weight,\n uint256 totalWeight,\n uint256 timestamp\n );\n\n /**\n * @notice Event emitted when a reward is notified.\n * @param sender Address of the sender.\n * @param reward Address of the reward.\n * @param amount Amount of the reward.\n */\n event NotifyReward(address indexed sender, address indexed reward, uint256 amount);\n\n /**\n * @notice Event emitted when a token is whitelisted.\n * @param whitelister Address of the whitelister.\n * @param token Address of the token.\n * @param _bool Boolean indicating whitelist status.\n */\n event WhitelistToken(address indexed whitelister, address indexed token, bool indexed _bool);\n\n /**\n * @notice Event emitted when an NFT is whitelisted.\n * @param whitelister Address of the whitelister.\n * @param tokenId ID of the token.\n * @param _bool Boolean indicating whitelist status.\n */\n event WhitelistNFT(address indexed whitelister, uint256 indexed tokenId, bool indexed _bool);\n\n event LpTokensSet(address[] indexed lpTokens);\n event MpoSet(address indexed mpo);\n event GovernorSet(address indexed governor);\n event MarketsAdded(Market[] markets);\n event MarketRewardAccumulatorsSet(\n address[] indexed markets,\n MarketSide[] indexed marketSides,\n address[] indexed rewardAccumulators\n );\n event BribesSet(address[] indexed rewardAccumulators, address[] indexed bribes);\n event MaxVotingNumSet(uint256 indexed maxVotingNum);\n event RewardAccumulatorAliveToggled(address indexed market, MarketSide indexed marketSide, bool isAlive);\n event Initialized(address[] tokens, address mpo, address rewardToken, address ve, address governor);\n\n /**\n * @notice Get the weight of a market.\n * @param market Address of the market.\n * @param marketSide Side of the market.\n * @param lpToken Address of the LP token.\n * @return The weight of the market.\n */\n function weights(address market, MarketSide marketSide, address lpToken) external view returns (uint256);\n\n /**\n * @notice Get the votes for a token.\n * @param tokenId ID of the token.\n * @param market Address of the market.\n * @param marketSide Side of the market.\n * @param lpToken Address of the LP token.\n * @return The votes for the token.\n */\n function votes(\n uint256 tokenId,\n address market,\n MarketSide marketSide,\n address lpToken\n ) external view returns (uint256);\n\n /**\n * @notice Get the used weights for a token.\n * @param tokenId ID of the token.\n * @param lpToken Address of the LP token.\n * @return The used weights for the token.\n */\n function usedWeights(uint256 tokenId, address lpToken) external view returns (uint256);\n\n /**\n * @notice Get the last voted timestamp for a token.\n * @param tokenId ID of the token.\n * @return The last voted timestamp for the token.\n */\n function lastVoted(uint256 tokenId) external view returns (uint256);\n\n /**\n * @notice Check if a token is whitelisted.\n * @param token Address of the token.\n * @return True if the token is whitelisted, false otherwise.\n */\n function isWhitelistedToken(address token) external view returns (bool);\n\n /**\n * @notice Check if an NFT is whitelisted.\n * @param tokenId ID of the token.\n * @return True if the NFT is whitelisted, false otherwise.\n */\n function isWhitelistedNFT(uint256 tokenId) external view returns (bool);\n\n /**\n * @notice Get the address of the ve contract.\n * @return The address of the ve contract.\n */\n function ve() external view returns (address);\n\n /**\n * @notice Get the address of the governor.\n * @return The address of the governor.\n */\n function governor() external view returns (address);\n\n /**\n * @notice Update voting balances in voting rewards contracts.\n * @param _tokenId ID of veNFT whose balance you wish to update.\n */\n function poke(uint256 _tokenId) external;\n\n /**\n * @notice Vote for pools. Votes distributed proportionally based on weights.\n * @dev Can only vote or deposit into a managed NFT once per epoch.\n * Can only vote for gauges that have not been killed.\n * Throws if length of _poolVote and _weights do not match.\n * @param _tokenId ID of veNFT you are voting with.\n * @param _poolVote Array of pools you are voting for.\n * @param _marketVoteSide Array of market vote sides you are voting for.\n * @param _weights Weights of pools.\n */\n function vote(\n uint256 _tokenId,\n address[] calldata _poolVote,\n MarketSide[] calldata _marketVoteSide,\n uint256[] calldata _weights\n ) external;\n\n /**\n * @notice Reset voting state. Required if you wish to make changes to veNFT state.\n * @dev Cannot reset in the same epoch that you voted in.\n * Can vote or deposit into a managed NFT again after reset.\n * @param _tokenId ID of veNFT that you are resetting.\n */\n function reset(uint256 _tokenId) external;\n\n /**\n * @notice Distributes rewards to eligible markets.\n */\n function distributeRewards() external;\n\n /**\n * @notice Claim bribes for a given NFT.\n * @dev Utility to help batch bribe claims.\n * @param _bribes Array of BribeVotingReward contracts to collect from.\n * @param _tokens Array of tokens that are used as bribes.\n * @param _tokenId ID of veNFT that you wish to claim bribes for.\n */\n function claimBribes(address[] memory _bribes, address[][] memory _tokens, uint256 _tokenId) external;\n\n /**\n * @notice Whitelist (or unwhitelist) token for use in bribes.\n * @dev Throws if not called by governor.\n * @param _token Address of the token.\n * @param _bool Boolean indicating whitelist status.\n */\n function whitelistToken(address _token, bool _bool) external;\n\n /**\n * @notice Whitelist (or unwhitelist) token id for voting in last hour prior to epoch flip.\n * @dev Throws if not called by governor.\n * Throws if already whitelisted.\n * @param _tokenId ID of the token.\n * @param _bool Boolean indicating whitelist status.\n */\n function whitelistNFT(uint256 _tokenId, bool _bool) external;\n\n /**\n * @notice Set the LP tokens.\n * @param _lpTokens Array of LP token addresses.\n */\n function setLpTokens(address[] memory _lpTokens) external;\n\n /**\n * @notice Set the Master Price Oracle (MPO) address.\n * @param _mpo Address of the Master Price Oracle.\n */\n function setMpo(address _mpo) external;\n\n /**\n * @notice Set a new governor.\n * @param _governor Address of the new governor.\n */\n function setGovernor(address _governor) external;\n\n /**\n * @notice Add new markets.\n * @param _markets Array of Market structs to be added.\n */\n function addMarkets(Market[] calldata _markets) external;\n\n /**\n * @notice Set reward accumulators for markets.\n * @param _markets Array of market addresses.\n * @param _marketSides Array of market sides.\n * @param _rewardAccumulators Array of reward accumulator addresses.\n */\n function setMarketRewardAccumulators(\n address[] calldata _markets,\n MarketSide[] calldata _marketSides,\n address[] calldata _rewardAccumulators\n ) external;\n\n /**\n * @notice Set bribes for reward accumulators.\n * @param _rewardAccumulators Array of reward accumulator addresses.\n * @param _bribes Array of bribe addresses.\n */\n function setBribes(address[] calldata _rewardAccumulators, address[] calldata _bribes) external;\n\n /**\n * @notice Set the maximum number of votes.\n * @param _maxVotingNum Maximum number of votes allowed.\n */\n function setMaxVotingNum(uint256 _maxVotingNum) external;\n\n /**\n * @notice Toggle the alive status of a reward accumulator.\n * @param _market Address of the market.\n * @param _marketSide Side of the market.\n * @param _isAlive Boolean indicating if the reward accumulator is alive.\n */\n function toggleRewardAccumulatorAlive(address _market, MarketSide _marketSide, bool _isAlive) external;\n\n /**\n * @notice Get the start of the epoch for a given timestamp.\n * @param _timestamp The timestamp to calculate the epoch start for.\n * @return The start of the epoch.\n */\n function epochStart(uint256 _timestamp) external pure returns (uint256);\n\n /**\n * @notice Get the next epoch for a given timestamp.\n * @param _timestamp The timestamp to calculate the next epoch for.\n * @return The next epoch.\n */\n function epochNext(uint256 _timestamp) external pure returns (uint256);\n\n /**\n * @notice Get the start of the voting period for a given timestamp.\n * @param _timestamp The timestamp to calculate the voting start for.\n * @return The start of the voting period.\n */\n function epochVoteStart(uint256 _timestamp) external pure returns (uint256);\n\n /**\n * @notice Get the end of the voting period for a given timestamp.\n * @param _timestamp The timestamp to calculate the voting end for.\n * @return The end of the voting period.\n */\n function epochVoteEnd(uint256 _timestamp) external pure returns (uint256);\n\n /**\n * @notice Get the number of markets.\n * @return The number of markets.\n */\n function marketsLength() external view returns (uint256);\n\n /**\n * @notice Get all LP reward tokens.\n * @return An array of addresses representing all LP reward tokens.\n */\n function getAllLpRewardTokens() external view returns (address[] memory);\n\n /**\n * @notice Get vote details for a specific token ID and LP asset.\n * @param _tokenId The ID of the token.\n * @param _lpAsset The address of the LP asset.\n * @return A struct containing vote details.\n */\n function getVoteDetails(uint256 _tokenId, address _lpAsset) external view returns (VoteDetails memory);\n}\n" + }, + "contracts/src/veION/libraries/BalanceLogicLibrary.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport \"../interfaces/IveIONStructsEnumsErrorsEvents.sol\";\n\nlibrary BalanceLogicLibrary {\n uint256 internal constant _WEEK = 1 weeks;\n\n /// @notice Calculates the voting power for a given NFT at a specific time.\n /// @dev This function is compatible with the ERC20 `balanceOf` interface for Aragon.\n /// It retrieves the last user point before a specified timestamp and computes the voting power at that time.\n /// @param s_userPointEpoch Mapping of user point epochs for all tokens.\n /// @param s_userPointHistory Mapping of user point history for all tokens.\n /// @param _lpType The type of LP token associated with the NFT.\n /// @param _tokenId The ID of the NFT for which to calculate voting power.\n /// @param _t The epoch time at which to calculate the voting power.\n /// @param _isPermanent A boolean indicating if the lock is permanent.\n /// @return The calculated voting power of the user at the specified time.\n function balanceOfNFTAt(\n mapping(uint256 => mapping(IveIONStructsEnumsErrorsEvents.LpTokenType => uint256)) storage s_userPointEpoch,\n mapping(uint256 => mapping(IveIONStructsEnumsErrorsEvents.LpTokenType => IveIONStructsEnumsErrorsEvents.UserPoint[1000000000]))\n storage s_userPointHistory,\n IveIONStructsEnumsErrorsEvents.LpTokenType _lpType,\n uint256 _tokenId,\n uint256 _t,\n bool _isPermanent\n ) internal view returns (uint256) {\n uint256 _epoch = getPastUserPointIndex(s_userPointEpoch, s_userPointHistory, _lpType, _tokenId, _t);\n // epoch 0 is an empty point\n if (_epoch == 0) return 0;\n IveIONStructsEnumsErrorsEvents.UserPoint memory lastPoint = s_userPointHistory[_tokenId][_lpType][_epoch];\n if (_isPermanent) {\n return lastPoint.permanent + lastPoint.permanentDelegate;\n } else {\n uint256 reduction = lastPoint.slope * (_t - lastPoint.ts);\n if (reduction > lastPoint.bias) {\n lastPoint.bias = 0;\n } else {\n lastPoint.bias -= reduction;\n }\n return lastPoint.bias;\n }\n }\n\n /// @notice Binary search to get the user point index for a token id at or prior to a given timestamp\n /// @dev If a user point does not exist prior to the timestamp, this will return 0.\n /// @param s_userPointEpoch State of all user point epochs\n /// @param s_userPointHistory State of all user point history\n /// @param _tokenId .\n /// @param _timestamp .\n /// @return User point index\n function getPastUserPointIndex(\n mapping(uint256 => mapping(IveIONStructsEnumsErrorsEvents.LpTokenType => uint256)) storage s_userPointEpoch,\n mapping(uint256 => mapping(IveIONStructsEnumsErrorsEvents.LpTokenType => IveIONStructsEnumsErrorsEvents.UserPoint[1000000000]))\n storage s_userPointHistory,\n IveIONStructsEnumsErrorsEvents.LpTokenType _lpType,\n uint256 _tokenId,\n uint256 _timestamp\n ) internal view returns (uint256) {\n uint256 _userEpoch = s_userPointEpoch[_tokenId][_lpType];\n if (_userEpoch == 0) return 0;\n // First check most recent balance\n if (s_userPointHistory[_tokenId][_lpType][_userEpoch].ts <= _timestamp) return (_userEpoch);\n // Next check implicit zero balance\n if (s_userPointHistory[_tokenId][_lpType][1].ts > _timestamp) return 0;\n uint256 lower = 0;\n uint256 upper = _userEpoch;\n while (upper > lower) {\n uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow\n IveIONStructsEnumsErrorsEvents.UserPoint storage userPoint = s_userPointHistory[_tokenId][_lpType][center];\n if (userPoint.ts == _timestamp) {\n return center;\n } else if (userPoint.ts < _timestamp) {\n lower = center;\n } else {\n upper = center - 1;\n }\n }\n return lower;\n }\n}\n" + }, + "contracts/src/veION/libraries/IonicTimeLibrary.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nlibrary IonicTimeLibrary {\n uint256 internal constant _WEEK = 7 days;\n\n /// @dev Returns start of epoch based on current timestamp\n function epochStart(uint256 timestamp) internal pure returns (uint256) {\n unchecked {\n return timestamp - (timestamp % _WEEK);\n }\n }\n\n /// @dev Returns start of next epoch / end of current epoch\n function epochNext(uint256 timestamp) internal pure returns (uint256) {\n unchecked {\n return timestamp - (timestamp % _WEEK) + _WEEK;\n }\n }\n\n /// @dev Returns start of voting window\n function epochVoteStart(uint256 timestamp) internal pure returns (uint256) {\n unchecked {\n return timestamp - (timestamp % _WEEK) + 1 hours;\n }\n }\n\n /// @dev Returns end of voting window / beginning of unrestricted voting window\n function epochVoteEnd(uint256 timestamp) internal pure returns (uint256) {\n unchecked {\n return timestamp - (timestamp % _WEEK) + _WEEK - 12 hours;\n }\n }\n}\n" + }, + "contracts/src/veION/RewardAccumulator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport { Ownable2StepUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\ncontract RewardAccumulator is Ownable2StepUpgradeable {\n using SafeERC20 for IERC20;\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n function initialize() external initializer {\n __Ownable2Step_init();\n }\n\n function approve(address _token, address _spender) external onlyOwner {\n IERC20(_token).safeIncreaseAllowance(_spender, type(uint256).max);\n }\n}\n" + }, + "contracts/src/veION/stake/IStakeStrategy.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\n/**\n * @title IStakeStrategy\n * @notice Interface for the VeloIonModeStakingModeReward contract.\n */\ninterface IStakeStrategy {\n /// @notice Emitted when the contract is initialized\n event Initialized(\n address indexed escrow,\n address indexed stakingToken,\n address indexed stakingContract,\n address stakingWalletImplementation\n );\n\n /// @notice Emitted when tokens are staked\n event Staked(address indexed from, uint256 amount, address indexed veloWallet);\n\n /// @notice Emitted when rewards are claimed\n event Claimed(address indexed from, address indexed veloWallet);\n\n /// @notice Emitted when tokens are withdrawn\n event Withdrawn(address indexed owner, address indexed withdrawTo, uint256 amount);\n\n /// @notice Emitted when staking wallet is transferred\n event StakingWalletTransferred(address indexed from, address indexed to, uint256 amount);\n\n /// @notice Emitted when escrow is set\n event EscrowSet(address indexed newEscrow);\n\n /// @notice Emitted when staking token is set\n event StakingTokenSet(address indexed newStakingToken);\n\n /// @notice Emitted when staking contract is set\n event StakingContractSet(address indexed newStakingContract);\n\n /// @notice Emitted when upgradeable beacon is set\n event UpgradeableBeaconSet(address indexed newBeacon);\n\n /**\n * @notice Stakes a specified amount of tokens from a given address.\n * @param _from The address from which tokens will be staked.\n * @param _amount The amount of tokens to stake.\n * @param _data Additional data that might be needed for staking.\n */\n function stake(address _from, uint256 _amount, bytes memory _data) external;\n\n /**\n * @notice Claims rewards for a given address.\n * @param _from The address for which to claim rewards.\n */\n function claim(address _from) external;\n\n /**\n * @notice Withdraws a specified amount of tokens for a given address.\n * @param _owner The address from which tokens will be withdrawn.\n * @param _amount The amount of tokens to withdraw.\n */\n function withdraw(address _owner, address _withdrawTo, uint256 _amount) external;\n\n /**\n * @notice Returns the current reward rate for the staking strategy.\n * @return The reward rate as a uint256.\n */\n function rewardRate() external view returns (uint256);\n\n /**\n * @notice Returns the period finish time for the staking strategy.\n * @return The period finish time as a uint256.\n */\n function periodFinish() external view returns (uint256);\n\n /**\n * @notice Returns the balance of a specific address.\n * @param account The address to query the balance of.\n * @return The balance as a uint256.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @notice Returns the total supply of staked tokens.\n * @return The total supply as a uint256.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @notice Returns the address of the reward token for the staking strategy.\n * @return The address of the reward token.\n */\n function rewardToken() external view returns (address);\n\n /**\n * @notice Returns the address of the staking contract.\n * @return The address of the staking contract.\n */\n function stakingContract() external view returns (address);\n\n /**\n * @notice Returns the address of the staking token.\n * @return The address of the staking token.\n */\n function stakingToken() external view returns (address);\n\n /**\n * @notice Returns the staking wallet address for a specific user.\n * @param user The address of the user.\n * @return The address of the user's staking wallet.\n */\n function userStakingWallet(address user) external view returns (address);\n\n /**\n * @notice Transfers the staking wallet from one user to another.\n * @param from The current owner of the staking wallet.\n * @param to The new owner of the staking wallet.\n */\n function transferStakingWallet(address from, address to, uint256 _amount) external;\n\n /**\n * @notice Sets the escrow address.\n * @param _escrow The address of the new escrow.\n */\n function setEscrow(address _escrow) external;\n\n /**\n * @notice Sets the staking token address.\n * @param _stakingToken The address of the new staking token.\n */\n function setStakingToken(address _stakingToken) external;\n\n /**\n * @notice Sets the staking contract address.\n * @param _stakingContract The address of the new staking contract.\n */\n function setStakingContract(address _stakingContract) external;\n\n /**\n * @notice Sets the address of the beacon.\n * @param _beacon The address of the new beacon contract.\n */\n function setUpgradeableBeacon(address _beacon) external;\n}\n" + }, + "contracts/src/veION/stake/IStakeWallet.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\ninterface IStakeWallet {\n /// @notice Emitted when tokens are staked\n event Staked(uint256 amount);\n\n /// @notice Emitted when rewards are claimed\n event Claimed(address indexed from, uint256 rewardAmount);\n\n /// @notice Emitted when tokens are withdrawn\n event Withdrawn(address indexed withdrawTo, uint256 amount);\n\n /**\n * @notice Stakes a specified amount of tokens according to the strategy.\n * @param amount The amount of tokens to stake.\n * @param data Additional data required for the staking strategy.\n */\n function stake(address from, uint256 amount, bytes memory data) external;\n\n /**\n * @notice Claims rewards for the caller.\n */\n function claim(address from) external;\n\n /**\n * @notice Withdraws a specified amount of staked tokens.\n * @param withdrawTo The address to withdraw tokens to.\n * @param amount The amount of tokens to withdraw.\n */\n function withdraw(address withdrawTo, uint256 amount) external;\n}\n" + }, + "contracts/src/veION/stake/velo/IVeloIonModeStaking.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\ninterface IVeloIonModeStaking {\n event Deposit(address indexed from, address indexed to, uint256 amount);\n event Withdraw(address indexed from, uint256 amount);\n event NotifyReward(address indexed from, uint256 amount);\n event ClaimFees(uint256 claimed0, uint256 claimed1);\n event ClaimRewards(address indexed from, uint256 amount);\n\n /// @notice Address of the pool LP token which is deposited (staked) for rewards\n function stakingToken() external view returns (address);\n\n /// @notice Address of the token (VELO v2) rewarded to stakers\n function rewardToken() external view returns (address);\n\n /// @notice Address of the Converter contract linked to the gauge\n function feeConverter() external view returns (address);\n\n /// @notice Address of the staking rewards factory that created this gauge\n function factory() external view returns (address);\n\n /// @notice Timestamp end of current rewards period\n function periodFinish() external view returns (uint256);\n\n /// @notice Current reward rate of rewardToken to distribute per second\n function rewardRate() external view returns (uint256);\n\n /// @notice Most recent timestamp contract has updated state\n function lastUpdateTime() external view returns (uint256);\n\n /// @notice Most recent stored value of rewardPerToken\n function rewardPerTokenStored() external view returns (uint256);\n\n /// @notice Amount of stakingToken deposited for rewards\n function totalSupply() external view returns (uint256);\n\n /// @notice Get the amount of stakingToken deposited by an account\n function balanceOf(address) external view returns (uint256);\n\n /// @notice Cached rewardPerTokenStored for an account based on their most recent action\n function userRewardPerTokenPaid(address) external view returns (uint256);\n\n /// @notice Cached amount of rewardToken earned for an account\n function rewards(address) external view returns (uint256);\n\n /// @notice View to see the rewardRate given the timestamp of the start of the epoch\n function rewardRateByEpoch(uint256) external view returns (uint256);\n\n /// @notice Get the current reward rate per unit of stakingToken deposited\n function rewardPerToken() external view returns (uint256 _rewardPerToken);\n\n /// @notice Returns the last time the reward was modified or periodFinish if the reward has ended\n function lastTimeRewardApplicable() external view returns (uint256 _time);\n\n /// @notice Returns accrued balance to date from last claim / first deposit.\n function earned(address _account) external view returns (uint256 _earned);\n\n /// @notice Total amount of rewardToken to distribute for the current rewards period\n function left() external view returns (uint256 _left);\n\n /// @notice Claims accrued Fees from Pool and distributes them to the Converter\n /// @return _claimed0 Amount of Fees claimed in token0\n /// @return _claimed1 Amount of Fees claimed in token1\n function claimFees() external returns (uint256 _claimed0, uint256 _claimed1);\n\n /// @notice Retrieve rewards for an address.\n /// @dev Throws if not called by same address or voter.\n /// @param _account .\n function getReward(address _account) external;\n\n /// @notice Deposit LP tokens into gauge for msg.sender\n /// @param _amount .\n function deposit(uint256 _amount) external;\n\n /// @notice Deposit LP tokens into gauge for any user\n /// @param _amount .\n /// @param _recipient Recipient to give balance to\n function deposit(uint256 _amount, address _recipient) external;\n\n /// @notice Withdraw LP tokens for user\n /// @param _amount .\n function withdraw(uint256 _amount) external;\n\n /// @dev Notifies gauge of gauge rewards. Assumes gauge reward tokens is 18 decimals.\n /// If not 18 decimals, rewardRate may have rounding issues.\n function notifyRewardMatch(uint256 amount) external;\n\n /// @dev Notifies gauge of gauge rewards. Assumes gauge reward tokens is 18 decimals.\n /// If not 18 decimals, rewardRate may have rounding issues.\n function notifyRewardAmount(uint256 amount) external;\n}\n" + }, + "contracts/src/veION/stake/velo/VeloAeroStakingStrategy.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport \"../IStakeStrategy.sol\";\nimport \"./VeloAeroStakingWallet.sol\";\nimport \"./IVeloIonModeStaking.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol\";\nimport { BeaconProxy } from \"@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol\";\nimport { UpgradeableBeacon } from \"@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol\";\n\n/**\n * @title VeloAeroStakingStrategy\n * @notice Staking interface for usage in veION when staking Velodrome/Aerodrome style LP.\n * @author Jourdan Dunkley (https://github.com/jourdanDunkley)\n */\ncontract VeloAeroStakingStrategy is IStakeStrategy, Ownable2StepUpgradeable {\n using SafeERC20 for IERC20;\n\n /// @notice Address of the escrow responsible for managing staking operations\n address public escrow;\n /// @notice Address of the token being staked\n address public stakingToken;\n /// @notice Address of the contract where staking operations are executed\n address public stakingContract;\n /// @notice Address of beacon contract that manages wallet proxies\n UpgradeableBeacon public veloAeroBeacon;\n /// @notice Mapping of user addresses to their respective staking wallet addresses\n mapping(address => address) public userStakingWallet;\n\n /// @dev Modifier to restrict function access to only the escrow address\n modifier onlyEscrow() {\n require(msg.sender == escrow, \"Not authorized: Only escrow can call this function\");\n _;\n }\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n /**\n * @notice Initializes the staking strategy contract with necessary parameters\n * @dev This function can only be called once due to the initializer modifier\n * @param _escrow The address of the escrow responsible for staking operations\n * @param _stakingToken The address of the token to be staked\n * @param _stakingContract The address of the contract handling staking\n * @param _stakingWalletImplementation The address of the staking wallet implementation\n */\n function initialize(\n address _escrow,\n address _stakingToken,\n address _stakingContract,\n address _stakingWalletImplementation\n ) public initializer {\n __Ownable2Step_init();\n escrow = _escrow;\n stakingToken = _stakingToken;\n stakingContract = _stakingContract;\n\n veloAeroBeacon = new UpgradeableBeacon(_stakingWalletImplementation);\n veloAeroBeacon.transferOwnership(msg.sender);\n\n emit Initialized(_escrow, _stakingToken, _stakingContract, _stakingWalletImplementation);\n }\n\n /// @inheritdoc IStakeStrategy\n function stake(address _from, uint256 _amount, bytes memory _data) external override onlyEscrow {\n IERC20(stakingToken).safeTransferFrom(msg.sender, address(this), _amount);\n\n address veloWallet = userStakingWallet[_from];\n if (veloWallet == address(0)) {\n BeaconProxy newWallet = new BeaconProxy(address(veloAeroBeacon), \"\");\n veloWallet = address(newWallet);\n VeloAeroStakingWallet(veloWallet).initialize(IStakeStrategy(address(this)));\n userStakingWallet[_from] = veloWallet;\n }\n\n IERC20(stakingToken).approve(veloWallet, _amount);\n VeloAeroStakingWallet(veloWallet).stake(_from, _amount, _data);\n emit Staked(_from, _amount, veloWallet);\n }\n\n /// @inheritdoc IStakeStrategy\n function claim(address _from) external onlyEscrow {\n VeloAeroStakingWallet veloWallet = VeloAeroStakingWallet(userStakingWallet[_from]);\n veloWallet.claim(_from);\n emit Claimed(_from, address(veloWallet));\n }\n\n /// @inheritdoc IStakeStrategy\n function withdraw(address _owner, address _withdrawTo, uint256 _amount) external onlyEscrow {\n VeloAeroStakingWallet veloWallet = VeloAeroStakingWallet(userStakingWallet[_owner]);\n veloWallet.withdraw(_withdrawTo, _amount);\n emit Withdrawn(_owner, _withdrawTo, _amount);\n }\n\n /// @inheritdoc IStakeStrategy\n function transferStakingWallet(address _from, address _to, uint256 _amount) external onlyEscrow {\n address fromWallet = userStakingWallet[_from];\n address toWallet = userStakingWallet[_to];\n\n if (toWallet == address(0)) {\n BeaconProxy newWallet = new BeaconProxy(address(veloAeroBeacon), \"\");\n toWallet = address(newWallet);\n VeloAeroStakingWallet(toWallet).initialize(IStakeStrategy(address(this)));\n userStakingWallet[_to] = toWallet;\n }\n\n VeloAeroStakingWallet(fromWallet).withdraw(address(this), _amount);\n IERC20(stakingToken).approve(address(toWallet), _amount);\n VeloAeroStakingWallet(toWallet).stake(_to, _amount, \"\");\n emit StakingWalletTransferred(_from, _to, _amount);\n }\n\n /// @inheritdoc IStakeStrategy\n function rewardRate() external view override returns (uint256) {\n return IVeloIonModeStaking(stakingContract).rewardRate();\n }\n\n /// @inheritdoc IStakeStrategy\n function periodFinish() external view override returns (uint256) {\n return IVeloIonModeStaking(stakingContract).periodFinish();\n }\n\n /// @inheritdoc IStakeStrategy\n function balanceOf(address account) public view override returns (uint256) {\n return IVeloIonModeStaking(stakingContract).balanceOf(account);\n }\n\n /// @inheritdoc IStakeStrategy\n function totalSupply() external view override returns (uint256) {\n return IVeloIonModeStaking(stakingContract).totalSupply();\n }\n\n /// @inheritdoc IStakeStrategy\n function rewardToken() public view returns (address) {\n return IVeloIonModeStaking(stakingContract).rewardToken();\n }\n\n /// @inheritdoc IStakeStrategy\n function setEscrow(address _escrow) external onlyOwner {\n require(_escrow != address(0), \"Invalid address\");\n escrow = _escrow;\n emit EscrowSet(_escrow);\n }\n\n /// @inheritdoc IStakeStrategy\n function setStakingToken(address _stakingToken) external onlyOwner {\n require(_stakingToken != address(0), \"Invalid address\");\n stakingToken = _stakingToken;\n emit StakingTokenSet(_stakingToken);\n }\n\n /// @inheritdoc IStakeStrategy\n function setStakingContract(address _stakingContract) external onlyOwner {\n require(_stakingContract != address(0), \"Invalid address\");\n stakingContract = _stakingContract;\n emit StakingContractSet(_stakingContract);\n }\n\n /// @inheritdoc IStakeStrategy\n function setUpgradeableBeacon(address _beacon) external onlyOwner {\n require(_beacon != address(0), \"Invalid address\");\n veloAeroBeacon = UpgradeableBeacon(_beacon);\n emit UpgradeableBeaconSet(_beacon);\n }\n}\n" + }, + "contracts/src/veION/stake/velo/VeloAeroStakingWallet.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport { IStakeWallet } from \"../IStakeWallet.sol\";\nimport { IStakeStrategy } from \"../IStakeStrategy.sol\";\nimport { IVeloIonModeStaking } from \"./IVeloIonModeStaking.sol\";\nimport { IERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport { SafeERC20Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport { Initializable } from \"@openzeppelin-contracts-upgradeable/contracts/proxy/utils/Initializable.sol\";\n\n/**\n * @title VeloAeroStakingWallet\n * @notice Staking interface for usage in veION when staking Velodrome/Aerodrome style LP.\n * @dev This contract allows staking and claiming rewards with a specific staking strategy.\n * @dev The staking strategy is set during contract deployment and can only be called by the strategy.\n * @dev The contract is designed to be used with the Velodrome/Aerodrome style LP.\n * @author Jourdan Dunkley \n */\ncontract VeloAeroStakingWallet is IStakeWallet, Initializable {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n IStakeStrategy public stakeStrategy;\n\n /// @dev Modifier to restrict function access to only the stake strategy contract\n modifier onlyStakeStrategy() {\n require(msg.sender == address(stakeStrategy), \"Not authorized: Only stake strategy can call this function\");\n _;\n }\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n /**\n * @notice Initializes the contract with a staking strategy\n * @dev Can only be called once due to initializer modifier\n * @param _stakeStrategy The address of the staking strategy contract\n */\n function initialize(IStakeStrategy _stakeStrategy) external initializer {\n stakeStrategy = _stakeStrategy;\n }\n\n /// @inheritdoc IStakeWallet\n function stake(address /* _from */, uint256 _amount, bytes memory /* _data */) external override onlyStakeStrategy {\n IERC20Upgradeable stakingToken = IERC20Upgradeable(stakeStrategy.stakingToken());\n IVeloIonModeStaking stakingContract = IVeloIonModeStaking(stakeStrategy.stakingContract());\n\n stakingToken.safeTransferFrom(msg.sender, address(this), _amount);\n stakingToken.approve(address(stakingContract), _amount);\n stakingContract.deposit(_amount);\n emit Staked(_amount);\n }\n\n /// @inheritdoc IStakeWallet\n function claim(address _from) external onlyStakeStrategy {\n IERC20Upgradeable rewardToken = IERC20Upgradeable(stakeStrategy.rewardToken());\n IVeloIonModeStaking stakingContract = IVeloIonModeStaking(stakeStrategy.stakingContract());\n\n stakingContract.getReward(address(this));\n uint256 rewardAmount = rewardToken.balanceOf(address(this));\n IERC20Upgradeable(rewardToken).safeTransfer(_from, rewardAmount);\n emit Claimed(_from, rewardAmount);\n }\n\n /// @inheritdoc IStakeWallet\n function withdraw(address _withdrawTo, uint256 _amount) external onlyStakeStrategy {\n IERC20Upgradeable stakingToken = IERC20Upgradeable(stakeStrategy.stakingToken());\n IVeloIonModeStaking stakingContract = IVeloIonModeStaking(stakeStrategy.stakingContract());\n\n stakingContract.withdraw(_amount);\n stakingToken.safeTransfer(_withdrawTo, _amount);\n emit Withdrawn(_withdrawTo, _amount);\n }\n}\n" + }, + "contracts/src/veION/veION.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport { ERC721Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol\";\nimport { IveIONCore, IMasterPriceOracle, IAeroVotingEscrow, IAeroVoter } from \"./interfaces/IveIONCore.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IVoter } from \"./interfaces/IVoter.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol\";\nimport { veIONStorage } from \"./veIONStorage.sol\";\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { IAddressesProvider } from \"./interfaces/IveIONCore.sol\";\nimport { IStakeStrategy } from \"./stake/IStakeStrategy.sol\";\n\n/**\n * @title veION Contract\n * @notice This contract manages the veION framework, enabling the staking and management LP tokens for voting power.\n * @author Jourdan Dunkley (https://github.com/jourdanDunkley)\n */\ncontract veION is Ownable2StepUpgradeable, ERC721Upgradeable, ReentrancyGuardUpgradeable, veIONStorage, IveIONCore {\n using EnumerableSet for EnumerableSet.UintSet;\n using EnumerableSet for EnumerableSet.AddressSet;\n using SafeERC20 for IERC20;\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n /**\n * @notice Initializes the veION contract with the given AddressesProvider.\n * @dev This function is called only once during the contract deployment.\n * It initializes the Ownable, ERC721, and ReentrancyGuard modules.\n * @param _ap The AddressesProvider contract used for address management.\n */\n function initialize(IAddressesProvider _ap) public initializer {\n __Ownable2Step_init();\n __ERC721_init(\"veION\", \"veION\");\n __ReentrancyGuard_init();\n ap = _ap;\n emit Initialized(address(_ap));\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ External Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IveIONCore\n function createLockFor(\n address[] calldata _tokenAddress,\n uint256[] calldata _tokenAmount,\n uint256[] calldata _duration,\n bool[] memory _stakeUnderlying,\n address _to\n ) external override nonReentrant returns (uint256) {\n return _createLock(_tokenAddress, _tokenAmount, _duration, _stakeUnderlying, _to);\n }\n\n /// @inheritdoc IveIONCore\n function createLock(\n address[] calldata _tokenAddress,\n uint256[] calldata _tokenAmount,\n uint256[] calldata _duration,\n bool[] memory _stakeUnderlying\n ) external override nonReentrant returns (uint256) {\n return _createLock(_tokenAddress, _tokenAmount, _duration, _stakeUnderlying, _msgSender());\n }\n\n /// @inheritdoc IveIONCore\n function increaseAmount(\n address _tokenAddress,\n uint256 _tokenId,\n uint256 _tokenAmount,\n bool _stakeUnderlying\n ) external nonReentrant {\n LpTokenType _lpType = s_lpType[_tokenAddress];\n LockedBalance memory oldLocked = s_locked[_tokenId][_lpType];\n\n if (ownerOf(_tokenId) != _msgSender()) revert NotOwner();\n if (_tokenAmount == 0) revert ZeroAmount();\n if (oldLocked.amount == 0) revert NoLockFound();\n if (oldLocked.end <= block.timestamp && !oldLocked.isPermanent) revert LockExpired();\n\n if (oldLocked.isPermanent) s_permanentLockBalance[_lpType] += _tokenAmount;\n\n _depositFor(\n _tokenAddress,\n _tokenId,\n _tokenAmount,\n 0,\n _stakeUnderlying,\n oldLocked,\n DepositType.INCREASE_LOCK_AMOUNT,\n _lpType,\n _msgSender()\n );\n }\n\n /// @inheritdoc IveIONCore\n function lockAdditionalAsset(\n address _tokenAddress,\n uint256 _tokenAmount,\n uint256 _tokenId,\n uint256 _duration,\n bool _stakeUnderlying\n ) external nonReentrant {\n LpTokenType lpType = s_lpType[_tokenAddress];\n LockedBalance storage lockedBalance = s_locked[_tokenId][lpType];\n uint256 unlockTime = ((block.timestamp + _duration) / _WEEK) * _WEEK;\n\n if (ownerOf(_tokenId) != _msgSender()) revert NotOwner();\n if (_tokenAmount == 0) revert ZeroAmount();\n if (s_voted[_tokenId]) revert AlreadyVoted();\n if (!s_assetsLocked[_tokenId].add(_tokenAddress)) revert DuplicateAsset();\n if (_tokenAmount < s_minimumLockAmount[lpType]) revert MinimumNotMet();\n if (unlockTime > block.timestamp + _MAXTIME) revert LockDurationTooLong();\n if (_duration < s_minimumLockDuration) revert LockDurationTooShort();\n\n if (lockedBalance.isPermanent) s_permanentLockBalance[lpType] += _tokenAmount;\n\n _depositFor(\n _tokenAddress,\n _tokenId,\n _tokenAmount,\n unlockTime,\n _stakeUnderlying,\n lockedBalance,\n DepositType.LOCK_ADDITIONAL,\n lpType,\n _msgSender()\n );\n }\n\n /// @inheritdoc IveIONCore\n function increaseUnlockTime(address _tokenAddress, uint256 _tokenId, uint256 _lockDuration) external nonReentrant {\n LpTokenType _lpType = s_lpType[_tokenAddress];\n LockedBalance memory oldLocked = s_locked[_tokenId][_lpType];\n uint256 unlockTime = ((block.timestamp + _lockDuration) / _WEEK) * _WEEK; // Locktime is rounded down to weeks\n\n if (ownerOf(_tokenId) != _msgSender()) revert NotOwner();\n if (oldLocked.isPermanent) revert PermanentLock();\n if (oldLocked.end <= block.timestamp) revert LockExpired();\n if (oldLocked.amount <= 0) revert NoLockFound();\n if (unlockTime <= oldLocked.end) revert LockDurationNotInFuture();\n if (unlockTime > block.timestamp + _MAXTIME) revert LockDurationTooLong();\n\n _depositFor(\n _tokenAddress,\n _tokenId,\n 0,\n unlockTime,\n false,\n oldLocked,\n DepositType.INCREASE_UNLOCK_TIME,\n _lpType,\n _msgSender()\n );\n }\n\n /// @inheritdoc IveIONCore\n function delegate(uint256 fromTokenId, uint256 toTokenId, address lpToken, uint256 amount) external nonReentrant {\n LpTokenType lpType = s_lpType[lpToken];\n LockedBalance memory fromLocked = s_locked[fromTokenId][lpType];\n LockedBalance memory toLocked = s_locked[toTokenId][lpType];\n\n if (ownerOf(fromTokenId) != _msgSender()) revert NotOwner();\n if (amount > fromLocked.amount) revert AmountTooBig();\n if (!fromLocked.isPermanent) revert NotPermanentLock();\n if (!toLocked.isPermanent) revert NotPermanentLock();\n if (s_delegatorsBlocked[toTokenId][lpToken]) revert NotAcceptingDelegators();\n\n fromLocked.amount -= amount;\n toLocked.delegateAmount += amount;\n\n if (s_delegations[fromTokenId][toTokenId][lpType] == 0) {\n s_delegatees[fromTokenId][lpType].add(toTokenId);\n s_delegators[toTokenId][lpType].add(fromTokenId);\n }\n\n s_delegations[fromTokenId][toTokenId][lpType] += amount;\n\n s_locked[fromTokenId][lpType] = fromLocked;\n s_locked[toTokenId][lpType] = toLocked;\n _checkpoint(fromTokenId, s_locked[fromTokenId][lpType], lpType);\n _checkpoint(toTokenId, s_locked[toTokenId][lpType], lpType);\n\n if (s_voted[toTokenId]) IVoter(s_voter).poke(toTokenId);\n if (s_voted[fromTokenId]) IVoter(s_voter).poke(fromTokenId);\n\n emit Delegated(fromTokenId, toTokenId, lpToken, amount);\n }\n\n /**\n * @dev Internal function to remove a delegation between two veNFTs.\n * @param fromTokenId ID of the veNFT from which delegation is being removed.\n * @param toTokenId ID of the veNFT to which delegation is being removed.\n * @param lpToken Address of the LP token associated with the delegation.\n * @param amount Amount of delegation to remove.\n */\n function _removeDelegation(uint256 fromTokenId, uint256 toTokenId, address lpToken, uint256 amount) internal {\n LpTokenType lpType = s_lpType[lpToken];\n LockedBalance memory fromLocked = s_locked[fromTokenId][lpType];\n LockedBalance memory toLocked = s_locked[toTokenId][lpType];\n\n if (ownerOf(fromTokenId) != _msgSender() && ownerOf(toTokenId) != _msgSender()) revert NotOwner();\n if (s_delegations[fromTokenId][toTokenId][lpType] == 0) revert NoDelegationBetweenTokens(fromTokenId, toTokenId);\n\n amount = amount > s_delegations[fromTokenId][toTokenId][lpType]\n ? s_delegations[fromTokenId][toTokenId][lpType]\n : amount;\n\n toLocked.delegateAmount -= amount;\n fromLocked.amount += amount;\n\n s_delegations[fromTokenId][toTokenId][lpType] -= amount;\n if (s_delegations[fromTokenId][toTokenId][lpType] == 0) {\n s_delegatees[fromTokenId][lpType].remove(toTokenId);\n s_delegators[toTokenId][lpType].remove(fromTokenId);\n }\n\n s_locked[toTokenId][lpType] = toLocked;\n s_locked[fromTokenId][lpType] = fromLocked;\n _checkpoint(toTokenId, s_locked[toTokenId][lpType], lpType);\n _checkpoint(fromTokenId, s_locked[fromTokenId][lpType], lpType);\n\n if (s_voted[toTokenId]) IVoter(s_voter).poke(toTokenId);\n if (s_voted[fromTokenId]) IVoter(s_voter).poke(fromTokenId);\n\n emit DelegationRemoved(fromTokenId, toTokenId, lpToken, amount);\n }\n\n /// @inheritdoc IveIONCore\n function removeDelegatees(\n uint256 fromTokenId,\n uint256[] memory toTokenIds,\n address lpToken,\n uint256[] memory amounts\n ) public nonReentrant {\n if (toTokenIds.length != amounts.length) revert ArrayMismatch();\n uint256 toTokenIdsLength = toTokenIds.length;\n for (uint256 i = 0; i < toTokenIdsLength; i++) {\n _removeDelegation(fromTokenId, toTokenIds[i], lpToken, amounts[i]);\n }\n }\n\n /// @inheritdoc IveIONCore\n function removeDelegators(\n uint256[] memory fromTokenIds,\n uint256 toTokenId,\n address lpToken,\n uint256[] memory amounts\n ) external nonReentrant {\n if (fromTokenIds.length != amounts.length) revert ArrayMismatch();\n uint256 fromTokenIdsLength = fromTokenIds.length;\n for (uint256 i = 0; i < fromTokenIdsLength; i++) {\n _removeDelegation(fromTokenIds[i], toTokenId, lpToken, amounts[i]);\n }\n }\n\n /// @inheritdoc IveIONCore\n function lockPermanent(address _tokenAddress, uint256 _tokenId) external nonReentrant {\n LpTokenType _lpType = s_lpType[_tokenAddress];\n LockedBalance memory _newLocked = s_locked[_tokenId][_lpType];\n if (ownerOf(_tokenId) != _msgSender()) revert NotOwner();\n if (_newLocked.isPermanent) revert PermanentLock();\n if (_newLocked.end <= block.timestamp) revert LockExpired();\n if (_newLocked.amount <= 0) revert NoLockFound();\n\n s_permanentLockBalance[_lpType] += _newLocked.amount;\n _newLocked.end = 0;\n _newLocked.isPermanent = true;\n _newLocked.boost = _calculateBoost(_MAXTIME);\n\n s_locked[_tokenId][_lpType] = _newLocked;\n _checkpoint(_tokenId, _newLocked, _lpType);\n\n emit PermanentLockCreated(_tokenAddress, _tokenId, _newLocked.amount);\n }\n\n /// @inheritdoc IveIONCore\n function unlockPermanent(address _tokenAddress, uint256 _tokenId) external nonReentrant {\n LpTokenType _lpType = s_lpType[_tokenAddress];\n LockedBalance memory _newLocked = s_locked[_tokenId][_lpType];\n if (ownerOf(_tokenId) != _msgSender()) revert NotOwner();\n if (!_newLocked.isPermanent) revert NotPermanentLock();\n if (s_delegatees[_tokenId][_lpType].length() != 0) revert TokenHasDelegatees();\n if (s_delegators[_tokenId][_lpType].length() != 0) revert TokenHasDelegators();\n\n s_permanentLockBalance[_lpType] -= _newLocked.amount;\n _newLocked.end = ((block.timestamp + _MAXTIME) / _WEEK) * _WEEK;\n _newLocked.isPermanent = false;\n\n s_locked[_tokenId][_lpType] = _newLocked;\n _checkpoint(_tokenId, _newLocked, _lpType);\n\n emit PermanentLockRemoved(_tokenAddress, _tokenId, _newLocked.amount);\n }\n\n /**\n * @notice Overrides the _burn function from ERC721 to include additional logic for bridging.\n * @param tokenId Token ID to burn.\n */\n function _burn(uint256 tokenId) internal override {\n super._burn(tokenId);\n }\n\n /**\n * @notice Hook that is called before any token transfer. This includes minting\n * and burning. It updates the ownership mappings and handles delegation and\n * staking logic when transferring tokens between addresses.\n *\n * @param from The address which previously owned the token.\n * @param to The address that will receive the token.\n * @param tokenId The ID of the token being transferred.\n */\n function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override {\n super._beforeTokenTransfer(from, to, tokenId);\n\n if (from != address(0)) s_ownerToTokenIds[from].remove(tokenId);\n if (to != address(0)) s_ownerToTokenIds[to].add(tokenId);\n\n if (from != address(0) && to != address(0)) {\n address[] memory assetsLocked = s_assetsLocked[tokenId].values();\n uint256 assetsLockedLength = assetsLocked.length;\n for (uint256 i = 0; i < assetsLockedLength; i++) {\n address asset = assetsLocked[i];\n LpTokenType _lpType = s_lpType[asset];\n\n uint256[] memory delegatees = s_delegatees[tokenId][_lpType].values();\n uint256[] memory amounts = new uint256[](delegatees.length);\n uint256 delegateesLength = delegatees.length;\n for (uint256 j = 0; j < delegateesLength; j++) {\n amounts[j] = type(uint256).max;\n }\n\n if (delegateesLength != 0) {\n removeDelegatees(tokenId, delegatees, asset, amounts);\n }\n\n uint256 amountStaked = s_underlyingStake[tokenId][asset];\n if (amountStaked != 0) {\n IStakeStrategy _stakeStrategy = s_stakeStrategy[_lpType];\n _stakeStrategy.transferStakingWallet(from, to, amountStaked);\n }\n\n LockedBalance memory lock = s_locked[tokenId][_lpType];\n s_userCumulativeAssetValues[from][asset] -= lock.amount;\n s_userCumulativeAssetValues[to][asset] += lock.amount;\n }\n }\n }\n\n /// @inheritdoc IveIONCore\n function voting(uint256 _tokenId, bool _voting) external {\n if (_msgSender() != s_voter) revert NotVoter();\n s_voted[_tokenId] = _voting;\n emit Voted(_tokenId, _voting);\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Internal Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n struct DepositVars {\n uint256 supplyBefore;\n uint256 totalLockTime;\n LockedBalance newLocked;\n address from;\n }\n\n /**\n * @notice Deposits tokens for a specific veNFT, updating its locked balance and boost.\n * @dev This function handles the deposit logic for veNFTs, including updating the locked balance,\n * calculating the boost based on the lock duration, and transferring tokens.\n * @param _tokenAddress The address of the token to deposit.\n * @param _tokenId The ID of the veNFT to deposit tokens for.\n * @param _tokenAmount The amount of tokens to deposit.\n * @param _unlockTime The time at which the lock will expire.\n * @param _stakeUnderlying A boolean indicating whether to stake the underlying tokens.\n * @param _oldLocked The previous locked balance of the veNFT.\n * @param _depositType The type of deposit being made.\n * @param _lpType The LP token type associated with the deposit.\n * @param _to The address to which the veNFT is assigned.\n */\n function _depositFor(\n address _tokenAddress,\n uint256 _tokenId,\n uint256 _tokenAmount,\n uint256 _unlockTime,\n bool _stakeUnderlying,\n LockedBalance memory _oldLocked,\n DepositType _depositType,\n LpTokenType _lpType,\n address _to\n ) internal {\n if (!s_whitelistedToken[_tokenAddress]) revert TokenNotWhitelisted();\n\n DepositVars memory vars;\n vars.supplyBefore = s_supply[_lpType];\n s_supply[_lpType] = vars.supplyBefore + _tokenAmount;\n\n (\n vars.newLocked.tokenAddress,\n vars.newLocked.amount,\n vars.newLocked.start,\n vars.newLocked.end,\n vars.newLocked.isPermanent,\n vars.newLocked.boost\n ) = (\n _oldLocked.tokenAddress,\n _oldLocked.amount,\n _oldLocked.start,\n _oldLocked.end,\n _oldLocked.isPermanent,\n _oldLocked.boost\n );\n\n vars.newLocked.tokenAddress = _tokenAddress;\n vars.newLocked.amount += _tokenAmount;\n if (_unlockTime != 0) {\n if (vars.newLocked.start == 0) vars.newLocked.start = block.timestamp;\n vars.newLocked.end = _unlockTime;\n vars.totalLockTime = vars.newLocked.end - vars.newLocked.start;\n vars.newLocked.boost = _calculateBoost(vars.totalLockTime);\n }\n s_locked[_tokenId][_lpType] = vars.newLocked;\n\n _checkpoint(_tokenId, vars.newLocked, _lpType);\n\n vars.from = _msgSender();\n if (_tokenAmount != 0) {\n s_userCumulativeAssetValues[ownerOf(_tokenId)][_tokenAddress] += _tokenAmount;\n IERC20(_tokenAddress).safeTransferFrom(vars.from, address(this), _tokenAmount);\n (IStakeStrategy _stakeStrategy, bytes memory _stakeData) = _getStakeStrategy(_lpType);\n if (address(_stakeStrategy) != address(0) && _stakeUnderlying) {\n _handleTokenStake(_to, _tokenId, _tokenAddress, _tokenAmount, _stakeStrategy, _stakeData);\n }\n }\n\n emit Deposit(_to, _tokenId, _depositType, _tokenAmount, vars.newLocked.end, block.timestamp);\n emit Supply(vars.supplyBefore, s_supply[_lpType]);\n }\n\n /**\n * @notice Handles the staking of tokens using a specified staking strategy.\n * @param _to The address to which the stake is attributed.\n * @param _tokenId The ID of the token being staked.\n * @param _tokenAddress The address of the token being staked.\n * @param _tokenAmount The amount of tokens to stake.\n * @param _stakeStrategy The staking strategy to use.\n * @param _stakeData Additional data required for staking.\n */\n function _handleTokenStake(\n address _to,\n uint256 _tokenId,\n address _tokenAddress,\n uint256 _tokenAmount,\n IStakeStrategy _stakeStrategy,\n bytes memory _stakeData\n ) internal {\n IERC20(_tokenAddress).approve(address(_stakeStrategy), _tokenAmount);\n _stakeStrategy.stake(_to, _tokenAmount, _stakeData);\n s_underlyingStake[_tokenId][_tokenAddress] += _tokenAmount;\n }\n\n /**\n * @notice Updates the user point history and epoch for a given token and LP token type.\n * @param _tokenId The ID of the token.\n * @param _newLocked The new locked balance information.\n * @param _lpType The LP token type.\n */\n function _checkpoint(uint256 _tokenId, LockedBalance memory _newLocked, LpTokenType _lpType) internal {\n UserPoint memory uNew;\n uNew.permanent = _newLocked.isPermanent ? _newLocked.amount : 0;\n uNew.permanentDelegate = _newLocked.isPermanent ? _newLocked.delegateAmount : 0;\n\n if (_newLocked.end > block.timestamp && _newLocked.amount > 0) {\n uNew.slope = _newLocked.amount / _MAXTIME;\n uNew.bias = uNew.slope * (_newLocked.end - block.timestamp);\n }\n\n uNew.ts = block.timestamp;\n uNew.blk = block.number;\n uint256 userEpoch = s_userPointEpoch[_tokenId][_lpType];\n if (userEpoch != 0 && s_userPointHistory[_tokenId][_lpType][userEpoch].ts == block.timestamp) {\n s_userPointHistory[_tokenId][_lpType][userEpoch] = uNew;\n } else {\n s_userPointEpoch[_tokenId][_lpType] = ++userEpoch;\n s_userPointHistory[_tokenId][_lpType][userEpoch] = uNew;\n }\n }\n\n /**\n * @notice Creates a lock for multiple tokens with specified durations and staking options.\n * @param _tokenAddress Array of token addresses to lock.\n * @param _tokenAmount Array of token amounts to lock.\n * @param _duration Array of durations for each lock.\n * @param _stakeUnderlying Array of booleans indicating whether to stake the underlying tokens.\n * @param _to The address to which the lock is attributed.\n * @return The ID of the newly created lock.\n */\n function _createLock(\n address[] memory _tokenAddress,\n uint256[] memory _tokenAmount,\n uint256[] memory _duration,\n bool[] memory _stakeUnderlying,\n address _to\n ) internal returns (uint256) {\n uint256 _tokenId = ++s_tokenId;\n uint256 _length = _tokenAddress.length;\n _safeMint(_to, _tokenId);\n\n if (\n _tokenAddress.length != _tokenAmount.length ||\n _tokenAmount.length != _duration.length ||\n _duration.length != _stakeUnderlying.length\n ) {\n revert ArrayMismatch();\n }\n\n for (uint256 i = 0; i < _length; i++) {\n LpTokenType _lpType = s_lpType[_tokenAddress[i]];\n uint256 unlockTime = ((block.timestamp + _duration[i]) / _WEEK) * _WEEK;\n\n if (!s_assetsLocked[_tokenId].add(_tokenAddress[i])) revert DuplicateAsset();\n if (_tokenAmount[i] == 0) revert ZeroAmount();\n if (_duration[i] < s_minimumLockDuration) revert LockDurationTooShort();\n if (unlockTime > block.timestamp + _MAXTIME) revert LockDurationTooLong();\n if (_tokenAmount[i] < s_minimumLockAmount[_lpType]) revert MinimumNotMet();\n\n _depositFor(\n _tokenAddress[i],\n _tokenId,\n _tokenAmount[i],\n unlockTime,\n _stakeUnderlying[i],\n s_locked[_tokenId][_lpType],\n DepositType.CREATE_LOCK_TYPE,\n _lpType,\n _to\n );\n }\n return _tokenId;\n }\n\n /**\n * @notice Calculates the boost for a given lock duration.\n * @param _duration The duration of the lock.\n * @return The calculated boost value.\n */\n function _calculateBoost(uint256 _duration) internal view returns (uint256) {\n uint256 minDuration = s_minimumLockDuration;\n uint256 maxDuration = _MAXTIME;\n uint256 minBoost = 1e18;\n uint256 maxBoost = 2e18;\n\n if (_duration <= minDuration) {\n return minBoost;\n } else if (_duration >= maxDuration) {\n return maxBoost;\n } else {\n return minBoost + ((_duration - minDuration) * (maxBoost - minBoost)) / (maxDuration - minDuration);\n }\n }\n\n /**\n * @notice Retrieves the staking strategy and data for a given LP token type.\n * @param _lpType The LP token type.\n * @return _stakeStrategy The staking strategy for the LP token type.\n * @return _stakeData The staking data for the LP token type.\n */\n function _getStakeStrategy(\n LpTokenType _lpType\n ) internal view returns (IStakeStrategy _stakeStrategy, bytes memory _stakeData) {\n IStakeStrategy strategy = s_stakeStrategy[_lpType];\n return (strategy, \"\");\n }\n\n /// @inheritdoc IveIONCore\n function setExtensions(address _veIONFirstExtension, address _veIONSecondExtension) external onlyOwner {\n require(_veIONFirstExtension != address(0), \"Invalid First Extension Address\");\n require(_veIONSecondExtension != address(0), \"Invalid Second Extension Address\");\n require(_veIONFirstExtension != _veIONSecondExtension, \"Submitted Identical Addresses\");\n veIONFirstExtension = _veIONFirstExtension;\n veIONSecondExtension = _veIONSecondExtension;\n emit ExtensionsSet(_veIONFirstExtension, _veIONSecondExtension);\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external {\n address impl = veIONFirstExtension;\n require(impl != address(0), \"Implementation not set\");\n\n assembly {\n calldatacopy(0, 0, calldatasize())\n\n let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)\n\n returndatacopy(0, 0, returndatasize())\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n}\n" + }, + "contracts/src/veION/veIONFirstExtension.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport { ERC721Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol\";\nimport { IMasterPriceOracle, IAeroVotingEscrow, IAeroVoter } from \"./interfaces/IveIONCore.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IVoter } from \"./interfaces/IVoter.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol\";\nimport { veIONStorage } from \"./veIONStorage.sol\";\nimport { BalanceLogicLibrary } from \"./libraries/BalanceLogicLibrary.sol\";\nimport { IveIONFirstExtension } from \"./interfaces/IveIONFirstExtension.sol\";\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { IAddressesProvider } from \"./interfaces/IveIONCore.sol\";\nimport { IStakeStrategy } from \"./stake/IStakeStrategy.sol\";\n\n/**\n * @title veION Contract First Extensions\n * @notice This contract manages the veION framework, enabling the staking and management LP tokens for voting power.\n * @author Jourdan Dunkley (https://github.com/jourdanDunkley)\n */\ncontract veIONFirstExtension is\n Ownable2StepUpgradeable,\n ERC721Upgradeable,\n ReentrancyGuardUpgradeable,\n veIONStorage,\n IveIONFirstExtension\n{\n using EnumerableSet for EnumerableSet.UintSet;\n using EnumerableSet for EnumerableSet.AddressSet;\n using SafeERC20 for IERC20;\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ External Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IveIONFirstExtension\n function withdraw(address _tokenAddress, uint256 _tokenId) external nonReentrant {\n address sender = _msgSender();\n LpTokenType _lpType = s_lpType[_tokenAddress];\n LockedBalance memory oldLocked = s_locked[_tokenId][_lpType];\n\n if (ownerOf(_tokenId) != _msgSender()) revert NotOwner();\n if (s_voted[_tokenId]) revert AlreadyVoted();\n if (oldLocked.isPermanent) revert PermanentLock();\n if (!s_whitelistedToken[_tokenAddress]) revert TokenNotWhitelisted();\n if (oldLocked.amount == 0 || !s_assetsLocked[_tokenId].contains(_tokenAddress)) revert NoLockFound();\n\n uint256 value = oldLocked.amount;\n s_userCumulativeAssetValues[sender][_tokenAddress] -= value;\n uint256 fee = 0;\n\n if (block.timestamp < oldLocked.end) {\n uint256 daysLocked = ((oldLocked.end - oldLocked.start) * 1e18) / 1 days;\n uint256 daysLeft = ((oldLocked.end - block.timestamp) * 1e18) / 1 days;\n uint256 timeFactor = (daysLeft * 1e18) / daysLocked;\n uint256 veLPLocked = s_supply[_lpType];\n uint256 LPInCirculation = IERC20(_tokenAddress).totalSupply();\n uint256 ratioFactor = 1e18 - (veLPLocked * 1e18) / LPInCirculation;\n fee = (timeFactor * ratioFactor * oldLocked.boost) / 1e36;\n if (fee > s_maxEarlyWithdrawFee) fee = s_maxEarlyWithdrawFee;\n fee = (value * fee) / 1e18;\n value -= fee;\n\n uint256 feeToDistribute = (fee * 75) / 100;\n uint256 feeToProtocol = fee - feeToDistribute;\n s_protocolFees[_lpType] += feeToProtocol;\n s_distributedFees[_lpType] += feeToDistribute;\n }\n\n s_locked[_tokenId][_lpType] = LockedBalance(address(0), 0, 0, 0, 0, false, 0);\n s_assetsLocked[_tokenId].remove(_tokenAddress);\n uint256 supplyBefore = s_supply[_lpType];\n\n uint256 amountStaked = s_underlyingStake[_tokenId][_tokenAddress];\n if (amountStaked != 0) {\n (IStakeStrategy _stakeStrategy, ) = _getStakeStrategy(_lpType);\n if (address(_stakeStrategy) != address(0)) {\n _handleTokenWithdrawStake(sender, address(this), _tokenId, _tokenAddress, amountStaked, _stakeStrategy);\n }\n }\n\n s_supply[_lpType] = supplyBefore - oldLocked.amount;\n _checkpoint(_tokenId, LockedBalance(address(0), 0, 0, 0, 0, false, 0), _lpType);\n\n // Check if all LP types for this token have zero balance\n bool shouldBurn = true;\n address[] memory lockedAssets = s_assetsLocked[_tokenId].values();\n uint256 lockedAssetsLength = lockedAssets.length;\n for (uint256 i = 0; i < lockedAssetsLength; i++) {\n LpTokenType assetLpType = s_lpType[lockedAssets[i]];\n if (s_locked[_tokenId][assetLpType].amount > 0) {\n shouldBurn = false;\n break;\n }\n }\n\n if (shouldBurn) _burn(_tokenId);\n\n IERC20(_tokenAddress).safeTransfer(sender, value);\n emit Withdraw(sender, _tokenId, value, block.timestamp);\n emit Supply(supplyBefore, supplyBefore - oldLocked.amount);\n }\n\n /// @inheritdoc IveIONFirstExtension\n function merge(uint256 _from, uint256 _to) external nonReentrant {\n if (_from == _to) revert SameNFT();\n if (s_voted[_from] || s_voted[_to]) revert AlreadyVoted();\n if (ownerOf(_from) != _msgSender()) revert NotOwner();\n if (ownerOf(_to) != _msgSender()) revert NotOwner();\n\n address[] memory assetsLocked = s_assetsLocked[_from].values();\n uint256 assetsLockedLength = assetsLocked.length;\n for (uint256 i = 0; i < assetsLockedLength; i++) {\n address asset = assetsLocked[i];\n LpTokenType lpType = s_lpType[asset];\n\n LockedBalance memory oldLockedTo = s_locked[_to][lpType];\n LockedBalance memory oldLockedFrom = s_locked[_from][lpType];\n\n if (oldLockedTo.end != 0 && oldLockedTo.end <= block.timestamp) revert LockExpired();\n if (oldLockedFrom.end != 0 && oldLockedFrom.end <= block.timestamp) revert LockExpired();\n if (oldLockedFrom.isPermanent) revert PermanentLock();\n if (oldLockedTo.isPermanent) revert PermanentLock();\n\n LockedBalance memory newLockedTo;\n\n newLockedTo.tokenAddress = asset;\n newLockedTo.amount = oldLockedTo.amount + oldLockedFrom.amount;\n newLockedTo.start = oldLockedTo.start < oldLockedFrom.start && oldLockedTo.start != 0\n ? oldLockedTo.start\n : oldLockedFrom.start;\n newLockedTo.end = oldLockedTo.end > oldLockedFrom.end ? oldLockedTo.end : oldLockedFrom.end;\n newLockedTo.boost = _calculateBoost(newLockedTo.end - newLockedTo.start);\n\n s_locked[_from][lpType] = LockedBalance(address(0), 0, 0, 0, 0, false, 0);\n _checkpoint(_from, LockedBalance(address(0), 0, 0, 0, 0, false, 0), lpType);\n s_locked[_to][lpType] = newLockedTo;\n _checkpoint(_to, newLockedTo, lpType);\n\n s_assetsLocked[_from].remove(asset);\n if (!s_assetsLocked[_to].contains(asset)) {\n s_assetsLocked[_to].add(asset);\n }\n\n if (s_underlyingStake[_from][asset] != 0) {\n s_underlyingStake[_to][asset] += s_underlyingStake[_from][asset];\n s_underlyingStake[_from][asset] = 0;\n }\n }\n _burn(_from);\n emit MergeCompleted(_from, _to, assetsLocked, assetsLocked.length);\n }\n\n /// @inheritdoc IveIONFirstExtension\n function split(\n address _tokenAddress,\n uint256 _from,\n uint256 _splitAmount\n ) external nonReentrant returns (uint256 _tokenId1, uint256 _tokenId2) {\n address ownerFrom = _ownerOf(_from);\n LpTokenType _lpType = s_lpType[_tokenAddress];\n LockedBalance memory oldLocked = s_locked[_from][_lpType];\n uint256 minimumLockAmount = s_minimumLockAmount[_lpType];\n\n if (s_voted[_from]) revert AlreadyVoted();\n if (!s_canSplit[ownerFrom] && !s_canSplit[address(0)]) revert SplitNotAllowed();\n if (ownerFrom != _msgSender()) revert NotOwner();\n if (oldLocked.end <= block.timestamp && !oldLocked.isPermanent) revert LockExpired();\n if (_splitAmount >= oldLocked.amount) revert AmountTooBig();\n if (_splitAmount < minimumLockAmount) revert SplitTooSmall();\n if (oldLocked.amount - _splitAmount < minimumLockAmount) revert NotEnoughRemainingAfterSplit();\n\n LockedBalance memory oldLockedTemp = oldLocked;\n\n oldLocked.amount -= _splitAmount;\n s_locked[_from][_lpType] = oldLocked;\n _checkpoint(_from, oldLocked, _lpType);\n\n LockedBalance memory splitLocked = oldLockedTemp;\n splitLocked.amount = _splitAmount;\n _tokenId2 = _createSplitVE(ownerFrom, splitLocked, _lpType, _tokenAddress);\n _tokenId1 = _from;\n\n if (s_underlyingStake[_from][_tokenAddress] != 0) {\n s_underlyingStake[_from][_tokenAddress] -= _splitAmount;\n s_underlyingStake[_tokenId2][_tokenAddress] = _splitAmount;\n }\n\n emit SplitCompleted(_from, _tokenId1, _tokenId2, _splitAmount, _tokenAddress);\n }\n\n /// @inheritdoc IveIONFirstExtension\n function claimEmissions(address _tokenAddress) external nonReentrant {\n LpTokenType _lpType = s_lpType[_tokenAddress];\n IStakeStrategy _stakeStrategy = s_stakeStrategy[_lpType];\n if (_stakeStrategy.userStakingWallet(_msgSender()) == address(0)) revert NoUnderlyingStake();\n _stakeStrategy.claim(_msgSender());\n emit EmissionsClaimed(_msgSender(), _tokenAddress);\n }\n\n /**\n * @notice Overrides the _burn function from ERC721 to include additional logic for bridging.\n * @param tokenId Token ID to burn.\n */\n function _burn(uint256 tokenId) internal override {\n super._burn(tokenId);\n }\n\n /**\n * @notice Hook that is called before any token transfer. This includes minting\n * and burning. It updates the ownership mappings and handles delegation and\n * staking logic when transferring tokens between addresses.\n *\n * @param from The address which previously owned the token.\n * @param to The address that will receive the token.\n * @param tokenId The ID of the token being transferred.\n */\n function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override {\n super._beforeTokenTransfer(from, to, tokenId);\n\n if (from != address(0)) s_ownerToTokenIds[from].remove(tokenId);\n if (to != address(0)) s_ownerToTokenIds[to].add(tokenId);\n\n if (from != address(0) && to != address(0)) {\n address[] memory assetsLocked = s_assetsLocked[tokenId].values();\n uint256 assetsLockedLength = assetsLocked.length;\n for (uint256 i = 0; i < assetsLockedLength; i++) {\n address asset = assetsLocked[i];\n LpTokenType _lpType = s_lpType[asset];\n\n uint256[] memory delegatees = s_delegatees[tokenId][_lpType].values();\n uint256[] memory amounts = new uint256[](delegatees.length);\n uint256 delegateesLength = delegatees.length;\n for (uint256 j = 0; j < delegateesLength; j++) {\n amounts[j] = type(uint256).max;\n }\n\n if (delegateesLength != 0) {\n removeDelegatees(tokenId, delegatees, asset, amounts);\n }\n\n uint256 amountStaked = s_underlyingStake[tokenId][asset];\n if (amountStaked != 0) {\n IStakeStrategy _stakeStrategy = s_stakeStrategy[_lpType];\n _stakeStrategy.transferStakingWallet(from, to, amountStaked);\n }\n\n LockedBalance memory lock = s_locked[tokenId][_lpType];\n s_userCumulativeAssetValues[from][asset] -= lock.amount;\n s_userCumulativeAssetValues[to][asset] += lock.amount;\n }\n }\n }\n\n /**\n * @dev Internal function to remove a delegation between two veNFTs.\n * @param fromTokenId ID of the veNFT from which delegation is being removed.\n * @param toTokenId ID of the veNFT to which delegation is being removed.\n * @param lpToken Address of the LP token associated with the delegation.\n * @param amount Amount of delegation to remove.\n */\n function _removeDelegation(uint256 fromTokenId, uint256 toTokenId, address lpToken, uint256 amount) internal {\n LpTokenType lpType = s_lpType[lpToken];\n LockedBalance memory fromLocked = s_locked[fromTokenId][lpType];\n LockedBalance memory toLocked = s_locked[toTokenId][lpType];\n\n if (ownerOf(fromTokenId) != _msgSender() && ownerOf(toTokenId) != _msgSender()) revert NotOwner();\n if (s_delegations[fromTokenId][toTokenId][lpType] == 0) revert NoDelegationBetweenTokens(fromTokenId, toTokenId);\n\n amount = amount > s_delegations[fromTokenId][toTokenId][lpType]\n ? s_delegations[fromTokenId][toTokenId][lpType]\n : amount;\n\n toLocked.delegateAmount -= amount;\n fromLocked.amount += amount;\n\n s_delegations[fromTokenId][toTokenId][lpType] -= amount;\n if (s_delegations[fromTokenId][toTokenId][lpType] == 0) {\n s_delegatees[fromTokenId][lpType].remove(toTokenId);\n s_delegators[toTokenId][lpType].remove(fromTokenId);\n }\n\n s_locked[toTokenId][lpType] = toLocked;\n s_locked[fromTokenId][lpType] = fromLocked;\n _checkpoint(toTokenId, s_locked[toTokenId][lpType], lpType);\n _checkpoint(fromTokenId, s_locked[fromTokenId][lpType], lpType);\n\n if (s_voted[toTokenId]) IVoter(s_voter).poke(toTokenId);\n if (s_voted[fromTokenId]) IVoter(s_voter).poke(fromTokenId);\n\n emit DelegationRemoved(fromTokenId, toTokenId, lpToken, amount);\n }\n\n /**\n * @notice Removes delegatees from a specific veNFT\n * @param fromTokenId ID of the veNFT from which delegatees are removed\n * @param toTokenIds Array of veNFT IDs that are delegatees to be removed\n * @param lpToken Address of the LP token associated with the delegation\n * @param amounts Array of amounts of voting power to remove from each delegatee\n */\n function removeDelegatees(\n uint256 fromTokenId,\n uint256[] memory toTokenIds,\n address lpToken,\n uint256[] memory amounts\n ) public nonReentrant {\n if (toTokenIds.length != amounts.length) revert ArrayMismatch();\n uint256 toTokenIdsLength = toTokenIds.length;\n for (uint256 i = 0; i < toTokenIdsLength; i++) {\n _removeDelegation(fromTokenId, toTokenIds[i], lpToken, amounts[i]);\n }\n }\n\n /// @inheritdoc IveIONFirstExtension\n function allowDelegators(uint256 _tokenId, address _tokenAddress, bool _blocked) external nonReentrant {\n if (ownerOf(_tokenId) != _msgSender()) revert NotOwner();\n s_delegatorsBlocked[_tokenId][_tokenAddress] = _blocked;\n emit DelegatorsBlocked(_tokenId, _tokenAddress, _blocked);\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Internal Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /**\n * @notice Handles the withdrawal of staked tokens using a specified staking strategy.\n * @param _owner The address of the owner of the stake.\n * @param _withdrawTo The address to which the withdrawn tokens are sent.\n * @param _tokenId The ID of the token being withdrawn.\n * @param _tokenAddress The address of the token being withdrawn.\n * @param _tokenAmount The amount of tokens to withdraw.\n * @param _stakeStrategy The staking strategy to use for withdrawal.\n */\n function _handleTokenWithdrawStake(\n address _owner,\n address _withdrawTo,\n uint256 _tokenId,\n address _tokenAddress,\n uint256 _tokenAmount,\n IStakeStrategy _stakeStrategy\n ) internal {\n _stakeStrategy.claim(_owner);\n _stakeStrategy.withdraw(_owner, _withdrawTo, _tokenAmount);\n s_underlyingStake[_tokenId][_tokenAddress] -= _tokenAmount;\n }\n\n /**\n * @notice Updates the user point history and epoch for a given token and LP token type.\n * @param _tokenId The ID of the token.\n * @param _newLocked The new locked balance information.\n * @param _lpType The LP token type.\n */\n function _checkpoint(uint256 _tokenId, LockedBalance memory _newLocked, LpTokenType _lpType) internal {\n UserPoint memory uNew;\n uNew.permanent = _newLocked.isPermanent ? _newLocked.amount : 0;\n uNew.permanentDelegate = _newLocked.isPermanent ? _newLocked.delegateAmount : 0;\n\n if (_newLocked.end > block.timestamp && _newLocked.amount > 0) {\n uNew.slope = _newLocked.amount / _MAXTIME;\n uNew.bias = uNew.slope * (_newLocked.end - block.timestamp);\n }\n\n uNew.ts = block.timestamp;\n uNew.blk = block.number;\n uint256 userEpoch = s_userPointEpoch[_tokenId][_lpType];\n if (userEpoch != 0 && s_userPointHistory[_tokenId][_lpType][userEpoch].ts == block.timestamp) {\n s_userPointHistory[_tokenId][_lpType][userEpoch] = uNew;\n } else {\n s_userPointEpoch[_tokenId][_lpType] = ++userEpoch;\n s_userPointHistory[_tokenId][_lpType][userEpoch] = uNew;\n }\n }\n\n /**\n * @notice Calculates the boost for a given lock duration.\n * @param _duration The duration of the lock.\n * @return The calculated boost value.\n */\n function _calculateBoost(uint256 _duration) internal view returns (uint256) {\n uint256 minDuration = s_minimumLockDuration;\n uint256 maxDuration = _MAXTIME;\n uint256 minBoost = 1e18;\n uint256 maxBoost = 2e18;\n\n if (_duration <= minDuration) {\n return minBoost;\n } else if (_duration >= maxDuration) {\n return maxBoost;\n } else {\n return minBoost + ((_duration - minDuration) * (maxBoost - minBoost)) / (maxDuration - minDuration);\n }\n }\n\n /**\n * @notice Creates a new split veNFT with specified locked balance and LP token type.\n * @param _to The address to which the new veNFT is attributed.\n * @param _newLocked The locked balance information for the new veNFT.\n * @param _lpType The LP token type.\n * @param _tokenAddress The address of the token being locked.\n * @return _tokenId The ID of the newly created veNFT.\n */\n function _createSplitVE(\n address _to,\n LockedBalance memory _newLocked,\n LpTokenType _lpType,\n address _tokenAddress\n ) private returns (uint256 _tokenId) {\n _tokenId = ++s_tokenId;\n _safeMint(_to, _tokenId);\n s_locked[_tokenId][_lpType] = _newLocked;\n s_assetsLocked[_tokenId].add(_tokenAddress);\n _checkpoint(_tokenId, _newLocked, _lpType);\n }\n\n /**\n * @notice Retrieves the staking strategy and data for a given LP token type.\n * @param _lpType The LP token type.\n * @return _stakeStrategy The staking strategy for the LP token type.\n * @return _stakeData The staking data for the LP token type.\n */\n function _getStakeStrategy(\n LpTokenType _lpType\n ) internal view returns (IStakeStrategy _stakeStrategy, bytes memory _stakeData) {\n IStakeStrategy strategy = s_stakeStrategy[_lpType];\n return (strategy, \"\");\n }\n\n /**\n * @notice Calculates the total boost for a given token ID and LP token type.\n * @param _tokenId The ID of the token.\n * @param _lpType The LP token type.\n * @return The total boost value.\n */\n function _getTotalBoost(uint256 _tokenId, LpTokenType _lpType) internal view returns (uint256) {\n uint256 totalBoost = s_locked[_tokenId][_lpType].boost;\n if (s_limitedBoostActive) totalBoost += s_limitedBoost;\n if (s_veAERO == address(0)) return totalBoost;\n\n address _owner = ownerOf(_tokenId);\n IAeroVoter aeroVoter = IAeroVoter(s_aeroVoting);\n IAeroVotingEscrow veAERO = IAeroVotingEscrow(s_veAERO);\n uint256 _balance = veAERO.balanceOf(_owner);\n for (uint256 i = 0; i < _balance; i++) {\n uint256 veAeroTokenId = veAERO.ownerToNFTokenIdList(_owner, i);\n uint256 weightToVoteRatio = (aeroVoter.votes(veAeroTokenId, s_ionicPool) * 1e18) / aeroVoter.weights(s_ionicPool);\n totalBoost += (s_aeroVoterBoost * weightToVoteRatio) / 1e18;\n }\n\n return totalBoost;\n }\n\n /**\n * @notice Retrieves the ETH price of a given token.\n * @dev Uses the MasterPriceOracle to fetch the price.\n * @param _token The address of the token for which the ETH price is requested.\n * @return The ETH price of the specified token.\n */\n function _getEthPrice(address _token) internal view returns (uint256) {\n IMasterPriceOracle mpo = IMasterPriceOracle(ap.getAddress(\"MasterPriceOracle\"));\n return mpo.price(_token);\n }\n\n // // ╔═══════════════════════════════════════════════════════════════════════════╗\n // // ║ View Functions ║\n // // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IveIONFirstExtension\n function balanceOfNFT(\n uint256 _tokenId\n ) public view returns (address[] memory _assets, uint256[] memory _balances, uint256[] memory _boosts) {\n address[] memory assetsLocked = s_assetsLocked[_tokenId].values();\n\n _assets = new address[](assetsLocked.length);\n _balances = new uint256[](assetsLocked.length);\n _boosts = new uint256[](assetsLocked.length);\n uint256 assetsLockedLength = assetsLocked.length;\n for (uint256 i = 0; i < assetsLockedLength; i++) {\n address asset = assetsLocked[i];\n LpTokenType lpType = s_lpType[asset];\n LockedBalance memory lockedBalance = s_locked[_tokenId][lpType];\n _boosts[i] = _getTotalBoost(_tokenId, lpType);\n _assets[i] = asset;\n _balances[i] = BalanceLogicLibrary.balanceOfNFTAt(\n s_userPointEpoch,\n s_userPointHistory,\n lpType,\n _tokenId,\n block.timestamp,\n lockedBalance.isPermanent\n );\n }\n\n return (_assets, _balances, _boosts);\n }\n\n /// @inheritdoc IveIONFirstExtension\n function getTotalEthValueOfTokens(address _owner) external view returns (uint256 totalValue) {\n IVoter voter = IVoter(s_voter);\n address[] memory lpTokens = voter.getAllLpRewardTokens();\n uint256 lpTokensLength = lpTokens.length;\n for (uint256 i = 0; i < lpTokensLength; i++) {\n uint256 ethValue = (s_userCumulativeAssetValues[_owner][lpTokens[i]] * _getEthPrice(lpTokens[i])) / PRECISION;\n totalValue += ethValue;\n }\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external {\n address impl = veIONSecondExtension;\n require(impl != address(0), \"Implementation not set\");\n\n assembly {\n calldatacopy(0, 0, calldatasize())\n\n let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)\n\n returndatacopy(0, 0, returndatasize())\n switch result\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n}\n" + }, + "contracts/src/veION/veIONSecondExtension.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport { ERC721Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol\";\nimport { IMasterPriceOracle, IAeroVotingEscrow, IAeroVoter } from \"./interfaces/IveIONCore.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IVoter } from \"./interfaces/IVoter.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol\";\nimport { veIONStorage } from \"./veIONStorage.sol\";\nimport { BalanceLogicLibrary } from \"./libraries/BalanceLogicLibrary.sol\";\nimport { IveIONSecondExtension } from \"./interfaces/IveIONSecondExtension.sol\";\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { IAddressesProvider } from \"./interfaces/IveIONCore.sol\";\nimport { IStakeStrategy } from \"./stake/IStakeStrategy.sol\";\n\n/**\n * @title veION Contract Second Extension\n * @notice This contract manages the veION framework, enabling the staking and management LP tokens for voting power.\n * @author Jourdan Dunkley (https://github.com/jourdanDunkley)\n */\ncontract veIONSecondExtension is\n Ownable2StepUpgradeable,\n ERC721Upgradeable,\n ReentrancyGuardUpgradeable,\n veIONStorage,\n IveIONSecondExtension\n{\n using EnumerableSet for EnumerableSet.UintSet;\n using EnumerableSet for EnumerableSet.AddressSet;\n using SafeERC20 for IERC20;\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n /// @inheritdoc IveIONSecondExtension\n function whitelistTokens(address[] memory _tokens, bool[] memory _isWhitelisted) external onlyOwner {\n require(_tokens.length == _isWhitelisted.length, \"Unequal Arrays\");\n for (uint256 i; i < _tokens.length; i++) s_whitelistedToken[_tokens[i]] = _isWhitelisted[i];\n emit TokensWhitelisted(_tokens, _isWhitelisted);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function withdrawProtocolFees(address _tokenAddress, address _recipient) external onlyOwner {\n LpTokenType lpType = s_lpType[_tokenAddress];\n uint256 protocolFees = s_protocolFees[lpType];\n require(protocolFees > 0, \"No protocol fees available\");\n s_protocolFees[lpType] = 0;\n IERC20(_tokenAddress).safeTransfer(_recipient, protocolFees);\n emit ProtocolFeesWithdrawn(_tokenAddress, _recipient, protocolFees);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function withdrawDistributedFees(address _tokenAddress, address _recipient) external onlyOwner {\n LpTokenType lpType = s_lpType[_tokenAddress];\n uint256 distributedFees = s_distributedFees[lpType];\n require(distributedFees > 0, \"No distributed fees available\");\n s_distributedFees[lpType] = 0;\n IERC20(_tokenAddress).safeTransfer(_recipient, distributedFees);\n emit DistributedFeesWithdrawn(_tokenAddress, _recipient, distributedFees);\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Setter Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IveIONSecondExtension\n function toggleSplit(address _account, bool _isAllowed) external onlyOwner {\n s_canSplit[_account] = _isAllowed;\n emit SplitToggle(_account, _isAllowed);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function toggleLimitedBoost(bool _isBoosted) external onlyOwner {\n s_limitedBoostActive = _isBoosted;\n emit LimitedBoostToggled(_isBoosted);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setLimitedTimeBoost(uint256 _boostAmount) external onlyOwner {\n if (_boostAmount <= 0) revert BoostAmountMustBeGreaterThanZero();\n s_limitedBoost = _boostAmount;\n emit LimitedTimeBoostSet(_boostAmount);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setVoter(address _voter) external onlyOwner {\n if (address(_voter) == address(0)) revert InvalidAddress();\n s_voter = _voter;\n emit VoterSet(_voter);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setMinimumLockAmount(address _tokenAddress, uint256 _minimumAmount) external onlyOwner {\n if (_minimumAmount <= 0) revert MinimumAmountMustBeGreaterThanZero();\n LpTokenType lpType = s_lpType[_tokenAddress];\n s_minimumLockAmount[lpType] = _minimumAmount;\n emit MinimumLockAmountSet(_tokenAddress, _minimumAmount);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setMinimumLockDuration(uint256 _minimumLockDuration) external onlyOwner {\n if (_minimumLockDuration <= 0) revert MinimumLockDurationMustBeGreaterThanZero();\n s_minimumLockDuration = _minimumLockDuration;\n emit MinimumLockDurationSet(_minimumLockDuration);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setIonicPool(address _ionicPool) external onlyOwner {\n if (address(_ionicPool) == address(0)) revert InvalidAddress();\n s_ionicPool = _ionicPool;\n emit IonicPoolSet(_ionicPool);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setAeroVoting(address _aeroVoting) external onlyOwner {\n if (address(_aeroVoting) == address(0)) revert InvalidAddress();\n s_aeroVoting = _aeroVoting;\n emit AeroVotingSet(_aeroVoting);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setAeroVoterBoost(uint256 _aeroVoterBoost) external onlyOwner {\n if (_aeroVoterBoost <= 0) revert AeroBoostAmountMustBeGreaterThanZero();\n s_aeroVoterBoost = _aeroVoterBoost;\n emit AeroVoterBoostSet(_aeroVoterBoost);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setMaxEarlyWithdrawFee(uint256 _maxEarlyWithdrawFee) external onlyOwner {\n if (_maxEarlyWithdrawFee <= 0) revert MaxEarlyWithdrawFeeMustBeGreaterThanZero();\n s_maxEarlyWithdrawFee = _maxEarlyWithdrawFee;\n emit MaxEarlyWithdrawFeeSet(_maxEarlyWithdrawFee);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setLpTokenType(address _token, LpTokenType _type) external onlyOwner {\n if (_token == address(0)) revert InvalidTokenAddress();\n s_lpType[_token] = _type;\n emit LpTokenTypeSet(_token, _type);\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setStakeStrategy(LpTokenType _lpType, IStakeStrategy _strategy) external onlyOwner {\n if (address(_strategy) == address(0)) revert InvalidStrategyAddress();\n s_stakeStrategy[_lpType] = IStakeStrategy(_strategy);\n emit StakeStrategySet(_lpType, address(_strategy));\n }\n\n /// @inheritdoc IveIONSecondExtension\n function setVeAERO(address _veAERO) external onlyOwner {\n if (_veAERO == address(0)) revert InvalidVeAEROAddress();\n s_veAERO = _veAERO;\n emit VeAEROSet(_veAERO);\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ View Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IveIONSecondExtension\n function getUserLock(uint256 _tokenId, LpTokenType _lpType) external view returns (LockedBalance memory) {\n return s_locked[_tokenId][_lpType];\n }\n\n /// @inheritdoc IveIONSecondExtension\n function getOwnedTokenIds(address _owner) external view returns (uint256[] memory) {\n return s_ownerToTokenIds[_owner].values();\n }\n\n /// @inheritdoc IveIONSecondExtension\n function getAssetsLocked(uint256 _tokenId) external view returns (address[] memory) {\n return s_assetsLocked[_tokenId].values();\n }\n\n /// @inheritdoc IveIONSecondExtension\n function getDelegatees(uint256 _tokenId, LpTokenType _lpType) external view returns (uint256[] memory) {\n return s_delegatees[_tokenId][_lpType].values();\n }\n\n /// @inheritdoc IveIONSecondExtension\n function getDelegators(uint256 _tokenId, LpTokenType _lpType) external view returns (uint256[] memory) {\n return s_delegators[_tokenId][_lpType].values();\n }\n\n /// @inheritdoc IveIONSecondExtension\n function getUserPoint(\n uint256 _tokenId,\n LpTokenType _lpType,\n uint256 _epoch\n ) external view returns (UserPoint memory) {\n return s_userPointHistory[_tokenId][_lpType][_epoch];\n }\n}\n" + }, + "contracts/src/veION/veIONStorage.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport { IAddressesProvider } from \"./interfaces/IveIONCore.sol\";\nimport { IStakeStrategy } from \"./stake/IStakeStrategy.sol\";\nimport { EnumerableSet } from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport { IveIONStructsEnumsErrorsEvents } from \"./interfaces/IveIONStructsEnumsErrorsEvents.sol\";\n\nabstract contract veIONStorage is IveIONStructsEnumsErrorsEvents {\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Constants ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n /// @notice Represents the duration of one week in seconds.\n uint256 internal constant _WEEK = 1 weeks;\n /// @notice Represents the maximum lock time in seconds (2 years).\n uint256 internal constant _MAXTIME = 2 * 365 * 86400;\n /// @notice Precision used for calculations, set to 1e18.\n uint256 public constant PRECISION = 1e18;\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ State Variables ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n /// @notice The current token ID counter.\n uint256 public s_tokenId;\n /// @notice The amount of limited boost available.\n uint256 public s_limitedBoost;\n /// @notice Indicates whether the limited boost is active.\n bool public s_limitedBoostActive;\n /// @notice Address of the veAERO contract.\n address public s_veAERO;\n /// @notice Address of the AeroVoting contract.\n address public s_aeroVoting;\n /// @notice Address of the Ionic Pool.\n address public s_ionicPool;\n /// @notice Address of the voter contract.\n address public s_voter;\n /// @notice The boost amount for AeroVoter.\n uint256 public s_aeroVoterBoost;\n /// @notice The minimum duration for locking.\n uint256 public s_minimumLockDuration;\n /// @notice The maximum fee for early withdrawal.\n uint256 public s_maxEarlyWithdrawFee;\n /// @notice The AddressesProvider contract used for address management.\n IAddressesProvider public ap;\n /// @notice The address of the logic contract for the veION first extension.\n address public veIONFirstExtension;\n /// @notice The address of the logic contract for the veION second extension.\n address public veIONSecondExtension;\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Mappings ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n /// @dev Maps LP token types to their minimum lock amounts.\n mapping(LpTokenType => uint256) public s_minimumLockAmount;\n /// @dev Maps token addresses to their whitelist status.\n mapping(address => bool) public s_whitelistedToken;\n /// @dev Maps token addresses to their corresponding LP token types.\n mapping(address => LpTokenType) public s_lpType;\n /// @dev Maps user addresses to their ability to split.\n mapping(address => bool) public s_canSplit;\n /// @dev Maps token IDs and LP token types to their locked balances.\n mapping(uint256 => mapping(LpTokenType => LockedBalance)) public s_locked;\n /// @dev Maps token IDs and LP token types to user epochs.\n mapping(uint256 => mapping(LpTokenType => uint256)) public s_userPointEpoch;\n /// @dev Maps token IDs and LP token types to user point history.\n mapping(uint256 => mapping(LpTokenType => UserPoint[1000000000])) public s_userPointHistory;\n /// @dev Maps token IDs to sets of locked asset addresses.\n mapping(uint256 => EnumerableSet.AddressSet) internal s_assetsLocked;\n /// @dev Maps token IDs to their voting status.\n mapping(uint256 => bool) public s_voted;\n /// @dev Maps LP token types to their total supply.\n mapping(LpTokenType => uint256) public s_supply;\n /// @dev Maps LP token types to their permanent lock balances.\n mapping(LpTokenType => uint256) public s_permanentLockBalance;\n /// @dev Maps LP token types to their underlying stake strategies.\n mapping(LpTokenType => IStakeStrategy) public s_stakeStrategy;\n /// @dev Maps token IDs and LP token addresses to their underlying stake amounts.\n mapping(uint256 => mapping(address => uint256)) public s_underlyingStake;\n /// @dev Maps LP token types to their protocol fees.\n mapping(LpTokenType => uint256) public s_protocolFees;\n /// @dev Maps LP token types to their distributed fees.\n mapping(LpTokenType => uint256) public s_distributedFees;\n /// @dev Maps delegators, delegatees, and LP token types to delegation amounts.\n mapping(uint256 => mapping(uint256 => mapping(LpTokenType => uint256))) public s_delegations;\n /// @dev Maps token IDs and LP token types to sets of delegatees.\n mapping(uint256 => mapping(LpTokenType => EnumerableSet.UintSet)) internal s_delegatees;\n /// @dev Maps token IDs and LP token types to sets of delegators.\n mapping(uint256 => mapping(LpTokenType => EnumerableSet.UintSet)) internal s_delegators;\n /// @dev Maps owner addresses to sets of token IDs they own.\n mapping(address => EnumerableSet.UintSet) internal s_ownerToTokenIds;\n /// @dev Maps user addresses and token addresses to cumulative asset values.\n mapping(address => mapping(address => uint256)) public s_userCumulativeAssetValues;\n /// @dev Maps token Id and lp onto delegator permissioning.\n mapping(uint256 => mapping(address => bool)) public s_delegatorsBlocked;\n\n uint256[50] private __gap;\n}\n" + }, + "contracts/src/veION/Voter.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.22;\n\nimport { Math } from \"@openzeppelin/contracts/utils/math/Math.sol\";\nimport { IVoter } from \"./interfaces/IVoter.sol\";\nimport { IERC20 } from \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport { SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\nimport { IonicTimeLibrary } from \"./libraries/IonicTimeLibrary.sol\";\nimport { IveION } from \"./interfaces/IveION.sol\";\nimport { IBribeRewards } from \"./interfaces/IBribeRewards.sol\";\nimport { IonicComptroller } from \"../compound/ComptrollerInterface.sol\";\nimport { ICErc20 } from \"../compound/CTokenInterfaces.sol\";\nimport { MasterPriceOracle } from \"../oracles/MasterPriceOracle.sol\";\nimport { ERC721Upgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/token/ERC721/ERC721Upgradeable.sol\";\nimport { Ownable2StepUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/access/Ownable2StepUpgradeable.sol\";\nimport { ReentrancyGuardUpgradeable } from \"@openzeppelin-contracts-upgradeable/contracts/security/ReentrancyGuardUpgradeable.sol\";\n\n/**\n * @title Voter Contract\n * @notice This contract allows veION holders to vote for various markets\n * @author Jourdan Dunkley (https://github.com/jourdanDunkley)\n */\ncontract Voter is IVoter, Ownable2StepUpgradeable, ReentrancyGuardUpgradeable {\n using SafeERC20 for IERC20;\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ State Variables ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n ///@notice The ve token that governs these contracts\n address public ve;\n ///@notice Base token of ve contract\n address internal rewardToken;\n ///@notice Standard OZ IGovernor using ve for vote weights\n address public governor;\n ///@notice Master Price Oracle instance\n MasterPriceOracle public mpo;\n ///@notice List of LP tokens\n address[] public lpTokens;\n ///@notice Total Voting Weights for each address\n mapping(address => uint256) public totalWeight;\n ///@notice Maximum number of markets one voter can vote for at once\n uint256 public maxVotingNum;\n ///@notice Minimum value for maxVotingNum\n uint256 internal constant MIN_MAXVOTINGNUM = 10;\n ///@notice All markets viable for incentives\n Market[] public markets;\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Mappings ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n ///@notice Mapping from Reward Accumulator to Bribes Voting Reward\n mapping(address => address) public rewardAccumulatorToBribe;\n ///@notice Mapping from Market to Market Side to LP Asset to weights\n mapping(address => mapping(MarketSide => mapping(address => uint256))) public weights;\n ///@notice Mapping from NFT to Pool to LP Asset to Votes\n mapping(uint256 => mapping(address => mapping(MarketSide => mapping(address => uint256)))) public votes;\n ///@notice Mapping from NFT to Pool to LP Asset to Base Weights\n mapping(uint256 => mapping(address => mapping(MarketSide => mapping(address => uint256)))) public baseWeights;\n ///@notice Mapping from NFT to List of markets voted for by NFT\n mapping(uint256 => mapping(address => address[])) public marketVote;\n ///@notice Mapping from NFT to List of market vote sides voted for by NFT\n mapping(uint256 => mapping(address => MarketSide[])) public marketVoteSide;\n ///@notice Mapping from NFT to Total voting weight of NFT\n mapping(uint256 => mapping(address => uint256)) public usedWeights;\n ///@notice Mapping from NFT to Timestamp of last vote (ensures single vote per epoch)\n mapping(uint256 => uint256) public lastVoted;\n ///@notice Mapping from Token to Whitelisted status\n mapping(address => bool) public isWhitelistedToken;\n ///@notice Mapping from TokenId to Whitelisted status\n mapping(uint256 => bool) public isWhitelistedNFT;\n ///@notice Mapping from Reward Accumulator to Liveness status\n mapping(address => bool) public isAlive;\n ///@notice Mapping from Market to Market Side to Reward Accumulator\n mapping(address => mapping(MarketSide => address)) public marketToRewardAccumulators;\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Modifiers ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n /**\n * @notice Modifier to ensure that the function is called only in a new epoch since the last vote.\n * @dev Reverts if the current epoch start time is less than or equal to the last voted timestamp for the given token ID.\n * Also reverts if the current time is within the vote distribution window.\n * @param _tokenId The ID of the veNFT to check the last voted timestamp.\n */\n modifier onlyNewEpoch(uint256 _tokenId) {\n if (IonicTimeLibrary.epochStart(block.timestamp) <= lastVoted[_tokenId]) revert AlreadyVotedOrDeposited();\n if (block.timestamp <= IonicTimeLibrary.epochVoteStart(block.timestamp)) revert DistributeWindow();\n _;\n }\n\n /**\n * @notice Modifier to ensure that the function is called only by the governance address.\n * @dev Reverts if the caller is not the current governor.\n */\n modifier onlyGovernance() {\n if (msg.sender != governor) revert NotGovernor();\n _;\n }\n\n constructor() {\n _disableInitializers(); // Locks the implementation contract from being initialized\n }\n\n /**\n * @notice Initializes the Voter contract with the specified parameters.\n * @dev Requires initialization with at least one reward token.\n * @param _tokens An array of token addresses to be whitelisted.\n * @param _mpo The MasterPriceOracle contract address.\n * @param _rewardToken The address of the reward token.\n * @param _ve The address of the veION contract.\n * @custom:reverts TokensArrayEmpty if the _tokens array is empty.\n */\n function initialize(\n address[] calldata _tokens,\n MasterPriceOracle _mpo,\n address _rewardToken,\n address _ve\n ) external initializer {\n __Ownable2Step_init();\n __ReentrancyGuard_init();\n uint256 _length = _tokens.length;\n if (_length == 0) revert TokensArrayEmpty();\n for (uint256 i = 0; i < _length; i++) {\n _whitelistToken(_tokens[i], true);\n }\n mpo = _mpo;\n rewardToken = _rewardToken;\n ve = _ve;\n governor = msg.sender;\n\n emit Initialized(_tokens, address(_mpo), _rewardToken, _ve, governor);\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ External Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IVoter\n function vote(\n uint256 _tokenId,\n address[] calldata _marketVote,\n MarketSide[] calldata _marketVoteSide,\n uint256[] calldata _weights\n ) external nonReentrant onlyNewEpoch(_tokenId) {\n VoteLocalVars memory vars;\n vars.sender = msg.sender;\n if (ERC721Upgradeable(ve).ownerOf(_tokenId) != vars.sender) revert NotOwner();\n if (\n _marketVote.length != _marketVoteSide.length ||\n _marketVoteSide.length != _weights.length ||\n _weights.length != _marketVote.length\n ) revert UnequalLengths();\n if (_marketVote.length > maxVotingNum) revert TooManyPools();\n vars.timestamp = block.timestamp;\n if ((vars.timestamp > IonicTimeLibrary.epochVoteEnd(vars.timestamp)) && !isWhitelistedNFT[_tokenId])\n revert NotWhitelistedNFT();\n uint256 totalVoteWeight = 0;\n\n for (uint256 i = 0; i < _marketVote.length; i++) {\n totalVoteWeight += _weights[i];\n }\n for (uint256 i = 0; i < lpTokens.length; i++) {\n _reset(_tokenId, lpTokens[i]);\n }\n\n lastVoted[_tokenId] = vars.timestamp;\n (vars.votingLPs, vars.votingLPBalances, vars.boosts) = IveION(ve).balanceOfNFT(_tokenId);\n for (uint256 j = 0; j < vars.votingLPs.length; j++) {\n _vote(\n _tokenId,\n vars.votingLPs[j],\n (vars.votingLPBalances[j] * vars.boosts[j]) / 1e18,\n _marketVote,\n _marketVoteSide,\n _weights,\n totalVoteWeight\n );\n }\n }\n\n /// @inheritdoc IVoter\n function poke(uint256 _tokenId) external nonReentrant {\n if (block.timestamp <= IonicTimeLibrary.epochVoteStart(block.timestamp)) revert DistributeWindow();\n (address[] memory _votingLPs, uint256[] memory _votingLPBalances, uint256[] memory _boosts) = IveION(ve)\n .balanceOfNFT(_tokenId);\n\n for (uint256 i = 0; i < _votingLPs.length; i++) {\n uint256 effectiveBalance = (_votingLPBalances[i] * _boosts[i]) / 1e18;\n _poke(_tokenId, lpTokens[i], effectiveBalance);\n }\n }\n\n /// @inheritdoc IVoter\n function reset(uint256 _tokenId) public nonReentrant onlyNewEpoch(_tokenId) {\n if (ERC721Upgradeable(ve).ownerOf(_tokenId) != msg.sender) revert NotOwner();\n for (uint256 i = 0; i < lpTokens.length; i++) {\n _reset(_tokenId, lpTokens[i]);\n }\n }\n\n /// @inheritdoc IVoter\n function claimBribes(address[] memory _bribes, address[][] memory _tokens, uint256 _tokenId) external nonReentrant {\n if (_bribes.length != _tokens.length) revert UnequalLengths();\n if (ERC721Upgradeable(ve).ownerOf(_tokenId) != _msgSender()) revert NotOwner();\n uint256 _length = _bribes.length;\n for (uint256 i = 0; i < _length; i++) {\n IBribeRewards(_bribes[i]).getReward(_tokenId, _tokens[i]);\n }\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Admin External Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IVoter\n function distributeRewards() external onlyGovernance {\n if (block.timestamp <= IonicTimeLibrary.epochVoteEnd(block.timestamp)) revert NotDistributeWindow();\n uint256 _reward = IERC20(rewardToken).balanceOf(address(this));\n uint256 _totalLPValueETH = _calculateTotalLPValue();\n for (uint256 i = 0; i < markets.length; i++) {\n uint256 _marketWeightETH = _calculateMarketLPValue(markets[i].marketAddress, markets[i].side);\n if (_marketWeightETH > 0) {\n IERC20(rewardToken).safeTransfer(\n marketToRewardAccumulators[markets[i].marketAddress][markets[i].side],\n (_reward * _marketWeightETH) / _totalLPValueETH\n );\n }\n }\n }\n\n /// @inheritdoc IVoter\n function whitelistToken(address _token, bool _bool) external onlyGovernance {\n _whitelistToken(_token, _bool);\n }\n\n /// @inheritdoc IVoter\n function whitelistNFT(uint256 _tokenId, bool _bool) external onlyGovernance {\n address _sender = msg.sender;\n isWhitelistedNFT[_tokenId] = _bool;\n emit WhitelistNFT(_sender, _tokenId, _bool);\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Internal Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /**\n * @notice Internal function to handle voting logic for a given token ID and voting asset.\n * @param _tokenId The ID of the token used for voting.\n * @param _votingAsset The address of the asset being used for voting.\n * @param _votingAssetBalance The balance of the voting asset.\n * @param _marketVote An array of market addresses to vote for.\n * @param _marketVoteSide An array of market sides corresponding to the markets.\n * @param _weights An array of weights for each market.\n * @param totalVoteWeight The total weight of the vote.\n */\n function _vote(\n uint256 _tokenId,\n address _votingAsset,\n uint256 _votingAssetBalance,\n address[] memory _marketVote,\n MarketSide[] memory _marketVoteSide,\n uint256[] memory _weights,\n uint256 totalVoteWeight\n ) internal {\n VoteVars memory vars;\n uint256 marketVoteLength = _marketVote.length;\n for (uint256 i = 0; i < marketVoteLength; i++) {\n vars.market = _marketVote[i];\n vars.marketSide = _marketVoteSide[i];\n vars.rewardAccumulator = marketToRewardAccumulators[vars.market][vars.marketSide];\n vars.bribes = rewardAccumulatorToBribe[vars.rewardAccumulator];\n if (_weights[i] == 0) revert ZeroWeight();\n if (vars.rewardAccumulator == address(0)) revert RewardAccumulatorDoesNotExist(vars.market);\n if (!isAlive[vars.rewardAccumulator]) revert RewardAccumulatorNotAlive(vars.rewardAccumulator);\n\n vars.marketWeight = (_weights[i] * _votingAssetBalance) / totalVoteWeight;\n if (votes[_tokenId][vars.market][vars.marketSide][_votingAsset] != 0) revert NonZeroVotes();\n\n marketVote[_tokenId][_votingAsset].push(vars.market);\n marketVoteSide[_tokenId][_votingAsset].push(vars.marketSide);\n\n weights[vars.market][vars.marketSide][_votingAsset] += vars.marketWeight;\n votes[_tokenId][vars.market][vars.marketSide][_votingAsset] += vars.marketWeight;\n baseWeights[_tokenId][vars.market][vars.marketSide][_votingAsset] = _weights[i];\n IBribeRewards(vars.bribes).deposit(_votingAsset, uint256(vars.marketWeight), _tokenId);\n vars.usedWeight += vars.marketWeight;\n vars.totalWeight += vars.marketWeight;\n emit Voted(\n msg.sender,\n vars.market,\n _tokenId,\n vars.marketWeight,\n weights[vars.market][vars.marketSide][_votingAsset],\n block.timestamp\n );\n }\n IveION(ve).voting(_tokenId, true);\n totalWeight[_votingAsset] += uint256(vars.totalWeight);\n usedWeights[_tokenId][_votingAsset] = uint256(vars.usedWeight);\n }\n\n /**\n * @notice Internal function to update voting balances for a given token ID and voting asset.\n * @param _tokenId The ID of the token whose voting balance is being updated.\n * @param _votingAsset The address of the asset being used for voting.\n * @param _votingAssetBalance The balance of the voting asset.\n */\n function _poke(uint256 _tokenId, address _votingAsset, uint256 _votingAssetBalance) internal {\n address[] memory _marketVote = marketVote[_tokenId][_votingAsset];\n MarketSide[] memory _marketVoteSide = marketVoteSide[_tokenId][_votingAsset];\n uint256 _marketCnt = _marketVote.length;\n uint256[] memory _weights = new uint256[](_marketCnt);\n uint256 totalVoteWeight = 0;\n\n for (uint256 i = 0; i < _marketCnt; i++) {\n _weights[i] = baseWeights[_tokenId][_marketVote[i]][_marketVoteSide[i]][_votingAsset];\n }\n\n for (uint256 i = 0; i < _marketVote.length; i++) {\n totalVoteWeight += _weights[i];\n }\n\n _reset(_tokenId, _votingAsset);\n _vote(_tokenId, _votingAsset, _votingAssetBalance, _marketVote, _marketVoteSide, _weights, totalVoteWeight);\n }\n\n /**\n * @notice Internal function to reset voting state for a given token ID and voting asset.\n * @param _tokenId The ID of the token whose voting state is being reset.\n * @param _votingAsset The address of the asset being used for voting.\n */\n function _reset(uint256 _tokenId, address _votingAsset) internal {\n address[] storage _marketVote = marketVote[_tokenId][_votingAsset];\n MarketSide[] storage _marketVoteSide = marketVoteSide[_tokenId][_votingAsset];\n uint256 _marketVoteCnt = _marketVote.length;\n\n for (uint256 i = 0; i < _marketVoteCnt; i++) {\n address _market = _marketVote[i];\n MarketSide _marketSide = _marketVoteSide[i];\n\n uint256 _votes = votes[_tokenId][_market][_marketSide][_votingAsset];\n if (_votes != 0) {\n weights[_market][_marketSide][_votingAsset] -= _votes;\n delete votes[_tokenId][_market][_marketSide][_votingAsset];\n IBribeRewards(rewardAccumulatorToBribe[marketToRewardAccumulators[_market][_marketSide]]).withdraw(\n _votingAsset,\n uint256(_votes),\n _tokenId\n );\n totalWeight[_votingAsset] -= _votes;\n emit Abstained(\n msg.sender,\n _market,\n _tokenId,\n _votes,\n weights[_market][_marketSide][_votingAsset],\n block.timestamp\n );\n }\n }\n usedWeights[_tokenId][_votingAsset] = 0;\n delete marketVote[_tokenId][_votingAsset];\n delete marketVoteSide[_tokenId][_votingAsset];\n IveION(ve).voting(_tokenId, false);\n }\n\n /**\n * @notice Internal function to whitelist or unwhitelist a token for use in bribes.\n * @param _token The address of the token to be whitelisted or unwhitelisted.\n * @param _bool Boolean indicating whether to whitelist (true) or unwhitelist (false) the token.\n */\n function _whitelistToken(address _token, bool _bool) internal {\n isWhitelistedToken[_token] = _bool;\n emit WhitelistToken(msg.sender, _token, _bool);\n }\n\n /**\n * @notice Internal function to calculate the ETH value of a given amount of LP tokens.\n * @param amount The amount of LP tokens.\n * @param lpToken The address of the LP token.\n * @return The ETH value of the given amount of LP tokens.\n */\n function _getTokenEthValue(uint256 amount, address lpToken) internal view returns (uint256) {\n uint256 tokenPriceInEth = mpo.price(lpToken); // Fetch price of 1 lpToken in ETH\n uint256 ethValue = amount * tokenPriceInEth;\n return ethValue;\n }\n\n /**\n * @notice Internal function to calculate the total ETH value of all LP tokens in the markets.\n * @return _totalLPValueETH The total ETH value of all LP tokens.\n */\n function _calculateTotalLPValue() internal view returns (uint256 _totalLPValueETH) {\n uint256 marketLength = markets.length;\n for (uint256 i = 0; i < marketLength; i++)\n _totalLPValueETH += _calculateMarketLPValue(markets[i].marketAddress, markets[i].side);\n }\n\n /**\n * @notice Internal function to calculate the ETH value of LP tokens for a specific market.\n * @param _market The address of the market.\n * @param _marketSide The side of the market.\n * @return _marketLPValueETH The ETH value of LP tokens for the specified market.\n */\n function _calculateMarketLPValue(\n address _market,\n MarketSide _marketSide\n ) internal view returns (uint256 _marketLPValueETH) {\n uint256 lpTokensLength = lpTokens.length;\n for (uint256 i = 0; i < lpTokensLength; i++) {\n uint256 _lpAmount = weights[_market][_marketSide][lpTokens[i]];\n uint256 tokenEthValue = _getTokenEthValue(_lpAmount, lpTokens[i]);\n _marketLPValueETH += tokenEthValue;\n }\n }\n\n /**\n * @notice Internal function to check if a market exists.\n * @param _marketAddress The address of the market.\n * @param _marketSide The side of the market.\n * @return True if the market exists, false otherwise.\n */\n function _marketExists(address _marketAddress, MarketSide _marketSide) internal view returns (bool) {\n uint256 marketLength = markets.length;\n for (uint256 j = 0; j < marketLength; j++) {\n if (markets[j].marketAddress == _marketAddress && markets[j].side == _marketSide) {\n return true;\n }\n }\n return false;\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Setter Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IVoter\n function setLpTokens(address[] memory _lpTokens) external onlyOwner {\n require(_lpTokens.length != 0, \"LpTokens array cannot be empty\");\n lpTokens = _lpTokens;\n emit LpTokensSet(_lpTokens);\n }\n\n /// @inheritdoc IVoter\n function setMpo(address _mpo) external onlyOwner {\n if (_mpo == address(0)) revert ZeroAddress();\n mpo = MasterPriceOracle(_mpo);\n emit MpoSet(_mpo);\n }\n\n /// @inheritdoc IVoter\n function setGovernor(address _governor) public onlyOwner {\n if (_governor == address(0)) revert ZeroAddress();\n governor = _governor;\n emit GovernorSet(_governor);\n }\n\n /// @inheritdoc IVoter\n function addMarkets(Market[] calldata _markets) external onlyGovernance {\n for (uint256 i = 0; i < _markets.length; i++) {\n Market memory newMarket = _markets[i];\n if (_marketExists(newMarket.marketAddress, newMarket.side)) revert MarketAlreadyExists();\n markets.push(newMarket);\n }\n emit MarketsAdded(_markets);\n }\n\n /// @inheritdoc IVoter\n function setMarketRewardAccumulators(\n address[] calldata _markets,\n MarketSide[] calldata _marketSides,\n address[] calldata _rewardAccumulators\n ) external onlyGovernance {\n uint256 _length = _markets.length;\n if (_marketSides.length != _length) revert MismatchedArrayLengths();\n if (_rewardAccumulators.length != _length) revert MismatchedArrayLengths();\n for (uint256 i = 0; i < _length; i++) {\n marketToRewardAccumulators[_markets[i]][_marketSides[i]] = _rewardAccumulators[i];\n isAlive[_rewardAccumulators[i]] = true;\n }\n emit MarketRewardAccumulatorsSet(_markets, _marketSides, _rewardAccumulators);\n }\n\n /// @inheritdoc IVoter\n function setBribes(address[] calldata _rewardAccumulators, address[] calldata _bribes) external onlyGovernance {\n uint256 _length = _bribes.length;\n if (_rewardAccumulators.length != _length) revert MismatchedArrayLengths();\n for (uint256 i = 0; i < _length; i++) {\n rewardAccumulatorToBribe[_rewardAccumulators[i]] = _bribes[i];\n }\n emit BribesSet(_rewardAccumulators, _bribes);\n }\n\n /// @inheritdoc IVoter\n function setMaxVotingNum(uint256 _maxVotingNum) external onlyGovernance {\n if (_maxVotingNum < MIN_MAXVOTINGNUM) revert MaximumVotingNumberTooLow();\n if (_maxVotingNum == maxVotingNum) revert SameValue();\n maxVotingNum = _maxVotingNum;\n emit MaxVotingNumSet(_maxVotingNum);\n }\n\n /// @inheritdoc IVoter\n function toggleRewardAccumulatorAlive(\n address _market,\n MarketSide _marketSide,\n bool _isAlive\n ) external onlyGovernance {\n address _rewardAccumulator = marketToRewardAccumulators[_market][_marketSide];\n if (_rewardAccumulator == address(0)) revert RewardAccumulatorDoesNotExist(_market);\n isAlive[_rewardAccumulator] = _isAlive;\n emit RewardAccumulatorAliveToggled(_market, _marketSide, _isAlive);\n }\n\n // ╔═══════════════════════════════════════════════════════════════════════════╗\n // ║ Pure/View Functions ║\n // ╚═══════════════════════════════════════════════════════════════════════════╝\n\n /// @inheritdoc IVoter\n function epochStart(uint256 _timestamp) external pure returns (uint256) {\n return IonicTimeLibrary.epochStart(_timestamp);\n }\n\n /// @inheritdoc IVoter\n function epochNext(uint256 _timestamp) external pure returns (uint256) {\n return IonicTimeLibrary.epochNext(_timestamp);\n }\n\n /// @inheritdoc IVoter\n function epochVoteStart(uint256 _timestamp) external pure returns (uint256) {\n return IonicTimeLibrary.epochVoteStart(_timestamp);\n }\n\n /// @inheritdoc IVoter\n function epochVoteEnd(uint256 _timestamp) external pure returns (uint256) {\n return IonicTimeLibrary.epochVoteEnd(_timestamp);\n }\n\n /// @inheritdoc IVoter\n function marketsLength() external view returns (uint256) {\n return markets.length;\n }\n\n /// @inheritdoc IVoter\n function getAllLpRewardTokens() external view returns (address[] memory) {\n return lpTokens;\n }\n\n /// @inheritdoc IVoter\n function getVoteDetails(uint256 _tokenId, address _lpAsset) external view returns (VoteDetails memory) {\n uint256 length = marketVote[_tokenId][_lpAsset].length;\n address[] memory _marketVotes = new address[](length);\n MarketSide[] memory _marketVoteSides = new MarketSide[](length);\n uint256[] memory _votes = new uint256[](length);\n\n for (uint256 i = 0; i < length; i++) {\n _marketVotes[i] = marketVote[_tokenId][_lpAsset][i];\n _marketVoteSides[i] = marketVoteSide[_tokenId][_lpAsset][i];\n _votes[i] = votes[_tokenId][_marketVotes[i]][_marketVoteSides[i]][_lpAsset];\n }\n\n uint256 _usedWeight = usedWeights[_tokenId][_lpAsset];\n\n return\n VoteDetails({\n marketVotes: _marketVotes,\n marketVoteSides: _marketVoteSides,\n votes: _votes,\n usedWeight: _usedWeight\n });\n }\n}\n" + }, + "ops/interfaces/IResolver.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface IResolver {\n function checker()\n external\n view\n returns (bool canExec, bytes memory execPayload);\n}\n" + }, + "solidity-bytes-utils/contracts/BytesLib.sol": { + "content": "// SPDX-License-Identifier: Unlicense\n/*\n * @title Solidity Bytes Arrays Utils\n * @author Gonçalo Sá \n *\n * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.\n * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.\n */\npragma solidity >=0.8.0 <0.9.0;\n\n\nlibrary BytesLib {\n function concat(\n bytes memory _preBytes,\n bytes memory _postBytes\n )\n internal\n pure\n returns (bytes memory)\n {\n bytes memory tempBytes;\n\n assembly {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // Store the length of the first bytes array at the beginning of\n // the memory for tempBytes.\n let length := mload(_preBytes)\n mstore(tempBytes, length)\n\n // Maintain a memory counter for the current write location in the\n // temp bytes array by adding the 32 bytes for the array length to\n // the starting location.\n let mc := add(tempBytes, 0x20)\n // Stop copying when the memory counter reaches the length of the\n // first bytes array.\n let end := add(mc, length)\n\n for {\n // Initialize a copy counter to the start of the _preBytes data,\n // 32 bytes into its memory.\n let cc := add(_preBytes, 0x20)\n } lt(mc, end) {\n // Increase both counters by 32 bytes each iteration.\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // Write the _preBytes data into the tempBytes memory 32 bytes\n // at a time.\n mstore(mc, mload(cc))\n }\n\n // Add the length of _postBytes to the current length of tempBytes\n // and store it as the new length in the first 32 bytes of the\n // tempBytes memory.\n length := mload(_postBytes)\n mstore(tempBytes, add(length, mload(tempBytes)))\n\n // Move the memory counter back from a multiple of 0x20 to the\n // actual end of the _preBytes data.\n mc := end\n // Stop copying when the memory counter reaches the new combined\n // length of the arrays.\n end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n // Update the free-memory pointer by padding our last write location\n // to 32 bytes: add 31 bytes to the end of tempBytes to move to the\n // next 32 byte block, then round down to the nearest multiple of\n // 32. If the sum of the length of the two arrays is zero then add\n // one before rounding down to leave a blank 32 bytes (the length block with 0).\n mstore(0x40, and(\n add(add(end, iszero(add(length, mload(_preBytes)))), 31),\n not(31) // Round down to the nearest 32 bytes.\n ))\n }\n\n return tempBytes;\n }\n\n function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {\n assembly {\n // Read the first 32 bytes of _preBytes storage, which is the length\n // of the array. (We don't need to use the offset into the slot\n // because arrays use the entire slot.)\n let fslot := sload(_preBytes.slot)\n // Arrays of 31 bytes or less have an even value in their slot,\n // while longer arrays have an odd value. The actual length is\n // the slot divided by two for odd values, and the lowest order\n // byte divided by two for even values.\n // If the slot is even, bitwise and the slot with 255 and divide by\n // two to get the length. If the slot is odd, bitwise and the slot\n // with -1 and divide by two.\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n let newlength := add(slength, mlength)\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n switch add(lt(slength, 32), lt(newlength, 32))\n case 2 {\n // Since the new array still fits in the slot, we just need to\n // update the contents of the slot.\n // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length\n sstore(\n _preBytes.slot,\n // all the modifications to the slot are inside this\n // next block\n add(\n // we can just add to the slot contents because the\n // bytes we want to change are the LSBs\n fslot,\n add(\n mul(\n div(\n // load the bytes from memory\n mload(add(_postBytes, 0x20)),\n // zero all bytes to the right\n exp(0x100, sub(32, mlength))\n ),\n // and now shift left the number of bytes to\n // leave space for the length in the slot\n exp(0x100, sub(32, newlength))\n ),\n // increase length by the double of the memory\n // bytes length\n mul(mlength, 2)\n )\n )\n )\n }\n case 1 {\n // The stored value fits in the slot, but the combined value\n // will exceed it.\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // The contents of the _postBytes array start 32 bytes into\n // the structure. Our first read should obtain the `submod`\n // bytes that can fit into the unused space in the last word\n // of the stored array. To get this, we read 32 bytes starting\n // from `submod`, so the data we read overlaps with the array\n // contents by `submod` bytes. Masking the lowest-order\n // `submod` bytes allows us to add that value directly to the\n // stored value.\n\n let submod := sub(32, slength)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(\n sc,\n add(\n and(\n fslot,\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00\n ),\n and(mload(mc), mask)\n )\n )\n\n for {\n mc := add(mc, 0x20)\n sc := add(sc, 1)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n default {\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n // Start copying to the last used word of the stored array.\n let sc := add(keccak256(0x0, 0x20), div(slength, 32))\n\n // save new length\n sstore(_preBytes.slot, add(mul(newlength, 2), 1))\n\n // Copy over the first `submod` bytes of the new data as in\n // case 1 above.\n let slengthmod := mod(slength, 32)\n let mlengthmod := mod(mlength, 32)\n let submod := sub(32, slengthmod)\n let mc := add(_postBytes, submod)\n let end := add(_postBytes, mlength)\n let mask := sub(exp(0x100, submod), 1)\n\n sstore(sc, add(sload(sc), and(mload(mc), mask)))\n\n for {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } lt(mc, end) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n sstore(sc, mload(mc))\n }\n\n mask := exp(0x100, sub(mc, end))\n\n sstore(sc, mul(div(mload(mc), mask), mask))\n }\n }\n }\n\n function slice(\n bytes memory _bytes,\n uint256 _start,\n uint256 _length\n )\n internal\n pure\n returns (bytes memory)\n {\n require(_length + 31 >= _length, \"slice_overflow\");\n require(_bytes.length >= _start + _length, \"slice_outOfBounds\");\n\n bytes memory tempBytes;\n\n assembly {\n switch iszero(_length)\n case 0 {\n // Get a location of some free memory and store it in tempBytes as\n // Solidity does for memory variables.\n tempBytes := mload(0x40)\n\n // The first word of the slice result is potentially a partial\n // word read from the original array. To read it, we calculate\n // the length of that partial word and start copying that many\n // bytes into the array. The first word we copy will start with\n // data we don't care about, but the last `lengthmod` bytes will\n // land at the beginning of the contents of the new array. When\n // we're done copying, we overwrite the full first word with\n // the actual length of the slice.\n let lengthmod := and(_length, 31)\n\n // The multiplication in the next line is necessary\n // because when slicing multiples of 32 bytes (lengthmod == 0)\n // the following copy loop was copying the origin's length\n // and then ending prematurely not copying everything it should.\n let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))\n let end := add(mc, _length)\n\n for {\n // The multiplication in the next line has the same exact purpose\n // as the one above.\n let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)\n } lt(mc, end) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n mstore(mc, mload(cc))\n }\n\n mstore(tempBytes, _length)\n\n //update free-memory pointer\n //allocating the array padded to 32 bytes like the compiler does now\n mstore(0x40, and(add(mc, 31), not(31)))\n }\n //if we want a zero-length slice let's just return a zero-length array\n default {\n tempBytes := mload(0x40)\n //zero out the 32 bytes slice we are about to return\n //we need to do it because Solidity does not garbage collect\n mstore(tempBytes, 0)\n\n mstore(0x40, add(tempBytes, 0x20))\n }\n }\n\n return tempBytes;\n }\n\n function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {\n require(_bytes.length >= _start + 20, \"toAddress_outOfBounds\");\n address tempAddress;\n\n assembly {\n tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)\n }\n\n return tempAddress;\n }\n\n function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {\n require(_bytes.length >= _start + 1 , \"toUint8_outOfBounds\");\n uint8 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x1), _start))\n }\n\n return tempUint;\n }\n\n function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) {\n require(_bytes.length >= _start + 2, \"toUint16_outOfBounds\");\n uint16 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x2), _start))\n }\n\n return tempUint;\n }\n\n function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) {\n require(_bytes.length >= _start + 4, \"toUint32_outOfBounds\");\n uint32 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x4), _start))\n }\n\n return tempUint;\n }\n\n function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) {\n require(_bytes.length >= _start + 8, \"toUint64_outOfBounds\");\n uint64 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x8), _start))\n }\n\n return tempUint;\n }\n\n function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) {\n require(_bytes.length >= _start + 12, \"toUint96_outOfBounds\");\n uint96 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0xc), _start))\n }\n\n return tempUint;\n }\n\n function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) {\n require(_bytes.length >= _start + 16, \"toUint128_outOfBounds\");\n uint128 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x10), _start))\n }\n\n return tempUint;\n }\n\n function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) {\n require(_bytes.length >= _start + 32, \"toUint256_outOfBounds\");\n uint256 tempUint;\n\n assembly {\n tempUint := mload(add(add(_bytes, 0x20), _start))\n }\n\n return tempUint;\n }\n\n function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) {\n require(_bytes.length >= _start + 32, \"toBytes32_outOfBounds\");\n bytes32 tempBytes32;\n\n assembly {\n tempBytes32 := mload(add(add(_bytes, 0x20), _start))\n }\n\n return tempBytes32;\n }\n\n function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {\n bool success = true;\n\n assembly {\n let length := mload(_preBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(length, mload(_postBytes))\n case 1 {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n let mc := add(_preBytes, 0x20)\n let end := add(mc, length)\n\n for {\n let cc := add(_postBytes, 0x20)\n // the next line is the loop condition:\n // while(uint256(mc < end) + cb == 2)\n } eq(add(lt(mc, end), cb), 2) {\n mc := add(mc, 0x20)\n cc := add(cc, 0x20)\n } {\n // if any of these checks fails then arrays are not equal\n if iszero(eq(mload(mc), mload(cc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n\n function equalStorage(\n bytes storage _preBytes,\n bytes memory _postBytes\n )\n internal\n view\n returns (bool)\n {\n bool success = true;\n\n assembly {\n // we know _preBytes_offset is 0\n let fslot := sload(_preBytes.slot)\n // Decode the length of the stored array like in concatStorage().\n let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)\n let mlength := mload(_postBytes)\n\n // if lengths don't match the arrays are not equal\n switch eq(slength, mlength)\n case 1 {\n // slength can contain both the length and contents of the array\n // if length < 32 bytes so let's prepare for that\n // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage\n if iszero(iszero(slength)) {\n switch lt(slength, 32)\n case 1 {\n // blank the last byte which is the length\n fslot := mul(div(fslot, 0x100), 0x100)\n\n if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {\n // unsuccess:\n success := 0\n }\n }\n default {\n // cb is a circuit breaker in the for loop since there's\n // no said feature for inline assembly loops\n // cb = 1 - don't breaker\n // cb = 0 - break\n let cb := 1\n\n // get the keccak hash to get the contents of the array\n mstore(0x0, _preBytes.slot)\n let sc := keccak256(0x0, 0x20)\n\n let mc := add(_postBytes, 0x20)\n let end := add(mc, mlength)\n\n // the next line is the loop condition:\n // while(uint256(mc < end) + cb == 2)\n for {} eq(add(lt(mc, end), cb), 2) {\n sc := add(sc, 1)\n mc := add(mc, 0x20)\n } {\n if iszero(eq(sload(sc), mload(mc))) {\n // unsuccess:\n success := 0\n cb := 0\n }\n }\n }\n }\n }\n default {\n // unsuccess:\n success := 0\n }\n }\n\n return success;\n }\n}\n" + }, + "solmate/auth/Auth.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\nabstract contract Auth {\n event OwnerUpdated(address indexed user, address indexed newOwner);\n\n event AuthorityUpdated(address indexed user, Authority indexed newAuthority);\n\n address public owner;\n\n Authority public authority;\n\n constructor(address _owner, Authority _authority) {\n owner = _owner;\n authority = _authority;\n\n emit OwnerUpdated(msg.sender, _owner);\n emit AuthorityUpdated(msg.sender, _authority);\n }\n\n modifier requiresAuth() virtual {\n require(isAuthorized(msg.sender, msg.sig), \"UNAUTHORIZED\");\n\n _;\n }\n\n function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {\n Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.\n\n // Checking if the caller is the owner only after calling the authority saves gas in most cases, but be\n // aware that this makes protected functions uncallable even to the owner if the authority is out of order.\n return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;\n }\n\n function setAuthority(Authority newAuthority) public virtual {\n // We check if the caller is the owner first because we want to ensure they can\n // always swap out the authority even if it's reverting or using up a lot of gas.\n require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));\n\n authority = newAuthority;\n\n emit AuthorityUpdated(msg.sender, newAuthority);\n }\n\n function setOwner(address newOwner) public virtual requiresAuth {\n owner = newOwner;\n\n emit OwnerUpdated(msg.sender, newOwner);\n }\n}\n\n/// @notice A generic interface for a contract which provides authorization data to an Auth instance.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/Auth.sol)\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)\ninterface Authority {\n function canCall(\n address user,\n address target,\n bytes4 functionSig\n ) external view returns (bool);\n}\n" + }, + "solmate/auth/authorities/RolesAuthority.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {Auth, Authority} from \"../Auth.sol\";\n\n/// @notice Role based Authority that supports up to 256 roles.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/auth/authorities/RolesAuthority.sol)\n/// @author Modified from Dappsys (https://github.com/dapphub/ds-roles/blob/master/src/roles.sol)\ncontract RolesAuthority is Auth, Authority {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event UserRoleUpdated(address indexed user, uint8 indexed role, bool enabled);\n\n event PublicCapabilityUpdated(address indexed target, bytes4 indexed functionSig, bool enabled);\n\n event RoleCapabilityUpdated(uint8 indexed role, address indexed target, bytes4 indexed functionSig, bool enabled);\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(address _owner, Authority _authority) Auth(_owner, _authority) {}\n\n /*//////////////////////////////////////////////////////////////\n ROLE/USER STORAGE\n //////////////////////////////////////////////////////////////*/\n\n mapping(address => bytes32) public getUserRoles;\n\n mapping(address => mapping(bytes4 => bool)) public isCapabilityPublic;\n\n mapping(address => mapping(bytes4 => bytes32)) public getRolesWithCapability;\n\n function doesUserHaveRole(address user, uint8 role) public view virtual returns (bool) {\n return (uint256(getUserRoles[user]) >> role) & 1 != 0;\n }\n\n function doesRoleHaveCapability(\n uint8 role,\n address target,\n bytes4 functionSig\n ) public view virtual returns (bool) {\n return (uint256(getRolesWithCapability[target][functionSig]) >> role) & 1 != 0;\n }\n\n /*//////////////////////////////////////////////////////////////\n AUTHORIZATION LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function canCall(\n address user,\n address target,\n bytes4 functionSig\n ) public view virtual override returns (bool) {\n return\n isCapabilityPublic[target][functionSig] ||\n bytes32(0) != getUserRoles[user] & getRolesWithCapability[target][functionSig];\n }\n\n /*//////////////////////////////////////////////////////////////\n ROLE CAPABILITY CONFIGURATION LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function setPublicCapability(\n address target,\n bytes4 functionSig,\n bool enabled\n ) public virtual requiresAuth {\n isCapabilityPublic[target][functionSig] = enabled;\n\n emit PublicCapabilityUpdated(target, functionSig, enabled);\n }\n\n function setRoleCapability(\n uint8 role,\n address target,\n bytes4 functionSig,\n bool enabled\n ) public virtual requiresAuth {\n if (enabled) {\n getRolesWithCapability[target][functionSig] |= bytes32(1 << role);\n } else {\n getRolesWithCapability[target][functionSig] &= ~bytes32(1 << role);\n }\n\n emit RoleCapabilityUpdated(role, target, functionSig, enabled);\n }\n\n /*//////////////////////////////////////////////////////////////\n USER ROLE ASSIGNMENT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function setUserRole(\n address user,\n uint8 role,\n bool enabled\n ) public virtual requiresAuth {\n if (enabled) {\n getUserRoles[user] |= bytes32(1 << role);\n } else {\n getUserRoles[user] &= ~bytes32(1 << role);\n }\n\n emit UserRoleUpdated(user, role, enabled);\n }\n}\n" + }, + "solmate/mixins/ERC4626.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\nimport {SafeTransferLib} from \"../utils/SafeTransferLib.sol\";\nimport {FixedPointMathLib} from \"../utils/FixedPointMathLib.sol\";\n\n/// @notice Minimal ERC4626 tokenized Vault implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/mixins/ERC4626.sol)\nabstract contract ERC4626 is ERC20 {\n using SafeTransferLib for ERC20;\n using FixedPointMathLib for uint256;\n\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares);\n\n event Withdraw(\n address indexed caller,\n address indexed receiver,\n address indexed owner,\n uint256 assets,\n uint256 shares\n );\n\n /*//////////////////////////////////////////////////////////////\n IMMUTABLES\n //////////////////////////////////////////////////////////////*/\n\n ERC20 public immutable asset;\n\n constructor(\n ERC20 _asset,\n string memory _name,\n string memory _symbol\n ) ERC20(_name, _symbol, _asset.decimals()) {\n asset = _asset;\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n // Check for rounding error since we round down in previewDeposit.\n require((shares = previewDeposit(assets)) != 0, \"ZERO_SHARES\");\n\n // Need to transfer before minting or ERC777s could reenter.\n asset.safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function mint(uint256 shares, address receiver) public virtual returns (uint256 assets) {\n assets = previewMint(shares); // No need to check for rounding error, previewMint rounds up.\n\n // Need to transfer before minting or ERC777s could reenter.\n asset.safeTransferFrom(msg.sender, address(this), assets);\n\n _mint(receiver, shares);\n\n emit Deposit(msg.sender, receiver, assets, shares);\n\n afterDeposit(assets, shares);\n }\n\n function withdraw(\n uint256 assets,\n address receiver,\n address owner\n ) public virtual returns (uint256 shares) {\n shares = previewWithdraw(assets); // No need to check for rounding error, previewWithdraw rounds up.\n\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n asset.safeTransfer(receiver, assets);\n }\n\n function redeem(\n uint256 shares,\n address receiver,\n address owner\n ) public virtual returns (uint256 assets) {\n if (msg.sender != owner) {\n uint256 allowed = allowance[owner][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[owner][msg.sender] = allowed - shares;\n }\n\n // Check for rounding error since we round down in previewRedeem.\n require((assets = previewRedeem(shares)) != 0, \"ZERO_ASSETS\");\n\n beforeWithdraw(assets, shares);\n\n _burn(owner, shares);\n\n emit Withdraw(msg.sender, receiver, owner, assets, shares);\n\n asset.safeTransfer(receiver, assets);\n }\n\n /*//////////////////////////////////////////////////////////////\n ACCOUNTING LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function totalAssets() public view virtual returns (uint256);\n\n function convertToShares(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivDown(supply, totalAssets());\n }\n\n function convertToAssets(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivDown(totalAssets(), supply);\n }\n\n function previewDeposit(uint256 assets) public view virtual returns (uint256) {\n return convertToShares(assets);\n }\n\n function previewMint(uint256 shares) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? shares : shares.mulDivUp(totalAssets(), supply);\n }\n\n function previewWithdraw(uint256 assets) public view virtual returns (uint256) {\n uint256 supply = totalSupply; // Saves an extra SLOAD if totalSupply is non-zero.\n\n return supply == 0 ? assets : assets.mulDivUp(supply, totalAssets());\n }\n\n function previewRedeem(uint256 shares) public view virtual returns (uint256) {\n return convertToAssets(shares);\n }\n\n /*//////////////////////////////////////////////////////////////\n DEPOSIT/WITHDRAWAL LIMIT LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function maxDeposit(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxMint(address) public view virtual returns (uint256) {\n return type(uint256).max;\n }\n\n function maxWithdraw(address owner) public view virtual returns (uint256) {\n return convertToAssets(balanceOf[owner]);\n }\n\n function maxRedeem(address owner) public view virtual returns (uint256) {\n return balanceOf[owner];\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL HOOKS LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function beforeWithdraw(uint256 assets, uint256 shares) internal virtual {}\n\n function afterDeposit(uint256 assets, uint256 shares) internal virtual {}\n}\n" + }, + "solmate/tokens/ERC20.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol)\n/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)\n/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.\nabstract contract ERC20 {\n /*//////////////////////////////////////////////////////////////\n EVENTS\n //////////////////////////////////////////////////////////////*/\n\n event Transfer(address indexed from, address indexed to, uint256 amount);\n\n event Approval(address indexed owner, address indexed spender, uint256 amount);\n\n /*//////////////////////////////////////////////////////////////\n METADATA STORAGE\n //////////////////////////////////////////////////////////////*/\n\n string public name;\n\n string public symbol;\n\n uint8 public immutable decimals;\n\n /*//////////////////////////////////////////////////////////////\n ERC20 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 public totalSupply;\n\n mapping(address => uint256) public balanceOf;\n\n mapping(address => mapping(address => uint256)) public allowance;\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 STORAGE\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal immutable INITIAL_CHAIN_ID;\n\n bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;\n\n mapping(address => uint256) public nonces;\n\n /*//////////////////////////////////////////////////////////////\n CONSTRUCTOR\n //////////////////////////////////////////////////////////////*/\n\n constructor(\n string memory _name,\n string memory _symbol,\n uint8 _decimals\n ) {\n name = _name;\n symbol = _symbol;\n decimals = _decimals;\n\n INITIAL_CHAIN_ID = block.chainid;\n INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function approve(address spender, uint256 amount) public virtual returns (bool) {\n allowance[msg.sender][spender] = amount;\n\n emit Approval(msg.sender, spender, amount);\n\n return true;\n }\n\n function transfer(address to, uint256 amount) public virtual returns (bool) {\n balanceOf[msg.sender] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(msg.sender, to, amount);\n\n return true;\n }\n\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual returns (bool) {\n uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.\n\n if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;\n\n balanceOf[from] -= amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(from, to, amount);\n\n return true;\n }\n\n /*//////////////////////////////////////////////////////////////\n EIP-2612 LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) public virtual {\n require(deadline >= block.timestamp, \"PERMIT_DEADLINE_EXPIRED\");\n\n // Unchecked because the only math done is incrementing\n // the owner's nonce which cannot realistically overflow.\n unchecked {\n address recoveredAddress = ecrecover(\n keccak256(\n abi.encodePacked(\n \"\\x19\\x01\",\n DOMAIN_SEPARATOR(),\n keccak256(\n abi.encode(\n keccak256(\n \"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)\"\n ),\n owner,\n spender,\n value,\n nonces[owner]++,\n deadline\n )\n )\n )\n ),\n v,\n r,\n s\n );\n\n require(recoveredAddress != address(0) && recoveredAddress == owner, \"INVALID_SIGNER\");\n\n allowance[recoveredAddress][spender] = value;\n }\n\n emit Approval(owner, spender, value);\n }\n\n function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {\n return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();\n }\n\n function computeDomainSeparator() internal view virtual returns (bytes32) {\n return\n keccak256(\n abi.encode(\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\"),\n keccak256(bytes(name)),\n keccak256(\"1\"),\n block.chainid,\n address(this)\n )\n );\n }\n\n /*//////////////////////////////////////////////////////////////\n INTERNAL MINT/BURN LOGIC\n //////////////////////////////////////////////////////////////*/\n\n function _mint(address to, uint256 amount) internal virtual {\n totalSupply += amount;\n\n // Cannot overflow because the sum of all user\n // balances can't exceed the max uint256 value.\n unchecked {\n balanceOf[to] += amount;\n }\n\n emit Transfer(address(0), to, amount);\n }\n\n function _burn(address from, uint256 amount) internal virtual {\n balanceOf[from] -= amount;\n\n // Cannot underflow because a user's balance\n // will never be larger than the total supply.\n unchecked {\n totalSupply -= amount;\n }\n\n emit Transfer(from, address(0), amount);\n }\n}\n" + }, + "solmate/utils/FixedPointMathLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Arithmetic library with operations for fixed-point numbers.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)\n/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)\nlibrary FixedPointMathLib {\n /*//////////////////////////////////////////////////////////////\n SIMPLIFIED FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.\n\n function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.\n }\n\n function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.\n }\n\n function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.\n }\n\n function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {\n return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.\n }\n\n /*//////////////////////////////////////////////////////////////\n LOW LEVEL FIXED POINT OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function mulDivDown(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n assembly {\n // Store x * y in z for now.\n z := mul(x, y)\n\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n revert(0, 0)\n }\n\n // Divide z by the denominator.\n z := div(z, denominator)\n }\n }\n\n function mulDivUp(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 z) {\n assembly {\n // Store x * y in z for now.\n z := mul(x, y)\n\n // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))\n if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n revert(0, 0)\n }\n\n // First, divide z - 1 by the denominator and add 1.\n // We allow z - 1 to underflow if z is 0, because we multiply the\n // end result by 0 if z is zero, ensuring we return 0 if z is zero.\n z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))\n }\n }\n\n function rpow(\n uint256 x,\n uint256 n,\n uint256 scalar\n ) internal pure returns (uint256 z) {\n assembly {\n switch x\n case 0 {\n switch n\n case 0 {\n // 0 ** 0 = 1\n z := scalar\n }\n default {\n // 0 ** n = 0\n z := 0\n }\n }\n default {\n switch mod(n, 2)\n case 0 {\n // If n is even, store scalar in z for now.\n z := scalar\n }\n default {\n // If n is odd, store x in z for now.\n z := x\n }\n\n // Shifting right by 1 is like dividing by 2.\n let half := shr(1, scalar)\n\n for {\n // Shift n right by 1 before looping to halve it.\n n := shr(1, n)\n } n {\n // Shift n right by 1 each iteration to halve it.\n n := shr(1, n)\n } {\n // Revert immediately if x ** 2 would overflow.\n // Equivalent to iszero(eq(div(xx, x), x)) here.\n if shr(128, x) {\n revert(0, 0)\n }\n\n // Store x squared.\n let xx := mul(x, x)\n\n // Round to the nearest number.\n let xxRound := add(xx, half)\n\n // Revert if xx + half overflowed.\n if lt(xxRound, xx) {\n revert(0, 0)\n }\n\n // Set x to scaled xxRound.\n x := div(xxRound, scalar)\n\n // If n is even:\n if mod(n, 2) {\n // Compute z * x.\n let zx := mul(z, x)\n\n // If z * x overflowed:\n if iszero(eq(div(zx, x), z)) {\n // Revert if x is non-zero.\n if iszero(iszero(x)) {\n revert(0, 0)\n }\n }\n\n // Round to the nearest number.\n let zxRound := add(zx, half)\n\n // Revert if zx + half overflowed.\n if lt(zxRound, zx) {\n revert(0, 0)\n }\n\n // Return properly scaled zxRound.\n z := div(zxRound, scalar)\n }\n }\n }\n }\n }\n\n /*//////////////////////////////////////////////////////////////\n GENERAL NUMBER UTILITIES\n //////////////////////////////////////////////////////////////*/\n\n function sqrt(uint256 x) internal pure returns (uint256 z) {\n assembly {\n let y := x // We start y at x, which will help us make our initial estimate.\n\n z := 181 // The \"correct\" value is 1, but this saves a multiplication later.\n\n // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad\n // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.\n\n // We check y >= 2^(k + 8) but shift right by k bits\n // each branch to ensure that if x >= 256, then y >= 256.\n if iszero(lt(y, 0x10000000000000000000000000000000000)) {\n y := shr(128, y)\n z := shl(64, z)\n }\n if iszero(lt(y, 0x1000000000000000000)) {\n y := shr(64, y)\n z := shl(32, z)\n }\n if iszero(lt(y, 0x10000000000)) {\n y := shr(32, y)\n z := shl(16, z)\n }\n if iszero(lt(y, 0x1000000)) {\n y := shr(16, y)\n z := shl(8, z)\n }\n\n // Goal was to get z*z*y within a small factor of x. More iterations could\n // get y in a tighter range. Currently, we will have y in [256, 256*2^16).\n // We ensured y >= 256 so that the relative difference between y and y+1 is small.\n // That's not possible if x < 256 but we can just verify those cases exhaustively.\n\n // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.\n // Correctness can be checked exhaustively for x < 256, so we assume y >= 256.\n // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.\n\n // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range\n // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.\n\n // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate\n // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.\n\n // There is no overflow risk here since y < 2^136 after the first branch above.\n z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.\n\n // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n z := shr(1, add(z, div(x, z)))\n\n // If x+1 is a perfect square, the Babylonian method cycles between\n // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.\n // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division\n // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.\n // If you don't care whether the floor or ceil square root is returned, you can remove this statement.\n z := sub(z, lt(div(x, z), z))\n }\n }\n\n function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n // Mod x by y. Note this will return\n // 0 instead of reverting if y is zero.\n z := mod(x, y)\n }\n }\n\n function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {\n assembly {\n // Divide x by y. Note this will return\n // 0 instead of reverting if y is zero.\n r := div(x, y)\n }\n }\n\n function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {\n assembly {\n // Add 1 to x * y if x % y > 0. Note this will\n // return 0 instead of reverting if y is zero.\n z := add(gt(mod(x, y), 0), div(x, y))\n }\n }\n}\n" + }, + "solmate/utils/SafeCastLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\n/// @notice Safe unsigned integer casting library that reverts on overflow.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeCastLib.sol)\n/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)\nlibrary SafeCastLib {\n function safeCastTo248(uint256 x) internal pure returns (uint248 y) {\n require(x < 1 << 248);\n\n y = uint248(x);\n }\n\n function safeCastTo224(uint256 x) internal pure returns (uint224 y) {\n require(x < 1 << 224);\n\n y = uint224(x);\n }\n\n function safeCastTo192(uint256 x) internal pure returns (uint192 y) {\n require(x < 1 << 192);\n\n y = uint192(x);\n }\n\n function safeCastTo160(uint256 x) internal pure returns (uint160 y) {\n require(x < 1 << 160);\n\n y = uint160(x);\n }\n\n function safeCastTo128(uint256 x) internal pure returns (uint128 y) {\n require(x < 1 << 128);\n\n y = uint128(x);\n }\n\n function safeCastTo96(uint256 x) internal pure returns (uint96 y) {\n require(x < 1 << 96);\n\n y = uint96(x);\n }\n\n function safeCastTo64(uint256 x) internal pure returns (uint64 y) {\n require(x < 1 << 64);\n\n y = uint64(x);\n }\n\n function safeCastTo32(uint256 x) internal pure returns (uint32 y) {\n require(x < 1 << 32);\n\n y = uint32(x);\n }\n\n function safeCastTo24(uint256 x) internal pure returns (uint24 y) {\n require(x < 1 << 24);\n\n y = uint24(x);\n }\n\n function safeCastTo16(uint256 x) internal pure returns (uint16 y) {\n require(x < 1 << 16);\n\n y = uint16(x);\n }\n\n function safeCastTo8(uint256 x) internal pure returns (uint8 y) {\n require(x < 1 << 8);\n\n y = uint8(x);\n }\n}\n" + }, + "solmate/utils/SafeTransferLib.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"../tokens/ERC20.sol\";\n\n/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)\n/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.\n/// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller.\nlibrary SafeTransferLib {\n /*//////////////////////////////////////////////////////////////\n ETH OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferETH(address to, uint256 amount) internal {\n bool success;\n\n assembly {\n // Transfer the ETH and store if it succeeded or not.\n success := call(gas(), to, amount, 0, 0, 0, 0)\n }\n\n require(success, \"ETH_TRANSFER_FAILED\");\n }\n\n /*//////////////////////////////////////////////////////////////\n ERC20 OPERATIONS\n //////////////////////////////////////////////////////////////*/\n\n function safeTransferFrom(\n ERC20 token,\n address from,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), from) // Append the \"from\" argument.\n mstore(add(freeMemoryPointer, 36), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 68), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)\n )\n }\n\n require(success, \"TRANSFER_FROM_FAILED\");\n }\n\n function safeTransfer(\n ERC20 token,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n )\n }\n\n require(success, \"TRANSFER_FAILED\");\n }\n\n function safeApprove(\n ERC20 token,\n address to,\n uint256 amount\n ) internal {\n bool success;\n\n assembly {\n // Get a pointer to some free memory.\n let freeMemoryPointer := mload(0x40)\n\n // Write the abi-encoded calldata into memory, beginning with the function selector.\n mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)\n mstore(add(freeMemoryPointer, 4), to) // Append the \"to\" argument.\n mstore(add(freeMemoryPointer, 36), amount) // Append the \"amount\" argument.\n\n success := and(\n // Set success to whether the call reverted, if not we check it either\n // returned exactly 1 (can't just be non-zero data), or had no return data.\n or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),\n // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.\n // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.\n // Counterintuitively, this call must be positioned second to the or() call in the\n // surrounding and() call or else returndatasize() will be zero during the computation.\n call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)\n )\n }\n\n require(success, \"APPROVE_FAILED\");\n }\n}\n" + } + }, + "settings": { + "optimizer": { + "enabled": true, + "runs": 200 + }, + "evmVersion": "paris", + "outputSelection": { + "*": { + "*": [ + "abi", + "evm.bytecode", + "evm.deployedBytecode", + "evm.methodIdentifiers", + "metadata", + "devdoc", + "userdoc", + "storageLayout", + "evm.gasEstimates" + ], + "": [ + "ast" + ] + } + }, + "metadata": { + "useLiteralContent": true + } + } +} \ No newline at end of file diff --git a/packages/contracts/foundry.toml b/packages/contracts/foundry.toml index 9dca53404a..0b43094370 100644 --- a/packages/contracts/foundry.toml +++ b/packages/contracts/foundry.toml @@ -1,5 +1,5 @@ [profile.default] -src = 'contracts' +src = 'contracts/src' bytecode_hash = 'none' solc_version = "0.8.22" libs = ["lib"] diff --git a/packages/contracts/hardhat.config.ts b/packages/contracts/hardhat.config.ts index 9aa7449a24..f028edd4cb 100644 --- a/packages/contracts/hardhat.config.ts +++ b/packages/contracts/hardhat.config.ts @@ -50,7 +50,7 @@ const config: HardhatUserConfig = { contracts: [{ artifacts: "./out" }] }, paths: { - sources: "./contracts", + sources: "./contracts/src", tests: "./contracts/test", artifacts: "./artifacts" }, diff --git a/packages/contracts/tasks/chain-specific/base/erc4626.ts b/packages/contracts/tasks/chain-specific/base/erc4626.ts new file mode 100644 index 0000000000..0b1bb2af7e --- /dev/null +++ b/packages/contracts/tasks/chain-specific/base/erc4626.ts @@ -0,0 +1,26 @@ +import { base } from "@ionicprotocol/chains"; +import { Address, zeroAddress } from "viem"; +import { task } from "hardhat/config"; +import { deployIonicMarketERC4626 } from "../../erc4626/deploy"; +import { COMPTROLLER } from "."; + +task("deploy:erc4626:base", "Deploy ERC4626 on Base").setAction(async ({}, { deployments, viem, getNamedAccounts }) => { + const { deployer, multisig } = await getNamedAccounts(); + const comptroller = await viem.getContractAt( + "contracts/src/compound/ComptrollerInterface.sol:IonicComptroller", + COMPTROLLER + ); + const symbols = ["USDC", "WETH"]; + const assets = base.assets.filter((asset) => symbols.includes(asset.symbol)); + for (const asset of assets) { + const cToken = await comptroller.read.cTokensByUnderlying([asset.underlying]); + if (cToken !== zeroAddress) { + await deployIonicMarketERC4626({ + cToken, + deployer, + deployments, + multisig: "0x7d922bf0975424b3371074f54cC784AF738Dac0D" + }); + } + } +}); diff --git a/packages/contracts/tasks/chain-specific/base/index.ts b/packages/contracts/tasks/chain-specific/base/index.ts index 90ef9f5367..269d75217a 100644 --- a/packages/contracts/tasks/chain-specific/base/index.ts +++ b/packages/contracts/tasks/chain-specific/base/index.ts @@ -7,6 +7,7 @@ import "./liquidation"; import "./leverage"; import "./oracle"; import "./hypernative"; +import "./erc4626"; export const COMPTROLLER = "0x05c9C6417F246600f8f5f49fcA9Ee991bfF73D13"; diff --git a/packages/contracts/tasks/erc4626/deploy.ts b/packages/contracts/tasks/erc4626/deploy.ts new file mode 100644 index 0000000000..43f7c33f2d --- /dev/null +++ b/packages/contracts/tasks/erc4626/deploy.ts @@ -0,0 +1,44 @@ +import { task } from "hardhat/config"; +import { HardhatRuntimeEnvironment } from "hardhat/types"; + +task("deploy:erc4626", "Deploy ERC4626") + .addParam("cToken", "The cToken to deploy the ERC4626 for") + .addOptionalParam("rewardsRecipient", "The rewardsRecipient to deploy the ERC4626 for") + .setAction(async (taskArgs, { deployments, viem, getNamedAccounts }) => { + const { deployer } = await getNamedAccounts(); + await deployIonicMarketERC4626({ ...taskArgs, deployer, deployments }); + }); + +export const deployIonicMarketERC4626 = async ({ + cToken, + rewardsRecipient, + deployer, + deployments, + multisig +}: { + cToken: string; + rewardsRecipient?: string; + deployer: string; + deployments: HardhatRuntimeEnvironment["deployments"]; + multisig?: string; +}) => { + const flywheelLensRouter = await deployments.get("IonicFlywheelLensRouter"); + const erc4626 = await deployments.deploy(`IonicMarketERC4626_${cToken}`, { + contract: "IonicMarketERC4626", + from: deployer, + log: true, + proxy: { + proxyContract: "OpenZeppelinTransparentProxy", + execute: { + init: { + methodName: "initialize", + args: [cToken, flywheelLensRouter.address, rewardsRecipient ?? deployer] + } + }, + owner: multisig ?? deployer + } + }); + + console.log("ERC4626 deployed to:", erc4626.address); + return erc4626; +}; diff --git a/packages/contracts/tasks/erc4626/index.ts b/packages/contracts/tasks/erc4626/index.ts new file mode 100644 index 0000000000..722510c23f --- /dev/null +++ b/packages/contracts/tasks/erc4626/index.ts @@ -0,0 +1 @@ +import "./deploy"; diff --git a/packages/contracts/tasks/index.ts b/packages/contracts/tasks/index.ts index 1c277ebf52..d4e0f341f8 100644 --- a/packages/contracts/tasks/index.ts +++ b/packages/contracts/tasks/index.ts @@ -9,3 +9,4 @@ import "./market"; import "./chain-specific"; import "./oracle"; import "./misc"; +import "./erc4626"; \ No newline at end of file From fa03e5d8ef24dfa8a9dfeab062b5ddd1f859cddb Mon Sep 17 00:00:00 2001 From: Rahul Sethuram Date: Fri, 24 Jan 2025 15:35:37 +0400 Subject: [PATCH 7/9] fix: toml --- packages/contracts/foundry.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/contracts/foundry.toml b/packages/contracts/foundry.toml index 0b43094370..9dca53404a 100644 --- a/packages/contracts/foundry.toml +++ b/packages/contracts/foundry.toml @@ -1,5 +1,5 @@ [profile.default] -src = 'contracts/src' +src = 'contracts' bytecode_hash = 'none' solc_version = "0.8.22" libs = ["lib"] From b5b9645b98f4fb69de2339e08940d72e813306b6 Mon Sep 17 00:00:00 2001 From: Rahul Sethuram Date: Fri, 24 Jan 2025 16:11:21 +0400 Subject: [PATCH 8/9] feat: hh --- packages/contracts/hardhat.config.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/contracts/hardhat.config.ts b/packages/contracts/hardhat.config.ts index f028edd4cb..9aa7449a24 100644 --- a/packages/contracts/hardhat.config.ts +++ b/packages/contracts/hardhat.config.ts @@ -50,7 +50,7 @@ const config: HardhatUserConfig = { contracts: [{ artifacts: "./out" }] }, paths: { - sources: "./contracts/src", + sources: "./contracts", tests: "./contracts/test", artifacts: "./artifacts" }, From c6783a8edaa4e67de180dc94d2e994741d00c01e Mon Sep 17 00:00:00 2001 From: Rahul Sethuram Date: Fri, 24 Jan 2025 16:18:37 +0400 Subject: [PATCH 9/9] fix: license --- packages/contracts/contracts/ionic/strategies/IonicERC4626.sol | 2 +- .../contracts/contracts/ionic/strategies/IonicMarketERC4626.sol | 2 +- packages/contracts/contracts/ionic/strategies/MockERC4626.sol | 2 +- .../contracts/contracts/ionic/strategies/MockERC4626Dynamic.sol | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol b/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol index 94645b1e7c..a6e83439e4 100644 --- a/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol +++ b/packages/contracts/contracts/ionic/strategies/IonicERC4626.sol @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: AGPL-3.0-only +// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.8.0; import { FixedPointMathLib } from "solmate/utils/FixedPointMathLib.sol"; diff --git a/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol b/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol index 5ae87eb93c..24ab80e029 100644 --- a/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol +++ b/packages/contracts/contracts/ionic/strategies/IonicMarketERC4626.sol @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: Unlicense +// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.22; import { IonicERC4626, ERC20Upgradeable } from "./IonicERC4626.sol"; import { SafeERC20Upgradeable } from "@openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol"; diff --git a/packages/contracts/contracts/ionic/strategies/MockERC4626.sol b/packages/contracts/contracts/ionic/strategies/MockERC4626.sol index 1895ad1b91..c8bd582d4b 100644 --- a/packages/contracts/contracts/ionic/strategies/MockERC4626.sol +++ b/packages/contracts/contracts/ionic/strategies/MockERC4626.sol @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: AGPL-3.0-only +// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import { ERC20 } from "solmate/tokens/ERC20.sol"; diff --git a/packages/contracts/contracts/ionic/strategies/MockERC4626Dynamic.sol b/packages/contracts/contracts/ionic/strategies/MockERC4626Dynamic.sol index 6fdf4e8904..d7fe9f6d36 100644 --- a/packages/contracts/contracts/ionic/strategies/MockERC4626Dynamic.sol +++ b/packages/contracts/contracts/ionic/strategies/MockERC4626Dynamic.sol @@ -1,4 +1,4 @@ -// SPDX-License-Identifier: AGPL-3.0-only +// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import { ERC20 } from "solmate/tokens/ERC20.sol";