diff --git a/packages/chains/src/optimism/assets.ts b/packages/chains/src/optimism/assets.ts index 3a573dbc9..380cc8a12 100644 --- a/packages/chains/src/optimism/assets.ts +++ b/packages/chains/src/optimism/assets.ts @@ -18,6 +18,7 @@ export const wstETH = "0x1F32b1c2345538c0c6f582fCB022739c4A194Ebb"; export const SNX = "0x8700dAec35aF8Ff88c16BdF0418774CB3D7599B4"; export const WBTC = "0x68f180fcCe6836688e9084f035309E29Bf0A2095"; export const LUSD = "0xc40F949F8a4e094D1b49a23ea9241D289B7b2819"; +export const wUSDM = "0x57F5E098CaD7A3D1Eed53991D4d66C45C9AF7812"; export const assets: SupportedAsset[] = [ { @@ -129,6 +130,21 @@ export const assets: SupportedAsset[] = [ initialCf: "70", initialSupplyCap: parseEther(String(2_200_000)).toString(), initialBorrowCap: parseEther(String(1_700_000)).toString() + }, + { + symbol: assetSymbols.wUSDM, + underlying: wUSDM, + name: "Wrapped USDM", + decimals: 18, + oracle: OracleTypes.ChainlinkPriceOracleV2, + oracleSpecificParams: { + aggregator: "0xD673873c8627b29d9e245cDC133c6dA0a398b65A", + feedBaseCurrency: ChainlinkFeedBaseCurrency.USD + }, + extraDocs: defaultDocs("https://optimistic.etherscan.io", wUSDM), + initialCf: "82", + initialSupplyCap: parseEther(String(1_300_000)).toString(), + initialBorrowCap: parseEther(String(1_000_000)).toString() } ]; diff --git a/packages/contracts/deployments/optimism/UniswapV3LiquidatorFunder.json b/packages/contracts/deployments/optimism/UniswapV3LiquidatorFunder.json index 5ff0a1b15..22228cc55 100644 --- a/packages/contracts/deployments/optimism/UniswapV3LiquidatorFunder.json +++ b/packages/contracts/deployments/optimism/UniswapV3LiquidatorFunder.json @@ -1,545 +1,167 @@ { - "address": "0xdd7F712Af76074993F05C0d544331792997Bd39b", + "address": "0x30f604583991155e51fC891904E5c9b508C222Ec", "abi": [ { - "type": "function", - "name": "convert", "inputs": [ { + "internalType": "contract IERC20Upgradeable", "name": "inputToken", - "type": "address", - "internalType": "contract IERC20Upgradeable" + "type": "address" }, { + "internalType": "uint256", "name": "inputAmount", - "type": "uint256", - "internalType": "uint256" + "type": "uint256" }, { + "internalType": "bytes", "name": "strategyData", - "type": "bytes", - "internalType": "bytes" + "type": "bytes" } ], + "name": "convert", "outputs": [ { + "internalType": "contract IERC20Upgradeable", "name": "outputToken", - "type": "address", - "internalType": "contract IERC20Upgradeable" + "type": "address" }, { + "internalType": "uint256", "name": "outputAmount", - "type": "uint256", - "internalType": "uint256" + "type": "uint256" } ], - "stateMutability": "nonpayable" + "stateMutability": "nonpayable", + "type": "function" }, { - "type": "function", - "name": "estimateInputAmount", "inputs": [ { + "internalType": "uint256", "name": "outputAmount", - "type": "uint256", - "internalType": "uint256" + "type": "uint256" }, { + "internalType": "bytes", "name": "strategyData", - "type": "bytes", - "internalType": "bytes" + "type": "bytes" } ], + "name": "estimateInputAmount", "outputs": [ { + "internalType": "contract IERC20Upgradeable", "name": "inputToken", - "type": "address", - "internalType": "contract IERC20Upgradeable" + "type": "address" }, { + "internalType": "uint256", "name": "inputAmount", - "type": "uint256", - "internalType": "uint256" + "type": "uint256" } ], - "stateMutability": "view" + "stateMutability": "view", + "type": "function" }, { - "type": "function", - "name": "name", "inputs": [], + "name": "name", "outputs": [ { + "internalType": "string", "name": "", - "type": "string", - "internalType": "string" + "type": "string" } ], - "stateMutability": "pure" + "stateMutability": "pure", + "type": "function" }, { - "type": "function", - "name": "redeem", "inputs": [ { + "internalType": "contract IERC20Upgradeable", "name": "inputToken", - "type": "address", - "internalType": "contract IERC20Upgradeable" + "type": "address" }, { + "internalType": "uint256", "name": "inputAmount", - "type": "uint256", - "internalType": "uint256" + "type": "uint256" }, { + "internalType": "bytes", "name": "strategyData", - "type": "bytes", - "internalType": "bytes" + "type": "bytes" } ], + "name": "redeem", "outputs": [ { + "internalType": "contract IERC20Upgradeable", "name": "outputToken", - "type": "address", - "internalType": "contract IERC20Upgradeable" + "type": "address" }, { + "internalType": "uint256", "name": "outputAmount", - "type": "uint256", - "internalType": "uint256" + "type": "uint256" } ], - "stateMutability": "nonpayable" + "stateMutability": "nonpayable", + "type": "function" } ], - "transactionHash": "0x92d5cbfd67e645924411c8f661407e6a5b71070caf9a227390f4520fc2c0e411", + "transactionHash": "0x5dd72d2d34a59ee4135b02664503ea7aa8d23a80be86ce2674684138c2f31e11", "receipt": { "to": null, "from": "0x1155b614971f16758C92c4890eD338C9e3ede6b7", - "contractAddress": "0xdd7F712Af76074993F05C0d544331792997Bd39b", - "transactionIndex": 25, - "gasUsed": "377249", + "contractAddress": "0x30f604583991155e51fC891904E5c9b508C222Ec", + "transactionIndex": 1, + "gasUsed": "381373", "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", - "blockHash": "0x902ea5f904a862a92c09ab8a8447dfa49ac253d3c82ab758dac1ab6cadbd8596", - "transactionHash": "0x92d5cbfd67e645924411c8f661407e6a5b71070caf9a227390f4520fc2c0e411", + "blockHash": "0xed7d12c0ad40563fff769b546d2371a0e60b720946b17899c3197c12fdc1d180", + "transactionHash": "0x5dd72d2d34a59ee4135b02664503ea7aa8d23a80be86ce2674684138c2f31e11", "logs": [], - "blockNumber": 121602289, - "cumulativeGasUsed": "3380486", + "blockNumber": 125779522, + "cumulativeGasUsed": "425224", "status": 1, "byzantium": true }, "args": [], - "numDeployments": 1, - "metadata": { - "compiler": { - "version": "0.8.10+commit.fc410830" - }, - "language": "Solidity", - "output": { - "abi": [ - { - "inputs": [ - { - "internalType": "contract IERC20Upgradeable", - "name": "inputToken", - "type": "address" - }, - { - "internalType": "uint256", - "name": "inputAmount", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "strategyData", - "type": "bytes" - } - ], - "stateMutability": "nonpayable", - "type": "function", - "name": "convert", - "outputs": [ - { - "internalType": "contract IERC20Upgradeable", - "name": "outputToken", - "type": "address" - }, - { - "internalType": "uint256", - "name": "outputAmount", - "type": "uint256" - } - ] - }, - { - "inputs": [ - { - "internalType": "uint256", - "name": "outputAmount", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "strategyData", - "type": "bytes" - } - ], - "stateMutability": "view", - "type": "function", - "name": "estimateInputAmount", - "outputs": [ - { - "internalType": "contract IERC20Upgradeable", - "name": "inputToken", - "type": "address" - }, - { - "internalType": "uint256", - "name": "inputAmount", - "type": "uint256" - } - ] - }, - { - "inputs": [], - "stateMutability": "pure", - "type": "function", - "name": "name", - "outputs": [ - { - "internalType": "string", - "name": "", - "type": "string" - } - ] - }, - { - "inputs": [ - { - "internalType": "contract IERC20Upgradeable", - "name": "inputToken", - "type": "address" - }, - { - "internalType": "uint256", - "name": "inputAmount", - "type": "uint256" - }, - { - "internalType": "bytes", - "name": "strategyData", - "type": "bytes" - } - ], - "stateMutability": "nonpayable", - "type": "function", - "name": "redeem", - "outputs": [ - { - "internalType": "contract IERC20Upgradeable", - "name": "outputToken", - "type": "address" - }, - { - "internalType": "uint256", - "name": "outputAmount", - "type": "uint256" - } - ] + "numDeployments": 2, + "solcInputHash": "12da963895fa0833fcadb2c199c06f28", + "metadata": "{\"compiler\":{\"version\":\"0.8.22+commit.4fc1097e\"},\"language\":\"Solidity\",\"output\":{\"abi\":[{\"inputs\":[{\"internalType\":\"contract IERC20Upgradeable\",\"name\":\"inputToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"inputAmount\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"strategyData\",\"type\":\"bytes\"}],\"name\":\"convert\",\"outputs\":[{\"internalType\":\"contract IERC20Upgradeable\",\"name\":\"outputToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"outputAmount\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"outputAmount\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"strategyData\",\"type\":\"bytes\"}],\"name\":\"estimateInputAmount\",\"outputs\":[{\"internalType\":\"contract IERC20Upgradeable\",\"name\":\"inputToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"inputAmount\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"contract IERC20Upgradeable\",\"name\":\"inputToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"inputAmount\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"strategyData\",\"type\":\"bytes\"}],\"name\":\"redeem\",\"outputs\":[{\"internalType\":\"contract IERC20Upgradeable\",\"name\":\"outputToken\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"outputAmount\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}],\"devdoc\":{\"kind\":\"dev\",\"methods\":{\"estimateInputAmount(uint256,bytes)\":{\"details\":\"Estimates the needed input amount of the input token for the conversion to return the desired output amount.\",\"params\":{\"outputAmount\":\"the desired output amount\",\"strategyData\":\"the input token\"}},\"redeem(address,uint256,bytes)\":{\"details\":\"Redeems `inputToken` for `outputToken` where `inputAmount` < `outputAmount`\",\"params\":{\"inputAmount\":\"input amount\",\"inputToken\":\"Address of the token\",\"strategyData\":\"context specific data like input token, pool address and tx expiratio period\"}}},\"version\":1},\"userdoc\":{\"kind\":\"user\",\"methods\":{},\"version\":1}},\"settings\":{\"compilationTarget\":{\"contracts/liquidators/UniswapV3LiquidatorFunder.sol\":\"UniswapV3LiquidatorFunder\"},\"evmVersion\":\"paris\",\"libraries\":{},\"metadata\":{\"bytecodeHash\":\"ipfs\",\"useLiteralContent\":true},\"optimizer\":{\"enabled\":true,\"runs\":200},\"remappings\":[]},\"sources\":{\"contracts/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\\u00d7b\\u00f7denominator) 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\\u00d7b\\u00f7denominator) 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\",\"keccak256\":\"0xf42bdded6dc8044ea0321c72dcf05e2c422122beed96889c478326907ed51d16\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0x94c0f98bad3dc5b39706fbe5704b3a31d6399177fb72abc906f5ffa64c2562c2\",\"license\":\"GPL-2.0-or-later\"},\"contracts/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\",\"keccak256\":\"0x815e94e8e575e572117cf045489c699e2e0cb56b7d2dd1a9adb1b0b1f8ac25e1\",\"license\":\"GPL-3.0-only\"},\"contracts/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\",\"keccak256\":\"0x01e66a0dca41f6e36bc20da4f66ff0e47b6b09ee9dcf59ce272a6e15a6c91a19\",\"license\":\"GPL-2.0-or-later\"},\"contracts/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\",\"keccak256\":\"0xb2fb3532ff4b51c3aeedfbd85161048e9423d91e4e9c15a4784dbfd9431156ae\",\"license\":\"GPL-2.0-or-later\"},\"contracts/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\",\"keccak256\":\"0x3f485fb1a44e8fbeadefb5da07d66edab3cfe809f0ac4074b1e54e3eb3c4cf69\",\"license\":\"GPL-2.0-or-later\"},\"contracts/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\",\"keccak256\":\"0xe95fc9d2ee5575049d60bcd0927866fee6f01398456929833541c0c7ca3ed8f5\",\"license\":\"GPL-2.0-or-later\"},\"contracts/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\",\"keccak256\":\"0x432aca6b585c17a1130b0eb17a8f9ff1c3d1de49adbfea0e31b6d6c3c63c52a7\",\"license\":\"GPL-2.0-or-later\"},\"contracts/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\",\"keccak256\":\"0xcfbc88a172c99b9d4ef5b1fa9f97513fe6f41565f87cb5d8070a1f938985d70c\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0x04323a39bc058fccb502d2fb2ef9438560f4b8b06bc51d1a072c1b39b2006d45\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0x4354205b233dc56b0809867666845265260cb4059554a4bd4f35b0360508fea0\",\"license\":\"BUSL-1.1\"},\"contracts/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\",\"keccak256\":\"0xfebe8703ca93969f7314c5eefcd48125059abaa94182dac93ae202e761055d88\",\"license\":\"GPL-2.0-or-later\"},\"contracts/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\",\"keccak256\":\"0x6565078afaf4a8bc4804a95da936fd5a66c4b0095eabd462da0620d5388b7326\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0xd9c548394832b82a4c4221b5a323fe2986061b759637ad87b23430d43e8fefad\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0x07062c5e1b28cf94a3c995566bb9acc7f1f23f555e9765d6bba7629a71f7c30e\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0x43f569e74a7d31db8e077710734e3267de08f7ce6eb2618f153ea7338e1eb774\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0x9aeb9a4b82064c1e0cd82046e4f5a011f74485461676599f76de6ffb969a25a0\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0x34d6754b798385e60b1b7ca9a405d371ce4986f73b3d08ce906b47eff2eaca2a\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0xf25585e84e48d80c4d3ee87d73e57f0f81ca0e81876e50a29653b235762b544e\",\"license\":\"MIT\"},\"contracts/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 \\u2014 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 \\u2014 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 \\u2014 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\",\"keccak256\":\"0x53d99c9e769a4d6fc8f96a4db7c772a83a92b1822484992b2667b1afeb4c471e\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0x0dd2a7751c58a90757ef0c4e2a8f438d32e22e3f09eb0697229b1205ebda06dd\",\"license\":\"MIT\"},\"contracts/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\",\"keccak256\":\"0x6630728b314eb1b184ce20a66bb9797539211e40a7159890a0990de28e0f7e66\",\"license\":\"MIT\"},\"contracts/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(uint256 outputAmount, bytes memory strategyData)\\n external\\n view\\n returns (IERC20Upgradeable inputToken, uint256 inputAmount);\\n}\\n\",\"keccak256\":\"0xa8bb583271cf321f13f24304b0d03aa951d63aca61bcbbff22d2b44138240271\",\"license\":\"UNLICENSED\"},\"contracts/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\",\"keccak256\":\"0x4cf72f79d325ed14f3c8d52e013a8d1f8bfe15b59553bbd9dff251761baf60dd\",\"license\":\"UNLICENSED\"},\"contracts/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\",\"keccak256\":\"0xca10c4271aab376d1bd2a01c448f8102e997832da138dd982fc23cbe89c88b91\",\"license\":\"UNLICENSED\"},\"contracts/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\",\"keccak256\":\"0xf251b80dd8b16f0d8eeb90dd033f4fca4666c9c7931546f870ece6b6d4b900ff\",\"license\":\"UNLICENSED\"},\"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\"},\"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": "0x608060405234801561001057600080fd5b506105f0806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c806306fdde031461005157806310badf4e1461009957806330132996146100cb57806389eabf0214610099575b600080fd5b604080518082018252601981527f556e697377617056334c697175696461746f7246756e64657200000000000000602082015290516100909190610345565b60405180910390f35b6100ac6100a736600461044f565b6100de565b604080516001600160a01b039093168352602083019190915201610090565b6100ac6100d93660046104a8565b6100f8565b6000806100ec8585856101b6565b91509150935093915050565b600080600080600080868060200190518101906101159190610507565b6040516386ed50b160e01b81526001600160a01b0380871660048301528086166024830152604482018f905262ffffff8516606483015295995093975091955090935050908216906386ed50b190608401602060405180830381865afa158015610183573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101a79190610578565b93989397509295505050505050565b6000806000806000858060200190518101906101d29190610507565b5060405163095ea7b360e01b81526001600160a01b038083166004830152602482018d90529399508997509195509350908a16915063095ea7b3906044016020604051808303816000875af115801561022f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102539190610591565b506040805160e0810182526001600160a01b038a811682528581166020830190815262ffffff8681168486019081523060608601908152608086018e8152600060a0880181815260c0890191825298516304e45aaf60e01b815297518716600489015294518616602488015291519092166044860152905183166064850152516084840152925160a48301529151821660c4820152908216906304e45aaf9060e4016020604051808303816000875af1158015610314573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103389190610578565b9350505050935093915050565b60006020808352835180602085015260005b8181101561037357858101830151858201604001528201610357565b506000604082860101526040601f19601f8301168501019250505092915050565b6001600160a01b03811681146103a957600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126103d357600080fd5b813567ffffffffffffffff808211156103ee576103ee6103ac565b604051601f8301601f19908116603f01168101908282118183101715610416576104166103ac565b8160405283815286602085880101111561042f57600080fd5b836020870160208301376000602085830101528094505050505092915050565b60008060006060848603121561046457600080fd5b833561046f81610394565b925060208401359150604084013567ffffffffffffffff81111561049257600080fd5b61049e868287016103c2565b9150509250925092565b600080604083850312156104bb57600080fd5b82359150602083013567ffffffffffffffff8111156104d957600080fd5b6104e5858286016103c2565b9150509250929050565b805162ffffff8116811461050257600080fd5b919050565b600080600080600060a0868803121561051f57600080fd5b855161052a81610394565b602087015190955061053b81610394565b9350610549604087016104ef565b9250606086015161055981610394565b608087015190925061056a81610394565b809150509295509295909350565b60006020828403121561058a57600080fd5b5051919050565b6000602082840312156105a357600080fd5b815180151581146105b357600080fd5b939250505056fea26469706673582212207716a92ad1236e367da9c113a9a242d174933ce2c80dd5c13c7d7e6d17c3d27164736f6c63430008160033", + "deployedBytecode": "0x608060405234801561001057600080fd5b506004361061004c5760003560e01c806306fdde031461005157806310badf4e1461009957806330132996146100cb57806389eabf0214610099575b600080fd5b604080518082018252601981527f556e697377617056334c697175696461746f7246756e64657200000000000000602082015290516100909190610345565b60405180910390f35b6100ac6100a736600461044f565b6100de565b604080516001600160a01b039093168352602083019190915201610090565b6100ac6100d93660046104a8565b6100f8565b6000806100ec8585856101b6565b91509150935093915050565b600080600080600080868060200190518101906101159190610507565b6040516386ed50b160e01b81526001600160a01b0380871660048301528086166024830152604482018f905262ffffff8516606483015295995093975091955090935050908216906386ed50b190608401602060405180830381865afa158015610183573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101a79190610578565b93989397509295505050505050565b6000806000806000858060200190518101906101d29190610507565b5060405163095ea7b360e01b81526001600160a01b038083166004830152602482018d90529399508997509195509350908a16915063095ea7b3906044016020604051808303816000875af115801561022f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102539190610591565b506040805160e0810182526001600160a01b038a811682528581166020830190815262ffffff8681168486019081523060608601908152608086018e8152600060a0880181815260c0890191825298516304e45aaf60e01b815297518716600489015294518616602488015291519092166044860152905183166064850152516084840152925160a48301529151821660c4820152908216906304e45aaf9060e4016020604051808303816000875af1158015610314573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103389190610578565b9350505050935093915050565b60006020808352835180602085015260005b8181101561037357858101830151858201604001528201610357565b506000604082860101526040601f19601f8301168501019250505092915050565b6001600160a01b03811681146103a957600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126103d357600080fd5b813567ffffffffffffffff808211156103ee576103ee6103ac565b604051601f8301601f19908116603f01168101908282118183101715610416576104166103ac565b8160405283815286602085880101111561042f57600080fd5b836020870160208301376000602085830101528094505050505092915050565b60008060006060848603121561046457600080fd5b833561046f81610394565b925060208401359150604084013567ffffffffffffffff81111561049257600080fd5b61049e868287016103c2565b9150509250925092565b600080604083850312156104bb57600080fd5b82359150602083013567ffffffffffffffff8111156104d957600080fd5b6104e5858286016103c2565b9150509250929050565b805162ffffff8116811461050257600080fd5b919050565b600080600080600060a0868803121561051f57600080fd5b855161052a81610394565b602087015190955061053b81610394565b9350610549604087016104ef565b9250606086015161055981610394565b608087015190925061056a81610394565b809150509295509295909350565b60006020828403121561058a57600080fd5b5051919050565b6000602082840312156105a357600080fd5b815180151581146105b357600080fd5b939250505056fea26469706673582212207716a92ad1236e367da9c113a9a242d174933ce2c80dd5c13c7d7e6d17c3d27164736f6c63430008160033", + "devdoc": { + "kind": "dev", + "methods": { + "estimateInputAmount(uint256,bytes)": { + "details": "Estimates the needed input amount of the input token for the conversion to return the desired output amount.", + "params": { + "outputAmount": "the desired output amount", + "strategyData": "the input token" } - ], - "devdoc": { - "kind": "dev", - "methods": { - "estimateInputAmount(uint256,bytes)": { - "details": "Estimates the needed input amount of the input token for the conversion to return the desired output amount.", - "params": { - "outputAmount": "the desired output amount", - "strategyData": "the input token" - } - }, - "redeem(address,uint256,bytes)": { - "details": "Redeems `inputToken` for `outputToken` where `inputAmount` < `outputAmount`", - "params": { - "inputAmount": "input amount", - "inputToken": "Address of the token", - "strategyData": "context specific data like input token, pool address and tx expiratio period" - } - } - }, - "version": 1 - }, - "userdoc": { - "kind": "user", - "methods": {}, - "version": 1 - } - }, - "settings": { - "remappings": [ - "@openzeppelin/=lib/openzeppelin-contracts/", - "@pythnetwork/pyth-sdk-solidity/=lib/pyth-sdk-solidity/", - "ds-test/=lib/forge-std/lib/ds-test/src/", - "flywheel-v2/=lib/flywheel-v2/src/", - "flywheel/=lib/flywheel-v2/src/", - "forge-std/=lib/forge-std/src/", - "fuse-flywheel/=lib/fuse-flywheel/src/", - "libcompound/=lib/fuse-flywheel/lib/libcompound/src/", - "openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/", - "openzeppelin-contracts/=lib/openzeppelin-contracts/", - "ops/=lib/ops/contracts/", - "pyth-sdk-solidity/=lib/pyth-sdk-solidity/", - "solidity-bytes-utils/=lib/solidity-bytes-utils/", - "solmate/=lib/solmate/src/", - "weird-erc20/=lib/fuse-flywheel/lib/libcompound/lib/solmate/lib/weird-erc20/src/" - ], - "optimizer": { - "enabled": true, - "runs": 200 - }, - "metadata": { - "bytecodeHash": "none" - }, - "compilationTarget": { - "contracts/liquidators/UniswapV3LiquidatorFunder.sol": "UniswapV3LiquidatorFunder" - }, - "evmVersion": "london", - "libraries": {} - }, - "sources": { - "contracts/external/uniswap/FullMath.sol": { - "keccak256": "0xf42bdded6dc8044ea0321c72dcf05e2c422122beed96889c478326907ed51d16", - "urls": [ - "bzz-raw://bbfbeea6a13bcccc9cda3baca1abad21d0321f58b2e4ca1409676e875211c0e2", - "dweb:/ipfs/QmTyabQbLPZtgxWUWjKKcZbyGq8RLqrF2tYiHgcyAMkLhx" - ], - "license": "MIT" - }, - "contracts/external/uniswap/ISwapRouter.sol": { - "keccak256": "0xbf2cbc91aa604597c3ef848d2f06cadd3311f6c7ede999c4d1285f3fb0a6c29c", - "urls": [ - "bzz-raw://8ed6693c1a8d97a3d5cdb4a6841ceb0cb560a5b2d9bcd0cc154747f8f9042d95", - "dweb:/ipfs/QmTWgMBEGSg3hkw156sH6EdPKJs33aEMvRnAuPxBU4Rkwh" - ], - "license": "GPL-2.0-or-later" }, - "contracts/external/uniswap/IUniswapV3Factory.sol": { - "keccak256": "0x94c0f98bad3dc5b39706fbe5704b3a31d6399177fb72abc906f5ffa64c2562c2", - "urls": [ - "bzz-raw://73cda2d2ad8a6c05e0f8062a321aaff79875af0ae453851f9b38be1681e959a2", - "dweb:/ipfs/QmV9enKToiN6j1L8tyhtnnLaF71zezfbvBGGMttzpFxvib" - ], - "license": "GPL-2.0-or-later" - }, - "contracts/external/uniswap/IUniswapV3Pool.sol": { - "keccak256": "0x815e94e8e575e572117cf045489c699e2e0cb56b7d2dd1a9adb1b0b1f8ac25e1", - "urls": [ - "bzz-raw://534fe33dbc8e307f2147cc69d29a355286a771df150bed70c4c374ea7febb6c1", - "dweb:/ipfs/QmWohCBjoNJ4EvnagKDAXMdbWKQfkzy6b38nv4MiA954kP" - ], - "license": "GPL-3.0-only" - }, - "contracts/external/uniswap/IUniswapV3PoolActions.sol": { - "keccak256": "0x01e66a0dca41f6e36bc20da4f66ff0e47b6b09ee9dcf59ce272a6e15a6c91a19", - "urls": [ - "bzz-raw://95ee248454c4ebf271eccb55e75a7d8dda95fa5d5b7a79663fafda8aafc33f48", - "dweb:/ipfs/QmNRebYSFFqF5YDAwLRHWhkVKXXkG14WZG9DBFUz6JvYzv" - ], - "license": "GPL-2.0-or-later" - }, - "contracts/external/uniswap/IUniswapV3PoolImmutables.sol": { - "keccak256": "0xb2fb3532ff4b51c3aeedfbd85161048e9423d91e4e9c15a4784dbfd9431156ae", - "urls": [ - "bzz-raw://5f965f4e671be7be392920a11b6e4002bb7c37f7a982e623bce8009756d905eb", - "dweb:/ipfs/QmQsL77K4wBdo438WJQFGmivkre8DwX5MUAUn9CXjd6mQ3" - ], - "license": "GPL-2.0-or-later" - }, - "contracts/external/uniswap/TickMath.sol": { - "keccak256": "0x432aca6b585c17a1130b0eb17a8f9ff1c3d1de49adbfea0e31b6d6c3c63c52a7", - "urls": [ - "bzz-raw://10c432b1dd129bb34296da0afd02173ecfe5202b9c74f4c932ca637598d1d83f", - "dweb:/ipfs/QmRCsdh53Hgj116nygDMXaR6yimaoPLDKfQpXUyePN8RmQ" - ], - "license": "GPL-2.0-or-later" - }, - "contracts/external/uniswap/quoter/Quoter.sol": { - "keccak256": "0xcfbc88a172c99b9d4ef5b1fa9f97513fe6f41565f87cb5d8070a1f938985d70c", - "urls": [ - "bzz-raw://03242a2062487ac15664c4f14d0e1370dd198538eef6df0ef5b64da29533ea22", - "dweb:/ipfs/QmPedCVSAQqskamWeciGUqHaeYQYvsJC3A4obtn5s1cqeP" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/UniswapV3Quoter.sol": { - "keccak256": "0x04323a39bc058fccb502d2fb2ef9438560f4b8b06bc51d1a072c1b39b2006d45", - "urls": [ - "bzz-raw://7858414b0f2e41f0cf0f21a7c9583998f3a15acf7892367bd6496086a022fe3d", - "dweb:/ipfs/QmdGuWgJakrFp1fuyoT3uDzTcS338JyAKd9j6zizzuDsrW" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/interfaces/IQuoter.sol": { - "keccak256": "0x4354205b233dc56b0809867666845265260cb4059554a4bd4f35b0360508fea0", - "urls": [ - "bzz-raw://34bd85abf2e9afdccff4fdb86238f65f0d65763d7ab3085c1c8e0a9cb2bb8336", - "dweb:/ipfs/Qmei92ZwCECLoUn5Qo5dPjHQKWaeLxaaKupUSbSMQYKEKW" - ], - "license": "BUSL-1.1" - }, - "contracts/external/uniswap/quoter/interfaces/IUniswapV3Quoter.sol": { - "keccak256": "0xfebe8703ca93969f7314c5eefcd48125059abaa94182dac93ae202e761055d88", - "urls": [ - "bzz-raw://0f4e9637fbbfb9827b7618a526e77aed7aaaeeac8171ffabf10c63750e47c110", - "dweb:/ipfs/QmQSka5JJRCETfpf2zxWbATGM9tMpcEVMNqYTwcPMwRYCw" - ], - "license": "GPL-2.0-or-later" - }, - "contracts/external/uniswap/quoter/libraries/BitMath.sol": { - "keccak256": "0x6565078afaf4a8bc4804a95da936fd5a66c4b0095eabd462da0620d5388b7326", - "urls": [ - "bzz-raw://4a58e5028df3b3a6cf226a38eab08e63395585fc830f4fb94814faf19a8c5328", - "dweb:/ipfs/QmPeBHp7gpAjHAGDE2RTxbsst2itdM2EVHTe3msNhNae9s" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/libraries/FixedPoint96.sol": { - "keccak256": "0xd9c548394832b82a4c4221b5a323fe2986061b759637ad87b23430d43e8fefad", - "urls": [ - "bzz-raw://5a529f5e9e305dce4759053bd37bf792365eba7acffe2a8f78194026e132406b", - "dweb:/ipfs/QmcMKr1Bpuyy9xpxSxAozKRpuRr5gn4jmm7WbbW7EDxPKn" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/libraries/LiquidityMath.sol": { - "keccak256": "0x07062c5e1b28cf94a3c995566bb9acc7f1f23f555e9765d6bba7629a71f7c30e", - "urls": [ - "bzz-raw://92e8ea45e9f8ee9003d5d42d9ec392e0c1defcd6062ad25da66eb70be6690c4a", - "dweb:/ipfs/QmYwGkkhzXj9JU7yMZPtVn3nweVzc1VBGKSWazQybCgAmC" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/libraries/LowGasSafeMath.sol": { - "keccak256": "0x43f569e74a7d31db8e077710734e3267de08f7ce6eb2618f153ea7338e1eb774", - "urls": [ - "bzz-raw://e3e318fb677fb99c201f388e40dd93f67cad4cb1c2a0d8dd901aa9813bba0f9c", - "dweb:/ipfs/QmejmugUfzgFuvDq2Vnjxsi9e8W2BvNNxanXeTYCmDMETU" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/libraries/SafeCast.sol": { - "keccak256": "0x9aeb9a4b82064c1e0cd82046e4f5a011f74485461676599f76de6ffb969a25a0", - "urls": [ - "bzz-raw://f3110d69148e257380ab72f4b5c27a1e7a021e73944c0166bc3a6a0925a0f803", - "dweb:/ipfs/Qmdj8kRv48exiVRUwyG4tBbiGoXRGXm4HfL68oPcgpupfX" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/libraries/SqrtPriceMath.sol": { - "keccak256": "0x34d6754b798385e60b1b7ca9a405d371ce4986f73b3d08ce906b47eff2eaca2a", - "urls": [ - "bzz-raw://4cbca60e47507c6303fc088bec93ac3786b1032b69f83ff3917800cd9cc4f5b2", - "dweb:/ipfs/QmR3mMMZPrUksTxMyF5NKA2tJXgviXNxREd8Mb5ESnYd18" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/libraries/SwapMath.sol": { - "keccak256": "0xf25585e84e48d80c4d3ee87d73e57f0f81ca0e81876e50a29653b235762b544e", - "urls": [ - "bzz-raw://874eebad61e4a8f1c3581610bf9a007ec7ee28c150c7e3aebc0da9abf57f5a4f", - "dweb:/ipfs/QmUR6SavN7CCjGhSvHJoteJaoYNLejPojKs1MRdubowREB" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/libraries/Tick.sol": { - "keccak256": "0x53d99c9e769a4d6fc8f96a4db7c772a83a92b1822484992b2667b1afeb4c471e", - "urls": [ - "bzz-raw://70d06ee5667c6f132175f712753337182bb3628f37ec1debd45ddf704ee7bdab", - "dweb:/ipfs/Qmb8ipgNiFyHTjgkgB9X3EetLPwYavUZwLo69zUTJEXsib" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/libraries/TickBitmap.sol": { - "keccak256": "0x0dd2a7751c58a90757ef0c4e2a8f438d32e22e3f09eb0697229b1205ebda06dd", - "urls": [ - "bzz-raw://5f675c996f9ded31becef610d52b62b658aaa7747d9baf8285d36a3d2e6d1189", - "dweb:/ipfs/QmQp2Rj62adULrkbWrWGm7zJwuQrvfp8UcB7Ge4sS5Yovh" - ], - "license": "MIT" - }, - "contracts/external/uniswap/quoter/libraries/UnsafeMath.sol": { - "keccak256": "0x6630728b314eb1b184ce20a66bb9797539211e40a7159890a0990de28e0f7e66", - "urls": [ - "bzz-raw://6b6614cc8be2c075f08acc3a50ee17c2f1f44648de752095e684ff3fa2e9f608", - "dweb:/ipfs/Qme8NDfnaUogxXkbdSDkuzgotEhu9SHr6SsGwX7qvyZkYi" - ], - "license": "MIT" - }, - "contracts/liquidators/IFundsConversionStrategy.sol": { - "keccak256": "0xa8bb583271cf321f13f24304b0d03aa951d63aca61bcbbff22d2b44138240271", - "urls": [ - "bzz-raw://75dcf6023f0638ea92256efb1c052b54229479ab8da3f51a0a72d78523b6ad6b", - "dweb:/ipfs/QmTzBcHW2j7RK2GVAc1Bn5XnL9Nxm6bRdxodcnkrf3zY4G" - ], - "license": "UNLICENSED" - }, - "contracts/liquidators/IRedemptionStrategy.sol": { - "keccak256": "0x4cf72f79d325ed14f3c8d52e013a8d1f8bfe15b59553bbd9dff251761baf60dd", - "urls": [ - "bzz-raw://057886f22f3ce6c62b3052f70cbe2684371c8b2541ad5cd6e8df917a9973a8e6", - "dweb:/ipfs/QmeHaakFX1WHDx3NhuwhmxKLWySGiG3JCZrGHTrjC8jyAL" - ], - "license": "UNLICENSED" - }, - "contracts/liquidators/UniswapV3Liquidator.sol": { - "keccak256": "0xf17713fef94adc7f2e65caeb7ed1fabf06456ec8ff5804d2e4d2f74f4ec3ef9b", - "urls": [ - "bzz-raw://cede45c3e4f14efee44e899af3f2b22f16d0cc2826d81d8953645c584d07694f", - "dweb:/ipfs/QmeeDK4KnJ7BH2JZsSdJPeutPpajq6x2GoTySkRcFTtbss" - ], - "license": "UNLICENSED" - }, - "contracts/liquidators/UniswapV3LiquidatorFunder.sol": { - "keccak256": "0x13555f27f7c68bc5f8458804576e258bac169bf7f4590a8ce92c9d4aaf622ef1", - "urls": [ - "bzz-raw://cef858e267204eefaa90706cf0c03e6b24ff4ab894caf9cb026f62bfc41d5a87", - "dweb:/ipfs/QmZYsHSNKGTD9Sn7EZQWqDtR3tnsiqwanwX3ejN1NXg6MM" - ], - "license": "UNLICENSED" - }, - "lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol": { - "keccak256": "0x4e733d3164f73f461eaf9d8087a7ad1ea180bdc8ba0d3d61b0e1ae16d8e63dff", - "urls": [ - "bzz-raw://75b47c3aeca7b66ea6752f8be020ec5c1c502de6ec9065272dae23d3a52196e2", - "dweb:/ipfs/QmUebPMHv16tYKFh5BmBQkMfRFb5b8UZ2RgVwdjxCeufVF" - ], - "license": "MIT" - }, - "lib/solmate/src/utils/FixedPointMathLib.sol": { - "keccak256": "0xab8ca9afbb0f7412e1408d4f111b53cc00813bc752236638ad336050ea2188f8", - "urls": [ - "bzz-raw://cd892e4743a124063b7bc590c6f88f209a18a4831b18045afd843264fa75427f", - "dweb:/ipfs/QmRunGD7E8enP5oZKiN8DxvAJew7J3jaz1iiHTFZj5Ghfc" - ], - "license": "AGPL-3.0-only" + "redeem(address,uint256,bytes)": { + "details": "Redeems `inputToken` for `outputToken` where `inputAmount` < `outputAmount`", + "params": { + "inputAmount": "input amount", + "inputToken": "Address of the token", + "strategyData": "context specific data like input token, pool address and tx expiratio period" + } } }, "version": 1 }, - "bytecode": { - "object": "0x608060405234801561001057600080fd5b506105dd806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c806306fdde031461005157806310badf4e1461009957806330132996146100cb57806389eabf0214610099575b600080fd5b604080518082018252601981527f556e697377617056334c697175696461746f7246756e64657200000000000000602082015290516100909190610355565b60405180910390f35b6100ac6100a7366004610465565b6100de565b604080516001600160a01b039093168352602083019190915201610090565b6100ac6100d93660046104be565b6100f8565b6000806100ec8585856101b6565b91509150935093915050565b60008060008060008086806020019051810190610115919061051d565b6040516386ed50b160e01b81526001600160a01b0380871660048301528086166024830152604482018f905262ffffff8516606483015295995093975091955090935050908216906386ed50b190608401602060405180830381865afa158015610183573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101a7919061058e565b93989397509295505050505050565b6000806000806000858060200190518101906101d2919061051d565b5060405163095ea7b360e01b81526001600160a01b038083166004830152602482018d90529399508997509195509350908a16915063095ea7b3906044016020604051808303816000875af115801561022f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061025391906105a7565b5060408051610100810182526001600160a01b038a811682528581166020830190815262ffffff8681168486019081523060608601908152426080870190815260a087018f8152600060c0890181815260e08a01918252995163414bf38960e01b81529851881660048a0152955187166024890152925190931660448701525184166064860152905160848501525160a4840152925160c48301529151821660e48201529082169063414bf38990610104016020604051808303816000875af1158015610324573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610348919061058e565b9350505050935093915050565b600060208083528351808285015260005b8181101561038257858101830151858201604001528201610366565b81811115610394576000604083870101525b50601f01601f1916929092016040019392505050565b6001600160a01b03811681146103bf57600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126103e957600080fd5b813567ffffffffffffffff80821115610404576104046103c2565b604051601f8301601f19908116603f0116810190828211818310171561042c5761042c6103c2565b8160405283815286602085880101111561044557600080fd5b836020870160208301376000602085830101528094505050505092915050565b60008060006060848603121561047a57600080fd5b8335610485816103aa565b925060208401359150604084013567ffffffffffffffff8111156104a857600080fd5b6104b4868287016103d8565b9150509250925092565b600080604083850312156104d157600080fd5b82359150602083013567ffffffffffffffff8111156104ef57600080fd5b6104fb858286016103d8565b9150509250929050565b805162ffffff8116811461051857600080fd5b919050565b600080600080600060a0868803121561053557600080fd5b8551610540816103aa565b6020870151909550610551816103aa565b935061055f60408701610505565b9250606086015161056f816103aa565b6080870151909250610580816103aa565b809150509295509295909350565b6000602082840312156105a057600080fd5b5051919050565b6000602082840312156105b957600080fd5b815180151581146105c957600080fd5b939250505056fea164736f6c634300080a000a", - "sourceMap": "380:1255:227:-:0;;;;;;;;;;;;;;;;;;;", - "linkReferences": {} - }, - "deployedBytecode": { - "object": "0x608060405234801561001057600080fd5b506004361061004c5760003560e01c806306fdde031461005157806310badf4e1461009957806330132996146100cb57806389eabf0214610099575b600080fd5b604080518082018252601981527f556e697377617056334c697175696461746f7246756e64657200000000000000602082015290516100909190610355565b60405180910390f35b6100ac6100a7366004610465565b6100de565b604080516001600160a01b039093168352602083019190915201610090565b6100ac6100d93660046104be565b6100f8565b6000806100ec8585856101b6565b91509150935093915050565b60008060008060008086806020019051810190610115919061051d565b6040516386ed50b160e01b81526001600160a01b0380871660048301528086166024830152604482018f905262ffffff8516606483015295995093975091955090935050908216906386ed50b190608401602060405180830381865afa158015610183573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101a7919061058e565b93989397509295505050505050565b6000806000806000858060200190518101906101d2919061051d565b5060405163095ea7b360e01b81526001600160a01b038083166004830152602482018d90529399508997509195509350908a16915063095ea7b3906044016020604051808303816000875af115801561022f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061025391906105a7565b5060408051610100810182526001600160a01b038a811682528581166020830190815262ffffff8681168486019081523060608601908152426080870190815260a087018f8152600060c0890181815260e08a01918252995163414bf38960e01b81529851881660048a0152955187166024890152925190931660448701525184166064860152905160848501525160a4840152925160c48301529151821660e48201529082169063414bf38990610104016020604051808303816000875af1158015610324573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610348919061058e565b9350505050935093915050565b600060208083528351808285015260005b8181101561038257858101830151858201604001528201610366565b81811115610394576000604083870101525b50601f01601f1916929092016040019392505050565b6001600160a01b03811681146103bf57600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b600082601f8301126103e957600080fd5b813567ffffffffffffffff80821115610404576104046103c2565b604051601f8301601f19908116603f0116810190828211818310171561042c5761042c6103c2565b8160405283815286602085880101111561044557600080fd5b836020870160208301376000602085830101528094505050505092915050565b60008060006060848603121561047a57600080fd5b8335610485816103aa565b925060208401359150604084013567ffffffffffffffff8111156104a857600080fd5b6104b4868287016103d8565b9150509250925092565b600080604083850312156104d157600080fd5b82359150602083013567ffffffffffffffff8111156104ef57600080fd5b6104fb858286016103d8565b9150509250929050565b805162ffffff8116811461051857600080fd5b919050565b600080600080600060a0868803121561053557600080fd5b8551610540816103aa565b6020870151909550610551816103aa565b935061055f60408701610505565b9250606086015161056f816103aa565b6080870151909250610580816103aa565b809150509295509295909350565b6000602082840312156105a057600080fd5b5051919050565b6000602082840312156105b957600080fd5b815180151581146105c957600080fd5b939250505056fea164736f6c634300080a000a", - "sourceMap": "380:1255:227:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1485:148;1594:34;;;;;;;;;;;;;;;;1485:148;;;;1594:34;1485:148;:::i;:::-;;;;;;;;652:255:226;;;;;;:::i;:::-;;:::i;:::-;;;;-1:-1:-1;;;;;2421:32:504;;;2403:51;;2485:2;2470:18;;2463:34;;;;2376:18;652:255:226;2201:302:504;991:490:227;;;;;;:::i;:::-;;:::i;652:255:226:-;789:29;820:20;855:47;864:10;876:11;889:12;855:8;:47::i;:::-;848:54;;;;652:255;;;;;;:::o;991:490:227:-;1104:28;1134:19;1164;1185:20;1207:10;1221:13;1256:12;1238:91;;;;;;;;;;;;:::i;:::-;1350:77;;-1:-1:-1;;;1350:77:227;;-1:-1:-1;;;;;4228:15:504;;;1350:77:227;;;4210:34:504;4280:15;;;4260:18;;;4253:43;4312:18;;;4305:34;;;4387:8;4375:21;;4355:18;;;4348:49;1163:166:227;;-1:-1:-1;1163:166:227;;-1:-1:-1;1163:166:227;;-1:-1:-1;1163:166:227;;-1:-1:-1;;1350:31:227;;;;;;4144:19:504;;1350:77:227;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;1464:11;;1336:91;;-1:-1:-1;991:490:227;;-1:-1:-1;;;;;;991:490:227:o;911:721:226:-;1041:29;1072:20;1103;1125:10;1137:22;1183:12;1165:92;;;;;;;;;;;;:::i;:::-;-1:-1:-1;1315:52:226;;-1:-1:-1;;;1315:52:226;;-1:-1:-1;;;;;2421:32:504;;;1315:52:226;;;2403:51:504;2470:18;;;2463:34;;;1100:157:226;;-1:-1:-1;1100:157:226;;-1:-1:-1;1100:157:226;;-1:-1:-1;1100:157:226;-1:-1:-1;1315:18:226;;;;-1:-1:-1;1315:18:226;;2376::504;;1315:52:226;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;-1:-1:-1;1424:197:226;;;;;;;;-1:-1:-1;;;;;1424:197:226;;;;;;;;;;;;;;;;;;;;;;;;1540:4;1424:197;;;;;;1555:15;1424:197;;;;;;;;;;;;-1:-1:-1;1424:197:226;;;;;;;;;;;;1389:238;;-1:-1:-1;;;1389:238:226;;6311:13:504;;6307:22;;1389:238:226;;;6289:41:504;6372:24;;6368:33;;6346:20;;;6339:63;6444:24;;6440:39;;;6418:20;;;6411:69;6522:24;6518:33;;6496:20;;;6489:63;6590:24;;6568:20;;;6561:54;6653:24;6631:20;;;6624:54;6716:24;;6694:20;;;6687:54;6783:24;;6779:33;;6757:20;;;6750:63;1389:27:226;;;;;;6223:19:504;;1389:238:226;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;1374:253;;1094:538;;;911:721;;;;;;:::o;14:597:504:-;126:4;155:2;184;173:9;166:21;216:6;210:13;259:6;254:2;243:9;239:18;232:34;284:1;294:140;308:6;305:1;302:13;294:140;;;403:14;;;399:23;;393:30;369:17;;;388:2;365:26;358:66;323:10;;294:140;;;452:6;449:1;446:13;443:91;;;522:1;517:2;508:6;497:9;493:22;489:31;482:42;443:91;-1:-1:-1;595:2:504;574:15;-1:-1:-1;;570:29:504;555:45;;;;602:2;551:54;;14:597;-1:-1:-1;;;14:597:504:o;616:150::-;-1:-1:-1;;;;;710:31:504;;700:42;;690:70;;756:1;753;746:12;690:70;616:150;:::o;771:127::-;832:10;827:3;823:20;820:1;813:31;863:4;860:1;853:15;887:4;884:1;877:15;903:718;945:5;998:3;991:4;983:6;979:17;975:27;965:55;;1016:1;1013;1006:12;965:55;1052:6;1039:20;1078:18;1115:2;1111;1108:10;1105:36;;;1121:18;;:::i;:::-;1196:2;1190:9;1164:2;1250:13;;-1:-1:-1;;1246:22:504;;;1270:2;1242:31;1238:40;1226:53;;;1294:18;;;1314:22;;;1291:46;1288:72;;;1340:18;;:::i;:::-;1380:10;1376:2;1369:22;1415:2;1407:6;1400:18;1461:3;1454:4;1449:2;1441:6;1437:15;1433:26;1430:35;1427:55;;;1478:1;1475;1468:12;1427:55;1542:2;1535:4;1527:6;1523:17;1516:4;1508:6;1504:17;1491:54;1589:1;1582:4;1577:2;1569:6;1565:15;1561:26;1554:37;1609:6;1600:15;;;;;;903:718;;;;:::o;1626:570::-;1740:6;1748;1756;1809:2;1797:9;1788:7;1784:23;1780:32;1777:52;;;1825:1;1822;1815:12;1777:52;1864:9;1851:23;1883:50;1927:5;1883:50;:::i;:::-;1952:5;-1:-1:-1;2004:2:504;1989:18;;1976:32;;-1:-1:-1;2059:2:504;2044:18;;2031:32;2086:18;2075:30;;2072:50;;;2118:1;2115;2108:12;2072:50;2141:49;2182:7;2173:6;2162:9;2158:22;2141:49;:::i;:::-;2131:59;;;1626:570;;;;;:::o;2508:388::-;2585:6;2593;2646:2;2634:9;2625:7;2621:23;2617:32;2614:52;;;2662:1;2659;2652:12;2614:52;2698:9;2685:23;2675:33;;2759:2;2748:9;2744:18;2731:32;2786:18;2778:6;2775:30;2772:50;;;2818:1;2815;2808:12;2772:50;2841:49;2882:7;2873:6;2862:9;2858:22;2841:49;:::i;:::-;2831:59;;;2508:388;;;;;:::o;2901:165::-;2979:13;;3032:8;3021:20;;3011:31;;3001:59;;3056:1;3053;3046:12;3001:59;2901:165;;;:::o;3071:867::-;3229:6;3237;3245;3253;3261;3314:3;3302:9;3293:7;3289:23;3285:33;3282:53;;;3331:1;3328;3321:12;3282:53;3363:9;3357:16;3382:50;3426:5;3382:50;:::i;:::-;3501:2;3486:18;;3480:25;3451:5;;-1:-1:-1;3514:52:504;3480:25;3514:52;:::i;:::-;3585:7;-1:-1:-1;3611:48:504;3655:2;3640:18;;3611:48;:::i;:::-;3601:58;;3704:2;3693:9;3689:18;3683:25;3717:52;3761:7;3717:52;:::i;:::-;3840:3;3825:19;;3819:26;3788:7;;-1:-1:-1;3854:52:504;3819:26;3854:52;:::i;:::-;3925:7;3915:17;;;3071:867;;;;;;;;:::o;4408:184::-;4478:6;4531:2;4519:9;4510:7;4506:23;4502:32;4499:52;;;4547:1;4544;4537:12;4499:52;-1:-1:-1;4570:16:504;;4408:184;-1:-1:-1;4408:184:504:o;5740:277::-;5807:6;5860:2;5848:9;5839:7;5835:23;5831:32;5828:52;;;5876:1;5873;5866:12;5828:52;5908:9;5902:16;5961:5;5954:13;5947:21;5940:5;5937:32;5927:60;;5983:1;5980;5973:12;5927:60;6006:5;5740:277;-1:-1:-1;;;5740:277:504:o", - "linkReferences": {} + "userdoc": { + "kind": "user", + "methods": {}, + "version": 1 }, - "methodIdentifiers": { - "convert(address,uint256,bytes)": "89eabf02", - "estimateInputAmount(uint256,bytes)": "30132996", - "name()": "06fdde03", - "redeem(address,uint256,bytes)": "10badf4e" + "storageLayout": { + "storage": [], + "types": null } } \ No newline at end of file diff --git a/packages/contracts/deployments/optimism/solcInputs/12da963895fa0833fcadb2c199c06f28.json b/packages/contracts/deployments/optimism/solcInputs/12da963895fa0833fcadb2c199c06f28.json new file mode 100644 index 000000000..0ad1a8d89 --- /dev/null +++ b/packages/contracts/deployments/optimism/solcInputs/12da963895fa0833fcadb2c199c06f28.json @@ -0,0 +1,600 @@ +{ + "language": "Solidity", + "sources": { + "@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/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/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/ProxyAdmin.sol": { + "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (proxy/transparent/ProxyAdmin.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./TransparentUpgradeableProxy.sol\";\nimport \"../../access/Ownable.sol\";\n\n/**\n * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an\n * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}.\n */\ncontract ProxyAdmin is Ownable {\n /**\n * @dev Returns the current implementation of `proxy`.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function getProxyImplementation(TransparentUpgradeableProxy proxy) public view virtual returns (address) {\n // We need to manually run the static call since the getter cannot be flagged as view\n // bytes4(keccak256(\"implementation()\")) == 0x5c60da1b\n (bool success, bytes memory returndata) = address(proxy).staticcall(hex\"5c60da1b\");\n require(success);\n return abi.decode(returndata, (address));\n }\n\n /**\n * @dev Returns the current admin of `proxy`.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function getProxyAdmin(TransparentUpgradeableProxy proxy) public view virtual returns (address) {\n // We need to manually run the static call since the getter cannot be flagged as view\n // bytes4(keccak256(\"admin()\")) == 0xf851a440\n (bool success, bytes memory returndata) = address(proxy).staticcall(hex\"f851a440\");\n require(success);\n return abi.decode(returndata, (address));\n }\n\n /**\n * @dev Changes the admin of `proxy` to `newAdmin`.\n *\n * Requirements:\n *\n * - This contract must be the current admin of `proxy`.\n */\n function changeProxyAdmin(TransparentUpgradeableProxy proxy, address newAdmin) public virtual onlyOwner {\n proxy.changeAdmin(newAdmin);\n }\n\n /**\n * @dev Upgrades `proxy` to `implementation`. See {TransparentUpgradeableProxy-upgradeTo}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function upgrade(TransparentUpgradeableProxy proxy, address implementation) public virtual onlyOwner {\n proxy.upgradeTo(implementation);\n }\n\n /**\n * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. See\n * {TransparentUpgradeableProxy-upgradeToAndCall}.\n *\n * Requirements:\n *\n * - This contract must be the admin of `proxy`.\n */\n function upgradeAndCall(\n TransparentUpgradeableProxy proxy,\n address implementation,\n bytes memory data\n ) public payable virtual onlyOwner {\n proxy.upgradeToAndCall{value: msg.value}(implementation, data);\n }\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/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" + }, + "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/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/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/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/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/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/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/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/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/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\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\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 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 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 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 /*** 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 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 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 /*** 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/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/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 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 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 transferAllowed(address cToken, address src, address dst, uint256 transferTokens) external returns (uint256);\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/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/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 { DiamondExtension, LibDiamond } from \"../ionic/DiamondExtension.sol\";\nimport { PoolLens } from \"../PoolLens.sol\";\nimport { IonicUniV3Liquidator } from \"../IonicUniV3Liquidator.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 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 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 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 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 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 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 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 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) 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) 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) 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 // unused function\n // comptroller.borrowVerify(address(this), borrower, borrowAmount);\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 // unused function\n // comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);\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 // unused function\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/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 { Multicall } from \"../utils/Multicall.sol\";\n\nimport { IERC20, SafeERC20 } from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport { AddressesProvider } from \"../ionic/AddressesProvider.sol\";\n\ncontract CTokenFirstExtension is\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(\n address spender,\n address src,\n address dst,\n uint256 tokens\n ) 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 // unused function\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(address dst, uint256 amount) public override nonReentrant(false) isAuthorized 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 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(address spender, uint256 amount) public override isAuthorized 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(uint256 newReserveFactorMantissa) 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(uint256 newAdminFeeMantissa) 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(InterestRateModel newInterestRateModel)\n public\n override\n nonReentrant(false)\n returns (uint256)\n {\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(uint256 blockNumber, uint256 cashPrior)\n internal\n view\n returns (InterestAccrual memory accrual)\n {\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)\n external\n view\n override\n returns (\n uint256,\n uint256,\n uint256,\n uint256\n )\n {\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 {\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(bytes[] calldata data)\n public\n payable\n override(CTokenFirstExtensionInterface, Multicall)\n returns (bytes[] memory results)\n {\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/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/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/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/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/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/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/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/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/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/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/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/external/balancer/IBalancerPool.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity >=0.8.0;\n\nimport { IBalancerVault } from \"./IBalancerVault.sol\";\n\ninterface IBalancerPool {\n function getFinalTokens() external view returns (address[] memory);\n\n function getNormalizedWeight(address token) external view returns (uint256);\n\n function getNormalizedWeights() external view returns (uint256[] memory);\n\n function getSwapFee() external view returns (uint256);\n\n function getNumTokens() external view returns (uint256);\n\n function getBalance(address token) external view returns (uint256);\n\n function totalSupply() external view returns (uint256);\n\n function getPoolId() external view returns (bytes32);\n\n function getVault() external view returns (IBalancerVault);\n\n function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;\n\n function swapExactAmountIn(\n address tokenIn,\n uint256 tokenAmountIn,\n address tokenOut,\n uint256 minAmountOut,\n uint256 maxPrice\n ) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);\n\n function swapExactAmountOut(\n address tokenIn,\n uint256 maxAmountIn,\n address tokenOut,\n uint256 tokenAmountOut,\n uint256 maxPrice\n ) external returns (uint256 tokenAmountIn, uint256 spotPriceAfter);\n\n function joinswapExternAmountIn(\n address tokenIn,\n uint256 tokenAmountIn,\n uint256 minPoolAmountOut\n ) external returns (uint256 poolAmountOut);\n\n function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;\n\n function exitswapExternAmountOut(\n address tokenOut,\n uint256 tokenAmountOut,\n uint256 maxPoolAmountIn\n ) external returns (uint256 poolAmountIn);\n}\n" + }, + "contracts/external/balancer/IBalancerVault.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\npragma solidity >=0.8.0;\n\nimport { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ninterface IAsset {}\n\nenum UserBalanceOpKind {\n DEPOSIT_INTERNAL,\n WITHDRAW_INTERNAL,\n TRANSFER_INTERNAL,\n TRANSFER_EXTERNAL\n}\n\nenum SwapKind {\n GIVEN_IN,\n GIVEN_OUT\n}\n\nenum ExitKind {\n EXACT_BPT_IN_FOR_ONE_TOKEN_OUT,\n EXACT_BPT_IN_FOR_TOKENS_OUT,\n BPT_IN_FOR_EXACT_TOKENS_OUT,\n MANAGEMENT_FEE_TOKENS_OUT\n}\n\nstruct UserBalanceOp {\n UserBalanceOpKind kind;\n IAsset asset;\n uint256 amount;\n address sender;\n address payable recipient;\n}\nstruct FundManagement {\n address sender;\n bool fromInternalBalance;\n address payable recipient;\n bool toInternalBalance;\n}\n\nstruct SingleSwap {\n bytes32 poolId;\n SwapKind kind;\n IAsset assetIn;\n IAsset assetOut;\n uint256 amount;\n bytes userData;\n}\n\nstruct ExitPoolRequest {\n IERC20Upgradeable[] assets;\n uint256[] minAmountsOut;\n bytes userData;\n bool toInternalBalance;\n}\n\ninterface IBalancerVault {\n function swap(\n SingleSwap memory singleSwap,\n FundManagement memory funds,\n uint256 limit,\n uint256 deadline\n ) external returns (uint256 amountCalculated);\n\n function manageUserBalance(UserBalanceOp[] memory ops) external payable;\n\n function getPoolTokens(bytes32 poolId)\n external\n view\n returns (\n IERC20Upgradeable[] memory tokens,\n uint256[] memory balances,\n uint256 lastChangeBlock\n );\n\n function exitPool(\n bytes32 poolId,\n address sender,\n address payable recipient,\n ExitPoolRequest memory request\n ) external;\n}\n" + }, + "contracts/external/bomb/IXBomb.sol": { + "content": "pragma solidity >=0.8.0;\n\nimport { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ninterface IXBomb is IERC20Upgradeable {\n function reward() external view returns (IERC20Upgradeable);\n\n function leave(uint256 _share) external;\n\n function enter(uint256 _amount) external;\n\n function getExchangeRate() external view returns (uint256);\n\n function toREWARD(uint256 stakedAmount) external view returns (uint256 rewardAmount);\n\n function toSTAKED(uint256 rewardAmount) external view returns (uint256 stakedAmount);\n\n function name() external view returns (string memory);\n\n function symbol() external view returns (string memory);\n}\n" + }, + "contracts/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/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/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/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/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/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(\n uint256 _token_amount,\n int128 i,\n uint256 min_amount\n ) 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(\n int128 i,\n int128 j,\n uint256 dx,\n uint256 min_dy\n ) external returns (uint256);\n\n function get_dy(\n int128 i,\n int128 j,\n uint256 _dx\n ) 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/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/external/jarvis/ISynthereumDeployment.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.4;\n\nimport { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"./ISynthereumFinder.sol\";\n\n/**\n * @title Interface that a pool MUST have in order to be included in the deployer\n */\ninterface ISynthereumDeployment {\n /**\n * @notice Get Synthereum finder of the pool/self-minting derivative\n * @return finder Returns finder contract\n */\n function synthereumFinder() external view returns (ISynthereumFinder finder);\n\n /**\n * @notice Get Synthereum version\n * @return poolVersion Returns the version of this pool/self-minting derivative\n */\n function version() external view returns (uint8 poolVersion);\n\n /**\n * @notice Get the collateral token of this pool/self-minting derivative\n * @return collateralCurrency The ERC20 collateral token\n */\n function collateralToken() external view returns (IERC20Upgradeable collateralCurrency);\n\n /**\n * @notice Get the synthetic token associated to this pool/self-minting derivative\n * @return syntheticCurrency The ERC20 synthetic token\n */\n function syntheticToken() external view returns (IERC20Upgradeable syntheticCurrency);\n\n /**\n * @notice Get the synthetic token symbol associated to this pool/self-minting derivative\n * @return symbol The ERC20 synthetic token symbol\n */\n function syntheticTokenSymbol() external view returns (string memory symbol);\n}\n" + }, + "contracts/external/jarvis/ISynthereumFinder.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.4;\n\n/**\n * @title Provides addresses of the contracts implementing certain interfaces.\n */\ninterface ISynthereumFinder {\n /**\n * @notice Updates the address of the contract that implements `interfaceName`.\n * @param interfaceName bytes32 encoding of the interface name that is either changed or registered.\n * @param implementationAddress address of the deployed contract that implements the interface.\n */\n function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external;\n\n /**\n * @notice Gets the address of the contract that implements the given `interfaceName`.\n * @param interfaceName queried interface.\n * @return implementationAddress Address of the deployed contract that implements the interface.\n */\n function getImplementationAddress(bytes32 interfaceName) external view returns (address);\n}\n" + }, + "contracts/external/jarvis/ISynthereumLiquidityPool.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.4;\n\nimport \"./ISynthereumLiquidityPoolGeneral.sol\";\n\n//import {\n//IEmergencyShutdown\n//} from '../../../common/interfaces/IEmergencyShutdown.sol';\n//import {ISynthereumLiquidityPoolGeneral} from './ILiquidityPoolGeneral.sol';\n//import {ISynthereumLiquidityPoolStorage} from './ILiquidityPoolStorage.sol';\n//import {ITypology} from '../../../common/interfaces/ITypology.sol';\n\n/**\n * @title Token Issuer Contract Interface\n */\n//ITypology,\n//IEmergencyShutdown,\ninterface ISynthereumLiquidityPool is ISynthereumLiquidityPoolGeneral {\n struct MintParams {\n // Minimum amount of synthetic tokens that a user wants to mint using collateral (anti-slippage)\n uint256 minNumTokens;\n // Amount of collateral that a user wants to spend for minting\n uint256 collateralAmount;\n // Expiration time of the transaction\n uint256 expiration;\n // Address to which send synthetic tokens minted\n address recipient;\n }\n\n struct RedeemParams {\n // Amount of synthetic tokens that user wants to use for redeeming\n uint256 numTokens;\n // Minimium amount of collateral that user wants to redeem (anti-slippage)\n uint256 minCollateral;\n // Expiration time of the transaction\n uint256 expiration;\n // Address to which send collateral tokens redeemed\n address recipient;\n }\n\n // struct ExchangeParams {\n // // Destination pool\n // ISynthereumLiquidityPoolGeneral destPool;\n // // Amount of source synthetic tokens that user wants to use for exchanging\n // uint256 numTokens;\n // // Minimum Amount of destination synthetic tokens that user wants to receive (anti-slippage)\n // uint256 minDestNumTokens;\n // // Expiration time of the transaction\n // uint256 expiration;\n // // Address to which send synthetic tokens exchanged\n // address recipient;\n // }\n\n /**\n * @notice Mint synthetic tokens using fixed amount of collateral\n * @notice This calculate the price using on chain price feed\n * @notice User must approve collateral transfer for the mint request to succeed\n * @param mintParams Input parameters for minting (see MintParams struct)\n * @return syntheticTokensMinted Amount of synthetic tokens minted by a user\n * @return feePaid Amount of collateral paid by the user as fee\n */\n function mint(MintParams calldata mintParams) external returns (uint256 syntheticTokensMinted, uint256 feePaid);\n\n /**\n * @notice Redeem amount of collateral using fixed number of synthetic token\n * @notice This calculate the price using on chain price feed\n * @notice User must approve synthetic token transfer for the redeem request to succeed\n * @param redeemParams Input parameters for redeeming (see RedeemParams struct)\n * @return collateralRedeemed Amount of collateral redeem by user\n * @return feePaid Amount of collateral paid by user as fee\n */\n function redeem(RedeemParams calldata redeemParams) external returns (uint256 collateralRedeemed, uint256 feePaid);\n\n // /**\n // * @notice Exchange a fixed amount of synthetic token of this pool, with an amount of synthetic tokens of an another pool\n // * @notice This calculate the price using on chain price feed\n // * @notice User must approve synthetic token transfer for the redeem request to succeed\n // * @param exchangeParams Input parameters for exchanging (see ExchangeParams struct)\n // * @return destNumTokensMinted Amount of collateral redeem by user\n // * @return feePaid Amount of collateral paid by user as fee\n // */\n // function exchange(ExchangeParams calldata exchangeParams)\n // external\n // returns (uint256 destNumTokensMinted, uint256 feePaid);\n\n /**\n * @notice Withdraw unused deposited collateral by the LP\n * @notice Only a sender with LP role can call this function\n * @param collateralAmount Collateral to be withdrawn\n * @return remainingLiquidity Remaining unused collateral in the pool\n */\n function withdrawLiquidity(uint256 collateralAmount) external returns (uint256 remainingLiquidity);\n\n /**\n * @notice Increase collaterallization of Lp position\n * @notice Only a sender with LP role can call this function\n * @param collateralToTransfer Collateral to be transferred before increase collateral in the position\n * @param collateralToIncrease Collateral to be added to the position\n * @return newTotalCollateral New total collateral amount\n */\n function increaseCollateral(uint256 collateralToTransfer, uint256 collateralToIncrease)\n external\n returns (uint256 newTotalCollateral);\n\n /**\n * @notice Decrease collaterallization of Lp position\n * @notice Check that final poosition is not undercollateralized\n * @notice Only a sender with LP role can call this function\n * @param collateralToDecrease Collateral to decreased from the position\n * @param collateralToWithdraw Collateral to be transferred to the LP\n * @return newTotalCollateral New total collateral amount\n */\n function decreaseCollateral(uint256 collateralToDecrease, uint256 collateralToWithdraw)\n external\n returns (uint256 newTotalCollateral);\n\n /**\n * @notice Withdraw fees gained by the sender\n * @return feeClaimed Amount of fee claimed\n */\n function claimFee() external returns (uint256 feeClaimed);\n\n /**\n * @notice Liquidate Lp position for an amount of synthetic tokens undercollateralized\n * @notice Revert if position is not undercollateralized\n * @param numSynthTokens Number of synthetic tokens that user wants to liquidate\n * @return synthTokensLiquidated Amount of synthetic tokens liquidated\n * @return collateralReceived Amount of received collateral equal to the value of tokens liquidated\n * @return rewardAmount Amount of received collateral as reward for the liquidation\n */\n function liquidate(uint256 numSynthTokens)\n external\n returns (\n uint256 synthTokensLiquidated,\n uint256 collateralReceived,\n uint256 rewardAmount\n );\n\n /**\n * @notice Redeem tokens after emergency shutdown\n * @return synthTokensSettled Amount of synthetic tokens liquidated\n * @return collateralSettled Amount of collateral withdrawn after emergency shutdown\n */\n function settleEmergencyShutdown() external returns (uint256 synthTokensSettled, uint256 collateralSettled);\n\n // /**\n // * @notice Update the fee percentage, recipients and recipient proportions\n // * @notice Only the maintainer can call this function\n // * @param _feeData Fee info (percentage + recipients + weigths)\n // */\n // function setFee(ISynthereumLiquidityPoolStorage.FeeData calldata _feeData)\n // external;\n\n /**\n * @notice Update the fee percentage\n * @notice Only the maintainer can call this function\n * @param _feePercentage The new fee percentage\n */\n function setFeePercentage(uint256 _feePercentage) external;\n\n /**\n * @notice Update the addresses of recipients for generated fees and proportions of fees each address will receive\n * @notice Only the maintainer can call this function\n * @param feeRecipients An array of the addresses of recipients that will receive generated fees\n * @param feeProportions An array of the proportions of fees generated each recipient will receive\n */\n function setFeeRecipients(address[] calldata feeRecipients, uint32[] calldata feeProportions) external;\n\n /**\n * @notice Update the overcollateralization percentage\n * @notice Only the maintainer can call this function\n * @param _overCollateralization Overcollateralization percentage\n */\n function setOverCollateralization(uint256 _overCollateralization) external;\n\n /**\n * @notice Update the liquidation reward percentage\n * @notice Only the maintainer can call this function\n * @param _liquidationReward Percentage of reward for correct liquidation by a liquidator\n */\n function setLiquidationReward(uint256 _liquidationReward) external;\n\n /**\n * @notice Returns fee percentage set by the maintainer\n * @return Fee percentage\n */\n function feePercentage() external view returns (uint256);\n\n /**\n * @notice Returns fee recipients info\n * @return Addresses, weigths and total of weigths\n */\n function feeRecipientsInfo()\n external\n view\n returns (\n address[] memory,\n uint32[] memory,\n uint256\n );\n\n /**\n * @notice Returns total number of synthetic tokens generated by this pool\n * @return Number of synthetic tokens\n */\n function totalSyntheticTokens() external view returns (uint256);\n\n /**\n * @notice Returns the total amount of collateral used for collateralizing tokens (users + LP)\n * @return Total collateral amount\n */\n function totalCollateralAmount() external view returns (uint256);\n\n /**\n * @notice Returns the total amount of fees to be withdrawn\n * @return Total fee amount\n */\n function totalFeeAmount() external view returns (uint256);\n\n /**\n * @notice Returns the user's fee to be withdrawn\n * @param user User's address\n * @return User's fee\n */\n function userFee(address user) external view returns (uint256);\n\n /**\n * @notice Returns the percentage of overcollateralization to which a liquidation can triggered\n * @return Percentage of overcollateralization\n */\n function collateralRequirement() external view returns (uint256);\n\n /**\n * @notice Returns the percentage of reward for correct liquidation by a liquidator\n * @return Percentage of reward\n */\n function liquidationReward() external view returns (uint256);\n\n /**\n * @notice Returns the price of the pair at the moment of the shutdown\n * @return Price of the pair\n */\n function emergencyShutdownPrice() external view returns (uint256);\n\n /**\n * @notice Returns the timestamp (unix time) at the moment of the shutdown\n * @return Timestamp\n */\n function emergencyShutdownTimestamp() external view returns (uint256);\n\n /**\n * @notice Returns if position is overcollateralized and thepercentage of coverage of the collateral according to the last price\n * @return True if position is overcollaterlized, otherwise false + percentage of coverage (totalCollateralAmount / (price * tokensCollateralized))\n */\n function collateralCoverage() external returns (bool, uint256);\n\n /**\n * @notice Returns the synthetic tokens will be received and fees will be paid in exchange for an input collateral amount\n * @notice This function is only trading-informative, it doesn't check liquidity and collateralization conditions\n * @param inputCollateral Input collateral amount to be exchanged\n * @return synthTokensReceived Synthetic tokens will be minted\n * @return feePaid Collateral fee will be paid\n */\n function getMintTradeInfo(uint256 inputCollateral)\n external\n view\n returns (uint256 synthTokensReceived, uint256 feePaid);\n\n /**\n * @notice Returns the collateral amount will be received and fees will be paid in exchange for an input amount of synthetic tokens\n * @notice This function is only trading-informative, it doesn't check liquidity and collateralization conditions\n * @param syntheticTokens Amount of synthetic tokens to be exchanged\n * @return collateralAmountReceived Collateral amount will be received by the user\n * @return feePaid Collateral fee will be paid\n */\n function getRedeemTradeInfo(uint256 syntheticTokens)\n external\n view\n returns (uint256 collateralAmountReceived, uint256 feePaid);\n\n // /**\n // * @notice Returns the destination synthetic tokens amount will be received and fees will be paid in exchange for an input amount of synthetic tokens\n // * @notice This function is only trading-informative, it doesn't check liquidity and collateralization conditions\n // * @param syntheticTokens Amount of synthetic tokens to be exchanged\n // * @param destinationPool Pool in which mint the destination synthetic token\n // * @return destSyntheticTokensReceived Synthetic tokens will be received from destination pool\n // * @return feePaid Collateral fee will be paid\n // */\n // function getExchangeTradeInfo(\n // uint256 syntheticTokens,\n // ISynthereumLiquidityPoolGeneral destinationPool\n // )\n // external\n // view\n // returns (uint256 destSyntheticTokensReceived, uint256 feePaid);\n /**\n * @notice Shutdown the pool or self-minting-derivative in case of emergency\n * @notice Only Synthereum manager contract can call this function\n * @return timestamp Timestamp of emergency shutdown transaction\n * @return price Price of the pair at the moment of shutdown execution\n */\n function emergencyShutdown() external returns (uint256 timestamp, uint256 price);\n}\n" + }, + "contracts/external/jarvis/ISynthereumLiquidityPoolGeneral.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity ^0.8.4;\n\nimport \"./ISynthereumDeployment.sol\";\n\ninterface ISynthereumLiquidityPoolGeneral is\n ISynthereumDeployment\n //,\n //ISynthereumLiquidityPoolInteraction\n{}\n" + }, + "contracts/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/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/external/saddle/ISwap.sol": { + "content": "// SPDX-License-Identifier: MIT\n\npragma solidity >=0.8.0;\n\ninterface ISwap {\n // pool data view functions\n function getA() external view returns (uint256);\n\n function getAPrecise() external view returns (uint256);\n\n function getToken(uint8 index) external view returns (address);\n\n function getTokenIndex(address tokenAddress) external view returns (uint8);\n\n function getTokenBalance(uint8 index) external view returns (uint256);\n\n function getVirtualPrice() external view returns (uint256);\n\n function owner() external view returns (address);\n\n function isGuarded() external view returns (bool);\n\n function paused() external view returns (bool);\n\n // min return calculation functions\n function calculateSwap(\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dx\n ) external view returns (uint256);\n\n function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256);\n\n function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory);\n\n function calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex)\n external\n view\n returns (uint256 availableTokenAmount);\n\n function swap(\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dx,\n uint256 minDy,\n uint256 deadline\n ) external returns (uint256);\n\n function addLiquidity(\n uint256[] calldata amounts,\n uint256 minToMint,\n uint256 deadline\n ) external returns (uint256);\n\n function removeLiquidity(\n uint256 amount,\n uint256[] calldata minAmounts,\n uint256 deadline\n ) external returns (uint256[] memory);\n\n function removeLiquidityOneToken(\n uint256 tokenAmount,\n uint8 tokenIndex,\n uint256 minAmount,\n uint256 deadline\n ) external returns (uint256);\n\n function removeLiquidityImbalance(\n uint256[] calldata amounts,\n uint256 maxBurnAmount,\n uint256 deadline\n ) external returns (uint256);\n}\n" + }, + "contracts/external/solidly/IPair.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.8.0;\n\nstruct Observation {\n uint256 timestamp;\n uint256 reserve0Cumulative;\n uint256 reserve1Cumulative;\n}\n\ninterface IPair {\n function observations(uint256 index) external pure returns (Observation memory);\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 factory() external view returns (address);\n\n function token0() external view returns (address);\n\n function token1() external view returns (address);\n\n function metadata()\n external\n view\n returns (\n uint256 dec0,\n uint256 dec1,\n uint256 r0,\n uint256 r1,\n bool st,\n address t0,\n address t1\n );\n\n function claimFees() external returns (uint256, uint256);\n\n function tokens() external returns (address, address);\n\n function stable() external view returns (bool);\n\n function observationLength() external view returns (uint256);\n\n function lastObservation() external view returns (Observation memory);\n\n function current(address tokenIn, uint256 amountIn) external view returns (uint256 amountOut);\n\n function currentCumulativePrices()\n external\n view\n returns (\n uint256 reserve0Cumulative,\n uint256 reserve1Cumulative,\n uint256 blockTimestamp\n );\n\n function transferFrom(\n address src,\n address dst,\n uint256 amount\n ) external returns (bool);\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 function swap(\n uint256 amount0Out,\n uint256 amount1Out,\n address to,\n bytes calldata data\n ) external;\n\n function burn(address to) external returns (uint256 amount0, uint256 amount1);\n\n function mint(address to) external returns (uint256 liquidity);\n\n function sync() external;\n\n function transfer(address dst, uint256 amount) external returns (bool);\n\n function getReserves()\n external\n view\n returns (\n uint256 _reserve0,\n uint256 _reserve1,\n uint256 _blockTimestampLast\n );\n\n function getAmountOut(uint256, address) external view returns (uint256);\n}\n" + }, + "contracts/external/solidly/IRouter.sol": { + "content": "pragma solidity >=0.8.0;\n\ninterface IRouter {\n struct Route {\n address from;\n address to;\n bool stable;\n }\n\n function isPair(address pair) external view returns (bool);\n\n function getReserves(\n address tokenA,\n address tokenB,\n bool stable\n ) external view returns (uint256 reserveA, uint256 reserveB);\n\n function pairFor(\n address tokenA,\n address tokenB,\n bool stable\n ) external view returns (address pair);\n\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 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 )\n external\n returns (\n uint256 amountA,\n uint256 amountB,\n uint256 liquidity\n );\n\n function swapExactTokensForTokensSimple(\n uint256 amountIn,\n uint256 amountOutMin,\n address tokenFrom,\n address tokenTo,\n bool stable,\n address to,\n uint256 deadline\n ) external returns (uint256[] memory amounts);\n\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 function getAmountsOut(uint256 amountIn, Route[] memory routes) external view returns (uint256[] memory amounts);\n\n function quoteAddLiquidity(\n address tokenA,\n address tokenB,\n bool stable,\n uint256 amountADesired,\n uint256 amountBDesired\n )\n external\n view\n returns (\n uint256 amountA,\n uint256 amountB,\n uint256 liquidity\n );\n}\n" + }, + "contracts/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/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/FeeDistributor.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\";\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(address oldImplementation, address newImplementation)\n external\n onlyOwner\n {\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(address cErc20Delegate, DiamondExtension[] calldata extensions)\n external\n onlyOwner\n {\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(\n address pool,\n address user,\n address target,\n bytes4 functionSig\n ) external view returns (bool) {\n return authoritiesRegistry.canCall(pool, user, target, functionSig);\n }\n}\n" + }, + "contracts/ILiquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\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/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/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/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/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/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(\n ICErc20 _collateralMarket,\n ICErc20 _stableMarket,\n bool _whitelisted\n ) external;\n}\n\ninterface ILeveredPositionFactoryFirstExtension {\n function getRedemptionStrategies(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n external\n view\n 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\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/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\ncontract LeveredPosition is LeveredPositionStorage, IFlashLoanReceiver {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n error OnlyWhenClosed();\n error NotPositionOwner();\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(\n address assetAddress,\n uint256 borrowedAmount,\n bytes calldata data\n ) 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 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 } 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(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n private\n returns (uint256 outputAmount)\n {\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/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(\n IFeeDistributor _feeDistributor,\n ILiquidatorsRegistry _registry,\n uint256 _blocksPerYear\n ) {\n feeDistributor = _feeDistributor;\n liquidatorsRegistry = _registry;\n blocksPerYear = _blocksPerYear;\n }\n\n /*----------------------------------------------------------------\n Admin Functions\n ----------------------------------------------------------------*/\n\n function _setPairWhitelisted(\n ICErc20 _collateralMarket,\n ICErc20 _stableMarket,\n bool _whitelisted\n ) 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(DiamondExtension extensionToAdd, DiamondExtension extensionToReplace)\n public\n override\n onlyOwner\n {\n LibDiamond.registerExtension(extensionToAdd, extensionToReplace);\n }\n}\n" + }, + "contracts/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 = 9;\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 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 /*----------------------------------------------------------------\n View Functions\n ----------------------------------------------------------------*/\n\n function getMinBorrowNative() external view returns (uint256) {\n return feeDistributor.minBorrowEth();\n }\n\n function getRedemptionStrategies(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n external\n view\n returns (IRedemptionStrategy[] memory strategies, bytes[] memory strategiesData)\n {\n return liquidatorsRegistry.getRedemptionStrategies(inputToken, outputToken);\n }\n\n function getPositionsByAccount(address account)\n external\n view\n returns (address[] memory positions, bool[] memory closed)\n {\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 // TODO\n return address(0);\n }\n}\n" + }, + "contracts/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/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" + }, + "contracts/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\";\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(ICErc20 _collateralMarket)\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(LeveredPosition[] calldata positions, uint256[] calldata supplyApys)\n external\n view\n returns (PositionInfo[] memory infos)\n {\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/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/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/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/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/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/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 flywheelPreBorrowerAction(address market, address borrower) external;\n\n function flywheelPreTransferAction(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/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 flywheelPreBorrowerAction(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 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 // TODO remove\n function marketState(ERC20 strategy) external view returns (uint224, uint32) {\n return (_strategyState[strategy].index, _strategyState[strategy].lastUpdatedTimestamp);\n }\n}\n" + }, + "contracts/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\";\n\nimport { SafeOwnableUpgradeable } from \"../../../ionic/SafeOwnableUpgradeable.sol\";\n\ncontract IonicFlywheelCore is SafeOwnableUpgradeable {\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 /// @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 constructor() {\n // prevents the misusage of the implementation contract\n _disableInitializers();\n }\n\n function initialize(\n ERC20 _rewardToken,\n IFlywheelRewards _flywheelRewards,\n IFlywheelBooster _flywheelBooster,\n address _owner\n ) public initializer {\n __SafeOwnable_init(msg.sender);\n\n rewardToken = _rewardToken;\n flywheelRewards = _flywheelRewards;\n flywheelBooster = _flywheelBooster;\n\n _transferOwnership(_owner);\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(\n ERC20 strategy,\n address user,\n address secondUser\n ) 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 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 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(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\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 // 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(\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 = (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)\n : strategy.balanceOf(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/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/IonicLiquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\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\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(\n address _wtoken,\n address _uniswapV2router,\n uint8 _flashSwapFee\n ) 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(\n IERC20Upgradeable token,\n address to,\n uint256 minAmount\n ) 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(\n IERC20Upgradeable token,\n address to,\n uint256 amount\n ) 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 /**\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(LiquidateToTokensWithFlashSwapVars calldata vars)\n external\n onlyLowHF(vars.borrower, vars.cTokenCollateral)\n returns (uint256)\n {\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(\n address,\n uint256,\n uint256,\n bytes calldata data\n ) 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(\n address sender,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) external {\n uniswapV2Call(sender, amount0, amount1, data);\n }\n\n function moraswapCall(\n address sender,\n uint256 amount0,\n uint256 amount1,\n bytes calldata data\n ) 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(IRedemptionStrategy[] calldata strategies, bool[] calldata whitelisted)\n external\n onlyOwner\n {\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/IonicUniV3Liquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\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\";\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 OwnableUpgradeable, ILiquidator, IUniswapV3FlashCallback, IExpressRelayFeeReceiver {\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 /**\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(LiquidateToTokensWithFlashSwapVars calldata vars)\n external\n onlyLowHF(vars.borrower, vars.cTokenCollateral)\n returns (uint256)\n {\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(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external {\n uniswapV3FlashCallback(fee0, fee1, data);\n }\n\n function algebraFlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) external {\n uniswapV3FlashCallback(fee0, fee1, data);\n }\n\n function uniswapV3FlashCallback(\n uint256 fee0,\n uint256 fee1,\n bytes calldata data\n ) 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(IRedemptionStrategy[] calldata strategies, bool[] calldata whitelisted)\n external\n onlyOwner\n {\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/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/liquidators/BalancerSwapLiquidator.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"./IRedemptionStrategy.sol\";\nimport \"../external/balancer/IBalancerPool.sol\";\nimport \"../external/balancer/IBalancerVault.sol\";\n\nimport { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\ncontract BalancerSwapLiquidator is IRedemptionStrategy {\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external override returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n (address outputTokenAddress, IBalancerPool pool) = abi.decode(strategyData, (address, IBalancerPool));\n\n IBalancerVault vault = pool.getVault();\n bytes32 poolId = pool.getPoolId();\n\n SingleSwap memory singleSwap = SingleSwap(\n poolId,\n SwapKind.GIVEN_IN,\n IAsset(address(inputToken)),\n IAsset(address(outputTokenAddress)),\n inputAmount,\n \"\"\n );\n\n FundManagement memory funds = FundManagement(\n address(this),\n false, // fromInternalBalance\n payable(address(this)),\n false // toInternalBalance\n );\n\n inputToken.approve(address(vault), inputAmount);\n vault.swap(singleSwap, funds, 0, block.timestamp + 10);\n outputAmount = IERC20Upgradeable(outputTokenAddress).balanceOf(address(this));\n return (IERC20Upgradeable(outputTokenAddress), outputAmount);\n }\n\n function name() public pure returns (string memory) {\n return \"BalancerSwapLiquidator\";\n }\n}\n" + }, + "contracts/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(\n IUniswapV2Router02 uniswapV2Router,\n uint256 inputAmount,\n address[] memory swapPath\n ) internal virtual;\n}\n" + }, + "contracts/liquidators/CurveLpTokenLiquidatorNoRegistry.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 \"../oracles/default/CurveLpTokenPriceOracleNoRegistry.sol\";\n\nimport { WETH } from \"solmate/tokens/WETH.sol\";\n\nimport \"./IRedemptionStrategy.sol\";\n\n/**\n * @title CurveLpTokenLiquidatorNoRegistry\n * @notice Redeems seized Curve LP token collateral for underlying tokens for use as a step in a liquidation.\n * @author David Lucid (https://github.com/davidlucid)\n */\ncontract CurveLpTokenLiquidatorNoRegistry 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 // TODO get the curvePool from the strategyData instead of the _oracle\n (address outputTokenAddress, address payable wtoken, address _oracle) = abi.decode(\n strategyData,\n (address, address, address)\n );\n // the oracle contains the pool registry\n CurveLpTokenPriceOracleNoRegistry oracle = CurveLpTokenPriceOracleNoRegistry(_oracle);\n\n // Remove liquidity from Curve pool in the form of one coin only (and store output as new collateral)\n ICurvePool curvePool = ICurvePool(oracle.poolOf(address(inputToken)));\n\n uint8 outputIndex = type(uint8).max;\n\n uint8 j = 0;\n while (outputIndex == type(uint8).max) {\n try curvePool.coins(uint256(j)) returns (address coin) {\n if (coin == outputTokenAddress) outputIndex = j;\n } catch {\n break;\n }\n j++;\n }\n\n curvePool.remove_liquidity_one_coin(inputAmount, int128(int8(outputIndex)), 1);\n\n // better safe than sorry\n if (outputTokenAddress == address(0) || outputTokenAddress == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {\n WETH(wtoken).deposit{ value: address(this).balance }();\n outputToken = IERC20Upgradeable(wtoken);\n } else {\n outputToken = IERC20Upgradeable(outputTokenAddress);\n }\n outputAmount = outputToken.balanceOf(address(this));\n\n return (outputToken, outputAmount);\n }\n\n function name() public pure returns (string memory) {\n return \"CurveLpTokenLiquidatorNoRegistry\";\n }\n}\n\ncontract CurveLpTokenWrapper is IRedemptionStrategy {\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n (ICurvePool curvePool, address _outputTokenAddress) = abi.decode(strategyData, (ICurvePool, address));\n outputToken = IERC20Upgradeable(_outputTokenAddress);\n\n uint8 inputIndex = type(uint8).max;\n\n uint8 j = 0;\n while (inputIndex == type(uint8).max) {\n try curvePool.coins(uint256(j)) returns (address coin) {\n if (coin == address(inputToken)) inputIndex = j;\n } catch {\n break;\n }\n j++;\n }\n\n inputToken.approve(address(curvePool), inputAmount);\n uint256[2] memory amounts;\n amounts[inputIndex] = inputAmount;\n curvePool.add_liquidity(amounts, 1);\n\n outputAmount = outputToken.balanceOf(address(this));\n }\n\n function name() public pure returns (string memory) {\n return \"CurveLpTokenWrapper\";\n }\n}\n" + }, + "contracts/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\";\n\nimport { WETH } from \"solmate/tokens/WETH.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 CurveLpTokenPriceOracleNoRegistry curveV1Oracle,\n CurveV2LpTokenPriceOracleNoRegistry curveV2Oracle,\n ,\n address outputTokenAddress,\n address payable wtoken\n ) = abi.decode(\n strategyData,\n (CurveLpTokenPriceOracleNoRegistry, CurveV2LpTokenPriceOracleNoRegistry, address, address, address)\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, outputTokenAddress);\n }\n if (address(curvePool) == address(0)) {\n (curvePool, i, j) = curveV1Oracle.getPoolForSwap(inputTokenAddress, outputTokenAddress);\n }\n require(address(curvePool) != address(0), \"!curve pool\");\n\n inputToken.approve(address(curvePool), inputAmount);\n curvePool.exchange(i, j, inputAmount, 0);\n\n // Convert to W_NATIVE if ETH\n if (outputTokenAddress == address(0) || outputTokenAddress == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {\n WETH(wtoken).deposit{ value: outputAmount }();\n outputToken = IERC20Upgradeable(wtoken);\n } else {\n outputToken = IERC20Upgradeable(outputTokenAddress);\n }\n outputAmount = outputToken.balanceOf(address(this));\n\n return (outputToken, outputAmount);\n }\n\n function name() public pure virtual returns (string memory) {\n return \"CurveSwapLiquidator\";\n }\n}\n" + }, + "contracts/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(uint256 outputAmount, bytes memory strategyData)\n external\n view\n returns (IERC20Upgradeable, uint256)\n {\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/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(uint256 outputAmount, bytes memory strategyData)\n external\n view\n returns (IERC20Upgradeable inputToken, uint256 inputAmount);\n}\n" + }, + "contracts/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/liquidators/JarvisLiquidatorFunder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport { IERC20MetadataUpgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport { FixedPointMathLib } from \"solmate/utils/FixedPointMathLib.sol\";\nimport { IFundsConversionStrategy } from \"./IFundsConversionStrategy.sol\";\nimport { ISynthereumLiquidityPool } from \"../external/jarvis/ISynthereumLiquidityPool.sol\";\n\ncontract JarvisLiquidatorFunder is IFundsConversionStrategy {\n using FixedPointMathLib for uint256;\n\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 ) 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 poolAddress, ) = abi.decode(strategyData, (address, address, uint256));\n ISynthereumLiquidityPool pool = ISynthereumLiquidityPool(poolAddress);\n\n // approve so the pool can pull out the input tokens\n inputToken.approve(address(pool), inputAmount);\n\n IERC20Upgradeable collateralToken = pool.collateralToken();\n IERC20Upgradeable syntheticToken = pool.syntheticToken();\n\n if (inputToken == syntheticToken) {\n outputToken = collateralToken;\n\n uint256 shutdownPrice = 0;\n // TODO figure out why this method was removed and what to use instead\n try pool.emergencyShutdownPrice() returns (uint256 price) {\n shutdownPrice = price;\n } catch {}\n\n if (shutdownPrice > 0) {\n // emergency shutdowns cannot be reverted, so this corner case must be covered\n (, uint256 collateralSettled) = pool.settleEmergencyShutdown();\n outputAmount = collateralSettled;\n // outputToken = collateralToken;\n } else {\n // redeem the underlying BUSD\n // fetch the estimated redeemable collateral in BUSD, less the fee paid\n (uint256 redeemableCollateralAmount, ) = pool.getRedeemTradeInfo(inputAmount);\n\n (uint256 collateralAmountReceived, ) = pool.redeem(\n ISynthereumLiquidityPool.RedeemParams(inputAmount, redeemableCollateralAmount, block.timestamp, address(this))\n );\n\n outputAmount = collateralAmountReceived;\n }\n } else if (inputToken == collateralToken) {\n outputToken = syntheticToken;\n\n // mint jBRL from the supplied bUSD\n (uint256 synthTokensReceived, ) = pool.getMintTradeInfo(inputAmount);\n\n (uint256 syntheticTokensMinted, ) = pool.mint(\n ISynthereumLiquidityPool.MintParams(synthTokensReceived, inputAmount, block.timestamp, address(this))\n );\n\n outputAmount = syntheticTokensMinted;\n } else {\n revert(\"unknown input token\");\n }\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 inputTokenAddress, address poolAddress, ) = abi.decode(strategyData, (address, address, uint256));\n\n inputToken = IERC20Upgradeable(inputTokenAddress);\n\n uint8 decimals = 18;\n try IERC20MetadataUpgradeable(inputTokenAddress).decimals() returns (uint8 dec) {\n decimals = dec;\n } catch {}\n uint256 ONE = 10**decimals;\n\n ISynthereumLiquidityPool pool = ISynthereumLiquidityPool(poolAddress);\n if (inputToken == pool.syntheticToken()) {\n // collateralAmountReceived / ONE = outputAmount / inputAmount\n // => inputAmount = (ONE * outputAmount) / collateralAmountReceived\n (uint256 collateralAmountReceived, ) = ISynthereumLiquidityPool(poolAddress).getRedeemTradeInfo(ONE);\n inputAmount = ONE.mulDivUp(outputAmount, collateralAmountReceived);\n } else if (inputToken == pool.collateralToken()) {\n // synthTokensReceived / ONE = outputAmount / inputAmount\n // => inputAmount = (ONE * outputAmount) / synthTokensReceived\n (uint256 synthTokensReceived, ) = ISynthereumLiquidityPool(poolAddress).getMintTradeInfo(ONE);\n inputAmount = ONE.mulDivUp(outputAmount, synthTokensReceived);\n } else {\n revert(\"unknown input token\");\n }\n }\n\n function name() public pure returns (string memory) {\n return \"JarvisLiquidatorFunder\";\n }\n}\n" + }, + "contracts/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/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(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n external\n view\n 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(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n external\n view\n returns (address);\n}\n\ninterface ILiquidatorsRegistryExtension {\n function getInputTokensByOutputToken(IERC20Upgradeable outputToken) external view returns (address[] memory);\n\n function getRedemptionStrategies(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n external\n view\n returns (IRedemptionStrategy[] memory strategies, bytes[] memory strategiesData);\n\n function getRedemptionStrategy(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n external\n view\n returns (IRedemptionStrategy strategy, bytes memory strategyData);\n\n function getAllRedemptionStrategies() external view returns (address[] memory);\n\n function getSlippage(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n external\n view\n 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\ninterface ILiquidatorsRegistry is\n ILiquidatorsRegistryExtension,\n ILiquidatorsRegistrySecondExtension,\n ILiquidatorsRegistryStorage\n{}\n" + }, + "contracts/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/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 } from \"../../external/solidly/IRouter.sol\";\nimport { IPair } from \"../../external/solidly/IPair.sol\";\nimport { IUniswapV2Pair } from \"../../external/uniswap/IUniswapV2Pair.sol\";\nimport { ICurvePool } from \"../../external/curve/ICurvePool.sol\";\n\nimport { CurveLpTokenPriceOracleNoRegistry } from \"../../oracles/default/CurveLpTokenPriceOracleNoRegistry.sol\";\nimport { CurveV2LpTokenPriceOracleNoRegistry } from \"../../oracles/default/CurveV2LpTokenPriceOracleNoRegistry.sol\";\nimport { SaddleLpPriceOracle } from \"../../oracles/default/SaddleLpPriceOracle.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\nimport { XBombSwap } from \"../XBombLiquidatorFunder.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(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n external\n view\n returns (uint256 slippage)\n {\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(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n public\n view\n returns (IRedemptionStrategy[] memory strategies, bytes[] memory strategiesData)\n {\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\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 // chain the next redeemed token from the default path\n nextRedeemedToken = defaultOutputToken[tokenToRedeem];\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(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n public\n view\n returns (IRedemptionStrategy strategy, bytes memory strategyData)\n {\n strategy = redemptionStrategiesByTokens[inputToken][outputToken];\n\n if (isStrategy(strategy, \"SolidlySwapLiquidator\")) {\n strategyData = solidlySwapLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"SolidlyLpTokenLiquidator\")) {\n strategyData = solidlyLpTokenLiquidatorData(inputToken, outputToken);\n } else 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 address swapRouter;\n if (block.chainid == 34443) {\n swapRouter = 0xAc48FcF1049668B285f3dC72483DF5Ae2162f7e8;\n } else {\n swapRouter = ap.getAddress(\"ALGEBRA_SWAP_ROUTER\");\n }\n strategyData = algebraSwapLiquidatorData(inputToken, outputToken, swapRouter);\n } else if (isStrategy(strategy, \"GammaAlgebraLpTokenLiquidator\")) {\n strategyData = gammaAlgebraLpTokenLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"GammaUniswapV3LpTokenLiquidator\")) {\n strategyData = gammaUniswapV3LpTokenLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"BalancerSwapLiquidator\")) {\n strategyData = balancerSwapLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"UniswapLpTokenLiquidator\") || isStrategy(strategy, \"GelatoGUniLiquidator\")) {\n strategyData = uniswapLpTokenLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"SaddleLpTokenLiquidator\")) {\n strategyData = saddleLpTokenLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"CurveLpTokenLiquidatorNoRegistry\")) {\n strategyData = curveLpTokenLiquidatorNoRegistryData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"CurveSwapLiquidator\")) {\n strategyData = curveSwapLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"CurveLpTokenWrapper\")) {\n strategyData = curveLpTokenWrapperData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"JarvisLiquidatorFunder\")) {\n strategyData = jarvisLiquidatorFunderData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"XBombLiquidatorFunder\")) {\n strategyData = xBombLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"BalancerLpTokenLiquidator\")) {\n strategyData = balancerLpTokenLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"AaveTokenLiquidator\")) {\n strategyData = aaveLiquidatorData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"GammaAlgebraLpTokenWrapper\")) {\n strategyData = gammaAlgebraLpTokenWrapperData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"GammaUniswapV3LpTokenWrapper\")) {\n strategyData = gammaUniswapV3LpTokenWrapperData(inputToken, outputToken);\n } else if (isStrategy(strategy, \"SolidlyLpTokenWrapper\")) {\n strategyData = solidlyLpTokenWrapperData(inputToken, outputToken);\n //} else if (isStrategy(strategy, \"ERC4626Liquidator\")) {\n // TODO strategyData = erc4626LiquidatorData(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(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (address)\n {\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 solidlySwapLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n // assuming bsc for the chain\n IRouter solidlyRouter = IRouter(ap.getAddress(\"SOLIDLY_SWAP_ROUTER\"));\n address tokenTo = address(outputToken);\n\n // Check if stable pair exists\n address volatilePair = solidlyRouter.pairFor(address(inputToken), tokenTo, false);\n address stablePair = solidlyRouter.pairFor(address(inputToken), tokenTo, true);\n\n require(\n solidlyRouter.isPair(stablePair) || solidlyRouter.isPair(volatilePair),\n \"Invalid SolidlyLiquidator swap path.\"\n );\n\n bool stable;\n if (!solidlyRouter.isPair(stablePair)) {\n stable = false;\n } else if (!solidlyRouter.isPair(volatilePair)) {\n stable = true;\n } else {\n (uint256 stableR0, uint256 stableR1) = solidlyRouter.getReserves(address(inputToken), tokenTo, true);\n (uint256 volatileR0, uint256 volatileR1) = solidlyRouter.getReserves(address(inputToken), tokenTo, false);\n // Determine which swap has higher liquidity\n if (stableR0 > volatileR0 && stableR1 > volatileR1) {\n stable = true;\n } else {\n stable = false;\n }\n }\n\n strategyData = abi.encode(solidlyRouter, outputToken, stable);\n }\n\n function solidlyLpTokenLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n IPair lpToken = IPair(address(inputToken));\n require(\n address(outputToken) == lpToken.token0() || address(outputToken) == lpToken.token1(),\n \"Output token does not match either of the pair tokens!\"\n );\n\n strategyData = abi.encode(ap.getAddress(\"SOLIDLY_SWAP_ROUTER\"), outputToken);\n }\n\n function aaveLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n pure\n returns (bytes memory strategyData)\n {\n strategyData = abi.encode(outputToken);\n }\n\n function gammaAlgebraLpTokenWrapperData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n address swapRouter = ap.getAddress(\"GAMMA_ALGEBRA_SWAP_ROUTER\");\n address proxy = ap.getAddress(\"GAMMA_ALGEBRA_UNI_PROXY\"); // IUniProxy\n address vault = address(outputToken); // IHypervisor\n\n strategyData = abi.encode(swapRouter, proxy, vault);\n }\n\n function gammaUniswapV3LpTokenWrapperData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n address swapRouter = ap.getAddress(\"GAMMA_UNISWAP_V3_SWAP_ROUTER\");\n address proxy = ap.getAddress(\"GAMMA_UNISWAP_V3_UNI_PROXY\"); // IUniProxy\n address vault = address(outputToken); // IHypervisor\n\n strategyData = abi.encode(swapRouter, proxy, vault);\n }\n\n function balancerLpTokenLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n pure\n returns (bytes memory strategyData)\n {\n strategyData = abi.encode(outputToken);\n }\n\n function uniswapV3LiquidatorFunderData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\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 uniswapV2LiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\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 algebraSwapLiquidatorData(\n IERC20Upgradeable inputToken,\n IERC20Upgradeable outputToken,\n address swapRouter\n ) internal view returns (bytes memory strategyData) {\n strategyData = abi.encode(outputToken, swapRouter);\n }\n\n function gammaAlgebraLpTokenLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n strategyData = abi.encode(outputToken, ap.getAddress(\"GAMMA_ALGEBRA_SWAP_ROUTER\"));\n }\n\n function gammaUniswapV3LpTokenLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n strategyData = abi.encode(outputToken, ap.getAddress(\"GAMMA_UNISWAP_V3_SWAP_ROUTER\"));\n }\n\n function uniswapLpTokenLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n IUniswapV2Pair lpToken = IUniswapV2Pair(address(inputToken));\n address token0 = lpToken.token0();\n address token1 = lpToken.token1();\n bool token0IsOutputToken = address(outputToken) == token0;\n bool token1IsOutputToken = address(outputToken) == token1;\n require(token0IsOutputToken || token1IsOutputToken, \"Output token does not match either of the pair tokens\");\n\n address[] memory swap0Path;\n address[] memory swap1Path;\n {\n if (token0IsOutputToken) {\n swap0Path = new address[](0);\n swap1Path = new address[](2);\n swap1Path[0] = token1;\n swap1Path[1] = token0;\n } else {\n swap1Path = new address[](0);\n swap0Path = new address[](2);\n swap0Path[0] = token0;\n swap0Path[1] = token1;\n }\n }\n\n strategyData = abi.encode(getUniswapV2Router(inputToken), swap0Path, swap1Path);\n }\n\n function saddleLpTokenLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n SaddleLpPriceOracle saddleLpPriceOracle = SaddleLpPriceOracle(ap.getAddress(\"SaddleLpPriceOracle\"));\n address[] memory tokens = saddleLpPriceOracle.getUnderlyingTokens(address(inputToken));\n\n address wnative = ap.getAddress(\"wtoken\");\n address preferredToken = pickPreferredToken(tokens, address(outputToken));\n address actualOutputToken = preferredToken;\n if (preferredToken == address(0) || preferredToken == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {\n actualOutputToken = wnative;\n }\n // TODO outputToken = actualOutputToken\n\n strategyData = abi.encode(preferredToken, saddleLpPriceOracle, wnative);\n }\n\n function curveLpTokenLiquidatorNoRegistryData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n CurveLpTokenPriceOracleNoRegistry curveLpOracle = CurveLpTokenPriceOracleNoRegistry(\n ap.getAddress(\"CurveLpTokenPriceOracleNoRegistry\")\n );\n ICurvePool curvePool = ICurvePool(curveLpOracle.poolOf(address(inputToken)));\n address[] memory tokens = getUnderlyingTokens(curvePool);\n\n address preferredToken = pickPreferredToken(tokens, address(outputToken));\n address actualOutputToken = preferredToken;\n address wnative = ap.getAddress(\"wtoken\");\n if (preferredToken == address(0) || preferredToken == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {\n actualOutputToken = wnative;\n }\n // TODO outputToken = actualOutputToken\n\n strategyData = abi.encode(preferredToken, wnative, curveLpOracle);\n }\n\n function getUnderlyingTokens(ICurvePool curvePool) internal view returns (address[] memory tokens) {\n uint8 j = 0;\n while (true) {\n try curvePool.coins(uint256(j)) returns (address coin) {} catch {\n break;\n }\n j++;\n }\n tokens = new address[](j);\n for (uint256 i = 0; i < j; i++) {\n tokens[i] = curvePool.coins(i);\n }\n }\n\n function curveLpTokenWrapperData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n CurveLpTokenPriceOracleNoRegistry curveLpOracle = CurveLpTokenPriceOracleNoRegistry(\n ap.getAddress(\"CurveLpTokenPriceOracleNoRegistry\")\n );\n\n strategyData = abi.encode(curveLpOracle.poolOf(address(outputToken)), outputToken);\n }\n\n function curveSwapLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n address curveV1Oracle = ap.getAddress(\"CurveLpTokenPriceOracleNoRegistry\");\n address curveV2Oracle = ap.getAddress(\"CurveV2LpTokenPriceOracleNoRegistry\");\n address wnative = ap.getAddress(\"wtoken\");\n\n strategyData = abi.encode(curveV1Oracle, curveV2Oracle, inputToken, outputToken, wnative);\n }\n\n function jarvisLiquidatorFunderData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n AddressesProvider.JarvisPool[] memory pools = ap.getJarvisPools();\n for (uint256 i = 0; i < pools.length; i++) {\n AddressesProvider.JarvisPool memory pool = pools[i];\n if (pool.syntheticToken == address(inputToken)) {\n strategyData = abi.encode(pool.syntheticToken, pool.liquidityPool, pool.expirationTime);\n //outputToken = pool.collateralToken;\n break;\n } else if (pool.collateralToken == address(inputToken)) {\n strategyData = abi.encode(pool.collateralToken, pool.liquidityPool, pool.expirationTime);\n }\n }\n }\n\n function balancerSwapLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n address poolAddress = ap.getBalancerPoolForTokens(address(inputToken), address(outputToken));\n if (poolAddress == address(0)) {\n // throw an error\n revert(\"No balancer pool found for the given tokens\");\n }\n strategyData = abi.encode(outputToken, poolAddress);\n }\n\n function solidlyLpTokenWrapperData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n IRouter solidlyRouter = IRouter(ap.getAddress(\"SOLIDLY_SWAP_ROUTER\"));\n IPair pair = IPair(address(outputToken));\n\n IRouter.Route[] memory swapPath0 = new IRouter.Route[](1);\n IRouter.Route[] memory swapPath1 = new IRouter.Route[](1);\n {\n bool isInputToken0 = pair.token0() == address(inputToken);\n bool isInputToken1 = pair.token1() == address(inputToken);\n require(isInputToken0 || isInputToken1, \"!input token not underlying\");\n\n swapPath0[0].stable = pair.stable();\n swapPath0[0].from = pair.token0();\n swapPath0[0].to = pair.token1();\n\n swapPath1[0].stable = pair.stable();\n swapPath1[0].from = pair.token1();\n swapPath1[0].to = pair.token0();\n }\n\n strategyData = abi.encode(solidlyRouter, pair, swapPath0, swapPath1);\n }\n\n // TODO remove after testing\n function xBombLiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n if (block.chainid == 56) {\n address xbomb = 0xAf16cB45B8149DA403AF41C63AbFEBFbcd16264b;\n address bomb = 0x522348779DCb2911539e76A1042aA922F9C47Ee3;\n strategyData = abi.encode(inputToken, xbomb, bomb);\n } else {\n IERC20Upgradeable chapelBomb = IERC20Upgradeable(0xe45589fBad3A1FB90F5b2A8A3E8958a8BAB5f768);\n IERC20Upgradeable chapelTUsd = IERC20Upgradeable(0x4f1885D25eF219D3D4Fa064809D6D4985FAb9A0b);\n IERC20Upgradeable chapelTDai = IERC20Upgradeable(0x8870f7102F1DcB1c35b01af10f1baF1B00aD6805);\n XBombSwap xbombSwapTUsd = XBombSwap(0x3d312B224DeC414FE865e1e9BfC13e2A86947D19);\n XBombSwap xbombSwapTDai = XBombSwap(0x8146293bf5225b471625372e985FDb7165C35fe2);\n\n if (inputToken == chapelBomb) {\n XBombSwap bombSwap;\n if (outputToken == chapelTUsd) {\n bombSwap = xbombSwapTUsd;\n } else if (outputToken == chapelTDai) {\n bombSwap = xbombSwapTDai;\n }\n strategyData = abi.encode(bombSwap, bombSwap, outputToken, outputToken);\n } else if (inputToken == chapelTUsd) {\n strategyData = abi.encode(inputToken, xbombSwapTUsd, inputToken, chapelBomb);\n } else if (inputToken == chapelTDai) {\n strategyData = abi.encode(inputToken, xbombSwapTDai, inputToken, chapelBomb);\n }\n }\n }\n\n // @notice addresses hardcoded, use only for ETHEREUM\n function erc4626LiquidatorData(IERC20Upgradeable inputToken, IERC20Upgradeable outputToken)\n internal\n view\n returns (bytes memory strategyData)\n {\n uint256 fee;\n address[] memory underlyingTokens;\n address inputTokenAddr = address(inputToken);\n address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;\n address dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;\n address usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7;\n address weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n address wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;\n address realYieldUSD = 0x97e6E0a40a3D02F12d1cEC30ebfbAE04e37C119E;\n address ethBtcTrend = 0x6b7f87279982d919Bbf85182DDeAB179B366D8f2;\n address ethBtcMomentum = address(255); // TODO\n\n if (inputTokenAddr == realYieldUSD) {\n fee = 10;\n underlyingTokens = new address[](3);\n underlyingTokens[0] = usdc;\n underlyingTokens[1] = dai;\n underlyingTokens[2] = usdt;\n } else if (inputTokenAddr == ethBtcMomentum || inputTokenAddr == ethBtcTrend) {\n fee = 500;\n underlyingTokens = new address[](3);\n underlyingTokens[0] = usdc;\n underlyingTokens[1] = weth;\n underlyingTokens[2] = wbtc;\n } else {\n fee = 300;\n underlyingTokens = new address[](1);\n underlyingTokens[0] = address(outputToken);\n }\n\n strategyData = abi.encode(\n outputToken,\n fee,\n ap.getAddress(\"UNISWAP_V3_ROUTER\"),\n underlyingTokens,\n ap.getAddress(\"Quoter\")\n );\n }\n}\n" + }, + "contracts/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 = 12;\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 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" + }, + "contracts/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" + }, + "contracts/liquidators/SolidlyLpTokenLiquidator.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/solidly/IRouter.sol\";\nimport \"../external/solidly/IPair.sol\";\n\nimport \"./IRedemptionStrategy.sol\";\n\n/**\n * @title SolidlyLpTokenLiquidator\n * @notice Exchanges seized Solidly LP token collateral for underlying tokens for use as a step in a liquidation.\n */\ncontract SolidlyLpTokenLiquidator is IRedemptionStrategy {\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n /**\n * @dev Internal function to approve unlimited tokens of `erc20Contract` to `to`.\n */\n function safeApprove(\n IERC20Upgradeable token,\n address to,\n uint256 minAmount\n ) internal {\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 // Exit Uniswap pool\n IPair pair = IPair(address(inputToken));\n bool stable = pair.stable();\n\n address token0 = pair.token0();\n address token1 = pair.token1();\n pair.transfer(address(pair), inputAmount);\n (uint256 amount0, uint256 amount1) = pair.burn(address(this));\n\n // Swap underlying tokens\n (IRouter solidlyRouter, address tokenTo) = abi.decode(strategyData, (IRouter, address));\n\n if (tokenTo != token0) {\n safeApprove(IERC20Upgradeable(token0), address(solidlyRouter), amount0);\n solidlyRouter.swapExactTokensForTokensSimple(amount0, 0, token0, tokenTo, stable, address(this), block.timestamp);\n } else {\n safeApprove(IERC20Upgradeable(token1), address(solidlyRouter), amount1);\n solidlyRouter.swapExactTokensForTokensSimple(amount1, 0, token1, tokenTo, stable, address(this), block.timestamp);\n }\n // Get new collateral\n outputToken = IERC20Upgradeable(tokenTo);\n outputAmount = outputToken.balanceOf(address(this));\n }\n\n function name() public pure returns (string memory) {\n return \"SolidlyLpTokenLiquidator\";\n }\n}\n\ncontract SolidlyLpTokenWrapper is IRedemptionStrategy {\n struct WrapSolidlyLpTokenVars {\n uint256 amountToSwapOfToken0ForToken1;\n uint256 amountToSwapOfToken1ForToken0;\n IRouter solidlyRouter;\n IERC20Upgradeable token0;\n IERC20Upgradeable token1;\n bool stable;\n IPair pair;\n IRouter.Route[] swapPath0;\n IRouter.Route[] swapPath1;\n uint256 ratio;\n }\n\n function redeem(\n IERC20Upgradeable inputToken,\n uint256 inputAmount,\n bytes memory strategyData\n ) external returns (IERC20Upgradeable outputToken, uint256 outputAmount) {\n WrapSolidlyLpTokenVars memory vars;\n (vars.solidlyRouter, vars.pair, vars.swapPath0, vars.swapPath1) = abi.decode(\n strategyData,\n (IRouter, IPair, IRouter.Route[], IRouter.Route[])\n );\n vars.token0 = IERC20Upgradeable(vars.pair.token0());\n vars.token1 = IERC20Upgradeable(vars.pair.token1());\n vars.stable = vars.pair.stable();\n\n // calculate the amount for token0 or token1 that needs to be swapped for the other\n {\n vars.amountToSwapOfToken1ForToken0 = inputAmount / 2;\n vars.amountToSwapOfToken0ForToken1 = inputAmount - vars.amountToSwapOfToken1ForToken0;\n if (vars.token0 == inputToken) {\n uint256 out1 = vars.solidlyRouter.getAmountsOut(vars.amountToSwapOfToken0ForToken1, vars.swapPath0)[\n vars.swapPath0.length\n ];\n // price1For0 is scaled to 18 + token1.decimals - token0.decimals\n uint256 price1For0 = (out1 * 1e18) / vars.amountToSwapOfToken0ForToken1;\n // use the quoted input amounts to check what is the actual required ratio of inputs\n (uint256 amount0, uint256 amount1, ) = vars.solidlyRouter.quoteAddLiquidity(\n address(vars.token0),\n address(vars.token1),\n vars.stable,\n vars.amountToSwapOfToken1ForToken0,\n out1\n );\n\n vars.ratio = (amount1 * 1e36) / (amount0 * price1For0);\n }\n\n if (vars.token1 == inputToken) {\n uint256 out0 = vars.solidlyRouter.getAmountsOut(vars.amountToSwapOfToken1ForToken0, vars.swapPath1)[\n vars.swapPath1.length\n ];\n // price0For1 is scaled to 18 + token0.decimals - token1.decimals\n uint256 price0For1 = (out0 * 1e18) / vars.amountToSwapOfToken1ForToken0;\n // use the quoted input amounts to check what is the actual required ratio of inputs\n (uint256 amount0, uint256 amount1, ) = vars.solidlyRouter.quoteAddLiquidity(\n address(vars.token0),\n address(vars.token1),\n vars.stable,\n out0,\n vars.amountToSwapOfToken0ForToken1\n );\n\n vars.ratio = (amount1 * price0For1) / amount0;\n }\n\n // recalculate the amounts to swap based on the ratio of the value of the required input amounts\n vars.amountToSwapOfToken1ForToken0 = (inputAmount * 1e18) / (vars.ratio + 1e18);\n vars.amountToSwapOfToken0ForToken1 = inputAmount - vars.amountToSwapOfToken1ForToken0;\n }\n\n // swap a part of the input token amount for the other token\n if (vars.token0 == inputToken) {\n inputToken.approve(address(vars.solidlyRouter), vars.amountToSwapOfToken0ForToken1);\n vars.solidlyRouter.swapExactTokensForTokens(\n vars.amountToSwapOfToken0ForToken1,\n 0,\n vars.swapPath0,\n address(this),\n block.timestamp\n );\n }\n if (vars.token1 == inputToken) {\n inputToken.approve(address(vars.solidlyRouter), vars.amountToSwapOfToken1ForToken0);\n vars.solidlyRouter.swapExactTokensForTokens(\n vars.amountToSwapOfToken1ForToken0,\n 0,\n vars.swapPath1,\n address(this),\n block.timestamp\n );\n }\n\n // provide the liquidity\n uint256 token0Balance = vars.token0.balanceOf(address(this));\n uint256 token1Balance = vars.token1.balanceOf(address(this));\n\n vars.token0.approve(address(vars.solidlyRouter), token0Balance);\n vars.token1.approve(address(vars.solidlyRouter), token1Balance);\n vars.solidlyRouter.addLiquidity(\n address(vars.token0),\n address(vars.token1),\n vars.stable,\n token0Balance,\n token1Balance,\n 1,\n 1,\n address(this),\n block.timestamp\n );\n\n outputToken = IERC20Upgradeable(address(vars.pair));\n outputAmount = outputToken.balanceOf(address(this));\n }\n\n function name() public pure returns (string memory) {\n return \"SolidlyLpTokenWrapper\";\n }\n}\n" + }, + "contracts/liquidators/SolidlySwapLiquidator.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 { IRouter } from \"../external/solidly/IRouter.sol\";\n\nimport \"./IRedemptionStrategy.sol\";\n\n/**\n * @title SolidlySwapLiquidator\n * @notice Exchanges seized token collateral for underlying tokens via a Solidly router for use as a step in a liquidation.\n */\ncontract SolidlySwapLiquidator 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 Solidly router and path\n (IRouter solidlyRouter, address tokenTo, bool stable) = abi.decode(strategyData, (IRouter, address, bool));\n\n // Swap underlying tokens\n inputToken.approve(address(solidlyRouter), inputAmount);\n solidlyRouter.swapExactTokensForTokensSimple(\n inputAmount,\n 0,\n address(inputToken),\n tokenTo,\n stable,\n address(this),\n block.timestamp\n );\n\n // Get new collateral\n outputToken = IERC20Upgradeable(tokenTo);\n outputAmount = outputToken.balanceOf(address(this));\n }\n\n function name() public pure returns (string memory) {\n return \"SolidlySwapLiquidator\";\n }\n}\n" + }, + "contracts/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/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(uint256 outputAmount, bytes memory strategyData)\n external\n view\n returns (IERC20Upgradeable inputToken, uint256 inputAmount)\n {\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/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/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/liquidators/XBombLiquidatorFunder.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"../external/bomb/IXBomb.sol\";\nimport \"./IRedemptionStrategy.sol\";\nimport \"./IFundsConversionStrategy.sol\";\nimport { MasterPriceOracle } from \"../oracles/MasterPriceOracle.sol\";\n\n/**\n * @title XBombLiquidatorFunder\n * @notice Exchanges seized xBOMB collateral for underlying BOMB tokens for use as a step in a liquidation.\n * @author Veliko Minkov \n */\ncontract XBombLiquidatorFunder is IFundsConversionStrategy {\n /**\n * @notice Redeems xBOMB for the underlying BOMB reward tokens.\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 ) 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 inputTokenAddress, address xbomb, IERC20Upgradeable bomb, IERC20Upgradeable _outputToken) = abi.decode(\n strategyData,\n (address, address, IERC20Upgradeable, IERC20Upgradeable)\n );\n if (inputTokenAddress == xbomb) {\n // burns the xBOMB and returns the underlying BOMB to the liquidator\n inputToken.approve(address(xbomb), inputAmount);\n IXBomb(xbomb).leave(inputAmount);\n\n outputToken = _outputToken;\n outputAmount = outputToken.balanceOf(address(this));\n } else if (inputTokenAddress == address(bomb)) {\n // mints xBOMB\n inputToken.approve(address(xbomb), inputAmount);\n IXBomb(xbomb).enter(inputAmount);\n\n outputToken = _outputToken;\n outputAmount = outputToken.balanceOf(address(this));\n } else {\n revert(\"unknown input token\");\n }\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, uint256)\n {\n (address inputTokenAddress, address xbomb, IERC20Upgradeable bomb, ) = abi.decode(\n strategyData,\n (address, address, IERC20Upgradeable, IERC20Upgradeable)\n );\n if (inputTokenAddress == xbomb) {\n // what amount of staked/xbomb equals the desired output amount of bomb?\n return (IERC20Upgradeable(inputTokenAddress), IXBomb(xbomb).toSTAKED(outputAmount));\n } else if (inputTokenAddress == address(bomb)) {\n // what amount of reward/bomb equals the desired output amount of xbomb?\n return (IERC20Upgradeable(inputTokenAddress), IXBomb(xbomb).toREWARD(outputAmount));\n } else {\n revert(\"unknown input token\");\n }\n }\n\n function name() public pure returns (string memory) {\n return \"XBombLiquidatorFunder\";\n }\n}\n\ncontract XBombSwap {\n IERC20Upgradeable public testingBomb;\n IERC20Upgradeable public testingStable;\n MasterPriceOracle public oracle;\n\n constructor(\n IERC20Upgradeable _testingBomb,\n IERC20Upgradeable _testingStable,\n MasterPriceOracle _oracle\n ) {\n testingBomb = _testingBomb;\n testingStable = _testingStable;\n oracle = _oracle;\n }\n\n function leave(uint256 _share) external {\n testingBomb.transferFrom(msg.sender, address(this), _share);\n testingStable.transfer(msg.sender, toREWARD(_share));\n }\n\n function enter(uint256 _amount) external {\n testingStable.transferFrom(msg.sender, address(this), _amount);\n testingBomb.transfer(msg.sender, toSTAKED(_amount));\n }\n\n function getExchangeRate() external view returns (uint256) {\n return 1e18;\n }\n\n function toREWARD(uint256 stakedAmount) public view returns (uint256) {\n uint256 bombPrice = oracle.price(address(testingBomb));\n uint256 stablePrice = oracle.price(address(testingStable));\n return (stakedAmount * bombPrice) / stablePrice;\n }\n\n function toSTAKED(uint256 rewardAmount) public view returns (uint256) {\n uint256 bombPrice = oracle.price(address(testingBomb));\n uint256 stablePrice = oracle.price(address(testingStable));\n return (rewardAmount * stablePrice) / bombPrice;\n }\n}\n" + }, + "contracts/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/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/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/oracles/default/SaddleLpPriceOracle.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { EIP20Interface } from \"../../compound/EIP20Interface.sol\";\n\nimport \"../../external/saddle/ISwap.sol\";\nimport \"../../ionic/SafeOwnableUpgradeable.sol\";\n\nimport \"../BasePriceOracle.sol\";\n\n/**\n * @title SaddleLpTokenPriceOracle\n * @author Carlo Mazzaferro (https://github.com/carlomazzaferro)\n * @notice SaddleLpPriceOracle is a price oracle for Saddle LP tokens (using the sender as a root oracle).\n * @dev Implements the `PriceOracle` interface used by Midas pools (and Compound v2).\n */\ncontract SaddleLpPriceOracle is SafeOwnableUpgradeable, BasePriceOracle {\n /**\n * @dev Maps Saddle LP token addresses to underlying token addresses.\n */\n mapping(address => address[]) public underlyingTokens;\n\n /**\n * @dev Maps Saddle LP token addresses to pool addresses.\n */\n mapping(address => address) public poolOf;\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 /**\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 Saddle, 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 * ISwap(pool).getVirtualPrice()) / 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 // require(pool == address(0), \"This LP token is already registered.\");\n poolOf[_lpToken] = _pool;\n underlyingTokens[_lpToken] = _underlyings;\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/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/PoolDirectory.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\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(address account)\n external\n view\n returns (uint256[] memory, Pool[] memory)\n {\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/PoolLens.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 { 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/test/config/BaseTest.t.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport \"forge-std/Vm.sol\";\nimport \"forge-std/Test.sol\";\nimport \"forge-std/console.sol\";\n\nimport { AddressesProvider } from \"../../ionic/AddressesProvider.sol\";\n\nimport \"@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol\";\nimport \"@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol\";\n\nabstract contract BaseTest is Test {\n uint128 constant ETHEREUM_MAINNET = 1;\n uint128 constant BSC_MAINNET = 56;\n uint128 constant POLYGON_MAINNET = 137;\n uint128 constant ARBITRUM_ONE = 42161;\n\n uint128 constant BSC_CHAPEL = 97;\n uint128 constant NEON_MAINNET = 245022934;\n uint128 constant LINEA_MAINNET = 59144;\n uint128 constant ZKEVM_MAINNET = 1101;\n uint128 constant MODE_MAINNET = 34443;\n uint128 constant BASE_MAINNET = 8453;\n\n // taken from ERC1967Upgrade\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n AddressesProvider public ap;\n ProxyAdmin public dpa;\n\n mapping(uint128 => uint256) private forkIds;\n\n constructor() {\n configureAddressesProvider(0);\n }\n\n uint256 constant CRITICAL = 100;\n uint256 constant NORMAL = 90;\n uint256 constant LOW = 80;\n\n modifier importance(uint256 testImportance) {\n uint256 runLevel = NORMAL;\n\n try vm.envUint(\"TEST_RUN_LEVEL\") returns (uint256 level) {\n runLevel = level;\n } catch {\n emit log(\"failed to get env param TEST_RUN_LEVEL\");\n }\n\n if (testImportance >= runLevel) {\n _;\n } else {\n emit log(\"not running the test\");\n }\n }\n\n modifier debuggingOnly() {\n try vm.envBool(\"LOCAL_FORGE_ENV\") returns (bool run) {\n if (run) _;\n } catch {\n emit log(\"skipping this test in the CI/CD - add LOCAL_FORGE_ENV=true to your .env file to run locally\");\n }\n }\n\n modifier fork(uint128 chainid) {\n if (shouldRunForChain(chainid)) {\n _forkAtBlock(chainid, 0);\n _;\n }\n }\n\n modifier forkAtBlock(uint128 chainid, uint256 blockNumber) {\n if (shouldRunForChain(chainid)) {\n _forkAtBlock(chainid, blockNumber);\n _;\n }\n }\n\n modifier whenForking() {\n try vm.activeFork() returns (uint256) {\n _;\n } catch {}\n }\n\n function shouldRunForChain(uint256 chainid) internal returns (bool) {\n bool run = true;\n try vm.envUint(\"TEST_RUN_CHAINID\") returns (uint256 envChainId) {\n run = envChainId == chainid;\n } catch {\n emit log(\"failed to get env param TEST_RUN_CHAINID\");\n }\n return run;\n }\n\n function _forkAtBlock(uint128 chainid, uint256 blockNumber) internal {\n if (block.chainid != chainid) {\n if (blockNumber != 0) {\n vm.selectFork(getArchiveForkId(chainid));\n vm.rollFork(blockNumber);\n } else {\n vm.selectFork(getForkId(chainid));\n }\n }\n configureAddressesProvider(chainid);\n afterForkSetUp();\n }\n\n function getForkId(uint128 chainid, bool archive) private returns (uint256) {\n return archive ? getForkId(chainid) : getArchiveForkId(chainid);\n }\n\n function getForkId(uint128 chainid) private returns (uint256) {\n if (forkIds[chainid] == 0) {\n if (chainid == BSC_MAINNET) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"bsc\")) + 100;\n } else if (chainid == BSC_CHAPEL) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"bsc_chapel\")) + 100;\n } else if (chainid == POLYGON_MAINNET) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"polygon\")) + 100;\n } else if (chainid == NEON_MAINNET) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"neon\")) + 100;\n } else if (chainid == ARBITRUM_ONE) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"arbitrum\")) + 100;\n } else if (chainid == ETHEREUM_MAINNET) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"ethereum\")) + 100;\n } else if (chainid == LINEA_MAINNET) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"linea\")) + 100;\n } else if (chainid == ZKEVM_MAINNET) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"zkevm\")) + 100;\n } else if (chainid == MODE_MAINNET) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"mode\")) + 100;\n } else if (chainid == BASE_MAINNET) {\n forkIds[chainid] = vm.createFork(vm.rpcUrl(\"base\")) + 100;\n }\n }\n\n return forkIds[chainid] - 100;\n }\n\n function getArchiveForkId(uint128 chainid) private returns (uint256) {\n // store the archive rpc urls in the forkIds mapping at an offset\n uint128 chainidWithOffset = chainid + type(uint64).max;\n if (forkIds[chainidWithOffset] == 0) {\n if (chainid == BSC_MAINNET) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"bsc_archive\")) + 100;\n } else if (chainid == BSC_CHAPEL) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"bsc_chapel_archive\")) + 100;\n } else if (chainid == POLYGON_MAINNET) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"polygon_archive\")) + 100;\n } else if (chainid == NEON_MAINNET) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"neon_archive\")) + 100;\n } else if (chainid == ARBITRUM_ONE) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"arbitrum_archive\")) + 100;\n } else if (chainid == ETHEREUM_MAINNET) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"ethereum_archive\")) + 100;\n } else if (chainid == LINEA_MAINNET) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"linea_archive\")) + 100;\n } else if (chainid == ZKEVM_MAINNET) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"zkevm_archive\")) + 100;\n } else if (chainid == MODE_MAINNET) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"mode_archive\")) + 100;\n } else if (chainid == BASE_MAINNET) {\n forkIds[chainidWithOffset] = vm.createFork(vm.rpcUrl(\"base_archive\")) + 100;\n }\n }\n return forkIds[chainidWithOffset] - 100;\n }\n\n function afterForkSetUp() internal virtual {}\n\n function configureAddressesProvider(uint128 chainid) private {\n if (chainid == BSC_MAINNET) {\n ap = AddressesProvider(address(0));\n } else if (chainid == BSC_CHAPEL) {\n ap = AddressesProvider(0x3dc8CE9f581e49B9E5304CF580940ad341F64c3f);\n } else if (block.chainid == POLYGON_MAINNET) {\n ap = AddressesProvider(0xE31baC0B582AA248c0017F87F24087cEa7A55E26);\n } else if (chainid == NEON_MAINNET) {\n ap = AddressesProvider(0xF4C60F6ac6b3AF54044757a1a54D76EEe28244CE);\n } else if (chainid == ARBITRUM_ONE) {\n ap = AddressesProvider(0x3B12BA992259Fb3855C4E1D452a754dCa2E276fC);\n } else if (chainid == LINEA_MAINNET) {\n ap = AddressesProvider(0x914694DA0bED80e74ef1a28029f016119782C0f1);\n } else if (chainid == ZKEVM_MAINNET) {\n ap = AddressesProvider(0x27aA55A3D55959261e119d75256aadAB79aE897C);\n } else if (chainid == MODE_MAINNET) {\n ap = AddressesProvider(0xb0033576a9E444Dd801d5B69e1b63DBC459A6115);\n } else if (chainid == BASE_MAINNET) {\n ap = AddressesProvider(0xcD4D7c8e2bA627684a9B18F7fe88239341D3ba5c);\n } else {\n dpa = new ProxyAdmin();\n AddressesProvider logic = new AddressesProvider();\n TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(\n address(logic),\n address(dpa),\n abi.encodeWithSelector(ap.initialize.selector, address(this))\n );\n ap = AddressesProvider(address(proxy));\n ap.setAddress(\"DefaultProxyAdmin\", address(dpa));\n }\n dpa = ProxyAdmin(ap.getAddress(\"DefaultProxyAdmin\"));\n if (ap.owner() == address(0)) {\n ap.initialize(address(this));\n }\n if (ap.getAddress(\"deployer\") == address(0)) {\n vm.prank(ap.owner());\n ap.setAddress(\"deployer\", 0x1155b614971f16758C92c4890eD338C9e3ede6b7);\n }\n }\n\n function diff(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a > b) {\n return a - b;\n } else {\n return b - a;\n }\n }\n\n function compareStrings(string memory a, string memory b) public pure returns (bool) {\n return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b))));\n }\n\n function asArray(address value) public pure returns (address[] memory) {\n address[] memory array = new address[](1);\n array[0] = value;\n return array;\n }\n\n function asArray(address value0, address value1) public pure returns (address[] memory) {\n address[] memory array = new address[](2);\n array[0] = value0;\n array[1] = value1;\n return array;\n }\n\n function asArray(\n address value0,\n address value1,\n address value2\n ) public pure returns (address[] memory) {\n address[] memory array = new address[](3);\n array[0] = value0;\n array[1] = value1;\n array[2] = value2;\n return array;\n }\n\n function asArray(bool value) public pure returns (bool[] memory) {\n bool[] memory array = new bool[](1);\n array[0] = value;\n return array;\n }\n\n function asArray(uint256 value0, uint256 value1) public pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](2);\n array[0] = value0;\n array[1] = value1;\n return array;\n }\n\n function asArray(uint256 value) public pure returns (uint256[] memory) {\n uint256[] memory array = new uint256[](1);\n array[0] = value;\n return array;\n }\n\n function asArray(bytes memory value) public pure returns (bytes[] memory) {\n bytes[] memory array = new bytes[](1);\n array[0] = value;\n return array;\n }\n\n function asArray(bytes memory value0, bytes memory value1) public pure returns (bytes[] memory) {\n bytes[] memory array = new bytes[](2);\n array[0] = value0;\n array[1] = value1;\n return array;\n }\n\n function asArray(\n bytes memory value0,\n bytes memory value1,\n bytes memory value2\n ) public pure returns (bytes[] memory) {\n bytes[] memory array = new bytes[](3);\n array[0] = value0;\n array[1] = value1;\n array[2] = value2;\n return array;\n }\n\n function sqrt(uint256 x) public 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/test/config/MarketsTest.t.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { BaseTest } from \"./BaseTest.t.sol\";\nimport { FeeDistributor } from \"../../FeeDistributor.sol\";\nimport { CErc20Delegate } from \"../../compound/CErc20Delegate.sol\";\nimport { CErc20PluginDelegate } from \"../../compound/CErc20PluginDelegate.sol\";\nimport { CErc20RewardsDelegate } from \"../../compound/CErc20RewardsDelegate.sol\";\nimport { CErc20PluginRewardsDelegate } from \"../../compound/CErc20PluginRewardsDelegate.sol\";\nimport { DiamondExtension } from \"../../ionic/DiamondExtension.sol\";\nimport { CTokenFirstExtension } from \"../../compound/CTokenFirstExtension.sol\";\nimport { Comptroller } from \"../../compound/Comptroller.sol\";\nimport { Unitroller } from \"../../compound/Unitroller.sol\";\nimport { ComptrollerFirstExtension } from \"../../compound/ComptrollerFirstExtension.sol\";\nimport { AuthoritiesRegistry } from \"../../ionic/AuthoritiesRegistry.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\n\nimport \"@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol\";\n\ncontract MarketsTest is BaseTest {\n FeeDistributor internal ffd;\n\n CErc20Delegate internal cErc20Delegate;\n CErc20PluginDelegate internal cErc20PluginDelegate;\n CErc20RewardsDelegate internal cErc20RewardsDelegate;\n CErc20PluginRewardsDelegate internal cErc20PluginRewardsDelegate;\n CTokenFirstExtension internal newCTokenExtension;\n\n address payable internal latestComptrollerImplementation;\n ComptrollerFirstExtension internal comptrollerExtension;\n\n function afterForkSetUp() internal virtual override {\n ffd = FeeDistributor(payable(ap.getAddress(\"FeeDistributor\")));\n upgradeFfd();\n cErc20Delegate = new CErc20Delegate();\n cErc20PluginDelegate = new CErc20PluginDelegate();\n cErc20RewardsDelegate = new CErc20RewardsDelegate();\n cErc20PluginRewardsDelegate = new CErc20PluginRewardsDelegate();\n newCTokenExtension = new CTokenFirstExtension();\n\n comptrollerExtension = new ComptrollerFirstExtension();\n Comptroller newComptrollerImplementation = new Comptroller();\n latestComptrollerImplementation = payable(address(newComptrollerImplementation));\n }\n\n function upgradeFfd() internal {\n {\n FeeDistributor newImpl = new FeeDistributor();\n TransparentUpgradeableProxy proxy = TransparentUpgradeableProxy(payable(address(ffd)));\n bytes32 bytesAtSlot = vm.load(address(proxy), 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103);\n address admin = address(uint160(uint256(bytesAtSlot)));\n vm.prank(admin);\n proxy.upgradeTo(address(newImpl));\n }\n\n if (address(ffd.authoritiesRegistry()) == address(0)) {\n AuthoritiesRegistry impl = new AuthoritiesRegistry();\n TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy(address(impl), address(1), \"\");\n AuthoritiesRegistry newAr = AuthoritiesRegistry(address(proxy));\n newAr.initialize(address(321));\n vm.prank(ffd.owner());\n ffd.reinitialize(newAr);\n }\n }\n\n function _prepareCTokenUpgrade(ICErc20 market) internal returns (address) {\n address implBefore = market.implementation();\n //emit log(\"implementation before\");\n //emit log_address(implBefore);\n\n CErc20Delegate newImpl;\n if (market.delegateType() == 1) {\n newImpl = cErc20Delegate;\n } else if (market.delegateType() == 2) {\n newImpl = cErc20PluginDelegate;\n } else if (market.delegateType() == 3) {\n newImpl = cErc20RewardsDelegate;\n } else {\n newImpl = cErc20PluginRewardsDelegate;\n }\n\n // set the new ctoken delegate as the latest\n uint8 delegateType = market.delegateType();\n vm.prank(ffd.owner());\n ffd._setLatestCErc20Delegate(delegateType, address(newImpl), abi.encode(address(0)));\n\n // add the extension to the auto upgrade config\n DiamondExtension[] memory cErc20DelegateExtensions = new DiamondExtension[](2);\n cErc20DelegateExtensions[0] = DiamondExtension(newImpl);\n cErc20DelegateExtensions[1] = newCTokenExtension;\n vm.prank(ffd.owner());\n ffd._setCErc20DelegateExtensions(address(newImpl), cErc20DelegateExtensions);\n\n return address(newImpl);\n }\n\n function _upgradeMarket(ICErc20 market) internal {\n address newDelegate = _prepareCTokenUpgrade(market);\n\n bytes memory becomeImplData = (address(newDelegate) == address(cErc20Delegate))\n ? bytes(\"\")\n : abi.encode(address(0));\n vm.prank(market.ionicAdmin());\n market._setImplementationSafe(newDelegate, becomeImplData);\n }\n\n function _prepareComptrollerUpgrade(address oldCompImpl) internal {\n vm.startPrank(ffd.owner());\n ffd._setLatestComptrollerImplementation(oldCompImpl, latestComptrollerImplementation);\n DiamondExtension[] memory extensions = new DiamondExtension[](2);\n extensions[0] = comptrollerExtension;\n extensions[1] = Comptroller(latestComptrollerImplementation);\n ffd._setComptrollerExtensions(latestComptrollerImplementation, extensions);\n vm.stopPrank();\n }\n\n function _upgradeExistingPool(address poolAddress) internal {\n Unitroller asUnitroller = Unitroller(payable(poolAddress));\n // change the implementation to the new that can add extensions\n address oldComptrollerImplementation = asUnitroller.comptrollerImplementation();\n\n _prepareComptrollerUpgrade(oldComptrollerImplementation);\n\n // upgrade to the new comptroller\n vm.startPrank(asUnitroller.admin());\n asUnitroller._upgrade();\n vm.stopPrank();\n }\n}\n" + }, + "contracts/test/LeveredPositionTest.t.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { MarketsTest, BaseTest } from \"./config/MarketsTest.t.sol\";\nimport { DiamondBase, DiamondExtension } from \"../ionic/DiamondExtension.sol\";\n\nimport { LeveredPosition } from \"../ionic/levered/LeveredPosition.sol\";\nimport { LeveredPositionFactory, IFeeDistributor } from \"../ionic/levered/LeveredPositionFactory.sol\";\nimport { JarvisLiquidatorFunder } from \"../liquidators/JarvisLiquidatorFunder.sol\";\nimport { BalancerSwapLiquidator } from \"../liquidators/BalancerSwapLiquidator.sol\";\nimport { AlgebraSwapLiquidator } from \"../liquidators/AlgebraSwapLiquidator.sol\";\nimport { SolidlyLpTokenLiquidator, SolidlyLpTokenWrapper } from \"../liquidators/SolidlyLpTokenLiquidator.sol\";\nimport { SolidlySwapLiquidator } from \"../liquidators/SolidlySwapLiquidator.sol\";\nimport { UniswapV3LiquidatorFunder } from \"../liquidators/UniswapV3LiquidatorFunder.sol\";\n\nimport { CurveLpTokenLiquidatorNoRegistry } from \"../liquidators/CurveLpTokenLiquidatorNoRegistry.sol\";\nimport { LeveredPositionFactoryFirstExtension } from \"../ionic/levered/LeveredPositionFactoryFirstExtension.sol\";\nimport { LeveredPositionFactorySecondExtension } from \"../ionic/levered/LeveredPositionFactorySecondExtension.sol\";\nimport { ILeveredPositionFactory } from \"../ionic/levered/ILeveredPositionFactory.sol\";\nimport { LeveredPositionsLens } from \"../ionic/levered/LeveredPositionsLens.sol\";\nimport { LiquidatorsRegistry } from \"../liquidators/registry/LiquidatorsRegistry.sol\";\nimport { LiquidatorsRegistryExtension } from \"../liquidators/registry/LiquidatorsRegistryExtension.sol\";\nimport { LiquidatorsRegistrySecondExtension } from \"../liquidators/registry/LiquidatorsRegistrySecondExtension.sol\";\nimport { ILiquidatorsRegistry } from \"../liquidators/registry/ILiquidatorsRegistry.sol\";\nimport { IRedemptionStrategy } from \"../liquidators/IRedemptionStrategy.sol\";\nimport { ICErc20 } from \"../compound/CTokenInterfaces.sol\";\nimport { IonicComptroller } from \"../compound/ComptrollerInterface.sol\";\nimport { ComptrollerFirstExtension } from \"../compound/ComptrollerFirstExtension.sol\";\nimport { SafeOwnable } from \"../ionic/SafeOwnable.sol\";\nimport { PoolRolesAuthority } from \"../ionic/PoolRolesAuthority.sol\";\n\nimport { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport { ERC20 } from \"solmate/tokens/ERC20.sol\";\n\ncontract LeveredPositionLensTest is BaseTest {\n LeveredPositionsLens lens;\n ILeveredPositionFactory factory;\n\n function afterForkSetUp() internal override {\n factory = ILeveredPositionFactory(ap.getAddress(\"LeveredPositionFactory\"));\n emit log_named_address(\"factory\", address(factory));\n lens = LeveredPositionsLens(ap.getAddress(\"LeveredPositionsLens\"));\n // lens = new LeveredPositionsLens();\n // lens.initialize(factory);\n }\n\n function testLPLens() public debuggingOnly fork(BSC_CHAPEL) {\n _testLPLens();\n }\n\n function _testLPLens() internal {\n address[] memory positions;\n bool[] memory closed;\n (positions, closed) = factory.getPositionsByAccount(0xb6c11605e971ab46B9BE4fDC48C9650A257075db);\n\n // address[] memory accounts = factory.getAccountsWithOpenPositions();\n // for (uint256 i = 0; i < accounts.length; i++) {\n // (positions, closed) = factory.getPositionsByAccount(accounts[i]);\n // if (positions.length > 0) break;\n // }\n\n uint256[] memory apys = new uint256[](positions.length);\n LeveredPosition[] memory pos = new LeveredPosition[](positions.length);\n for (uint256 j = 0; j < positions.length; j++) {\n apys[j] = 1e17;\n\n if (address(0) == positions[j]) revert(\"zero pos address\");\n pos[j] = LeveredPosition(positions[j]);\n }\n\n LeveredPositionsLens.PositionInfo[] memory infos = lens.getPositionsInfo(pos, apys);\n\n for (uint256 k = 0; k < infos.length; k++) {\n emit log_named_address(\"address\", address(pos[k]));\n emit log_named_uint(\"positionSupplyAmount\", infos[k].positionSupplyAmount);\n emit log_named_uint(\"positionValue\", infos[k].positionValue);\n emit log_named_uint(\"debtAmount\", infos[k].debtAmount);\n emit log_named_uint(\"debtValue\", infos[k].debtValue);\n emit log_named_uint(\"equityValue\", infos[k].equityValue);\n emit log_named_uint(\"equityAmount\", infos[k].equityAmount);\n emit log_named_int(\"currentApy\", infos[k].currentApy);\n emit log_named_uint(\"debtRatio\", infos[k].debtRatio);\n emit log_named_uint(\"liquidationThreshold\", infos[k].liquidationThreshold);\n emit log_named_uint(\"safetyBuffer\", infos[k].safetyBuffer);\n\n emit log(\"\");\n }\n }\n\n function testPrintLeveredPositions() public debuggingOnly fork(POLYGON_MAINNET) {\n address[] memory accounts = factory.getAccountsWithOpenPositions();\n\n emit log_named_array(\"accounts\", accounts);\n\n for (uint256 j = 0; j < accounts.length; j++) {\n address[] memory positions;\n bool[] memory closed;\n (positions, closed) = factory.getPositionsByAccount(accounts[j]);\n emit log_named_array(\"positions\", positions);\n //emit log_named_array(\"closed\", closed);\n }\n }\n\n function testScenarioLeverageFailed() public debuggingOnly forkAtBlock(MODE_MAINNET, 10672173) {\n address USER = 0x95Ce459B20586cf44ee6d295C4f28e1a134CF529;\n // IERC20Upgradeable(0x4200000000000000000000000000000000000006).approve(\n // address(factory),\n // 100000 ether\n // );\n vm.prank(ap.owner());\n ap.setAddress(\"IUniswapV2Router02\", 0x3a63171DD9BebF4D07BC782FECC7eb0b890C2A45);\n vm.startPrank(USER);\n LeveredPosition position = factory.createAndFundPositionAtRatio(\n ICErc20(0x71ef7EDa2Be775E5A7aa8afD02C45F059833e9d2),\n ICErc20(0x2BE717340023C9e14C1Bb12cb3ecBcfd3c3fB038),\n IERC20Upgradeable(0x4200000000000000000000000000000000000006),\n 16754252276537996590,\n 3000000000000000000\n );\n emit log_named_address(\"position\", address(position));\n\n // vm.stopPrank();\n // ILiquidatorsRegistry registry = factory.liquidatorsRegistry();\n // vm.startPrank(registry.owner());\n // registry._setRedemptionStrategy(\n // new UniswapV3LiquidatorFunder(),\n // IERC20Upgradeable(0xd988097fb8612cc24eeC14542bC03424c656005f),\n // IERC20Upgradeable(0x4200000000000000000000000000000000000006)\n // );\n // vm.stopPrank();\n // vm.startPrank(USER);\n\n vm.roll(10673509);\n position.adjustLeverageRatio(3000000000000000000);\n\n // vm.roll(10852409);\n // position.adjustLeverageRatio(3000000000000000000);\n\n // vm.roll(11268772);\n // position.adjustLeverageRatio(3000000000000000000);\n vm.stopPrank();\n }\n}\n\ncontract LeveredPositionFactoryTest is BaseTest {\n ILeveredPositionFactory factory;\n LeveredPositionsLens lens;\n\n function afterForkSetUp() internal override {\n factory = ILeveredPositionFactory(ap.getAddress(\"LeveredPositionFactory\"));\n lens = LeveredPositionsLens(ap.getAddress(\"LeveredPositionsLens\"));\n }\n\n function testChapelNetApy() public debuggingOnly fork(BSC_CHAPEL) {\n ICErc20 _stableMarket = ICErc20(address(1)); // DAI\n\n uint256 borrowRate = 5.2e16; // 5.2%\n vm.mockCall(\n address(_stableMarket),\n abi.encodeWithSelector(_stableMarket.borrowRatePerBlock.selector),\n abi.encode(borrowRate / factory.blocksPerYear())\n );\n\n uint256 _borrowRate = _stableMarket.borrowRatePerBlock() * factory.blocksPerYear();\n emit log_named_uint(\"_borrowRate\", _borrowRate);\n\n int256 netApy = lens.getNetAPY(\n 2.7e16, // 2.7%\n 1e18, // supply amount\n ICErc20(address(0)), // BOMB\n _stableMarket,\n 2e18 // ratio\n );\n\n emit log_named_int(\"net apy\", netApy);\n\n // boosted APY = 2x 2.7% = 5.4 % of the equity\n // borrow APR = 5.2%\n // diff = 5.4 - 5.2 = 0.2%\n assertApproxEqRel(netApy, 0.2e16, 1e12, \"!net apy\");\n }\n}\n\nabstract contract LeveredPositionTest is MarketsTest {\n ICErc20 collateralMarket;\n ICErc20 stableMarket;\n ILeveredPositionFactory factory;\n ILiquidatorsRegistry registry;\n LeveredPosition position;\n LeveredPositionsLens lens;\n\n uint256 minLevRatio;\n uint256 maxLevRatio;\n\n function afterForkSetUp() internal virtual override {\n super.afterForkSetUp();\n\n factory = ILeveredPositionFactory(ap.getAddress(\"LeveredPositionFactory\"));\n registry = factory.liquidatorsRegistry();\n // {\n // // upgrade the factory\n // LeveredPositionFactoryFirstExtension newExt1 = new LeveredPositionFactoryFirstExtension();\n // LeveredPositionFactorySecondExtension newExt2 = new LeveredPositionFactorySecondExtension();\n //\n // vm.startPrank(factory.owner());\n // DiamondBase asBase = DiamondBase(address(factory));\n // address[] memory oldExts = asBase._listExtensions();\n //\n // if (oldExts.length == 1) {\n // asBase._registerExtension(newExt1, DiamondExtension(oldExts[0]));\n // asBase._registerExtension(newExt2, DiamondExtension(address(0)));\n // } else if (oldExts.length == 2) {\n // asBase._registerExtension(newExt1, DiamondExtension(oldExts[0]));\n // asBase._registerExtension(newExt2, DiamondExtension(oldExts[1]));\n // }\n // vm.stopPrank();\n // }\n\n lens = LeveredPositionsLens(ap.getAddress(\"LeveredPositionsLens\"));\n }\n\n function upgradeRegistry() internal {\n DiamondBase asBase = DiamondBase(address(registry));\n address[] memory exts = asBase._listExtensions();\n LiquidatorsRegistryExtension newExt1 = new LiquidatorsRegistryExtension();\n LiquidatorsRegistrySecondExtension newExt2 = new LiquidatorsRegistrySecondExtension();\n vm.prank(SafeOwnable(address(registry)).owner());\n asBase._registerExtension(newExt1, DiamondExtension(exts[0]));\n vm.prank(SafeOwnable(address(registry)).owner());\n asBase._registerExtension(newExt2, DiamondExtension(exts[1]));\n }\n\n function upgradePoolAndMarkets() internal {\n _upgradeExistingPool(address(collateralMarket.comptroller()));\n _upgradeMarket(collateralMarket);\n _upgradeMarket(stableMarket);\n }\n\n function _unpauseMarkets(address collat, address stable) internal {\n ComptrollerFirstExtension asExtension = ComptrollerFirstExtension(address(ICErc20(stable).comptroller()));\n vm.startPrank(asExtension.admin());\n asExtension._setMintPaused(ICErc20(collat), false);\n asExtension._setMintPaused(ICErc20(stable), false);\n asExtension._setBorrowPaused(ICErc20(stable), false);\n vm.stopPrank();\n }\n\n function _configurePairAndLiquidator(address _collat, address _stable, IRedemptionStrategy _liquidator) internal {\n _configurePair(_collat, _stable);\n _configureTwoWayLiquidator(_collat, _stable, _liquidator);\n }\n\n function _configurePair(address _collat, address _stable) internal {\n collateralMarket = ICErc20(_collat);\n stableMarket = ICErc20(_stable);\n\n //upgradePoolAndMarkets();\n //_unpauseMarkets(_collat, _stable);\n vm.prank(factory.owner());\n factory._setPairWhitelisted(collateralMarket, stableMarket, true);\n }\n\n function _whitelistTestUser(address user) internal {\n address pool = address(collateralMarket.comptroller());\n PoolRolesAuthority pra = ffd.authoritiesRegistry().poolsAuthorities(pool);\n\n vm.startPrank(pra.owner());\n pra.setUserRole(user, pra.BORROWER_ROLE(), true);\n vm.stopPrank();\n }\n\n function _configureTwoWayLiquidator(\n address inputMarket,\n address outputMarket,\n IRedemptionStrategy strategy\n ) internal {\n IERC20Upgradeable inputToken = underlying(inputMarket);\n IERC20Upgradeable outputToken = underlying(outputMarket);\n vm.startPrank(registry.owner());\n registry._setRedemptionStrategy(strategy, inputToken, outputToken);\n registry._setRedemptionStrategy(strategy, outputToken, inputToken);\n vm.stopPrank();\n }\n\n function underlying(address market) internal view returns (IERC20Upgradeable) {\n return IERC20Upgradeable(ICErc20(market).underlying());\n }\n\n struct Liquidator {\n IERC20Upgradeable inputToken;\n IERC20Upgradeable outputToken;\n IRedemptionStrategy strategy;\n }\n\n function _configureMultipleLiquidators(Liquidator[] memory liquidators) internal {\n IRedemptionStrategy[] memory strategies = new IRedemptionStrategy[](liquidators.length);\n IERC20Upgradeable[] memory inputTokens = new IERC20Upgradeable[](liquidators.length);\n IERC20Upgradeable[] memory outputTokens = new IERC20Upgradeable[](liquidators.length);\n for (uint256 i = 0; i < liquidators.length; i++) {\n strategies[i] = liquidators[i].strategy;\n inputTokens[i] = liquidators[i].inputToken;\n outputTokens[i] = liquidators[i].outputToken;\n }\n vm.startPrank(registry.owner());\n registry._setRedemptionStrategies(strategies, inputTokens, outputTokens);\n vm.stopPrank();\n }\n\n function _fundMarketAndSelf(ICErc20 market, address whale) internal {\n IERC20Upgradeable token = IERC20Upgradeable(market.underlying());\n\n if (whale == address(0)) {\n whale = address(911);\n //vm.deal(address(token), whale, 100e18);\n }\n\n uint256 allTokens = token.balanceOf(whale);\n vm.prank(whale);\n token.transfer(address(this), allTokens / 20);\n\n if (market.getCash() < allTokens / 2) {\n _whitelistTestUser(whale);\n vm.startPrank(whale);\n token.approve(address(market), allTokens / 2);\n market.mint(allTokens / 2);\n vm.stopPrank();\n }\n }\n\n function _openLeveredPosition(\n address _positionOwner,\n uint256 _depositAmount\n ) internal returns (LeveredPosition _position, uint256 _maxRatio, uint256 _minRatio) {\n IERC20Upgradeable collateralToken = IERC20Upgradeable(collateralMarket.underlying());\n collateralToken.transfer(_positionOwner, _depositAmount);\n\n vm.startPrank(_positionOwner);\n collateralToken.approve(address(factory), _depositAmount);\n _position = factory.createAndFundPosition(collateralMarket, stableMarket, collateralToken, _depositAmount);\n vm.stopPrank();\n\n _maxRatio = _position.getMaxLeverageRatio();\n emit log_named_uint(\"max ratio\", _maxRatio);\n _minRatio = _position.getMinLeverageRatio();\n emit log_named_uint(\"min ratio\", _minRatio);\n\n assertGt(_maxRatio, _minRatio, \"max ratio <= min ratio\");\n }\n\n function testOpenLeveredPosition() public virtual whenForking {\n assertApproxEqRel(position.getCurrentLeverageRatio(), 1e18, 4e16, \"initial leverage ratio should be 1.0 (1e18)\");\n }\n\n function testAnyLeverageRatio(uint64 ratioDiff) public debuggingOnly whenForking {\n // ratioDiff is between 0 and 2^64 ~= 18.446e18\n uint256 targetLeverageRatio = 1e18 + uint256(ratioDiff);\n emit log_named_uint(\"fuzz max ratio\", maxLevRatio);\n emit log_named_uint(\"fuzz min ratio\", minLevRatio);\n emit log_named_uint(\"target ratio\", targetLeverageRatio);\n vm.assume(targetLeverageRatio < maxLevRatio);\n vm.assume(minLevRatio < targetLeverageRatio);\n\n uint256 borrowedAssetPrice = stableMarket.comptroller().oracle().getUnderlyingPrice(stableMarket);\n (uint256 sd, uint256 bd) = position.getSupplyAmountDelta(targetLeverageRatio);\n emit log_named_uint(\"borrows delta val\", (bd * borrowedAssetPrice) / 1e18);\n emit log_named_uint(\"min borrow value\", ffd.getMinBorrowEth(stableMarket));\n\n uint256 equityAmount = position.getEquityAmount();\n emit log_named_uint(\"equity amount\", equityAmount);\n\n uint256 currentLeverageRatio = position.getCurrentLeverageRatio();\n emit log_named_uint(\"current ratio\", currentLeverageRatio);\n\n uint256 leverageRatioRealized = position.adjustLeverageRatio(targetLeverageRatio);\n emit log_named_uint(\"equity amount\", position.getEquityAmount());\n assertApproxEqRel(leverageRatioRealized, targetLeverageRatio, 4e16, \"target ratio not matching\");\n }\n\n function testMinMaxLeverageRatio() public whenForking {\n assertGt(maxLevRatio, minLevRatio, \"max ratio <= min ratio\");\n\n // attempting to adjust to minLevRatio - 0.01 should fail\n vm.expectRevert(abi.encodeWithSelector(LeveredPosition.BorrowStableFailed.selector, 0x3fa));\n position.adjustLeverageRatio((minLevRatio + 1e18) / 2);\n // just testing\n position.adjustLeverageRatio(maxLevRatio);\n // but adjusting to the minLevRatio + 0.01 should succeed\n position.adjustLeverageRatio(minLevRatio + 0.01e18);\n }\n\n function testMaxLeverageRatio() public whenForking {\n uint256 _equityAmount = position.getEquityAmount();\n uint256 rate = lens.getBorrowRateAtRatio(collateralMarket, stableMarket, _equityAmount, maxLevRatio);\n emit log_named_uint(\"borrow rate at max ratio\", rate);\n\n position.adjustLeverageRatio(maxLevRatio);\n assertApproxEqRel(position.getCurrentLeverageRatio(), maxLevRatio, 4e16, \"target max ratio not matching\");\n }\n\n function testRewardsAccruedClaimed() public whenForking {\n address[] memory flywheels = position.pool().getRewardsDistributors();\n if (flywheels.length > 0) {\n vm.warp(block.timestamp + 60 * 60 * 24);\n vm.roll(block.number + 10000);\n\n (ERC20[] memory rewardTokens, uint256[] memory amounts) = position.getAccruedRewards();\n\n ERC20 rewardToken;\n bool atLeastOneAccrued = false;\n for (uint256 i = 0; i < amounts.length; i++) {\n atLeastOneAccrued = amounts[i] > 0;\n if (atLeastOneAccrued) {\n rewardToken = rewardTokens[i];\n emit log_named_address(\"accrued from reward token\", address(rewardTokens[i]));\n break;\n }\n }\n\n assertEq(atLeastOneAccrued, true, \"!should have accrued at least one reward token\");\n\n if (atLeastOneAccrued) {\n uint256 rewardsBalanceBefore = rewardToken.balanceOf(address(this));\n position.claimRewards();\n uint256 rewardsBalanceAfter = rewardToken.balanceOf(address(this));\n assertGt(rewardsBalanceAfter - rewardsBalanceBefore, 0, \"should have claimed some rewards\");\n }\n } else {\n emit log(\"no flywheels/rewards for the pair pool\");\n }\n }\n\n function testLeverMaxDown() public whenForking {\n IERC20Upgradeable stableAsset = IERC20Upgradeable(stableMarket.underlying());\n IERC20Upgradeable collateralAsset = IERC20Upgradeable(collateralMarket.underlying());\n uint256 startingEquity = position.getEquityAmount();\n\n uint256 leverageRatioRealized = position.adjustLeverageRatio(maxLevRatio);\n assertApproxEqRel(leverageRatioRealized, maxLevRatio, 4e16, \"target ratio not matching\");\n\n // decrease the ratio in 10 equal steps\n uint256 ratioDiffStep = (maxLevRatio - 1e18) / 9;\n while (leverageRatioRealized > 1e18) {\n uint256 targetLeverDownRatio = leverageRatioRealized - ratioDiffStep;\n if (targetLeverDownRatio < minLevRatio) targetLeverDownRatio = 1e18;\n leverageRatioRealized = position.adjustLeverageRatio(targetLeverDownRatio);\n assertApproxEqRel(leverageRatioRealized, targetLeverDownRatio, 3e16, \"target lever down ratio not matching\");\n }\n\n uint256 withdrawAmount = position.closePosition();\n emit log_named_uint(\"withdraw amount\", withdrawAmount);\n assertApproxEqRel(startingEquity, withdrawAmount, 5e16, \"!withdraw amount\");\n\n assertEq(position.getEquityAmount(), 0, \"!nonzero equity amount\");\n assertEq(position.getCurrentLeverageRatio(), 0, \"!nonzero leverage ratio\");\n }\n}\n\ncontract WmaticMaticXLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n upgradeRegistry();\n\n uint256 depositAmount = 500e18;\n\n address wmaticMarket = 0xCb8D7c2690536d3444Da3d207f62A939483c8A93;\n address maticxMarket = 0x6ebdbEe1a509247B4A3ac3b73a43bd434C52C7c2;\n address wmaticWhale = 0x6d80113e533a2C0fe82EaBD35f1875DcEA89Ea97;\n address maticxWhale = 0x72f0275444F2aF8dBf13F78D54A8D3aD7b6E68db;\n\n _configurePair(wmaticMarket, maticxMarket);\n _fundMarketAndSelf(ICErc20(wmaticMarket), wmaticWhale);\n _fundMarketAndSelf(ICErc20(maticxMarket), maticxWhale);\n\n // call amountOutAndSlippageOfSwap to cache the slippage\n {\n IERC20Upgradeable collateralToken = IERC20Upgradeable(collateralMarket.underlying());\n IERC20Upgradeable stableToken = IERC20Upgradeable(stableMarket.underlying());\n\n vm.startPrank(wmaticWhale);\n collateralToken.approve(address(registry), 1e36);\n registry.amountOutAndSlippageOfSwap(collateralToken, 100e18, stableToken);\n vm.stopPrank();\n vm.startPrank(maticxWhale);\n stableToken.approve(address(registry), 1e36);\n registry.amountOutAndSlippageOfSwap(stableToken, 100e18, collateralToken);\n vm.stopPrank();\n\n emit log_named_uint(\"slippage coll->stable\", registry.getSlippage(collateralToken, stableToken));\n emit log_named_uint(\"slippage stable->coll\", registry.getSlippage(stableToken, collateralToken));\n }\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract StkBnbWBnbLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(BSC_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 2e18;\n\n address stkBnbMarket = 0xAcfbf93d8fD1A9869bAb2328669dDba33296a421;\n address wbnbMarket = 0x3Af258d24EBdC03127ED6cEb8e58cA90835fbca5;\n address stkBnbWhale = 0x84b78452A97C5afDa1400943333F691448069A29; // algebra pool\n address wbnbWhale = 0x84b78452A97C5afDa1400943333F691448069A29; // algebra pool\n\n AlgebraSwapLiquidator liquidator = new AlgebraSwapLiquidator();\n _configurePairAndLiquidator(stkBnbMarket, wbnbMarket, liquidator);\n _fundMarketAndSelf(ICErc20(stkBnbMarket), stkBnbWhale);\n _fundMarketAndSelf(ICErc20(wbnbMarket), wbnbWhale);\n\n IERC20Upgradeable collateralToken = IERC20Upgradeable(collateralMarket.underlying());\n collateralToken.transfer(address(this), depositAmount);\n collateralToken.approve(address(factory), depositAmount);\n position = factory.createAndFundPosition(collateralMarket, stableMarket, collateralToken, depositAmount);\n }\n}\n\ninterface TwoBrl {\n function minter() external view returns (address);\n\n function mint(address payable _to, uint256 _value) external returns (bool);\n}\n\ncontract Jbrl2BrlLeveredPositionTest is LeveredPositionTest {\n IonicComptroller pool;\n ComptrollerFirstExtension asExtension;\n\n function setUp() public fork(BSC_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 1000e18;\n\n address twoBrlMarket = 0xf0a2852958aD041a9Fb35c312605482Ca3Ec17ba; // 2brl as collateral\n address jBrlMarket = 0x82A3103bc306293227B756f7554AfAeE82F8ab7a; // jbrl as borrowable\n address payable twoBrlWhale = payable(address(177)); // empty account\n address jBrlWhale = 0xA0695f78AF837F570bcc50f53e58Cda300798B65; // solidly pair BRZ-JBRL\n\n TwoBrl twoBrl = TwoBrl(ICErc20(twoBrlMarket).underlying());\n vm.prank(twoBrl.minter());\n twoBrl.mint(twoBrlWhale, depositAmount * 100);\n\n _configurePair(twoBrlMarket, jBrlMarket);\n _fundMarketAndSelf(ICErc20(twoBrlMarket), twoBrlWhale);\n _fundMarketAndSelf(ICErc20(jBrlMarket), jBrlWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract BombWbnbLeveredPositionTest is LeveredPositionTest {\n uint256 depositAmount = 100e18;\n address whale = 0xe7B7dF67C1fe053f1C6B965826d3bFF19603c482;\n address wbnbWhale = 0x57E30beb8054B248CE301FeabfD0c74677Fa40f0;\n uint256 ratioOnCreation = 1.0e18;\n uint256 minBorrowNative = 1e17;\n\n function setUp() public fork(BSC_CHAPEL) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n upgradeRegistry();\n\n vm.mockCall(\n address(ffd),\n abi.encodeWithSelector(IFeeDistributor.minBorrowEth.selector),\n abi.encode(minBorrowNative)\n );\n\n address xMarket = 0x9B6E1039103812E0dcC1100a158e4a68014b2571; // BOMB\n address yMarket = 0x9dD00920f5B74A31177cbaB834AB0904703c31B1; // WBNB\n\n collateralMarket = ICErc20(xMarket);\n stableMarket = ICErc20(yMarket);\n\n //upgradePoolAndMarkets();\n\n IERC20Upgradeable collateralToken = IERC20Upgradeable(collateralMarket.underlying());\n IERC20Upgradeable stableToken = IERC20Upgradeable(stableMarket.underlying());\n // call amountOutAndSlippageOfSwap to cache the slippage\n {\n vm.startPrank(whale);\n collateralToken.approve(address(registry), 1e36);\n registry.amountOutAndSlippageOfSwap(collateralToken, 1e18, stableToken);\n collateralToken.transfer(address(this), depositAmount);\n vm.stopPrank();\n\n vm.startPrank(wbnbWhale);\n stableToken.approve(address(registry), 1e36);\n registry.amountOutAndSlippageOfSwap(stableToken, 1e18, collateralToken);\n vm.stopPrank();\n }\n\n vm.prank(whale);\n collateralToken.transfer(address(this), depositAmount);\n\n collateralToken.approve(address(factory), depositAmount);\n position = factory.createAndFundPositionAtRatio(\n collateralMarket,\n stableMarket,\n collateralToken,\n depositAmount,\n ratioOnCreation\n );\n\n maxLevRatio = position.getMaxLeverageRatio();\n minLevRatio = position.getMinLeverageRatio();\n\n vm.label(address(position), \"Levered Position\");\n }\n}\n\ncontract PearlWUsdrWUsdrUsdrLpLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 0.000002e18;\n\n address lpTokenMarket = 0x06F61E22ef144f1cC4550D40ffbF681CB1C3aCAF;\n address wusdrMarket = 0x26EA46e975778662f98dAa0E7a12858dA9139262;\n address lpTokenWhale = 0x03Fa7A2628D63985bDFe07B95d4026663ED96065;\n address wUsdrWhale = 0x8711a1a52c34EDe8E61eF40496ab2618a8F6EA4B;\n\n _configurePair(lpTokenMarket, wusdrMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(wusdrMarket), wUsdrWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract PearlUsdrWUsdrUsdrLpLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 0.000002e18;\n\n address lpTokenMarket = 0x06F61E22ef144f1cC4550D40ffbF681CB1C3aCAF;\n address usdrMarket = 0x1F11940B239D129dE0e5D30A3E59089af5Ecd6ed;\n address lpTokenWhale = 0x03Fa7A2628D63985bDFe07B95d4026663ED96065;\n address usdrWhale = 0x00e8c0E92eB3Ad88189E7125Ec8825eDc03Ab265; // wUSDR contract\n\n _configurePair(lpTokenMarket, usdrMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdrMarket), usdrWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract PearlUsdcUsdrLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n upgradeRegistry();\n\n uint256 depositAmount = 800e9;\n\n address usdrMarket = 0x1F11940B239D129dE0e5D30A3E59089af5Ecd6ed;\n address usdcMarket = 0x71A7037a42D0fB9F905a76B7D16846b2EACC59Aa;\n address usdrWhale = 0x00e8c0E92eB3Ad88189E7125Ec8825eDc03Ab265; // wUSDR contract\n address usdcWhale = 0x5a52E96BAcdaBb82fd05763E25335261B270Efcb;\n\n IRedemptionStrategy liquidator = new SolidlySwapLiquidator();\n _configurePairAndLiquidator(usdrMarket, usdcMarket, liquidator);\n _fundMarketAndSelf(ICErc20(usdrMarket), usdrWhale);\n _fundMarketAndSelf(ICErc20(usdcMarket), usdcWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract PearlUsdcUsdcUsdrLpLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n upgradeRegistry();\n\n uint256 depositAmount = 10e9;\n\n // LP token underlying 0xD17cb0f162f133e339C0BbFc18c36c357E681D6b\n address lpTokenMarket = 0x83DF24fE1B1eBF38048B91ffc4a8De0bAa88b891;\n address usdcMarket = 0x71A7037a42D0fB9F905a76B7D16846b2EACC59Aa;\n address lpTokenWhale = 0x97Bd59A8202F8263C2eC39cf6cF6B438D0B45876; // Thena Gauge\n address usdcWhale = 0x5a52E96BAcdaBb82fd05763E25335261B270Efcb;\n\n _configurePair(lpTokenMarket, usdcMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdcMarket), usdcWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract PearlUsdrUsdcUsdrLpLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n upgradeRegistry();\n\n uint256 depositAmount = 10e9;\n\n // LP token underlying 0xD17cb0f162f133e339C0BbFc18c36c357E681D6b\n address lpTokenMarket = 0x83DF24fE1B1eBF38048B91ffc4a8De0bAa88b891;\n address usdrMarket = 0x1F11940B239D129dE0e5D30A3E59089af5Ecd6ed;\n address lpTokenWhale = 0x97Bd59A8202F8263C2eC39cf6cF6B438D0B45876; // Thena Gauge\n address usdrWhale = 0x00e8c0E92eB3Ad88189E7125Ec8825eDc03Ab265; // wUSDR contract\n\n _configurePair(lpTokenMarket, usdrMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdrMarket), usdrWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract PearlUsdrDaiUsdrLpLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n upgradeRegistry();\n\n uint256 depositAmount = 2e18;\n\n // LP token underlying 0xBD02973b441Aa83c8EecEA158b98B5984bb1036E\n address lpTokenMarket = 0xBcE30B4D78cEb9a75A1Aa62156529c3592b3F08b;\n address usdrMarket = 0x1F11940B239D129dE0e5D30A3E59089af5Ecd6ed;\n address lpTokenWhale = 0x85Fa2331040933A02b154579fAbE6A6a5A765279; // Thena Gauge\n address usdrWhale = 0x00e8c0E92eB3Ad88189E7125Ec8825eDc03Ab265; // wUSDR contract\n\n _configurePair(lpTokenMarket, usdrMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdrMarket), usdrWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract PearlUsdrTngblUsdrLpLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n upgradeRegistry();\n\n uint256 depositAmount = 0.02e18;\n\n // LP token underlying 0x0Edc235693C20943780b76D79DD763236E94C751\n address lpTokenMarket = 0x2E870Aeee3D9d1eA29Ec93d2c0A99A4e0D5EB697;\n address usdrMarket = 0x1F11940B239D129dE0e5D30A3E59089af5Ecd6ed;\n address lpTokenWhale = 0xdaeF32cA8D699015fcFB2884F6902fFCebE51c5b; // Thena Gauge\n address usdrWhale = 0x00e8c0E92eB3Ad88189E7125Ec8825eDc03Ab265; // wUSDR contract\n\n _configurePair(lpTokenMarket, usdrMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdrMarket), usdrWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract PearlUsdrWbtcUsdrLpLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n upgradeRegistry();\n\n uint256 depositAmount = 0.000000071325342755e18;\n\n // LP token underlying 0xb95E1C22dd965FafE926b2A793e9D6757b6613F4\n address lpTokenMarket = 0xffc8c8d747E52fAfbf973c64Bab10d38A6902c46;\n address usdrMarket = 0x1F11940B239D129dE0e5D30A3E59089af5Ecd6ed;\n address lpTokenWhale = 0x39976f6328ebA2a3C860b7DE5cF2c1bB41581FB8; // Thena Gauge\n address usdrWhale = 0x00e8c0E92eB3Ad88189E7125Ec8825eDc03Ab265; // wUSDR contract\n\n _configurePair(lpTokenMarket, usdrMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdrMarket), usdrWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract PearlUsdrWethUsdrLpLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n upgradeRegistry();\n\n uint256 depositAmount = 0.004081e18;\n\n // LP token underlying 0x343D9a8D2Bc6A62390aEc764bb5b900C4B039127\n address lpTokenMarket = 0x343D9a8D2Bc6A62390aEc764bb5b900C4B039127;\n address usdrMarket = 0x1F11940B239D129dE0e5D30A3E59089af5Ecd6ed;\n address lpTokenWhale = 0x7D02A8b758791A03319102f81bF61E220F73e43D; // Thena Gauge\n address usdrWhale = 0x00e8c0E92eB3Ad88189E7125Ec8825eDc03Ab265; // wUSDR contract\n\n _configurePair(lpTokenMarket, usdrMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdrMarket), usdrWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract PearlUsdrMaticUsdrLpLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n upgradeRegistry();\n\n uint256 depositAmount = 0.05e18;\n\n // LP token underlying vAMM-WMATIC/USDR\n address lpTokenMarket = 0xfacEdA4f9731797102f040380aD5e234c92d1942;\n address usdrMarket = 0x1F11940B239D129dE0e5D30A3E59089af5Ecd6ed;\n address lpTokenWhale = 0xdA0AfBeEEBef6dA2F060237D35cab759b99B13B6; // Thena Gauge\n address usdrWhale = 0x00e8c0E92eB3Ad88189E7125Ec8825eDc03Ab265; // wUSDR contract\n\n _configurePair(lpTokenMarket, usdrMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdrMarket), usdrWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract RetroCashAUsdcCashLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n upgradeRegistry();\n\n uint256 depositAmount = 300e18;\n\n // LP token underlying xCASH-USDC\n address lpTokenMarket = 0x1D2A7078a404ab970f951d5A6dbECD9e24838FB6;\n address cashMarket = 0xf69207CFDe6228A1e15A34F2b0c4fDe0845D9eBa;\n address lpTokenWhale = 0x35a499c15b4dDCf7e98628D415346B9795CCa80d;\n address cashWhale = 0x88C522E526E5Eea8d636fd6805cA7fEB488780D0;\n\n _configurePair(lpTokenMarket, cashMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(cashMarket), cashWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract RetroUsdcAUsdcCashLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 700e18;\n\n // LP token underlying xCASH-USDC\n address lpTokenMarket = 0x1D2A7078a404ab970f951d5A6dbECD9e24838FB6;\n address usdcMarket = 0x38EbA94210bCEf3F9231E1764EE230abC14D1cbc;\n address lpTokenWhale = 0x35a499c15b4dDCf7e98628D415346B9795CCa80d;\n address usdcWhale = 0x5a52E96BAcdaBb82fd05763E25335261B270Efcb;\n\n _configurePair(lpTokenMarket, usdcMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdcMarket), usdcWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract RetroUsdcAUsdcWethLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 1e18;\n\n // LP token underlying xUSDC-WETH05\n address lpTokenMarket = 0xC7cA03A0bE1dBAc350E5BfE5050fC5af6406490E;\n address usdcMarket = 0x38EbA94210bCEf3F9231E1764EE230abC14D1cbc;\n address lpTokenWhale = 0x38e481367E0c50f4166AD2A1C9fde0E3c662CFBa;\n address usdcWhale = 0x5a52E96BAcdaBb82fd05763E25335261B270Efcb;\n\n _configurePair(lpTokenMarket, usdcMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(usdcMarket), usdcWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract RetroCashUsdcLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 300e18;\n\n address cashMarket = 0xf69207CFDe6228A1e15A34F2b0c4fDe0845D9eBa;\n address usdcMarket = 0x38EbA94210bCEf3F9231E1764EE230abC14D1cbc;\n address cashWhale = 0x88C522E526E5Eea8d636fd6805cA7fEB488780D0;\n address usdcWhale = 0x5a52E96BAcdaBb82fd05763E25335261B270Efcb;\n\n _configurePair(cashMarket, usdcMarket);\n _fundMarketAndSelf(ICErc20(cashMarket), cashWhale);\n _fundMarketAndSelf(ICErc20(usdcMarket), usdcWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract RetroCashAUsdcWethLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 1e18;\n\n // LP token underlying xUSDC-WETH05\n address lpTokenMarket = 0xC7cA03A0bE1dBAc350E5BfE5050fC5af6406490E;\n address cashMarket = 0xf69207CFDe6228A1e15A34F2b0c4fDe0845D9eBa;\n address lpTokenWhale = 0x38e481367E0c50f4166AD2A1C9fde0E3c662CFBa;\n address cashWhale = 0x88C522E526E5Eea8d636fd6805cA7fEB488780D0;\n\n _configurePair(lpTokenMarket, cashMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(cashMarket), cashWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract RetroWethAWbtcWethLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 1e18;\n\n // LP token underlying xWBTC-WETH05\n address lpTokenMarket = 0xCB1a06eff3459078c26516ae3a1dB44A61D2DbCA;\n address wethMarket = 0x2469B23354cb7cA50b798663Ec5812Bf28d15e9e;\n address lpTokenWhale = 0x38e481367E0c50f4166AD2A1C9fde0E3c662CFBa;\n address wethWhale = 0x1eED63EfBA5f81D95bfe37d82C8E736b974F477b;\n\n _configurePair(lpTokenMarket, wethMarket);\n _fundMarketAndSelf(ICErc20(lpTokenMarket), lpTokenWhale);\n _fundMarketAndSelf(ICErc20(wethMarket), wethWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract DavosUsdcDusdLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(POLYGON_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 500e18;\n\n address dusdMarket = 0xE70d09dA78900A0429ee70b35200F70A30d7d2B9;\n address usdcMarket = 0x14787e50578d8c606C3d57bDbA53dD65Fd665449;\n address dusdWhale = 0xE69a1876bdACfa7A7a4F6D531BE2FDE843D2165C;\n address usdcWhale = 0x5a52E96BAcdaBb82fd05763E25335261B270Efcb;\n\n _configurePair(dusdMarket, usdcMarket);\n _fundMarketAndSelf(ICErc20(dusdMarket), dusdWhale);\n _fundMarketAndSelf(ICErc20(usdcMarket), usdcWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract ModeWethUSDCLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(MODE_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 1e17;\n\n address wethMarket = 0x71ef7EDa2Be775E5A7aa8afD02C45F059833e9d2;\n address USDCMarket = 0x2BE717340023C9e14C1Bb12cb3ecBcfd3c3fB038;\n address wethWhale = 0x7380511493DD4c2f1dD75E9CCe5bD52C787D4B51;\n address USDCWhale = 0x34b83A3759ba4c9F99c339604181bf6bBdED4C79;\n\n ICErc20[] memory cTokens = new ICErc20[](1);\n cTokens[0] = ICErc20(USDCMarket);\n\n uint256[] memory newBorrowCaps = new uint256[](1);\n newBorrowCaps[0] = 1e36;\n\n IonicComptroller comptroller = IonicComptroller(ICErc20(wethMarket).comptroller());\n\n vm.prank(comptroller.admin());\n comptroller._setMarketBorrowCaps(cTokens, newBorrowCaps);\n vm.stopPrank();\n\n _configurePair(wethMarket, USDCMarket);\n _fundMarketAndSelf(ICErc20(wethMarket), wethWhale);\n _fundMarketAndSelf(ICErc20(USDCMarket), USDCWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract ModeWethUSDTLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(MODE_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 1e18;\n\n address wethMarket = 0x71ef7EDa2Be775E5A7aa8afD02C45F059833e9d2;\n address USDTMarket = 0x94812F2eEa03A49869f95e1b5868C6f3206ee3D3;\n address wethWhale = 0x71ef7EDa2Be775E5A7aa8afD02C45F059833e9d2;\n address USDTWhale = 0x94812F2eEa03A49869f95e1b5868C6f3206ee3D3;\n\n ICErc20[] memory cTokens = new ICErc20[](1);\n cTokens[0] = ICErc20(USDTMarket);\n\n uint256[] memory newBorrowCaps = new uint256[](1);\n newBorrowCaps[0] = 1e36;\n\n IonicComptroller comptroller = IonicComptroller(ICErc20(wethMarket).comptroller());\n\n vm.prank(comptroller.admin());\n comptroller._setMarketBorrowCaps(cTokens, newBorrowCaps);\n\n _configurePair(wethMarket, USDTMarket);\n _fundMarketAndSelf(ICErc20(wethMarket), wethWhale);\n _fundMarketAndSelf(ICErc20(USDTMarket), USDTWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract ModeWbtcUSDCLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(MODE_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 1e6;\n\n address wbtcMarket = 0xd70254C3baD29504789714A7c69d60Ec1127375C;\n address USDCMarket = 0x2BE717340023C9e14C1Bb12cb3ecBcfd3c3fB038;\n address wbtcWhale = 0x3f3429D28438Cc14133966820b8A9Ea61Cf1D4F0;\n address USDCWhale = 0x34b83A3759ba4c9F99c339604181bf6bBdED4C79;\n\n ICErc20[] memory cTokens = new ICErc20[](1);\n cTokens[0] = ICErc20(USDCMarket);\n\n uint256[] memory newBorrowCaps = new uint256[](1);\n newBorrowCaps[0] = 1e36;\n\n IonicComptroller comptroller = IonicComptroller(ICErc20(wbtcMarket).comptroller());\n\n vm.prank(comptroller.admin());\n comptroller._setMarketBorrowCaps(cTokens, newBorrowCaps);\n vm.stopPrank();\n\n IERC20Upgradeable token = IERC20Upgradeable(ICErc20(wbtcMarket).underlying());\n\n _configurePair(wbtcMarket, USDCMarket);\n\n uint256 allTokens = token.balanceOf(wbtcWhale);\n\n vm.prank(wbtcWhale);\n token.transfer(address(this), allTokens);\n vm.stopPrank();\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\ncontract ModeWbtcUSDTLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(MODE_MAINNET) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 1e6;\n\n address wbtcMarket = 0xd70254C3baD29504789714A7c69d60Ec1127375C;\n address USDTMarket = 0x94812F2eEa03A49869f95e1b5868C6f3206ee3D3;\n address wbtcWhale = 0xd70254C3baD29504789714A7c69d60Ec1127375C;\n address USDTWhale = 0x94812F2eEa03A49869f95e1b5868C6f3206ee3D3;\n\n ICErc20[] memory cTokens = new ICErc20[](1);\n cTokens[0] = ICErc20(USDTMarket);\n\n uint256[] memory newBorrowCaps = new uint256[](1);\n newBorrowCaps[0] = 1e36;\n\n IonicComptroller comptroller = IonicComptroller(ICErc20(wbtcMarket).comptroller());\n\n vm.prank(comptroller.admin());\n comptroller._setMarketBorrowCaps(cTokens, newBorrowCaps);\n vm.stopPrank();\n\n _configurePair(wbtcMarket, USDTMarket);\n _fundMarketAndSelf(ICErc20(wbtcMarket), wbtcWhale);\n _fundMarketAndSelf(ICErc20(USDTMarket), USDTWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n\n/*\ncontract XYLeveredPositionTest is LeveredPositionTest {\n function setUp() public fork(X_CHAIN_ID) {}\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n uint256 depositAmount = 1e18;\n\n address xMarket = 0x...1;\n address yMarket = 0x...2;\n address xWhale = 0x...3;\n address yWhale = 0x...4;\n\n IRedemptionStrategy liquidator = new IRedemptionStrategy();\n _configurePairAndLiquidator(xMarket, yMarket, liquidator);\n _fundMarketAndSelf(ICErc20(xMarket), xWhale);\n _fundMarketAndSelf(ICErc20(yMarket), yWhale);\n\n (position, maxLevRatio, minLevRatio) = _openLeveredPosition(address(this), depositAmount);\n }\n}\n*/\n" + }, + "contracts/test/liquidators/IonicLiquidatorTest.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport \"openzeppelin-contracts-upgradeable/contracts/access/OwnableUpgradeable.sol\";\n\nimport { IonicLiquidator, ILiquidator } from \"../../IonicLiquidator.sol\";\nimport { IonicUniV3Liquidator } from \"../../IonicUniV3Liquidator.sol\";\nimport { ICurvePool } from \"../../external/curve/ICurvePool.sol\";\nimport { CurveSwapLiquidatorFunder } from \"../../liquidators/CurveSwapLiquidatorFunder.sol\";\nimport { UniswapV3LiquidatorFunder } from \"../../liquidators/UniswapV3LiquidatorFunder.sol\";\nimport { IonicComptroller } from \"../../compound/ComptrollerInterface.sol\";\nimport { IRedemptionStrategy } from \"../../liquidators/IRedemptionStrategy.sol\";\nimport { IFundsConversionStrategy } from \"../../liquidators/IFundsConversionStrategy.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { IUniswapV2Pair } from \"../../external/uniswap/IUniswapV2Pair.sol\";\nimport { ILiquidatorsRegistry } from \"../../liquidators/registry/ILiquidatorsRegistry.sol\";\nimport \"../../external/uniswap/quoter/interfaces/IUniswapV3Quoter.sol\";\nimport { AuthoritiesRegistry } from \"../../ionic/AuthoritiesRegistry.sol\";\nimport { LiquidatorsRegistrySecondExtension } from \"../../liquidators/registry/LiquidatorsRegistrySecondExtension.sol\";\nimport \"../../liquidators/registry/LiquidatorsRegistryExtension.sol\";\nimport { Unitroller } from \"../../compound/Unitroller.sol\";\nimport { BasePriceOracle } from \"../../oracles/BasePriceOracle.sol\";\n\nimport { BaseTest } from \"../config/BaseTest.t.sol\";\nimport { UpgradesBaseTest } from \"../UpgradesBaseTest.sol\";\nimport { TransparentUpgradeableProxy } from \"@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol\";\nimport { ProxyAdmin } from \"@openzeppelin/contracts/proxy/transparent/ProxyAdmin.sol\";\nimport { PoolLens } from \"../../PoolLens.sol\";\n\ncontract MockRedemptionStrategy is IRedemptionStrategy {\n function redeem(\n IERC20Upgradeable,\n uint256,\n bytes memory\n ) external returns (IERC20Upgradeable, uint256) {\n return (IERC20Upgradeable(address(0)), 1);\n }\n\n function name() public pure returns (string memory) {\n return \"MockRedemptionStrategy\";\n }\n}\n\ncontract IonicLiquidatorTest is UpgradesBaseTest {\n ILiquidator liquidator;\n address uniswapRouter;\n address swapRouter;\n IUniswapV3Quoter quoter;\n address usdcWhale;\n address wethWhale;\n address poolAddress;\n address uniV3PooForFlash;\n uint256 usdcMarketIndex;\n uint256 wethMarketIndex;\n\n AuthoritiesRegistry authRegistry;\n ILiquidatorsRegistry liquidatorsRegistry;\n\n function afterForkSetUp() internal override {\n super.afterForkSetUp();\n\n if (block.chainid == BSC_MAINNET) {\n uniswapRouter = 0x10ED43C718714eb63d5aA57B78B54704E256024E;\n } else if (block.chainid == POLYGON_MAINNET) {\n uniswapRouter = 0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff;\n swapRouter = 0xE592427A0AEce92De3Edee1F18E0157C05861564;\n quoter = IUniswapV3Quoter(0xb27308f9F90D607463bb33eA1BeBb41C27CE5AB6);\n usdcWhale = 0x625E7708f30cA75bfd92586e17077590C60eb4cD; // aave reserve\n wethWhale = 0x1eED63EfBA5f81D95bfe37d82C8E736b974F477b;\n poolAddress = 0x22A705DEC988410A959B8b17C8c23E33c121580b; // Retro stables pool\n uniV3PooForFlash = 0xA374094527e1673A86dE625aa59517c5dE346d32; // usdc-wmatic\n usdcMarketIndex = 3;\n wethMarketIndex = 5;\n } else if (block.chainid == MODE_MAINNET) {\n uniswapRouter = 0x5D61c537393cf21893BE619E36fC94cd73C77DD3; // kim router\n // uniswapRouter = 0xC9Adff795f46105E53be9bbf14221b1C9919EE25; // sup router\n // swapRouter = 0xC9Adff795f46105E53be9bbf14221b1C9919EE25; // sup router\n swapRouter = 0x5D61c537393cf21893BE619E36fC94cd73C77DD3; // kim router\n //quoter = IUniswapV3Quoter(0x7Fd569b2021850fbA53887dd07736010aCBFc787); // other sup quoter?\n quoter = IUniswapV3Quoter(0x5E6AEbab1AD525f5336Bd12E6847b851531F72ba); // sup quoter\n usdcWhale = 0x34b83A3759ba4c9F99c339604181bf6bBdED4C79; // vault\n wethWhale = 0xF4C85269240C1D447309fA602A90ac23F1CB0Dc0;\n poolAddress = 0xFB3323E24743Caf4ADD0fDCCFB268565c0685556;\n //uniV3PooForFlash = 0x293f2B2c17f8cEa4db346D87Ef5712C9dd0491EF; // kim weth-usdc pool\n uniV3PooForFlash = 0x047CF4b081ee80d2928cb2ce3F3C4964e26eB0B9; // kim usdt-usdc pool\n // uniV3PooForFlash = 0xf2e9C024F1C0B7a2a4ea11243C2D86A7b38DD72f; // sup univ2 0x34a1E3Db82f669f8cF88135422AfD80e4f70701A\n usdcMarketIndex = 1;\n wethMarketIndex = 0;\n // weth 0x4200000000000000000000000000000000000006\n // usdc 0xd988097fb8612cc24eeC14542bC03424c656005f\n }\n\n // vm.prank(ap.owner());\n // ap.setAddress(\"IUniswapV2Router02\", uniswapRouter);\n vm.prank(ap.owner());\n ap.setAddress(\"UNISWAP_V3_ROUTER\", uniswapRouter);\n\n authRegistry = AuthoritiesRegistry(ap.getAddress(\"AuthoritiesRegistry\"));\n liquidatorsRegistry = ILiquidatorsRegistry(ap.getAddress(\"LiquidatorsRegistry\"));\n liquidator = IonicLiquidator(payable(ap.getAddress(\"IonicLiquidator\")));\n }\n\n function upgradeRegistry() internal {\n DiamondBase asBase = DiamondBase(address(liquidatorsRegistry));\n address[] memory exts = asBase._listExtensions();\n LiquidatorsRegistryExtension newExt1 = new LiquidatorsRegistryExtension();\n LiquidatorsRegistrySecondExtension newExt2 = new LiquidatorsRegistrySecondExtension();\n vm.prank(SafeOwnable(address(liquidatorsRegistry)).owner());\n asBase._registerExtension(newExt1, DiamondExtension(exts[0]));\n vm.prank(SafeOwnable(address(liquidatorsRegistry)).owner());\n asBase._registerExtension(newExt2, DiamondExtension(exts[1]));\n }\n\n function testBsc() public fork(BSC_MAINNET) {\n testUpgrade();\n }\n\n function testPolygon() public fork(POLYGON_MAINNET) {\n testUpgrade();\n }\n\n function testUpgrade() internal {\n // in case these slots start to get used, please redeploy the FSL\n // with a larger storage gap to protect the owner variable of OwnableUpgradeable\n // from being overwritten by the IonicLiquidator storage\n for (uint256 i = 40; i < 51; i++) {\n address atSloti = address(uint160(uint256(vm.load(address(liquidator), bytes32(i)))));\n assertEq(\n atSloti,\n address(0),\n \"replace the FSL proxy/storage contract with a new one before the owner variable is overwritten\"\n );\n }\n }\n\n function testSpecificLiquidation() public debuggingOnly fork(MODE_MAINNET) {\n address borrower = 0x5834a3AAFA83A53822B313994Bb554d8E8c215dF;\n address debtMarketAddr = 0x71ef7EDa2Be775E5A7aa8afD02C45F059833e9d2;\n address collateralMarketAddr = 0x94812F2eEa03A49869f95e1b5868C6f3206ee3D3;\n\n liquidator = ILiquidator(payable(ap.getAddress(\"IonicUniV3Liquidator\")));\n\n ILiquidator.LiquidateToTokensWithFlashSwapVars memory vars;\n vars.borrower = borrower;\n vars.cErc20 = ICErc20(debtMarketAddr);\n vars.cTokenCollateral = ICErc20(collateralMarketAddr);\n vars.repayAmount = 0x408c7a4d7c4092;\n vars.flashSwapContract = 0x468cC91dF6F669CaE6cdCE766995Bd7874052FBc;\n vars.minProfitAmount = 0;\n vars.redemptionStrategies = new IRedemptionStrategy[](1);\n vars.strategyData = new bytes[](1);\n vars.debtFundingStrategies = new IFundsConversionStrategy[](0);\n vars.debtFundingStrategiesData = new bytes[](0);\n\n vars.redemptionStrategies[0] = IFundsConversionStrategy(0x5cA3fd2c285C4138185Ef1BdA7573D415020F3C8);\n vars.strategyData[\n 0\n ] = hex\"0000000000000000000000004200000000000000000000000000000000000006000000000000000000000000ac48fcf1049668b285f3dc72483df5ae2162f7e8\";\n\n liquidator.safeLiquidateToTokensWithFlashLoan(vars);\n }\n\n function testWithdrawalLiquidator() public debuggingOnly fork(MODE_MAINNET) {\n TransparentUpgradeableProxy proxyV3 = TransparentUpgradeableProxy(payable(ap.getAddress(\"IonicUniV3Liquidator\")));\n IonicUniV3Liquidator implV3 = new IonicUniV3Liquidator();\n IonicUniV3Liquidator liquidatorV3 = IonicUniV3Liquidator(payable(ap.getAddress(\"IonicUniV3Liquidator\")));\n ProxyAdmin proxyAdmin = ProxyAdmin(ap.getAddress(\"DefaultProxyAdmin\"));\n\n vm.startPrank(proxyAdmin.owner());\n proxyAdmin.upgrade(proxyV3, address(implV3));\n vm.stopPrank();\n\n vm.prank(0x4200000000000000000000000000000000000016);\n (bool success, ) = address(liquidatorV3).call{ value: 1 ether }(\"\");\n require(success, \"transfer of funds failed\");\n\n uint256 beforeBalance = liquidatorV3.owner().balance;\n\n vm.prank(liquidatorV3.owner());\n liquidatorV3.withdrawAll();\n\n emit log_named_uint(\"balance of liquidator\", liquidatorV3.owner().balance);\n\n assertEq(liquidatorV3.owner().balance, beforeBalance + 1 ether);\n assertEq(address(liquidatorV3).balance, 0);\n }\n\n function testLiquidateAfterUpgradeLiquidator() public debuggingOnly forkAtBlock(MODE_MAINNET, 9382006) {\n // upgrade IonicLiquidator\n TransparentUpgradeableProxy proxyV3 = TransparentUpgradeableProxy(payable(ap.getAddress(\"IonicUniV3Liquidator\")));\n IonicUniV3Liquidator implV3 = new IonicUniV3Liquidator();\n IonicUniV3Liquidator liquidatorV3 = IonicUniV3Liquidator(payable(ap.getAddress(\"IonicUniV3Liquidator\")));\n PoolLens lens = PoolLens(0x70BB19a56BfAEc65aE861E6275A90163AbDF36a6);\n\n ProxyAdmin proxyAdmin = ProxyAdmin(ap.getAddress(\"DefaultProxyAdmin\"));\n\n vm.startPrank(proxyAdmin.owner());\n proxyAdmin.upgrade(proxyV3, address(implV3));\n vm.stopPrank();\n\n vm.startPrank(0x1155b614971f16758C92c4890eD338C9e3ede6b7);\n liquidatorV3.setPoolLens(address(lens));\n liquidatorV3.setHealthFactorThreshold(1e18);\n vm.stopPrank();\n\n IonicComptroller pool = IonicComptroller(0xFB3323E24743Caf4ADD0fDCCFB268565c0685556);\n (, , uint256 liquidity, uint256 shortfall) = pool.getAccountLiquidity(0x92eA6902C5023CC632e3Fd84dE7CcA6b98FE853d);\n emit log_named_uint(\"liquidity\", liquidity);\n emit log_named_uint(\"shortfall\", shortfall);\n\n uint256 healthFactor = lens.getHealthFactor(0x92eA6902C5023CC632e3Fd84dE7CcA6b98FE853d, pool);\n emit log_named_uint(\"hf before\", healthFactor);\n\n ILiquidator.LiquidateToTokensWithFlashSwapVars memory vars = ILiquidator.LiquidateToTokensWithFlashSwapVars({\n borrower: 0x92eA6902C5023CC632e3Fd84dE7CcA6b98FE853d,\n repayAmount: 1134537086250983,\n cErc20: ICErc20(0x71ef7EDa2Be775E5A7aa8afD02C45F059833e9d2),\n cTokenCollateral: ICErc20(0x71ef7EDa2Be775E5A7aa8afD02C45F059833e9d2),\n flashSwapContract: 0x468cC91dF6F669CaE6cdCE766995Bd7874052FBc,\n minProfitAmount: 0,\n redemptionStrategies: new IRedemptionStrategy[](0),\n strategyData: new bytes[](0),\n debtFundingStrategies: new IFundsConversionStrategy[](0),\n debtFundingStrategiesData: new bytes[](0)\n });\n liquidatorV3.safeLiquidateToTokensWithFlashLoan(vars);\n\n uint256 healthFactorAfter = lens.getHealthFactor(0x92eA6902C5023CC632e3Fd84dE7CcA6b98FE853d, pool);\n emit log_named_uint(\"hf after\", healthFactorAfter);\n }\n\n function testLiquidateAfterUpgradeLiquidatorExpressRelay() public debuggingOnly forkAtBlock(MODE_MAINNET, 9382006) {\n // upgrade IonicLiquidator\n TransparentUpgradeableProxy proxyV3 = TransparentUpgradeableProxy(payable(ap.getAddress(\"IonicUniV3Liquidator\")));\n IonicUniV3Liquidator implV3 = new IonicUniV3Liquidator();\n IonicUniV3Liquidator liquidatorV3 = IonicUniV3Liquidator(payable(ap.getAddress(\"IonicUniV3Liquidator\")));\n PoolLens lens = PoolLens(0x70BB19a56BfAEc65aE861E6275A90163AbDF36a6);\n address expressRelay = makeAddr(\"expressRelay\");\n\n ProxyAdmin proxyAdmin = ProxyAdmin(ap.getAddress(\"DefaultProxyAdmin\"));\n\n vm.startPrank(proxyAdmin.owner());\n proxyAdmin.upgrade(proxyV3, address(implV3));\n vm.stopPrank();\n\n vm.startPrank(0x1155b614971f16758C92c4890eD338C9e3ede6b7);\n liquidatorV3.setPoolLens(address(lens));\n liquidatorV3.setHealthFactorThreshold(95e16);\n liquidatorV3.setExpressRelay(expressRelay);\n vm.stopPrank();\n\n IonicComptroller pool = IonicComptroller(0xFB3323E24743Caf4ADD0fDCCFB268565c0685556);\n (, , uint256 liquidity, uint256 shortfall) = pool.getAccountLiquidity(0x92eA6902C5023CC632e3Fd84dE7CcA6b98FE853d);\n emit log_named_uint(\"liquidity\", liquidity);\n emit log_named_uint(\"shortfall\", shortfall);\n\n uint256 healthFactor = lens.getHealthFactor(0x92eA6902C5023CC632e3Fd84dE7CcA6b98FE853d, pool);\n emit log_named_uint(\"hf before\", healthFactor);\n\n address borrower = address(0x92eA6902C5023CC632e3Fd84dE7CcA6b98FE853d);\n\n ILiquidator.LiquidateToTokensWithFlashSwapVars memory vars = ILiquidator.LiquidateToTokensWithFlashSwapVars({\n borrower: borrower,\n repayAmount: 1134537086250983,\n cErc20: ICErc20(0x71ef7EDa2Be775E5A7aa8afD02C45F059833e9d2),\n cTokenCollateral: ICErc20(0x71ef7EDa2Be775E5A7aa8afD02C45F059833e9d2),\n flashSwapContract: 0x468cC91dF6F669CaE6cdCE766995Bd7874052FBc,\n minProfitAmount: 0,\n redemptionStrategies: new IRedemptionStrategy[](0),\n strategyData: new bytes[](0),\n debtFundingStrategies: new IFundsConversionStrategy[](0),\n debtFundingStrategiesData: new bytes[](0)\n });\n\n vm.mockCall(\n expressRelay, \n abi.encodeWithSelector(bytes4(keccak256(\"isPermissioned(address,bytes)\")), address(liquidatorV3), abi.encode(borrower)),\n abi.encode(false) \n );\n vm.expectRevert(\"invalid liquidation\");\n liquidatorV3.safeLiquidateToTokensWithFlashLoan(vars);\n\n vm.mockCall(\n expressRelay, \n abi.encodeWithSelector(bytes4(keccak256(\"isPermissioned(address,bytes)\")), address(liquidatorV3), abi.encode(borrower)),\n abi.encode(true) \n );\n liquidatorV3.safeLiquidateToTokensWithFlashLoan(vars);\n\n uint256 healthFactorAfter = lens.getHealthFactor(0x92eA6902C5023CC632e3Fd84dE7CcA6b98FE853d, pool);\n emit log_named_uint(\"hf after\", healthFactorAfter);\n }\n\n // TODO test with marginal shortfall for liquidation penalty errors\n function _testLiquidatorLiquidate(address contractForFlashSwap) internal {\n IonicComptroller pool = IonicComptroller(poolAddress);\n // _upgradePoolWithExtension(Unitroller(payable(poolAddress)));\n //upgradeRegistry();\n\n ICErc20[] memory markets = pool.getAllMarkets();\n\n ICErc20 usdcMarket = markets[usdcMarketIndex];\n IERC20Upgradeable usdc = IERC20Upgradeable(usdcMarket.underlying());\n ICErc20 wethMarket = markets[wethMarketIndex];\n IERC20Upgradeable weth = IERC20Upgradeable(wethMarket.underlying());\n {\n emit log_named_address(\"usdc market\", address(usdcMarket));\n emit log_named_address(\"weth market\", address(wethMarket));\n emit log_named_address(\"usdc underlying\", usdcMarket.underlying());\n emit log_named_address(\"weth underlying\", wethMarket.underlying());\n vm.prank(pool.admin());\n pool._setBorrowCapForCollateral(address(usdcMarket), address(wethMarket), 1e36);\n }\n\n {\n vm.prank(pool.admin());\n pool._borrowCapWhitelist(0x2BE717340023C9e14C1Bb12cb3ecBcfd3c3fB038, address(this), true);\n }\n\n {\n vm.prank(wethWhale);\n weth.transfer(address(this), 0.1e18);\n\n weth.approve(address(wethMarket), 1e36);\n require(wethMarket.mint(0.1e18) == 0, \"mint weth failed\");\n pool.enterMarkets(asArray(address(usdcMarket), address(wethMarket)));\n }\n\n {\n vm.startPrank(usdcWhale);\n usdc.approve(address(usdcMarket), 2e36);\n require(usdcMarket.mint(70e6) == 0, \"mint usdc failed\");\n vm.stopPrank();\n }\n\n {\n require(usdcMarket.borrow(50e6) == 0, \"borrow usdc failed\");\n\n // the collateral prices change\n BasePriceOracle mpo = pool.oracle();\n uint256 priceCollateral = mpo.getUnderlyingPrice(wethMarket);\n vm.mockCall(\n address(mpo),\n abi.encodeWithSelector(mpo.getUnderlyingPrice.selector, wethMarket),\n abi.encode(priceCollateral / 10)\n );\n }\n\n (IRedemptionStrategy[] memory strategies, bytes[] memory strategiesData) = liquidatorsRegistry\n .getRedemptionStrategies(weth, usdc);\n\n uint256 seizedAmount = liquidator.safeLiquidateToTokensWithFlashLoan(\n ILiquidator.LiquidateToTokensWithFlashSwapVars({\n borrower: address(this),\n repayAmount: 10e6,\n cErc20: usdcMarket,\n cTokenCollateral: wethMarket,\n flashSwapContract: contractForFlashSwap,\n minProfitAmount: 6,\n redemptionStrategies: strategies,\n strategyData: strategiesData,\n debtFundingStrategies: new IFundsConversionStrategy[](0),\n debtFundingStrategiesData: new bytes[](0)\n })\n );\n\n emit log_named_uint(\"seized amount\", seizedAmount);\n require(seizedAmount > 0, \"didn't seize any assets\");\n }\n}\n" + }, + "contracts/test/liquidators/UniswapV3LiquidatorFunderTest.t.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { MasterPriceOracle } from \"../../oracles/MasterPriceOracle.sol\";\nimport { UniswapV3LiquidatorFunder } from \"../../liquidators/UniswapV3LiquidatorFunder.sol\";\nimport { IonicLiquidator } from \"../../IonicLiquidator.sol\";\nimport { IUniswapV2Pair } from \"../../external/uniswap/IUniswapV2Pair.sol\";\nimport { IUniswapV2Factory } from \"../../external/uniswap/IUniswapV2Factory.sol\";\nimport { IUniswapV3Factory } from \"../../external/uniswap/IUniswapV3Factory.sol\";\nimport { Quoter } from \"../../external/uniswap/quoter/Quoter.sol\";\nimport { IUniswapV3Pool } from \"../../external/uniswap/IUniswapV3Pool.sol\";\nimport { ISwapRouter } from \"../../external/uniswap/ISwapRouter.sol\";\nimport { IComptroller } from \"../../external/compound/IComptroller.sol\";\nimport { IUniswapV2Router02 } from \"../../external/uniswap/IUniswapV2Router02.sol\";\nimport { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\nimport { IRedemptionStrategy } from \"../../liquidators/IRedemptionStrategy.sol\";\nimport { IFundsConversionStrategy } from \"../../liquidators/IFundsConversionStrategy.sol\";\n\nimport { BaseTest } from \"../config/BaseTest.t.sol\";\n\ncontract UniswapV3LiquidatorFunderTest is BaseTest {\n UniswapV3LiquidatorFunder private uniswapv3Liquidator;\n\n IERC20Upgradeable parToken;\n IERC20Upgradeable usdcToken;\n address univ3SwapRouter;\n uint256 poolFee;\n Quoter quoter;\n MasterPriceOracle mpo;\n\n function afterForkSetUp() internal override {\n mpo = MasterPriceOracle(ap.getAddress(\"MasterPriceOracle\"));\n\n if (block.chainid == POLYGON_MAINNET) {\n quoter = new Quoter(0x1F98431c8aD98523631AE4a59f267346ea31F984);\n univ3SwapRouter = 0xE592427A0AEce92De3Edee1F18E0157C05861564;\n parToken = IERC20Upgradeable(0xE2Aa7db6dA1dAE97C5f5C6914d285fBfCC32A128); // PAR, 18 decimals\n usdcToken = IERC20Upgradeable(0x2791Bca1f2de4661ED88A30C99A7a9449Aa84174); // USDC, 6 decimals\n poolFee = 500;\n }\n uniswapv3Liquidator = new UniswapV3LiquidatorFunder();\n }\n\n function testUniV3ParUsdcRedeem() public fork(POLYGON_MAINNET) {\n uint256 parInputAmount = 10000e18;\n address parTokenWhale = 0xBA12222222228d8Ba445958a75a0704d566BF2C8; // Balancer V2\n\n vm.prank(parTokenWhale);\n parToken.transfer(address(uniswapv3Liquidator), parInputAmount);\n\n bytes memory data = abi.encode(parToken, usdcToken, poolFee, ISwapRouter(univ3SwapRouter), quoter);\n (IERC20Upgradeable outputToken, uint256 outputAmount) = uniswapv3Liquidator.redeem(parToken, parInputAmount, data);\n\n uint256 inputValue = (parInputAmount * mpo.price(address(parToken))) / 1e18;\n uint256 outputValue = (outputAmount * mpo.price(address(usdcToken))) / 1e6;\n\n assertEq(address(outputToken), address(usdcToken), \"!out tok\");\n assertApproxEqRel(inputValue, outputValue, 1e16, \"!out amount\");\n }\n}\n" + }, + "contracts/test/liquidators/UniswapV3LiquidatorTest.t.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >=0.8.0;\n\nimport { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\nimport { IonicUniV3Liquidator, IUniswapV3Pool, ILiquidator } from \"../../IonicUniV3Liquidator.sol\";\nimport \"../../external/uniswap/quoter/interfaces/IUniswapV3Quoter.sol\";\nimport { IRedemptionStrategy } from \"../../liquidators/IRedemptionStrategy.sol\";\nimport { ILiquidatorsRegistry } from \"../../liquidators/registry/ILiquidatorsRegistry.sol\";\nimport { IUniswapV2Router02 } from \"../../external/uniswap/IUniswapV2Router02.sol\";\nimport { IUniswapV3Factory } from \"../../external/uniswap/IUniswapV3Factory.sol\";\nimport { UniswapV2LiquidatorFunder } from \"../../liquidators/UniswapV2LiquidatorFunder.sol\";\nimport { UniswapV3LiquidatorFunder } from \"../../liquidators/UniswapV3LiquidatorFunder.sol\";\nimport { KimUniV2Liquidator } from \"../../liquidators/KimUniV2Liquidator.sol\";\n\nimport { IFundsConversionStrategy } from \"../../liquidators/IFundsConversionStrategy.sol\";\nimport { ICErc20 } from \"../../compound/CTokenInterfaces.sol\";\nimport { IonicComptroller } from \"../../compound/ComptrollerInterface.sol\";\nimport { AuthoritiesRegistry } from \"../../ionic/AuthoritiesRegistry.sol\";\nimport { PoolRolesAuthority } from \"../../ionic/PoolRolesAuthority.sol\";\n\nimport { BaseTest } from \"../config/BaseTest.t.sol\";\nimport \"./IonicLiquidatorTest.sol\";\n\ncontract UniswapV3LiquidatorTest is IonicLiquidatorTest {\n function testPolygonUniV3LiquidatorLiquidate() public fork(POLYGON_MAINNET) {\n IonicUniV3Liquidator _liquidator = new IonicUniV3Liquidator();\n _liquidator.initialize(ap.getAddress(\"wtoken\"), address(quoter));\n liquidator = _liquidator;\n _testLiquidatorLiquidate(uniV3PooForFlash);\n }\n\n function testModeUniV3LiquidatorLiquidate() public debuggingOnly fork(MODE_MAINNET) {\n IonicUniV3Liquidator _liquidator = new IonicUniV3Liquidator();\n _liquidator.initialize(ap.getAddress(\"wtoken\"), address(quoter));\n liquidator = _liquidator;\n\n IonicComptroller pool = IonicComptroller(poolAddress);\n {\n ICErc20[] memory markets = pool.getAllMarkets();\n\n ICErc20 usdcMarket = markets[usdcMarketIndex];\n IERC20Upgradeable usdc = IERC20Upgradeable(usdcMarket.underlying());\n ICErc20 wethMarket = markets[wethMarketIndex];\n IERC20Upgradeable weth = IERC20Upgradeable(wethMarket.underlying());\n {\n emit log_named_address(\"usdc market\", address(usdcMarket));\n emit log_named_address(\"weth market\", address(wethMarket));\n emit log_named_address(\"usdc underlying\", usdcMarket.underlying());\n emit log_named_address(\"weth underlying\", wethMarket.underlying());\n vm.startPrank(liquidatorsRegistry.owner());\n IRedemptionStrategy strategy = new UniswapV3LiquidatorFunder();\n liquidatorsRegistry._setRedemptionStrategy(strategy, weth, usdc);\n vm.stopPrank();\n vm.prank(OwnableUpgradeable(address(liquidator)).owner());\n liquidator._whitelistRedemptionStrategy(strategy, true);\n }\n }\n\n _testLiquidatorLiquidate(uniV3PooForFlash);\n }\n\n function testModeKimUniV2Liquidator() public fork(MODE_MAINNET) {\n IonicLiquidator _liquidator = new IonicLiquidator();\n _liquidator.initialize(ap.getAddress(\"wtoken\"), ap.getAddress(\"IUniswapV2Router02\"), 30);\n liquidator = _liquidator;\n liquidator.setPoolLens(0x70BB19a56BfAEc65aE861E6275A90163AbDF36a6);\n liquidator.setHealthFactorThreshold(1e18);\n\n IonicComptroller pool = IonicComptroller(poolAddress);\n {\n ICErc20[] memory markets = pool.getAllMarkets();\n\n ICErc20 usdcMarket = markets[usdcMarketIndex];\n IERC20Upgradeable usdc = IERC20Upgradeable(usdcMarket.underlying());\n ICErc20 wethMarket = markets[wethMarketIndex];\n IERC20Upgradeable weth = IERC20Upgradeable(wethMarket.underlying());\n {\n emit log_named_address(\"usdc market\", address(usdcMarket));\n emit log_named_address(\"weth market\", address(wethMarket));\n emit log_named_address(\"usdc underlying\", usdcMarket.underlying());\n emit log_named_address(\"weth underlying\", wethMarket.underlying());\n vm.startPrank(liquidatorsRegistry.owner());\n IRedemptionStrategy strategy = KimUniV2Liquidator(0x6aC17D406a820fa464fFdc0940FCa7E60b3b36B7);\n liquidatorsRegistry._setRedemptionStrategy(strategy, weth, usdc);\n vm.stopPrank();\n liquidator._whitelistRedemptionStrategy(strategy, true);\n }\n }\n\n _testLiquidatorLiquidate(uniV3PooForFlash);\n }\n\n function testUniV3PoolForFee() public debuggingOnly fork(MODE_MAINNET) {\n address wethAddr = 0x4200000000000000000000000000000000000006;\n address usdcAddr = 0xd988097fb8612cc24eeC14542bC03424c656005f;\n IERC20Upgradeable usdc = IERC20Upgradeable(usdcAddr);\n IERC20Upgradeable weth = IERC20Upgradeable(wethAddr);\n\n IUniswapV2Router02 kimRouter = IUniswapV2Router02(0x5D61c537393cf21893BE619E36fC94cd73C77DD3);\n address factoryAddress;\n //factory = kimRouter.factory();\n factoryAddress = 0xC33Ce0058004d44E7e1F366E5797A578fDF38584;\n IUniswapV3Factory factory = IUniswapV3Factory(factoryAddress);\n address pool;\n\n uint256 feeConfig = liquidatorsRegistry.uniswapV3Fees(usdc, weth);\n emit log_named_uint(\"feeConfig\", feeConfig);\n\n if (feeConfig == 0) {\n pool = factory.getPool(wethAddr, usdcAddr, uint24(feeConfig));\n emit log_named_address(\"Pool at fee 0\", pool);\n }\n\n pool = factory.getPool(wethAddr, usdcAddr, 500);\n emit log_named_address(\"Pool at fee 500\", pool);\n }\n}\n" + }, + "contracts/test/LoopTest.t.sol": { + "content": "// // SPDX-License-Identifier: UNLICENSED\n// pragma solidity >=0.8.0;\n\n// import \"forge-std/Test.sol\";\n\n// import { LeveredPosition } from \"../ionic/levered/LeveredPosition.sol\";\n// import { ILeveredPositionFactory } from \"../ionic/levered/ILeveredPositionFactory.sol\";\n// import { ICErc20 } from \"../compound/CTokenInterfaces.sol\";\n// import { ILiquidatorsRegistry } from \"../liquidators/registry/ILiquidatorsRegistry.sol\";\n// import { IRedemptionStrategy } from \"../liquidators/IRedemptionStrategy.sol\";\n// import { IERC20Upgradeable } from \"openzeppelin-contracts-upgradeable/contracts/token/ERC20/IERC20Upgradeable.sol\";\n\n// contract ezEthWethLeveredPositionTest is Test {\n// address me = 0x1155b614971f16758C92c4890eD338C9e3ede6b7;\n\n// function setUp() public {}\n\n// function test_ezEthWeth() public {\n// vm.createSelectFork(vm.rpcUrl(\"base_archive\"));\n// vm.rollFork(19713666);\n\n// ILeveredPositionFactory factory = ILeveredPositionFactory(0x0Bd42a5226db7FCEb9D3e50539778A15C3665da8);\n// ICErc20 collateralMarket = ICErc20(0x014e08F05ac11BB532BE62774A4C548368f59779);\n// ICErc20 stableMarket = ICErc20(0xa900A17a49Bc4D442bA7F72c39FA2108865671f0);\n// uint256 depositAmount = 48672877617700471281;\n\n// IERC20Upgradeable collateralToken = IERC20Upgradeable(collateralMarket.underlying());\n// emit log_named_uint(\"collateral balance\", collateralToken.balanceOf(me));\n\n// vm.startPrank(me);\n// collateralToken.approve(address(factory), depositAmount);\n// LeveredPosition position = factory.createAndFundPositionAtRatio(\n// collateralMarket,\n// stableMarket,\n// collateralToken,\n// depositAmount,\n// 3 ether\n// );\n// vm.stopPrank();\n\n// uint256 _maxRatio;\n// uint256 _minRatio;\n\n// _maxRatio = position.getMaxLeverageRatio();\n// emit log_named_uint(\"max ratio\", _maxRatio);\n// _minRatio = position.getMinLeverageRatio();\n// emit log_named_uint(\"min ratio\", _minRatio);\n// assertGt(_maxRatio, _minRatio, \"max ratio <= min ratio\");\n\n// uint256 currentRatio = position.getCurrentLeverageRatio();\n// emit log_named_uint(\"current ratio\", currentRatio);\n// }\n// }\n" + }, + "contracts/test/UpgradesBaseTest.sol": { + "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity ^0.8.0;\n\nimport { FeeDistributor } from \"../FeeDistributor.sol\";\nimport { Comptroller } from \"../compound/Comptroller.sol\";\nimport { DiamondExtension } from \"../ionic/DiamondExtension.sol\";\nimport { ComptrollerFirstExtension } from \"../compound/ComptrollerFirstExtension.sol\";\nimport { CTokenFirstExtension } from \"../compound/CTokenFirstExtension.sol\";\nimport { Unitroller } from \"../compound/Unitroller.sol\";\nimport { CErc20Delegate } from \"../compound/CErc20Delegate.sol\";\nimport { CErc20PluginDelegate } from \"../compound/CErc20PluginDelegate.sol\";\nimport { CErc20PluginRewardsDelegate } from \"../compound/CErc20PluginRewardsDelegate.sol\";\nimport { ICErc20 } from \"../compound/CTokenInterfaces.sol\";\n\nimport { BaseTest } from \"./config/BaseTest.t.sol\";\n\nimport { TransparentUpgradeableProxy } from \"@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol\";\n\nabstract contract UpgradesBaseTest is BaseTest {\n FeeDistributor internal ffd;\n ComptrollerFirstExtension internal poolExt;\n CTokenFirstExtension internal marketExt;\n\n function afterForkSetUp() internal virtual override {\n ffd = FeeDistributor(payable(ap.getAddress(\"FeeDistributor\")));\n poolExt = new ComptrollerFirstExtension();\n marketExt = new CTokenFirstExtension();\n }\n\n function _upgradePoolWithExtension(Unitroller asUnitroller) internal {\n address oldComptrollerImplementation = asUnitroller.comptrollerImplementation();\n\n // instantiate the new implementation\n Comptroller newComptrollerImplementation = new Comptroller();\n vm.startPrank(ffd.owner());\n address comptrollerImplementationAddress = address(newComptrollerImplementation);\n ffd._setLatestComptrollerImplementation(address(0), comptrollerImplementationAddress);\n // add the extension to the auto upgrade config\n DiamondExtension[] memory extensions = new DiamondExtension[](2);\n extensions[0] = poolExt;\n extensions[1] = newComptrollerImplementation;\n ffd._setComptrollerExtensions(comptrollerImplementationAddress, extensions);\n vm.stopPrank();\n\n // upgrade to the new comptroller\n vm.startPrank(asUnitroller.admin());\n asUnitroller._registerExtension(\n DiamondExtension(comptrollerImplementationAddress),\n DiamondExtension(asUnitroller.comptrollerImplementation())\n );\n asUnitroller._upgrade();\n vm.stopPrank();\n }\n\n function _upgradeMarketWithExtension(ICErc20 market) internal {\n address implBefore = market.implementation();\n\n // instantiate the new implementation\n CErc20Delegate newImpl;\n bytes memory becomeImplData = \"\";\n if (compareStrings(\"CErc20Delegate\", market.contractType())) {\n newImpl = new CErc20Delegate();\n } else if (compareStrings(\"CErc20PluginDelegate\", market.contractType())) {\n newImpl = new CErc20PluginDelegate();\n becomeImplData = abi.encode(address(0));\n } else {\n newImpl = new CErc20PluginRewardsDelegate();\n becomeImplData = abi.encode(address(0));\n }\n\n // set the new delegate as the latest\n ffd._setLatestCErc20Delegate(newImpl.delegateType(), address(newImpl), abi.encode(address(0)));\n\n // add the extension to the auto upgrade config\n DiamondExtension[] memory cErc20DelegateExtensions = new DiamondExtension[](2);\n cErc20DelegateExtensions[0] = marketExt;\n cErc20DelegateExtensions[1] = newImpl;\n vm.prank(ffd.owner());\n ffd._setCErc20DelegateExtensions(address(newImpl), cErc20DelegateExtensions);\n\n // upgrade to the new delegate\n vm.prank(address(ffd));\n market._setImplementationSafe(address(newImpl), becomeImplData);\n }\n}\n" + }, + "contracts/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/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/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" + }, + "ds-test/test.sol": { + "content": "// SPDX-License-Identifier: GPL-3.0-or-later\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see .\n\npragma solidity >=0.5.0;\n\ncontract DSTest {\n event log (string);\n event logs (bytes);\n\n event log_address (address);\n event log_bytes32 (bytes32);\n event log_int (int);\n event log_uint (uint);\n event log_bytes (bytes);\n event log_string (string);\n\n event log_named_address (string key, address val);\n event log_named_bytes32 (string key, bytes32 val);\n event log_named_decimal_int (string key, int val, uint decimals);\n event log_named_decimal_uint (string key, uint val, uint decimals);\n event log_named_int (string key, int val);\n event log_named_uint (string key, uint val);\n event log_named_bytes (string key, bytes val);\n event log_named_string (string key, string val);\n\n bool public IS_TEST = true;\n bool private _failed;\n\n address constant HEVM_ADDRESS =\n address(bytes20(uint160(uint256(keccak256('hevm cheat code')))));\n\n modifier mayRevert() { _; }\n modifier testopts(string memory) { _; }\n\n function failed() public returns (bool) {\n if (_failed) {\n return _failed;\n } else {\n bool globalFailed = false;\n if (hasHEVMContext()) {\n (, bytes memory retdata) = HEVM_ADDRESS.call(\n abi.encodePacked(\n bytes4(keccak256(\"load(address,bytes32)\")),\n abi.encode(HEVM_ADDRESS, bytes32(\"failed\"))\n )\n );\n globalFailed = abi.decode(retdata, (bool));\n }\n return globalFailed;\n }\n }\n\n function fail() internal virtual {\n if (hasHEVMContext()) {\n (bool status, ) = HEVM_ADDRESS.call(\n abi.encodePacked(\n bytes4(keccak256(\"store(address,bytes32,bytes32)\")),\n abi.encode(HEVM_ADDRESS, bytes32(\"failed\"), bytes32(uint256(0x01)))\n )\n );\n status; // Silence compiler warnings\n }\n _failed = true;\n }\n\n function hasHEVMContext() internal view returns (bool) {\n uint256 hevmCodeSize = 0;\n assembly {\n hevmCodeSize := extcodesize(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D)\n }\n return hevmCodeSize > 0;\n }\n\n modifier logs_gas() {\n uint startGas = gasleft();\n _;\n uint endGas = gasleft();\n emit log_named_uint(\"gas\", startGas - endGas);\n }\n\n function assertTrue(bool condition) internal {\n if (!condition) {\n emit log(\"Error: Assertion Failed\");\n fail();\n }\n }\n\n function assertTrue(bool condition, string memory err) internal {\n if (!condition) {\n emit log_named_string(\"Error\", err);\n assertTrue(condition);\n }\n }\n\n function assertEq(address a, address b) internal {\n if (a != b) {\n emit log(\"Error: a == b not satisfied [address]\");\n emit log_named_address(\" Left\", a);\n emit log_named_address(\" Right\", b);\n fail();\n }\n }\n function assertEq(address a, address b, string memory err) internal {\n if (a != b) {\n emit log_named_string (\"Error\", err);\n assertEq(a, b);\n }\n }\n\n function assertEq(bytes32 a, bytes32 b) internal {\n if (a != b) {\n emit log(\"Error: a == b not satisfied [bytes32]\");\n emit log_named_bytes32(\" Left\", a);\n emit log_named_bytes32(\" Right\", b);\n fail();\n }\n }\n function assertEq(bytes32 a, bytes32 b, string memory err) internal {\n if (a != b) {\n emit log_named_string (\"Error\", err);\n assertEq(a, b);\n }\n }\n function assertEq32(bytes32 a, bytes32 b) internal {\n assertEq(a, b);\n }\n function assertEq32(bytes32 a, bytes32 b, string memory err) internal {\n assertEq(a, b, err);\n }\n\n function assertEq(int a, int b) internal {\n if (a != b) {\n emit log(\"Error: a == b not satisfied [int]\");\n emit log_named_int(\" Left\", a);\n emit log_named_int(\" Right\", b);\n fail();\n }\n }\n function assertEq(int a, int b, string memory err) internal {\n if (a != b) {\n emit log_named_string(\"Error\", err);\n assertEq(a, b);\n }\n }\n function assertEq(uint a, uint b) internal {\n if (a != b) {\n emit log(\"Error: a == b not satisfied [uint]\");\n emit log_named_uint(\" Left\", a);\n emit log_named_uint(\" Right\", b);\n fail();\n }\n }\n function assertEq(uint a, uint b, string memory err) internal {\n if (a != b) {\n emit log_named_string(\"Error\", err);\n assertEq(a, b);\n }\n }\n function assertEqDecimal(int a, int b, uint decimals) internal {\n if (a != b) {\n emit log(\"Error: a == b not satisfied [decimal int]\");\n emit log_named_decimal_int(\" Left\", a, decimals);\n emit log_named_decimal_int(\" Right\", b, decimals);\n fail();\n }\n }\n function assertEqDecimal(int a, int b, uint decimals, string memory err) internal {\n if (a != b) {\n emit log_named_string(\"Error\", err);\n assertEqDecimal(a, b, decimals);\n }\n }\n function assertEqDecimal(uint a, uint b, uint decimals) internal {\n if (a != b) {\n emit log(\"Error: a == b not satisfied [decimal uint]\");\n emit log_named_decimal_uint(\" Left\", a, decimals);\n emit log_named_decimal_uint(\" Right\", b, decimals);\n fail();\n }\n }\n function assertEqDecimal(uint a, uint b, uint decimals, string memory err) internal {\n if (a != b) {\n emit log_named_string(\"Error\", err);\n assertEqDecimal(a, b, decimals);\n }\n }\n\n function assertGt(uint a, uint b) internal {\n if (a <= b) {\n emit log(\"Error: a > b not satisfied [uint]\");\n emit log_named_uint(\" Value a\", a);\n emit log_named_uint(\" Value b\", b);\n fail();\n }\n }\n function assertGt(uint a, uint b, string memory err) internal {\n if (a <= b) {\n emit log_named_string(\"Error\", err);\n assertGt(a, b);\n }\n }\n function assertGt(int a, int b) internal {\n if (a <= b) {\n emit log(\"Error: a > b not satisfied [int]\");\n emit log_named_int(\" Value a\", a);\n emit log_named_int(\" Value b\", b);\n fail();\n }\n }\n function assertGt(int a, int b, string memory err) internal {\n if (a <= b) {\n emit log_named_string(\"Error\", err);\n assertGt(a, b);\n }\n }\n function assertGtDecimal(int a, int b, uint decimals) internal {\n if (a <= b) {\n emit log(\"Error: a > b not satisfied [decimal int]\");\n emit log_named_decimal_int(\" Value a\", a, decimals);\n emit log_named_decimal_int(\" Value b\", b, decimals);\n fail();\n }\n }\n function assertGtDecimal(int a, int b, uint decimals, string memory err) internal {\n if (a <= b) {\n emit log_named_string(\"Error\", err);\n assertGtDecimal(a, b, decimals);\n }\n }\n function assertGtDecimal(uint a, uint b, uint decimals) internal {\n if (a <= b) {\n emit log(\"Error: a > b not satisfied [decimal uint]\");\n emit log_named_decimal_uint(\" Value a\", a, decimals);\n emit log_named_decimal_uint(\" Value b\", b, decimals);\n fail();\n }\n }\n function assertGtDecimal(uint a, uint b, uint decimals, string memory err) internal {\n if (a <= b) {\n emit log_named_string(\"Error\", err);\n assertGtDecimal(a, b, decimals);\n }\n }\n\n function assertGe(uint a, uint b) internal {\n if (a < b) {\n emit log(\"Error: a >= b not satisfied [uint]\");\n emit log_named_uint(\" Value a\", a);\n emit log_named_uint(\" Value b\", b);\n fail();\n }\n }\n function assertGe(uint a, uint b, string memory err) internal {\n if (a < b) {\n emit log_named_string(\"Error\", err);\n assertGe(a, b);\n }\n }\n function assertGe(int a, int b) internal {\n if (a < b) {\n emit log(\"Error: a >= b not satisfied [int]\");\n emit log_named_int(\" Value a\", a);\n emit log_named_int(\" Value b\", b);\n fail();\n }\n }\n function assertGe(int a, int b, string memory err) internal {\n if (a < b) {\n emit log_named_string(\"Error\", err);\n assertGe(a, b);\n }\n }\n function assertGeDecimal(int a, int b, uint decimals) internal {\n if (a < b) {\n emit log(\"Error: a >= b not satisfied [decimal int]\");\n emit log_named_decimal_int(\" Value a\", a, decimals);\n emit log_named_decimal_int(\" Value b\", b, decimals);\n fail();\n }\n }\n function assertGeDecimal(int a, int b, uint decimals, string memory err) internal {\n if (a < b) {\n emit log_named_string(\"Error\", err);\n assertGeDecimal(a, b, decimals);\n }\n }\n function assertGeDecimal(uint a, uint b, uint decimals) internal {\n if (a < b) {\n emit log(\"Error: a >= b not satisfied [decimal uint]\");\n emit log_named_decimal_uint(\" Value a\", a, decimals);\n emit log_named_decimal_uint(\" Value b\", b, decimals);\n fail();\n }\n }\n function assertGeDecimal(uint a, uint b, uint decimals, string memory err) internal {\n if (a < b) {\n emit log_named_string(\"Error\", err);\n assertGeDecimal(a, b, decimals);\n }\n }\n\n function assertLt(uint a, uint b) internal {\n if (a >= b) {\n emit log(\"Error: a < b not satisfied [uint]\");\n emit log_named_uint(\" Value a\", a);\n emit log_named_uint(\" Value b\", b);\n fail();\n }\n }\n function assertLt(uint a, uint b, string memory err) internal {\n if (a >= b) {\n emit log_named_string(\"Error\", err);\n assertLt(a, b);\n }\n }\n function assertLt(int a, int b) internal {\n if (a >= b) {\n emit log(\"Error: a < b not satisfied [int]\");\n emit log_named_int(\" Value a\", a);\n emit log_named_int(\" Value b\", b);\n fail();\n }\n }\n function assertLt(int a, int b, string memory err) internal {\n if (a >= b) {\n emit log_named_string(\"Error\", err);\n assertLt(a, b);\n }\n }\n function assertLtDecimal(int a, int b, uint decimals) internal {\n if (a >= b) {\n emit log(\"Error: a < b not satisfied [decimal int]\");\n emit log_named_decimal_int(\" Value a\", a, decimals);\n emit log_named_decimal_int(\" Value b\", b, decimals);\n fail();\n }\n }\n function assertLtDecimal(int a, int b, uint decimals, string memory err) internal {\n if (a >= b) {\n emit log_named_string(\"Error\", err);\n assertLtDecimal(a, b, decimals);\n }\n }\n function assertLtDecimal(uint a, uint b, uint decimals) internal {\n if (a >= b) {\n emit log(\"Error: a < b not satisfied [decimal uint]\");\n emit log_named_decimal_uint(\" Value a\", a, decimals);\n emit log_named_decimal_uint(\" Value b\", b, decimals);\n fail();\n }\n }\n function assertLtDecimal(uint a, uint b, uint decimals, string memory err) internal {\n if (a >= b) {\n emit log_named_string(\"Error\", err);\n assertLtDecimal(a, b, decimals);\n }\n }\n\n function assertLe(uint a, uint b) internal {\n if (a > b) {\n emit log(\"Error: a <= b not satisfied [uint]\");\n emit log_named_uint(\" Value a\", a);\n emit log_named_uint(\" Value b\", b);\n fail();\n }\n }\n function assertLe(uint a, uint b, string memory err) internal {\n if (a > b) {\n emit log_named_string(\"Error\", err);\n assertLe(a, b);\n }\n }\n function assertLe(int a, int b) internal {\n if (a > b) {\n emit log(\"Error: a <= b not satisfied [int]\");\n emit log_named_int(\" Value a\", a);\n emit log_named_int(\" Value b\", b);\n fail();\n }\n }\n function assertLe(int a, int b, string memory err) internal {\n if (a > b) {\n emit log_named_string(\"Error\", err);\n assertLe(a, b);\n }\n }\n function assertLeDecimal(int a, int b, uint decimals) internal {\n if (a > b) {\n emit log(\"Error: a <= b not satisfied [decimal int]\");\n emit log_named_decimal_int(\" Value a\", a, decimals);\n emit log_named_decimal_int(\" Value b\", b, decimals);\n fail();\n }\n }\n function assertLeDecimal(int a, int b, uint decimals, string memory err) internal {\n if (a > b) {\n emit log_named_string(\"Error\", err);\n assertLeDecimal(a, b, decimals);\n }\n }\n function assertLeDecimal(uint a, uint b, uint decimals) internal {\n if (a > b) {\n emit log(\"Error: a <= b not satisfied [decimal uint]\");\n emit log_named_decimal_uint(\" Value a\", a, decimals);\n emit log_named_decimal_uint(\" Value b\", b, decimals);\n fail();\n }\n }\n function assertLeDecimal(uint a, uint b, uint decimals, string memory err) internal {\n if (a > b) {\n emit log_named_string(\"Error\", err);\n assertLeDecimal(a, b, decimals);\n }\n }\n\n function assertEq(string memory a, string memory b) internal {\n if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) {\n emit log(\"Error: a == b not satisfied [string]\");\n emit log_named_string(\" Left\", a);\n emit log_named_string(\" Right\", b);\n fail();\n }\n }\n function assertEq(string memory a, string memory b, string memory err) internal {\n if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) {\n emit log_named_string(\"Error\", err);\n assertEq(a, b);\n }\n }\n\n function checkEq0(bytes memory a, bytes memory b) internal pure returns (bool ok) {\n ok = true;\n if (a.length == b.length) {\n for (uint i = 0; i < a.length; i++) {\n if (a[i] != b[i]) {\n ok = false;\n }\n }\n } else {\n ok = false;\n }\n }\n function assertEq0(bytes memory a, bytes memory b) internal {\n if (!checkEq0(a, b)) {\n emit log(\"Error: a == b not satisfied [bytes]\");\n emit log_named_bytes(\" Left\", a);\n emit log_named_bytes(\" Right\", b);\n fail();\n }\n }\n function assertEq0(bytes memory a, bytes memory b, string memory err) internal {\n if (!checkEq0(a, b)) {\n emit log_named_string(\"Error\", err);\n assertEq0(a, b);\n }\n }\n}\n" + }, + "forge-std/Base.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\nimport {StdStorage} from \"./StdStorage.sol\";\nimport {Vm, VmSafe} from \"./Vm.sol\";\n\nabstract contract CommonBase {\n // Cheat code address, 0x7109709ECfa91a80626fF3989D68f67F5b1DD12D.\n address internal constant VM_ADDRESS = address(uint160(uint256(keccak256(\"hevm cheat code\"))));\n // console.sol and console2.sol work by executing a staticcall to this address.\n address internal constant CONSOLE = 0x000000000000000000636F6e736F6c652e6c6f67;\n // Default address for tx.origin and msg.sender, 0x1804c8AB1F12E6bbf3894d4083f33e07309d1f38.\n address internal constant DEFAULT_SENDER = address(uint160(uint256(keccak256(\"foundry default caller\"))));\n // Address of the test contract, deployed by the DEFAULT_SENDER.\n address internal constant DEFAULT_TEST_CONTRACT = 0x5615dEB798BB3E4dFa0139dFa1b3D433Cc23b72f;\n // Deterministic deployment address of the Multicall3 contract.\n address internal constant MULTICALL3_ADDRESS = 0xcA11bde05977b3631167028862bE2a173976CA11;\n\n uint256 internal constant UINT256_MAX =\n 115792089237316195423570985008687907853269984665640564039457584007913129639935;\n\n Vm internal constant vm = Vm(VM_ADDRESS);\n StdStorage internal stdstore;\n}\n\nabstract contract TestBase is CommonBase {}\n\nabstract contract ScriptBase is CommonBase {\n // Used when deploying with create2, https://github.com/Arachnid/deterministic-deployment-proxy.\n address internal constant CREATE2_FACTORY = 0x4e59b44847b379578588920cA78FbF26c0B4956C;\n\n VmSafe internal constant vmSafe = VmSafe(VM_ADDRESS);\n}\n" + }, + "forge-std/console.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.4.22 <0.9.0;\n\nlibrary console {\n address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);\n\n function _sendLogPayload(bytes memory payload) private view {\n uint256 payloadLength = payload.length;\n address consoleAddress = CONSOLE_ADDRESS;\n /// @solidity memory-safe-assembly\n assembly {\n let payloadStart := add(payload, 32)\n let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)\n }\n }\n\n function log() internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log()\"));\n }\n\n function logInt(int p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(int)\", p0));\n }\n\n function logUint(uint p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint)\", p0));\n }\n\n function logString(string memory p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string)\", p0));\n }\n\n function logBool(bool p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool)\", p0));\n }\n\n function logAddress(address p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address)\", p0));\n }\n\n function logBytes(bytes memory p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes)\", p0));\n }\n\n function logBytes1(bytes1 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes1)\", p0));\n }\n\n function logBytes2(bytes2 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes2)\", p0));\n }\n\n function logBytes3(bytes3 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes3)\", p0));\n }\n\n function logBytes4(bytes4 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes4)\", p0));\n }\n\n function logBytes5(bytes5 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes5)\", p0));\n }\n\n function logBytes6(bytes6 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes6)\", p0));\n }\n\n function logBytes7(bytes7 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes7)\", p0));\n }\n\n function logBytes8(bytes8 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes8)\", p0));\n }\n\n function logBytes9(bytes9 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes9)\", p0));\n }\n\n function logBytes10(bytes10 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes10)\", p0));\n }\n\n function logBytes11(bytes11 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes11)\", p0));\n }\n\n function logBytes12(bytes12 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes12)\", p0));\n }\n\n function logBytes13(bytes13 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes13)\", p0));\n }\n\n function logBytes14(bytes14 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes14)\", p0));\n }\n\n function logBytes15(bytes15 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes15)\", p0));\n }\n\n function logBytes16(bytes16 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes16)\", p0));\n }\n\n function logBytes17(bytes17 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes17)\", p0));\n }\n\n function logBytes18(bytes18 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes18)\", p0));\n }\n\n function logBytes19(bytes19 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes19)\", p0));\n }\n\n function logBytes20(bytes20 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes20)\", p0));\n }\n\n function logBytes21(bytes21 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes21)\", p0));\n }\n\n function logBytes22(bytes22 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes22)\", p0));\n }\n\n function logBytes23(bytes23 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes23)\", p0));\n }\n\n function logBytes24(bytes24 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes24)\", p0));\n }\n\n function logBytes25(bytes25 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes25)\", p0));\n }\n\n function logBytes26(bytes26 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes26)\", p0));\n }\n\n function logBytes27(bytes27 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes27)\", p0));\n }\n\n function logBytes28(bytes28 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes28)\", p0));\n }\n\n function logBytes29(bytes29 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes29)\", p0));\n }\n\n function logBytes30(bytes30 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes30)\", p0));\n }\n\n function logBytes31(bytes31 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes31)\", p0));\n }\n\n function logBytes32(bytes32 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes32)\", p0));\n }\n\n function log(uint p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint)\", p0));\n }\n\n function log(string memory p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string)\", p0));\n }\n\n function log(bool p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool)\", p0));\n }\n\n function log(address p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address)\", p0));\n }\n\n function log(uint p0, uint p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint)\", p0, p1));\n }\n\n function log(uint p0, string memory p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string)\", p0, p1));\n }\n\n function log(uint p0, bool p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool)\", p0, p1));\n }\n\n function log(uint p0, address p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address)\", p0, p1));\n }\n\n function log(string memory p0, uint p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint)\", p0, p1));\n }\n\n function log(string memory p0, string memory p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string)\", p0, p1));\n }\n\n function log(string memory p0, bool p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool)\", p0, p1));\n }\n\n function log(string memory p0, address p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address)\", p0, p1));\n }\n\n function log(bool p0, uint p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint)\", p0, p1));\n }\n\n function log(bool p0, string memory p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string)\", p0, p1));\n }\n\n function log(bool p0, bool p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool)\", p0, p1));\n }\n\n function log(bool p0, address p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address)\", p0, p1));\n }\n\n function log(address p0, uint p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint)\", p0, p1));\n }\n\n function log(address p0, string memory p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string)\", p0, p1));\n }\n\n function log(address p0, bool p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool)\", p0, p1));\n }\n\n function log(address p0, address p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address)\", p0, p1));\n }\n\n function log(uint p0, uint p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,uint)\", p0, p1, p2));\n }\n\n function log(uint p0, uint p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,string)\", p0, p1, p2));\n }\n\n function log(uint p0, uint p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,bool)\", p0, p1, p2));\n }\n\n function log(uint p0, uint p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,address)\", p0, p1, p2));\n }\n\n function log(uint p0, string memory p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,uint)\", p0, p1, p2));\n }\n\n function log(uint p0, string memory p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,string)\", p0, p1, p2));\n }\n\n function log(uint p0, string memory p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,bool)\", p0, p1, p2));\n }\n\n function log(uint p0, string memory p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,address)\", p0, p1, p2));\n }\n\n function log(uint p0, bool p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,uint)\", p0, p1, p2));\n }\n\n function log(uint p0, bool p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,string)\", p0, p1, p2));\n }\n\n function log(uint p0, bool p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,bool)\", p0, p1, p2));\n }\n\n function log(uint p0, bool p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,address)\", p0, p1, p2));\n }\n\n function log(uint p0, address p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,uint)\", p0, p1, p2));\n }\n\n function log(uint p0, address p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,string)\", p0, p1, p2));\n }\n\n function log(uint p0, address p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,bool)\", p0, p1, p2));\n }\n\n function log(uint p0, address p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,address)\", p0, p1, p2));\n }\n\n function log(string memory p0, uint p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,uint)\", p0, p1, p2));\n }\n\n function log(string memory p0, uint p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,string)\", p0, p1, p2));\n }\n\n function log(string memory p0, uint p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,bool)\", p0, p1, p2));\n }\n\n function log(string memory p0, uint p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,address)\", p0, p1, p2));\n }\n\n function log(string memory p0, string memory p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint)\", p0, p1, p2));\n }\n\n function log(string memory p0, string memory p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string)\", p0, p1, p2));\n }\n\n function log(string memory p0, string memory p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool)\", p0, p1, p2));\n }\n\n function log(string memory p0, string memory p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address)\", p0, p1, p2));\n }\n\n function log(string memory p0, bool p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint)\", p0, p1, p2));\n }\n\n function log(string memory p0, bool p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string)\", p0, p1, p2));\n }\n\n function log(string memory p0, bool p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool)\", p0, p1, p2));\n }\n\n function log(string memory p0, bool p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address)\", p0, p1, p2));\n }\n\n function log(string memory p0, address p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint)\", p0, p1, p2));\n }\n\n function log(string memory p0, address p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string)\", p0, p1, p2));\n }\n\n function log(string memory p0, address p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool)\", p0, p1, p2));\n }\n\n function log(string memory p0, address p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address)\", p0, p1, p2));\n }\n\n function log(bool p0, uint p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,uint)\", p0, p1, p2));\n }\n\n function log(bool p0, uint p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,string)\", p0, p1, p2));\n }\n\n function log(bool p0, uint p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,bool)\", p0, p1, p2));\n }\n\n function log(bool p0, uint p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,address)\", p0, p1, p2));\n }\n\n function log(bool p0, string memory p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint)\", p0, p1, p2));\n }\n\n function log(bool p0, string memory p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string)\", p0, p1, p2));\n }\n\n function log(bool p0, string memory p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool)\", p0, p1, p2));\n }\n\n function log(bool p0, string memory p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address)\", p0, p1, p2));\n }\n\n function log(bool p0, bool p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint)\", p0, p1, p2));\n }\n\n function log(bool p0, bool p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string)\", p0, p1, p2));\n }\n\n function log(bool p0, bool p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool)\", p0, p1, p2));\n }\n\n function log(bool p0, bool p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address)\", p0, p1, p2));\n }\n\n function log(bool p0, address p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint)\", p0, p1, p2));\n }\n\n function log(bool p0, address p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string)\", p0, p1, p2));\n }\n\n function log(bool p0, address p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool)\", p0, p1, p2));\n }\n\n function log(bool p0, address p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address)\", p0, p1, p2));\n }\n\n function log(address p0, uint p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,uint)\", p0, p1, p2));\n }\n\n function log(address p0, uint p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,string)\", p0, p1, p2));\n }\n\n function log(address p0, uint p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,bool)\", p0, p1, p2));\n }\n\n function log(address p0, uint p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,address)\", p0, p1, p2));\n }\n\n function log(address p0, string memory p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint)\", p0, p1, p2));\n }\n\n function log(address p0, string memory p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string)\", p0, p1, p2));\n }\n\n function log(address p0, string memory p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool)\", p0, p1, p2));\n }\n\n function log(address p0, string memory p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address)\", p0, p1, p2));\n }\n\n function log(address p0, bool p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint)\", p0, p1, p2));\n }\n\n function log(address p0, bool p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string)\", p0, p1, p2));\n }\n\n function log(address p0, bool p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool)\", p0, p1, p2));\n }\n\n function log(address p0, bool p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address)\", p0, p1, p2));\n }\n\n function log(address p0, address p1, uint p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint)\", p0, p1, p2));\n }\n\n function log(address p0, address p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string)\", p0, p1, p2));\n }\n\n function log(address p0, address p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool)\", p0, p1, p2));\n }\n\n function log(address p0, address p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address)\", p0, p1, p2));\n }\n\n function log(uint p0, uint p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,string,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,string,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,address,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, uint p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,uint,address,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,string,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,string,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,address,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, string memory p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,string,address,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,string,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,string,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,address,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, bool p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,bool,address,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,string,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,string,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,address,string)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint p0, address p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint,address,address,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,string,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,string,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,address,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint,address,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,string,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,string,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,address,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint,address,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,string,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,string,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,address,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint,address,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, uint p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, uint p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, uint p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, uint p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, string memory p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, bool p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, address p2, uint p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,uint)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,address)\", p0, p1, p2, p3));\n }\n\n}" + }, + "forge-std/console2.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.4.22 <0.9.0;\n\n/// @dev The original console.sol uses `int` and `uint` for computing function selectors, but it should\n/// use `int256` and `uint256`. This modified version fixes that. This version is recommended\n/// over `console.sol` if you don't need compatibility with Hardhat as the logs will show up in\n/// forge stack traces. If you do need compatibility with Hardhat, you must use `console.sol`.\n/// Reference: https://github.com/NomicFoundation/hardhat/issues/2178\nlibrary console2 {\n address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);\n\n function _sendLogPayload(bytes memory payload) private view {\n uint256 payloadLength = payload.length;\n address consoleAddress = CONSOLE_ADDRESS;\n /// @solidity memory-safe-assembly\n assembly {\n let payloadStart := add(payload, 32)\n let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)\n }\n }\n\n function log() internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log()\"));\n }\n\n function logInt(int256 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(int256)\", p0));\n }\n\n function logUint(uint256 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256)\", p0));\n }\n\n function logString(string memory p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string)\", p0));\n }\n\n function logBool(bool p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool)\", p0));\n }\n\n function logAddress(address p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address)\", p0));\n }\n\n function logBytes(bytes memory p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes)\", p0));\n }\n\n function logBytes1(bytes1 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes1)\", p0));\n }\n\n function logBytes2(bytes2 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes2)\", p0));\n }\n\n function logBytes3(bytes3 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes3)\", p0));\n }\n\n function logBytes4(bytes4 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes4)\", p0));\n }\n\n function logBytes5(bytes5 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes5)\", p0));\n }\n\n function logBytes6(bytes6 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes6)\", p0));\n }\n\n function logBytes7(bytes7 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes7)\", p0));\n }\n\n function logBytes8(bytes8 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes8)\", p0));\n }\n\n function logBytes9(bytes9 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes9)\", p0));\n }\n\n function logBytes10(bytes10 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes10)\", p0));\n }\n\n function logBytes11(bytes11 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes11)\", p0));\n }\n\n function logBytes12(bytes12 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes12)\", p0));\n }\n\n function logBytes13(bytes13 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes13)\", p0));\n }\n\n function logBytes14(bytes14 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes14)\", p0));\n }\n\n function logBytes15(bytes15 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes15)\", p0));\n }\n\n function logBytes16(bytes16 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes16)\", p0));\n }\n\n function logBytes17(bytes17 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes17)\", p0));\n }\n\n function logBytes18(bytes18 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes18)\", p0));\n }\n\n function logBytes19(bytes19 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes19)\", p0));\n }\n\n function logBytes20(bytes20 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes20)\", p0));\n }\n\n function logBytes21(bytes21 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes21)\", p0));\n }\n\n function logBytes22(bytes22 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes22)\", p0));\n }\n\n function logBytes23(bytes23 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes23)\", p0));\n }\n\n function logBytes24(bytes24 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes24)\", p0));\n }\n\n function logBytes25(bytes25 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes25)\", p0));\n }\n\n function logBytes26(bytes26 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes26)\", p0));\n }\n\n function logBytes27(bytes27 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes27)\", p0));\n }\n\n function logBytes28(bytes28 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes28)\", p0));\n }\n\n function logBytes29(bytes29 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes29)\", p0));\n }\n\n function logBytes30(bytes30 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes30)\", p0));\n }\n\n function logBytes31(bytes31 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes31)\", p0));\n }\n\n function logBytes32(bytes32 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bytes32)\", p0));\n }\n\n function log(uint256 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256)\", p0));\n }\n\n function log(int256 p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(int256)\", p0));\n }\n\n function log(string memory p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string)\", p0));\n }\n\n function log(bool p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool)\", p0));\n }\n\n function log(address p0) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address)\", p0));\n }\n\n function log(uint256 p0, uint256 p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256)\", p0, p1));\n }\n\n function log(uint256 p0, string memory p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string)\", p0, p1));\n }\n\n function log(uint256 p0, bool p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool)\", p0, p1));\n }\n\n function log(uint256 p0, address p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address)\", p0, p1));\n }\n\n function log(string memory p0, uint256 p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256)\", p0, p1));\n }\n\n function log(string memory p0, int256 p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,int256)\", p0, p1));\n }\n\n function log(string memory p0, string memory p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string)\", p0, p1));\n }\n\n function log(string memory p0, bool p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool)\", p0, p1));\n }\n\n function log(string memory p0, address p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address)\", p0, p1));\n }\n\n function log(bool p0, uint256 p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256)\", p0, p1));\n }\n\n function log(bool p0, string memory p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string)\", p0, p1));\n }\n\n function log(bool p0, bool p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool)\", p0, p1));\n }\n\n function log(bool p0, address p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address)\", p0, p1));\n }\n\n function log(address p0, uint256 p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256)\", p0, p1));\n }\n\n function log(address p0, string memory p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string)\", p0, p1));\n }\n\n function log(address p0, bool p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool)\", p0, p1));\n }\n\n function log(address p0, address p1) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address)\", p0, p1));\n }\n\n function log(uint256 p0, uint256 p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256)\", p0, p1, p2));\n }\n\n function log(uint256 p0, uint256 p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string)\", p0, p1, p2));\n }\n\n function log(uint256 p0, uint256 p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool)\", p0, p1, p2));\n }\n\n function log(uint256 p0, uint256 p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address)\", p0, p1, p2));\n }\n\n function log(uint256 p0, string memory p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256)\", p0, p1, p2));\n }\n\n function log(uint256 p0, string memory p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string)\", p0, p1, p2));\n }\n\n function log(uint256 p0, string memory p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool)\", p0, p1, p2));\n }\n\n function log(uint256 p0, string memory p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address)\", p0, p1, p2));\n }\n\n function log(uint256 p0, bool p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256)\", p0, p1, p2));\n }\n\n function log(uint256 p0, bool p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string)\", p0, p1, p2));\n }\n\n function log(uint256 p0, bool p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool)\", p0, p1, p2));\n }\n\n function log(uint256 p0, bool p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address)\", p0, p1, p2));\n }\n\n function log(uint256 p0, address p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256)\", p0, p1, p2));\n }\n\n function log(uint256 p0, address p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string)\", p0, p1, p2));\n }\n\n function log(uint256 p0, address p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool)\", p0, p1, p2));\n }\n\n function log(uint256 p0, address p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address)\", p0, p1, p2));\n }\n\n function log(string memory p0, uint256 p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256)\", p0, p1, p2));\n }\n\n function log(string memory p0, uint256 p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string)\", p0, p1, p2));\n }\n\n function log(string memory p0, uint256 p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool)\", p0, p1, p2));\n }\n\n function log(string memory p0, uint256 p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address)\", p0, p1, p2));\n }\n\n function log(string memory p0, string memory p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256)\", p0, p1, p2));\n }\n\n function log(string memory p0, string memory p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string)\", p0, p1, p2));\n }\n\n function log(string memory p0, string memory p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool)\", p0, p1, p2));\n }\n\n function log(string memory p0, string memory p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address)\", p0, p1, p2));\n }\n\n function log(string memory p0, bool p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256)\", p0, p1, p2));\n }\n\n function log(string memory p0, bool p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string)\", p0, p1, p2));\n }\n\n function log(string memory p0, bool p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool)\", p0, p1, p2));\n }\n\n function log(string memory p0, bool p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address)\", p0, p1, p2));\n }\n\n function log(string memory p0, address p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256)\", p0, p1, p2));\n }\n\n function log(string memory p0, address p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string)\", p0, p1, p2));\n }\n\n function log(string memory p0, address p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool)\", p0, p1, p2));\n }\n\n function log(string memory p0, address p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address)\", p0, p1, p2));\n }\n\n function log(bool p0, uint256 p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256)\", p0, p1, p2));\n }\n\n function log(bool p0, uint256 p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string)\", p0, p1, p2));\n }\n\n function log(bool p0, uint256 p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool)\", p0, p1, p2));\n }\n\n function log(bool p0, uint256 p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address)\", p0, p1, p2));\n }\n\n function log(bool p0, string memory p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256)\", p0, p1, p2));\n }\n\n function log(bool p0, string memory p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string)\", p0, p1, p2));\n }\n\n function log(bool p0, string memory p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool)\", p0, p1, p2));\n }\n\n function log(bool p0, string memory p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address)\", p0, p1, p2));\n }\n\n function log(bool p0, bool p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256)\", p0, p1, p2));\n }\n\n function log(bool p0, bool p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string)\", p0, p1, p2));\n }\n\n function log(bool p0, bool p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool)\", p0, p1, p2));\n }\n\n function log(bool p0, bool p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address)\", p0, p1, p2));\n }\n\n function log(bool p0, address p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256)\", p0, p1, p2));\n }\n\n function log(bool p0, address p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string)\", p0, p1, p2));\n }\n\n function log(bool p0, address p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool)\", p0, p1, p2));\n }\n\n function log(bool p0, address p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address)\", p0, p1, p2));\n }\n\n function log(address p0, uint256 p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256)\", p0, p1, p2));\n }\n\n function log(address p0, uint256 p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string)\", p0, p1, p2));\n }\n\n function log(address p0, uint256 p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool)\", p0, p1, p2));\n }\n\n function log(address p0, uint256 p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address)\", p0, p1, p2));\n }\n\n function log(address p0, string memory p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256)\", p0, p1, p2));\n }\n\n function log(address p0, string memory p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string)\", p0, p1, p2));\n }\n\n function log(address p0, string memory p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool)\", p0, p1, p2));\n }\n\n function log(address p0, string memory p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address)\", p0, p1, p2));\n }\n\n function log(address p0, bool p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256)\", p0, p1, p2));\n }\n\n function log(address p0, bool p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string)\", p0, p1, p2));\n }\n\n function log(address p0, bool p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool)\", p0, p1, p2));\n }\n\n function log(address p0, bool p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address)\", p0, p1, p2));\n }\n\n function log(address p0, address p1, uint256 p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256)\", p0, p1, p2));\n }\n\n function log(address p0, address p1, string memory p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string)\", p0, p1, p2));\n }\n\n function log(address p0, address p1, bool p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool)\", p0, p1, p2));\n }\n\n function log(address p0, address p1, address p2) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address)\", p0, p1, p2));\n }\n\n function log(uint256 p0, uint256 p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,string,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, uint256 p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,uint256,address,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,string,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, string memory p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,string,address,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,string,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, bool p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,bool,address,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,string,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address,string)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(uint256 p0, address p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(uint256,address,address,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,string,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, uint256 p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,uint256,address,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,string,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, string memory p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,string,address,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,string,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, bool p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,bool,address,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,string,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,string)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(string memory p0, address p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(string,address,address,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,string,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, uint256 p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,uint256,address,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,string,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, string memory p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,string,address,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,string,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, bool p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,bool,address,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,string,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,string)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(bool p0, address p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(bool,address,address,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,string,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, uint256 p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,uint256,address,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,string,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, string memory p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,string,address,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,string,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, bool p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,bool,address,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, uint256 p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, uint256 p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, uint256 p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, uint256 p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,uint256,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, string memory p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, string memory p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, string memory p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, string memory p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,string,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, bool p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, bool p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, bool p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, bool p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,bool,address)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, address p2, uint256 p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,uint256)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, address p2, string memory p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,string)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, address p2, bool p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,bool)\", p0, p1, p2, p3));\n }\n\n function log(address p0, address p1, address p2, address p3) internal view {\n _sendLogPayload(abi.encodeWithSignature(\"log(address,address,address,address)\", p0, p1, p2, p3));\n }\n\n}" + }, + "forge-std/interfaces/IMulticall3.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\ninterface IMulticall3 {\n struct Call {\n address target;\n bytes callData;\n }\n\n struct Call3 {\n address target;\n bool allowFailure;\n bytes callData;\n }\n\n struct Call3Value {\n address target;\n bool allowFailure;\n uint256 value;\n bytes callData;\n }\n\n struct Result {\n bool success;\n bytes returnData;\n }\n\n function aggregate(Call[] calldata calls)\n external\n payable\n returns (uint256 blockNumber, bytes[] memory returnData);\n\n function aggregate3(Call3[] calldata calls) external payable returns (Result[] memory returnData);\n\n function aggregate3Value(Call3Value[] calldata calls) external payable returns (Result[] memory returnData);\n\n function blockAndAggregate(Call[] calldata calls)\n external\n payable\n returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData);\n\n function getBasefee() external view returns (uint256 basefee);\n\n function getBlockHash(uint256 blockNumber) external view returns (bytes32 blockHash);\n\n function getBlockNumber() external view returns (uint256 blockNumber);\n\n function getChainId() external view returns (uint256 chainid);\n\n function getCurrentBlockCoinbase() external view returns (address coinbase);\n\n function getCurrentBlockDifficulty() external view returns (uint256 difficulty);\n\n function getCurrentBlockGasLimit() external view returns (uint256 gaslimit);\n\n function getCurrentBlockTimestamp() external view returns (uint256 timestamp);\n\n function getEthBalance(address addr) external view returns (uint256 balance);\n\n function getLastBlockHash() external view returns (bytes32 blockHash);\n\n function tryAggregate(bool requireSuccess, Call[] calldata calls)\n external\n payable\n returns (Result[] memory returnData);\n\n function tryBlockAndAggregate(bool requireSuccess, Call[] calldata calls)\n external\n payable\n returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData);\n}\n" + }, + "forge-std/StdAssertions.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\nimport {DSTest} from \"ds-test/test.sol\";\nimport {stdMath} from \"./StdMath.sol\";\n\nabstract contract StdAssertions is DSTest {\n event log_array(uint256[] val);\n event log_array(int256[] val);\n event log_array(address[] val);\n event log_named_array(string key, uint256[] val);\n event log_named_array(string key, int256[] val);\n event log_named_array(string key, address[] val);\n\n function fail(string memory err) internal virtual {\n emit log_named_string(\"Error\", err);\n fail();\n }\n\n function assertFalse(bool data) internal virtual {\n assertTrue(!data);\n }\n\n function assertFalse(bool data, string memory err) internal virtual {\n assertTrue(!data, err);\n }\n\n function assertEq(bool a, bool b) internal virtual {\n if (a != b) {\n emit log(\"Error: a == b not satisfied [bool]\");\n emit log_named_string(\" Left\", a ? \"true\" : \"false\");\n emit log_named_string(\" Right\", b ? \"true\" : \"false\");\n fail();\n }\n }\n\n function assertEq(bool a, bool b, string memory err) internal virtual {\n if (a != b) {\n emit log_named_string(\"Error\", err);\n assertEq(a, b);\n }\n }\n\n function assertEq(bytes memory a, bytes memory b) internal virtual {\n assertEq0(a, b);\n }\n\n function assertEq(bytes memory a, bytes memory b, string memory err) internal virtual {\n assertEq0(a, b, err);\n }\n\n function assertEq(uint256[] memory a, uint256[] memory b) internal virtual {\n if (keccak256(abi.encode(a)) != keccak256(abi.encode(b))) {\n emit log(\"Error: a == b not satisfied [uint[]]\");\n emit log_named_array(\" Left\", a);\n emit log_named_array(\" Right\", b);\n fail();\n }\n }\n\n function assertEq(int256[] memory a, int256[] memory b) internal virtual {\n if (keccak256(abi.encode(a)) != keccak256(abi.encode(b))) {\n emit log(\"Error: a == b not satisfied [int[]]\");\n emit log_named_array(\" Left\", a);\n emit log_named_array(\" Right\", b);\n fail();\n }\n }\n\n function assertEq(address[] memory a, address[] memory b) internal virtual {\n if (keccak256(abi.encode(a)) != keccak256(abi.encode(b))) {\n emit log(\"Error: a == b not satisfied [address[]]\");\n emit log_named_array(\" Left\", a);\n emit log_named_array(\" Right\", b);\n fail();\n }\n }\n\n function assertEq(uint256[] memory a, uint256[] memory b, string memory err) internal virtual {\n if (keccak256(abi.encode(a)) != keccak256(abi.encode(b))) {\n emit log_named_string(\"Error\", err);\n assertEq(a, b);\n }\n }\n\n function assertEq(int256[] memory a, int256[] memory b, string memory err) internal virtual {\n if (keccak256(abi.encode(a)) != keccak256(abi.encode(b))) {\n emit log_named_string(\"Error\", err);\n assertEq(a, b);\n }\n }\n\n function assertEq(address[] memory a, address[] memory b, string memory err) internal virtual {\n if (keccak256(abi.encode(a)) != keccak256(abi.encode(b))) {\n emit log_named_string(\"Error\", err);\n assertEq(a, b);\n }\n }\n\n // Legacy helper\n function assertEqUint(uint256 a, uint256 b) internal virtual {\n assertEq(uint256(a), uint256(b));\n }\n\n function assertApproxEqAbs(uint256 a, uint256 b, uint256 maxDelta) internal virtual {\n uint256 delta = stdMath.delta(a, b);\n\n if (delta > maxDelta) {\n emit log(\"Error: a ~= b not satisfied [uint]\");\n emit log_named_uint(\" Left\", a);\n emit log_named_uint(\" Right\", b);\n emit log_named_uint(\" Max Delta\", maxDelta);\n emit log_named_uint(\" Delta\", delta);\n fail();\n }\n }\n\n function assertApproxEqAbs(uint256 a, uint256 b, uint256 maxDelta, string memory err) internal virtual {\n uint256 delta = stdMath.delta(a, b);\n\n if (delta > maxDelta) {\n emit log_named_string(\"Error\", err);\n assertApproxEqAbs(a, b, maxDelta);\n }\n }\n\n function assertApproxEqAbsDecimal(uint256 a, uint256 b, uint256 maxDelta, uint256 decimals) internal virtual {\n uint256 delta = stdMath.delta(a, b);\n\n if (delta > maxDelta) {\n emit log(\"Error: a ~= b not satisfied [uint]\");\n emit log_named_decimal_uint(\" Left\", a, decimals);\n emit log_named_decimal_uint(\" Right\", b, decimals);\n emit log_named_decimal_uint(\" Max Delta\", maxDelta, decimals);\n emit log_named_decimal_uint(\" Delta\", delta, decimals);\n fail();\n }\n }\n\n function assertApproxEqAbsDecimal(uint256 a, uint256 b, uint256 maxDelta, uint256 decimals, string memory err)\n internal\n virtual\n {\n uint256 delta = stdMath.delta(a, b);\n\n if (delta > maxDelta) {\n emit log_named_string(\"Error\", err);\n assertApproxEqAbsDecimal(a, b, maxDelta, decimals);\n }\n }\n\n function assertApproxEqAbs(int256 a, int256 b, uint256 maxDelta) internal virtual {\n uint256 delta = stdMath.delta(a, b);\n\n if (delta > maxDelta) {\n emit log(\"Error: a ~= b not satisfied [int]\");\n emit log_named_int(\" Left\", a);\n emit log_named_int(\" Right\", b);\n emit log_named_uint(\" Max Delta\", maxDelta);\n emit log_named_uint(\" Delta\", delta);\n fail();\n }\n }\n\n function assertApproxEqAbs(int256 a, int256 b, uint256 maxDelta, string memory err) internal virtual {\n uint256 delta = stdMath.delta(a, b);\n\n if (delta > maxDelta) {\n emit log_named_string(\"Error\", err);\n assertApproxEqAbs(a, b, maxDelta);\n }\n }\n\n function assertApproxEqAbsDecimal(int256 a, int256 b, uint256 maxDelta, uint256 decimals) internal virtual {\n uint256 delta = stdMath.delta(a, b);\n\n if (delta > maxDelta) {\n emit log(\"Error: a ~= b not satisfied [int]\");\n emit log_named_decimal_int(\" Left\", a, decimals);\n emit log_named_decimal_int(\" Right\", b, decimals);\n emit log_named_decimal_uint(\" Max Delta\", maxDelta, decimals);\n emit log_named_decimal_uint(\" Delta\", delta, decimals);\n fail();\n }\n }\n\n function assertApproxEqAbsDecimal(int256 a, int256 b, uint256 maxDelta, uint256 decimals, string memory err)\n internal\n virtual\n {\n uint256 delta = stdMath.delta(a, b);\n\n if (delta > maxDelta) {\n emit log_named_string(\"Error\", err);\n assertApproxEqAbsDecimal(a, b, maxDelta, decimals);\n }\n }\n\n function assertApproxEqRel(\n uint256 a,\n uint256 b,\n uint256 maxPercentDelta // An 18 decimal fixed point number, where 1e18 == 100%\n ) internal virtual {\n if (b == 0) return assertEq(a, b); // If the left is 0, right must be too.\n\n uint256 percentDelta = stdMath.percentDelta(a, b);\n\n if (percentDelta > maxPercentDelta) {\n emit log(\"Error: a ~= b not satisfied [uint]\");\n emit log_named_uint(\" Left\", a);\n emit log_named_uint(\" Right\", b);\n emit log_named_decimal_uint(\" Max % Delta\", maxPercentDelta, 18);\n emit log_named_decimal_uint(\" % Delta\", percentDelta, 18);\n fail();\n }\n }\n\n function assertApproxEqRel(\n uint256 a,\n uint256 b,\n uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100%\n string memory err\n ) internal virtual {\n if (b == 0) return assertEq(a, b, err); // If the left is 0, right must be too.\n\n uint256 percentDelta = stdMath.percentDelta(a, b);\n\n if (percentDelta > maxPercentDelta) {\n emit log_named_string(\"Error\", err);\n assertApproxEqRel(a, b, maxPercentDelta);\n }\n }\n\n function assertApproxEqRelDecimal(\n uint256 a,\n uint256 b,\n uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100%\n uint256 decimals\n ) internal virtual {\n if (b == 0) return assertEq(a, b); // If the left is 0, right must be too.\n\n uint256 percentDelta = stdMath.percentDelta(a, b);\n\n if (percentDelta > maxPercentDelta) {\n emit log(\"Error: a ~= b not satisfied [uint]\");\n emit log_named_decimal_uint(\" Left\", a, decimals);\n emit log_named_decimal_uint(\" Right\", b, decimals);\n emit log_named_decimal_uint(\" Max % Delta\", maxPercentDelta, 18);\n emit log_named_decimal_uint(\" % Delta\", percentDelta, 18);\n fail();\n }\n }\n\n function assertApproxEqRelDecimal(\n uint256 a,\n uint256 b,\n uint256 maxPercentDelta, // An 18 decimal fixed point number, where 1e18 == 100%\n uint256 decimals,\n string memory err\n ) internal virtual {\n if (b == 0) return assertEq(a, b, err); // If the left is 0, right must be too.\n\n uint256 percentDelta = stdMath.percentDelta(a, b);\n\n if (percentDelta > maxPercentDelta) {\n emit log_named_string(\"Error\", err);\n assertApproxEqRelDecimal(a, b, maxPercentDelta, decimals);\n }\n }\n\n function assertApproxEqRel(int256 a, int256 b, uint256 maxPercentDelta) internal virtual {\n if (b == 0) return assertEq(a, b); // If the left is 0, right must be too.\n\n uint256 percentDelta = stdMath.percentDelta(a, b);\n\n if (percentDelta > maxPercentDelta) {\n emit log(\"Error: a ~= b not satisfied [int]\");\n emit log_named_int(\" Left\", a);\n emit log_named_int(\" Right\", b);\n emit log_named_decimal_uint(\" Max % Delta\", maxPercentDelta, 18);\n emit log_named_decimal_uint(\" % Delta\", percentDelta, 18);\n fail();\n }\n }\n\n function assertApproxEqRel(int256 a, int256 b, uint256 maxPercentDelta, string memory err) internal virtual {\n if (b == 0) return assertEq(a, b, err); // If the left is 0, right must be too.\n\n uint256 percentDelta = stdMath.percentDelta(a, b);\n\n if (percentDelta > maxPercentDelta) {\n emit log_named_string(\"Error\", err);\n assertApproxEqRel(a, b, maxPercentDelta);\n }\n }\n\n function assertApproxEqRelDecimal(int256 a, int256 b, uint256 maxPercentDelta, uint256 decimals) internal virtual {\n if (b == 0) return assertEq(a, b); // If the left is 0, right must be too.\n\n uint256 percentDelta = stdMath.percentDelta(a, b);\n\n if (percentDelta > maxPercentDelta) {\n emit log(\"Error: a ~= b not satisfied [int]\");\n emit log_named_decimal_int(\" Left\", a, decimals);\n emit log_named_decimal_int(\" Right\", b, decimals);\n emit log_named_decimal_uint(\" Max % Delta\", maxPercentDelta, 18);\n emit log_named_decimal_uint(\" % Delta\", percentDelta, 18);\n fail();\n }\n }\n\n function assertApproxEqRelDecimal(int256 a, int256 b, uint256 maxPercentDelta, uint256 decimals, string memory err)\n internal\n virtual\n {\n if (b == 0) return assertEq(a, b, err); // If the left is 0, right must be too.\n\n uint256 percentDelta = stdMath.percentDelta(a, b);\n\n if (percentDelta > maxPercentDelta) {\n emit log_named_string(\"Error\", err);\n assertApproxEqRelDecimal(a, b, maxPercentDelta, decimals);\n }\n }\n\n function assertEqCall(address target, bytes memory callDataA, bytes memory callDataB) internal virtual {\n assertEqCall(target, callDataA, target, callDataB, true);\n }\n\n function assertEqCall(address targetA, bytes memory callDataA, address targetB, bytes memory callDataB)\n internal\n virtual\n {\n assertEqCall(targetA, callDataA, targetB, callDataB, true);\n }\n\n function assertEqCall(address target, bytes memory callDataA, bytes memory callDataB, bool strictRevertData)\n internal\n virtual\n {\n assertEqCall(target, callDataA, target, callDataB, strictRevertData);\n }\n\n function assertEqCall(\n address targetA,\n bytes memory callDataA,\n address targetB,\n bytes memory callDataB,\n bool strictRevertData\n ) internal virtual {\n (bool successA, bytes memory returnDataA) = address(targetA).call(callDataA);\n (bool successB, bytes memory returnDataB) = address(targetB).call(callDataB);\n\n if (successA && successB) {\n assertEq(returnDataA, returnDataB, \"Call return data does not match\");\n }\n\n if (!successA && !successB && strictRevertData) {\n assertEq(returnDataA, returnDataB, \"Call revert data does not match\");\n }\n\n if (!successA && successB) {\n emit log(\"Error: Calls were not equal\");\n emit log_named_bytes(\" Left call revert data\", returnDataA);\n emit log_named_bytes(\" Right call return data\", returnDataB);\n fail();\n }\n\n if (successA && !successB) {\n emit log(\"Error: Calls were not equal\");\n emit log_named_bytes(\" Left call return data\", returnDataA);\n emit log_named_bytes(\" Right call revert data\", returnDataB);\n fail();\n }\n }\n}\n" + }, + "forge-std/StdChains.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\nimport {VmSafe} from \"./Vm.sol\";\n\n/**\n * StdChains provides information about EVM compatible chains that can be used in scripts/tests.\n * For each chain, the chain's name, chain ID, and a default RPC URL are provided. Chains are\n * identified by their alias, which is the same as the alias in the `[rpc_endpoints]` section of\n * the `foundry.toml` file. For best UX, ensure the alias in the `foundry.toml` file match the\n * alias used in this contract, which can be found as the first argument to the\n * `setChainWithDefaultRpcUrl` call in the `initialize` function.\n *\n * There are two main ways to use this contract:\n * 1. Set a chain with `setChain(string memory chainAlias, ChainData memory chain)` or\n * `setChain(string memory chainAlias, Chain memory chain)`\n * 2. Get a chain with `getChain(string memory chainAlias)` or `getChain(uint256 chainId)`.\n *\n * The first time either of those are used, chains are initialized with the default set of RPC URLs.\n * This is done in `initialize`, which uses `setChainWithDefaultRpcUrl`. Defaults are recorded in\n * `defaultRpcUrls`.\n *\n * The `setChain` function is straightforward, and it simply saves off the given chain data.\n *\n * The `getChain` methods use `getChainWithUpdatedRpcUrl` to return a chain. For example, let's say\n * we want to retrieve `mainnet`'s RPC URL:\n * - If you haven't set any mainnet chain info with `setChain`, you haven't specified that\n * chain in `foundry.toml` and no env var is set, the default data and RPC URL will be returned.\n * - If you have set a mainnet RPC URL in `foundry.toml` it will return that, if valid (e.g. if\n * a URL is given or if an environment variable is given and that environment variable exists).\n * Otherwise, the default data is returned.\n * - If you specified data with `setChain` it will return that.\n *\n * Summarizing the above, the prioritization hierarchy is `setChain` -> `foundry.toml` -> environment variable -> defaults.\n */\nabstract contract StdChains {\n VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256(\"hevm cheat code\")))));\n\n bool private initialized;\n\n struct ChainData {\n string name;\n uint256 chainId;\n string rpcUrl;\n }\n\n struct Chain {\n // The chain name.\n string name;\n // The chain's Chain ID.\n uint256 chainId;\n // The chain's alias. (i.e. what gets specified in `foundry.toml`).\n string chainAlias;\n // A default RPC endpoint for this chain.\n // NOTE: This default RPC URL is included for convenience to facilitate quick tests and\n // experimentation. Do not use this RPC URL for production test suites, CI, or other heavy\n // usage as you will be throttled and this is a disservice to others who need this endpoint.\n string rpcUrl;\n }\n\n // Maps from the chain's alias (matching the alias in the `foundry.toml` file) to chain data.\n mapping(string => Chain) private chains;\n // Maps from the chain's alias to it's default RPC URL.\n mapping(string => string) private defaultRpcUrls;\n // Maps from a chain ID to it's alias.\n mapping(uint256 => string) private idToAlias;\n\n bool private fallbackToDefaultRpcUrls = true;\n\n // The RPC URL will be fetched from config or defaultRpcUrls if possible.\n function getChain(string memory chainAlias) internal virtual returns (Chain memory chain) {\n require(bytes(chainAlias).length != 0, \"StdChains getChain(string): Chain alias cannot be the empty string.\");\n\n initialize();\n chain = chains[chainAlias];\n require(\n chain.chainId != 0,\n string(abi.encodePacked(\"StdChains getChain(string): Chain with alias \\\"\", chainAlias, \"\\\" not found.\"))\n );\n\n chain = getChainWithUpdatedRpcUrl(chainAlias, chain);\n }\n\n function getChain(uint256 chainId) internal virtual returns (Chain memory chain) {\n require(chainId != 0, \"StdChains getChain(uint256): Chain ID cannot be 0.\");\n initialize();\n string memory chainAlias = idToAlias[chainId];\n\n chain = chains[chainAlias];\n\n require(\n chain.chainId != 0,\n string(abi.encodePacked(\"StdChains getChain(uint256): Chain with ID \", vm.toString(chainId), \" not found.\"))\n );\n\n chain = getChainWithUpdatedRpcUrl(chainAlias, chain);\n }\n\n // set chain info, with priority to argument's rpcUrl field.\n function setChain(string memory chainAlias, ChainData memory chain) internal virtual {\n require(\n bytes(chainAlias).length != 0,\n \"StdChains setChain(string,ChainData): Chain alias cannot be the empty string.\"\n );\n\n require(chain.chainId != 0, \"StdChains setChain(string,ChainData): Chain ID cannot be 0.\");\n\n initialize();\n string memory foundAlias = idToAlias[chain.chainId];\n\n require(\n bytes(foundAlias).length == 0 || keccak256(bytes(foundAlias)) == keccak256(bytes(chainAlias)),\n string(\n abi.encodePacked(\n \"StdChains setChain(string,ChainData): Chain ID \",\n vm.toString(chain.chainId),\n \" already used by \\\"\",\n foundAlias,\n \"\\\".\"\n )\n )\n );\n\n uint256 oldChainId = chains[chainAlias].chainId;\n delete idToAlias[oldChainId];\n\n chains[chainAlias] =\n Chain({name: chain.name, chainId: chain.chainId, chainAlias: chainAlias, rpcUrl: chain.rpcUrl});\n idToAlias[chain.chainId] = chainAlias;\n }\n\n // set chain info, with priority to argument's rpcUrl field.\n function setChain(string memory chainAlias, Chain memory chain) internal virtual {\n setChain(chainAlias, ChainData({name: chain.name, chainId: chain.chainId, rpcUrl: chain.rpcUrl}));\n }\n\n function _toUpper(string memory str) private pure returns (string memory) {\n bytes memory strb = bytes(str);\n bytes memory copy = new bytes(strb.length);\n for (uint256 i = 0; i < strb.length; i++) {\n bytes1 b = strb[i];\n if (b >= 0x61 && b <= 0x7A) {\n copy[i] = bytes1(uint8(b) - 32);\n } else {\n copy[i] = b;\n }\n }\n return string(copy);\n }\n\n // lookup rpcUrl, in descending order of priority:\n // current -> config (foundry.toml) -> environment variable -> default\n function getChainWithUpdatedRpcUrl(string memory chainAlias, Chain memory chain) private returns (Chain memory) {\n if (bytes(chain.rpcUrl).length == 0) {\n try vm.rpcUrl(chainAlias) returns (string memory configRpcUrl) {\n chain.rpcUrl = configRpcUrl;\n } catch (bytes memory err) {\n string memory envName = string(abi.encodePacked(_toUpper(chainAlias), \"_RPC_URL\"));\n if (fallbackToDefaultRpcUrls) {\n chain.rpcUrl = vm.envOr(envName, defaultRpcUrls[chainAlias]);\n } else {\n chain.rpcUrl = vm.envString(envName);\n }\n // distinguish 'not found' from 'cannot read'\n bytes memory notFoundError =\n abi.encodeWithSignature(\"CheatCodeError\", string(abi.encodePacked(\"invalid rpc url \", chainAlias)));\n if (keccak256(notFoundError) != keccak256(err) || bytes(chain.rpcUrl).length == 0) {\n /// @solidity memory-safe-assembly\n assembly {\n revert(add(32, err), mload(err))\n }\n }\n }\n }\n return chain;\n }\n\n function setFallbackToDefaultRpcUrls(bool useDefault) internal {\n fallbackToDefaultRpcUrls = useDefault;\n }\n\n function initialize() private {\n if (initialized) return;\n\n initialized = true;\n\n // If adding an RPC here, make sure to test the default RPC URL in `testRpcs`\n setChainWithDefaultRpcUrl(\"anvil\", ChainData(\"Anvil\", 31337, \"http://127.0.0.1:8545\"));\n setChainWithDefaultRpcUrl(\n \"mainnet\", ChainData(\"Mainnet\", 1, \"https://mainnet.infura.io/v3/f4a0bdad42674adab5fc0ac077ffab2b\")\n );\n setChainWithDefaultRpcUrl(\n \"goerli\", ChainData(\"Goerli\", 5, \"https://goerli.infura.io/v3/f4a0bdad42674adab5fc0ac077ffab2b\")\n );\n setChainWithDefaultRpcUrl(\n \"sepolia\", ChainData(\"Sepolia\", 11155111, \"https://sepolia.infura.io/v3/f4a0bdad42674adab5fc0ac077ffab2b\")\n );\n setChainWithDefaultRpcUrl(\"optimism\", ChainData(\"Optimism\", 10, \"https://mainnet.optimism.io\"));\n setChainWithDefaultRpcUrl(\"optimism_goerli\", ChainData(\"Optimism Goerli\", 420, \"https://goerli.optimism.io\"));\n setChainWithDefaultRpcUrl(\"arbitrum_one\", ChainData(\"Arbitrum One\", 42161, \"https://arb1.arbitrum.io/rpc\"));\n setChainWithDefaultRpcUrl(\n \"arbitrum_one_goerli\", ChainData(\"Arbitrum One Goerli\", 421613, \"https://goerli-rollup.arbitrum.io/rpc\")\n );\n setChainWithDefaultRpcUrl(\"arbitrum_nova\", ChainData(\"Arbitrum Nova\", 42170, \"https://nova.arbitrum.io/rpc\"));\n setChainWithDefaultRpcUrl(\"polygon\", ChainData(\"Polygon\", 137, \"https://polygon-rpc.com\"));\n setChainWithDefaultRpcUrl(\n \"polygon_mumbai\", ChainData(\"Polygon Mumbai\", 80001, \"https://rpc-mumbai.maticvigil.com\")\n );\n setChainWithDefaultRpcUrl(\"avalanche\", ChainData(\"Avalanche\", 43114, \"https://api.avax.network/ext/bc/C/rpc\"));\n setChainWithDefaultRpcUrl(\n \"avalanche_fuji\", ChainData(\"Avalanche Fuji\", 43113, \"https://api.avax-test.network/ext/bc/C/rpc\")\n );\n setChainWithDefaultRpcUrl(\n \"bnb_smart_chain\", ChainData(\"BNB Smart Chain\", 56, \"https://bsc-dataseed1.binance.org\")\n );\n setChainWithDefaultRpcUrl(\n \"bnb_smart_chain_testnet\",\n ChainData(\"BNB Smart Chain Testnet\", 97, \"https://rpc.ankr.com/bsc_testnet_chapel\")\n );\n setChainWithDefaultRpcUrl(\"gnosis_chain\", ChainData(\"Gnosis Chain\", 100, \"https://rpc.gnosischain.com\"));\n }\n\n // set chain info, with priority to chainAlias' rpc url in foundry.toml\n function setChainWithDefaultRpcUrl(string memory chainAlias, ChainData memory chain) private {\n string memory rpcUrl = chain.rpcUrl;\n defaultRpcUrls[chainAlias] = rpcUrl;\n chain.rpcUrl = \"\";\n setChain(chainAlias, chain);\n chain.rpcUrl = rpcUrl; // restore argument\n }\n}\n" + }, + "forge-std/StdCheats.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\nimport {StdStorage, stdStorage} from \"./StdStorage.sol\";\nimport {Vm} from \"./Vm.sol\";\n\nabstract contract StdCheatsSafe {\n Vm private constant vm = Vm(address(uint160(uint256(keccak256(\"hevm cheat code\")))));\n\n bool private gasMeteringOff;\n\n // Data structures to parse Transaction objects from the broadcast artifact\n // that conform to EIP1559. The Raw structs is what is parsed from the JSON\n // and then converted to the one that is used by the user for better UX.\n\n struct RawTx1559 {\n string[] arguments;\n address contractAddress;\n string contractName;\n // json value name = function\n string functionSig;\n bytes32 hash;\n // json value name = tx\n RawTx1559Detail txDetail;\n // json value name = type\n string opcode;\n }\n\n struct RawTx1559Detail {\n AccessList[] accessList;\n bytes data;\n address from;\n bytes gas;\n bytes nonce;\n address to;\n bytes txType;\n bytes value;\n }\n\n struct Tx1559 {\n string[] arguments;\n address contractAddress;\n string contractName;\n string functionSig;\n bytes32 hash;\n Tx1559Detail txDetail;\n string opcode;\n }\n\n struct Tx1559Detail {\n AccessList[] accessList;\n bytes data;\n address from;\n uint256 gas;\n uint256 nonce;\n address to;\n uint256 txType;\n uint256 value;\n }\n\n // Data structures to parse Transaction objects from the broadcast artifact\n // that DO NOT conform to EIP1559. The Raw structs is what is parsed from the JSON\n // and then converted to the one that is used by the user for better UX.\n\n struct TxLegacy {\n string[] arguments;\n address contractAddress;\n string contractName;\n string functionSig;\n string hash;\n string opcode;\n TxDetailLegacy transaction;\n }\n\n struct TxDetailLegacy {\n AccessList[] accessList;\n uint256 chainId;\n bytes data;\n address from;\n uint256 gas;\n uint256 gasPrice;\n bytes32 hash;\n uint256 nonce;\n bytes1 opcode;\n bytes32 r;\n bytes32 s;\n uint256 txType;\n address to;\n uint8 v;\n uint256 value;\n }\n\n struct AccessList {\n address accessAddress;\n bytes32[] storageKeys;\n }\n\n // Data structures to parse Receipt objects from the broadcast artifact.\n // The Raw structs is what is parsed from the JSON\n // and then converted to the one that is used by the user for better UX.\n\n struct RawReceipt {\n bytes32 blockHash;\n bytes blockNumber;\n address contractAddress;\n bytes cumulativeGasUsed;\n bytes effectiveGasPrice;\n address from;\n bytes gasUsed;\n RawReceiptLog[] logs;\n bytes logsBloom;\n bytes status;\n address to;\n bytes32 transactionHash;\n bytes transactionIndex;\n }\n\n struct Receipt {\n bytes32 blockHash;\n uint256 blockNumber;\n address contractAddress;\n uint256 cumulativeGasUsed;\n uint256 effectiveGasPrice;\n address from;\n uint256 gasUsed;\n ReceiptLog[] logs;\n bytes logsBloom;\n uint256 status;\n address to;\n bytes32 transactionHash;\n uint256 transactionIndex;\n }\n\n // Data structures to parse the entire broadcast artifact, assuming the\n // transactions conform to EIP1559.\n\n struct EIP1559ScriptArtifact {\n string[] libraries;\n string path;\n string[] pending;\n Receipt[] receipts;\n uint256 timestamp;\n Tx1559[] transactions;\n TxReturn[] txReturns;\n }\n\n struct RawEIP1559ScriptArtifact {\n string[] libraries;\n string path;\n string[] pending;\n RawReceipt[] receipts;\n TxReturn[] txReturns;\n uint256 timestamp;\n RawTx1559[] transactions;\n }\n\n struct RawReceiptLog {\n // json value = address\n address logAddress;\n bytes32 blockHash;\n bytes blockNumber;\n bytes data;\n bytes logIndex;\n bool removed;\n bytes32[] topics;\n bytes32 transactionHash;\n bytes transactionIndex;\n bytes transactionLogIndex;\n }\n\n struct ReceiptLog {\n // json value = address\n address logAddress;\n bytes32 blockHash;\n uint256 blockNumber;\n bytes data;\n uint256 logIndex;\n bytes32[] topics;\n uint256 transactionIndex;\n uint256 transactionLogIndex;\n bool removed;\n }\n\n struct TxReturn {\n string internalType;\n string value;\n }\n\n function assumeNoPrecompiles(address addr) internal virtual {\n // Assembly required since `block.chainid` was introduced in 0.8.0.\n uint256 chainId;\n assembly {\n chainId := chainid()\n }\n assumeNoPrecompiles(addr, chainId);\n }\n\n function assumeNoPrecompiles(address addr, uint256 chainId) internal pure virtual {\n // Note: For some chains like Optimism these are technically predeploys (i.e. bytecode placed at a specific\n // address), but the same rationale for excluding them applies so we include those too.\n\n // These should be present on all EVM-compatible chains.\n vm.assume(addr < address(0x1) || addr > address(0x9));\n\n // forgefmt: disable-start\n if (chainId == 10 || chainId == 420) {\n // https://github.com/ethereum-optimism/optimism/blob/eaa371a0184b56b7ca6d9eb9cb0a2b78b2ccd864/op-bindings/predeploys/addresses.go#L6-L21\n vm.assume(addr < address(0x4200000000000000000000000000000000000000) || addr > address(0x4200000000000000000000000000000000000800));\n } else if (chainId == 42161 || chainId == 421613) {\n // https://developer.arbitrum.io/useful-addresses#arbitrum-precompiles-l2-same-on-all-arb-chains\n vm.assume(addr < address(0x0000000000000000000000000000000000000064) || addr > address(0x0000000000000000000000000000000000000068));\n } else if (chainId == 43114 || chainId == 43113) {\n // https://github.com/ava-labs/subnet-evm/blob/47c03fd007ecaa6de2c52ea081596e0a88401f58/precompile/params.go#L18-L59\n vm.assume(addr < address(0x0100000000000000000000000000000000000000) || addr > address(0x01000000000000000000000000000000000000ff));\n vm.assume(addr < address(0x0200000000000000000000000000000000000000) || addr > address(0x02000000000000000000000000000000000000FF));\n vm.assume(addr < address(0x0300000000000000000000000000000000000000) || addr > address(0x03000000000000000000000000000000000000Ff));\n }\n // forgefmt: disable-end\n }\n\n function readEIP1559ScriptArtifact(string memory path)\n internal\n view\n virtual\n returns (EIP1559ScriptArtifact memory)\n {\n string memory data = vm.readFile(path);\n bytes memory parsedData = vm.parseJson(data);\n RawEIP1559ScriptArtifact memory rawArtifact = abi.decode(parsedData, (RawEIP1559ScriptArtifact));\n EIP1559ScriptArtifact memory artifact;\n artifact.libraries = rawArtifact.libraries;\n artifact.path = rawArtifact.path;\n artifact.timestamp = rawArtifact.timestamp;\n artifact.pending = rawArtifact.pending;\n artifact.txReturns = rawArtifact.txReturns;\n artifact.receipts = rawToConvertedReceipts(rawArtifact.receipts);\n artifact.transactions = rawToConvertedEIPTx1559s(rawArtifact.transactions);\n return artifact;\n }\n\n function rawToConvertedEIPTx1559s(RawTx1559[] memory rawTxs) internal pure virtual returns (Tx1559[] memory) {\n Tx1559[] memory txs = new Tx1559[](rawTxs.length);\n for (uint256 i; i < rawTxs.length; i++) {\n txs[i] = rawToConvertedEIPTx1559(rawTxs[i]);\n }\n return txs;\n }\n\n function rawToConvertedEIPTx1559(RawTx1559 memory rawTx) internal pure virtual returns (Tx1559 memory) {\n Tx1559 memory transaction;\n transaction.arguments = rawTx.arguments;\n transaction.contractName = rawTx.contractName;\n transaction.functionSig = rawTx.functionSig;\n transaction.hash = rawTx.hash;\n transaction.txDetail = rawToConvertedEIP1559Detail(rawTx.txDetail);\n transaction.opcode = rawTx.opcode;\n return transaction;\n }\n\n function rawToConvertedEIP1559Detail(RawTx1559Detail memory rawDetail)\n internal\n pure\n virtual\n returns (Tx1559Detail memory)\n {\n Tx1559Detail memory txDetail;\n txDetail.data = rawDetail.data;\n txDetail.from = rawDetail.from;\n txDetail.to = rawDetail.to;\n txDetail.nonce = _bytesToUint(rawDetail.nonce);\n txDetail.txType = _bytesToUint(rawDetail.txType);\n txDetail.value = _bytesToUint(rawDetail.value);\n txDetail.gas = _bytesToUint(rawDetail.gas);\n txDetail.accessList = rawDetail.accessList;\n return txDetail;\n }\n\n function readTx1559s(string memory path) internal view virtual returns (Tx1559[] memory) {\n string memory deployData = vm.readFile(path);\n bytes memory parsedDeployData = vm.parseJson(deployData, \".transactions\");\n RawTx1559[] memory rawTxs = abi.decode(parsedDeployData, (RawTx1559[]));\n return rawToConvertedEIPTx1559s(rawTxs);\n }\n\n function readTx1559(string memory path, uint256 index) internal view virtual returns (Tx1559 memory) {\n string memory deployData = vm.readFile(path);\n string memory key = string(abi.encodePacked(\".transactions[\", vm.toString(index), \"]\"));\n bytes memory parsedDeployData = vm.parseJson(deployData, key);\n RawTx1559 memory rawTx = abi.decode(parsedDeployData, (RawTx1559));\n return rawToConvertedEIPTx1559(rawTx);\n }\n\n // Analogous to readTransactions, but for receipts.\n function readReceipts(string memory path) internal view virtual returns (Receipt[] memory) {\n string memory deployData = vm.readFile(path);\n bytes memory parsedDeployData = vm.parseJson(deployData, \".receipts\");\n RawReceipt[] memory rawReceipts = abi.decode(parsedDeployData, (RawReceipt[]));\n return rawToConvertedReceipts(rawReceipts);\n }\n\n function readReceipt(string memory path, uint256 index) internal view virtual returns (Receipt memory) {\n string memory deployData = vm.readFile(path);\n string memory key = string(abi.encodePacked(\".receipts[\", vm.toString(index), \"]\"));\n bytes memory parsedDeployData = vm.parseJson(deployData, key);\n RawReceipt memory rawReceipt = abi.decode(parsedDeployData, (RawReceipt));\n return rawToConvertedReceipt(rawReceipt);\n }\n\n function rawToConvertedReceipts(RawReceipt[] memory rawReceipts) internal pure virtual returns (Receipt[] memory) {\n Receipt[] memory receipts = new Receipt[](rawReceipts.length);\n for (uint256 i; i < rawReceipts.length; i++) {\n receipts[i] = rawToConvertedReceipt(rawReceipts[i]);\n }\n return receipts;\n }\n\n function rawToConvertedReceipt(RawReceipt memory rawReceipt) internal pure virtual returns (Receipt memory) {\n Receipt memory receipt;\n receipt.blockHash = rawReceipt.blockHash;\n receipt.to = rawReceipt.to;\n receipt.from = rawReceipt.from;\n receipt.contractAddress = rawReceipt.contractAddress;\n receipt.effectiveGasPrice = _bytesToUint(rawReceipt.effectiveGasPrice);\n receipt.cumulativeGasUsed = _bytesToUint(rawReceipt.cumulativeGasUsed);\n receipt.gasUsed = _bytesToUint(rawReceipt.gasUsed);\n receipt.status = _bytesToUint(rawReceipt.status);\n receipt.transactionIndex = _bytesToUint(rawReceipt.transactionIndex);\n receipt.blockNumber = _bytesToUint(rawReceipt.blockNumber);\n receipt.logs = rawToConvertedReceiptLogs(rawReceipt.logs);\n receipt.logsBloom = rawReceipt.logsBloom;\n receipt.transactionHash = rawReceipt.transactionHash;\n return receipt;\n }\n\n function rawToConvertedReceiptLogs(RawReceiptLog[] memory rawLogs)\n internal\n pure\n virtual\n returns (ReceiptLog[] memory)\n {\n ReceiptLog[] memory logs = new ReceiptLog[](rawLogs.length);\n for (uint256 i; i < rawLogs.length; i++) {\n logs[i].logAddress = rawLogs[i].logAddress;\n logs[i].blockHash = rawLogs[i].blockHash;\n logs[i].blockNumber = _bytesToUint(rawLogs[i].blockNumber);\n logs[i].data = rawLogs[i].data;\n logs[i].logIndex = _bytesToUint(rawLogs[i].logIndex);\n logs[i].topics = rawLogs[i].topics;\n logs[i].transactionIndex = _bytesToUint(rawLogs[i].transactionIndex);\n logs[i].transactionLogIndex = _bytesToUint(rawLogs[i].transactionLogIndex);\n logs[i].removed = rawLogs[i].removed;\n }\n return logs;\n }\n\n // Deploy a contract by fetching the contract bytecode from\n // the artifacts directory\n // e.g. `deployCode(code, abi.encode(arg1,arg2,arg3))`\n function deployCode(string memory what, bytes memory args) internal virtual returns (address addr) {\n bytes memory bytecode = abi.encodePacked(vm.getCode(what), args);\n /// @solidity memory-safe-assembly\n assembly {\n addr := create(0, add(bytecode, 0x20), mload(bytecode))\n }\n\n require(addr != address(0), \"StdCheats deployCode(string,bytes): Deployment failed.\");\n }\n\n function deployCode(string memory what) internal virtual returns (address addr) {\n bytes memory bytecode = vm.getCode(what);\n /// @solidity memory-safe-assembly\n assembly {\n addr := create(0, add(bytecode, 0x20), mload(bytecode))\n }\n\n require(addr != address(0), \"StdCheats deployCode(string): Deployment failed.\");\n }\n\n /// @dev deploy contract with value on construction\n function deployCode(string memory what, bytes memory args, uint256 val) internal virtual returns (address addr) {\n bytes memory bytecode = abi.encodePacked(vm.getCode(what), args);\n /// @solidity memory-safe-assembly\n assembly {\n addr := create(val, add(bytecode, 0x20), mload(bytecode))\n }\n\n require(addr != address(0), \"StdCheats deployCode(string,bytes,uint256): Deployment failed.\");\n }\n\n function deployCode(string memory what, uint256 val) internal virtual returns (address addr) {\n bytes memory bytecode = vm.getCode(what);\n /// @solidity memory-safe-assembly\n assembly {\n addr := create(val, add(bytecode, 0x20), mload(bytecode))\n }\n\n require(addr != address(0), \"StdCheats deployCode(string,uint256): Deployment failed.\");\n }\n\n // creates a labeled address and the corresponding private key\n function makeAddrAndKey(string memory name) internal virtual returns (address addr, uint256 privateKey) {\n privateKey = uint256(keccak256(abi.encodePacked(name)));\n addr = vm.addr(privateKey);\n vm.label(addr, name);\n }\n\n // creates a labeled address\n function makeAddr(string memory name) internal virtual returns (address addr) {\n (addr,) = makeAddrAndKey(name);\n }\n\n function deriveRememberKey(string memory mnemonic, uint32 index)\n internal\n virtual\n returns (address who, uint256 privateKey)\n {\n privateKey = vm.deriveKey(mnemonic, index);\n who = vm.rememberKey(privateKey);\n }\n\n function _bytesToUint(bytes memory b) private pure returns (uint256) {\n require(b.length <= 32, \"StdCheats _bytesToUint(bytes): Bytes length exceeds 32.\");\n return abi.decode(abi.encodePacked(new bytes(32 - b.length), b), (uint256));\n }\n\n function isFork() internal view virtual returns (bool status) {\n try vm.activeFork() {\n status = true;\n } catch (bytes memory) {}\n }\n\n modifier skipWhenForking() {\n if (!isFork()) {\n _;\n }\n }\n\n modifier skipWhenNotForking() {\n if (isFork()) {\n _;\n }\n }\n\n modifier noGasMetering() {\n vm.pauseGasMetering();\n // To prevent turning gas monitoring back on with nested functions that use this modifier,\n // we check if gasMetering started in the off position. If it did, we don't want to turn\n // it back on until we exit the top level function that used the modifier\n //\n // i.e. funcA() noGasMetering { funcB() }, where funcB has noGasMetering as well.\n // funcA will have `gasStartedOff` as false, funcB will have it as true,\n // so we only turn metering back on at the end of the funcA\n bool gasStartedOff = gasMeteringOff;\n gasMeteringOff = true;\n\n _;\n\n // if gas metering was on when this modifier was called, turn it back on at the end\n if (!gasStartedOff) {\n gasMeteringOff = false;\n vm.resumeGasMetering();\n }\n }\n\n // a cheat for fuzzing addresses that are payable only\n // see https://github.com/foundry-rs/foundry/issues/3631\n function assumePayable(address addr) internal virtual {\n (bool success,) = payable(addr).call{value: 0}(\"\");\n vm.assume(success);\n }\n}\n\n// Wrappers around cheatcodes to avoid footguns\nabstract contract StdCheats is StdCheatsSafe {\n using stdStorage for StdStorage;\n\n StdStorage private stdstore;\n Vm private constant vm = Vm(address(uint160(uint256(keccak256(\"hevm cheat code\")))));\n\n // Skip forward or rewind time by the specified number of seconds\n function skip(uint256 time) internal virtual {\n vm.warp(block.timestamp + time);\n }\n\n function rewind(uint256 time) internal virtual {\n vm.warp(block.timestamp - time);\n }\n\n // Setup a prank from an address that has some ether\n function hoax(address msgSender) internal virtual {\n vm.deal(msgSender, 1 << 128);\n vm.prank(msgSender);\n }\n\n function hoax(address msgSender, uint256 give) internal virtual {\n vm.deal(msgSender, give);\n vm.prank(msgSender);\n }\n\n function hoax(address msgSender, address origin) internal virtual {\n vm.deal(msgSender, 1 << 128);\n vm.prank(msgSender, origin);\n }\n\n function hoax(address msgSender, address origin, uint256 give) internal virtual {\n vm.deal(msgSender, give);\n vm.prank(msgSender, origin);\n }\n\n // Start perpetual prank from an address that has some ether\n function startHoax(address msgSender) internal virtual {\n vm.deal(msgSender, 1 << 128);\n vm.startPrank(msgSender);\n }\n\n function startHoax(address msgSender, uint256 give) internal virtual {\n vm.deal(msgSender, give);\n vm.startPrank(msgSender);\n }\n\n // Start perpetual prank from an address that has some ether\n // tx.origin is set to the origin parameter\n function startHoax(address msgSender, address origin) internal virtual {\n vm.deal(msgSender, 1 << 128);\n vm.startPrank(msgSender, origin);\n }\n\n function startHoax(address msgSender, address origin, uint256 give) internal virtual {\n vm.deal(msgSender, give);\n vm.startPrank(msgSender, origin);\n }\n\n function changePrank(address msgSender) internal virtual {\n vm.stopPrank();\n vm.startPrank(msgSender);\n }\n\n // The same as Vm's `deal`\n // Use the alternative signature for ERC20 tokens\n function deal(address to, uint256 give) internal virtual {\n vm.deal(to, give);\n }\n\n // Set the balance of an account for any ERC20 token\n // Use the alternative signature to update `totalSupply`\n function deal(address token, address to, uint256 give) internal virtual {\n deal(token, to, give, false);\n }\n\n // Set the balance of an account for any ERC1155 token\n // Use the alternative signature to update `totalSupply`\n function dealERC1155(address token, address to, uint256 id, uint256 give) internal virtual {\n dealERC1155(token, to, id, give, false);\n }\n\n function deal(address token, address to, uint256 give, bool adjust) internal virtual {\n // get current balance\n (, bytes memory balData) = token.call(abi.encodeWithSelector(0x70a08231, to));\n uint256 prevBal = abi.decode(balData, (uint256));\n\n // update balance\n stdstore.target(token).sig(0x70a08231).with_key(to).checked_write(give);\n\n // update total supply\n if (adjust) {\n (, bytes memory totSupData) = token.call(abi.encodeWithSelector(0x18160ddd));\n uint256 totSup = abi.decode(totSupData, (uint256));\n if (give < prevBal) {\n totSup -= (prevBal - give);\n } else {\n totSup += (give - prevBal);\n }\n stdstore.target(token).sig(0x18160ddd).checked_write(totSup);\n }\n }\n\n function dealERC1155(address token, address to, uint256 id, uint256 give, bool adjust) internal virtual {\n // get current balance\n (, bytes memory balData) = token.call(abi.encodeWithSelector(0x00fdd58e, to, id));\n uint256 prevBal = abi.decode(balData, (uint256));\n\n // update balance\n stdstore.target(token).sig(0x00fdd58e).with_key(to).with_key(id).checked_write(give);\n\n // update total supply\n if (adjust) {\n (, bytes memory totSupData) = token.call(abi.encodeWithSelector(0xbd85b039, id));\n require(\n totSupData.length != 0,\n \"StdCheats deal(address,address,uint,uint,bool): target contract is not ERC1155Supply.\"\n );\n uint256 totSup = abi.decode(totSupData, (uint256));\n if (give < prevBal) {\n totSup -= (prevBal - give);\n } else {\n totSup += (give - prevBal);\n }\n stdstore.target(token).sig(0xbd85b039).with_key(id).checked_write(totSup);\n }\n }\n\n function dealERC721(address token, address to, uint256 id) internal virtual {\n // check if token id is already minted and the actual owner.\n (bool successMinted, bytes memory ownerData) = token.staticcall(abi.encodeWithSelector(0x6352211e, id));\n require(successMinted, \"StdCheats deal(address,address,uint,bool): id not minted.\");\n\n // get owner current balance\n (, bytes memory fromBalData) = token.call(abi.encodeWithSelector(0x70a08231, abi.decode(ownerData, (address))));\n uint256 fromPrevBal = abi.decode(fromBalData, (uint256));\n\n // get new user current balance\n (, bytes memory toBalData) = token.call(abi.encodeWithSelector(0x70a08231, to));\n uint256 toPrevBal = abi.decode(toBalData, (uint256));\n\n // update balances\n stdstore.target(token).sig(0x70a08231).with_key(abi.decode(ownerData, (address))).checked_write(--fromPrevBal);\n stdstore.target(token).sig(0x70a08231).with_key(to).checked_write(++toPrevBal);\n\n // update owner\n stdstore.target(token).sig(0x6352211e).with_key(id).checked_write(to);\n }\n}\n" + }, + "forge-std/StdError.sol": { + "content": "// SPDX-License-Identifier: MIT\n// Panics work for versions >=0.8.0, but we lowered the pragma to make this compatible with Test\npragma solidity >=0.6.2 <0.9.0;\n\nlibrary stdError {\n bytes public constant assertionError = abi.encodeWithSignature(\"Panic(uint256)\", 0x01);\n bytes public constant arithmeticError = abi.encodeWithSignature(\"Panic(uint256)\", 0x11);\n bytes public constant divisionError = abi.encodeWithSignature(\"Panic(uint256)\", 0x12);\n bytes public constant enumConversionError = abi.encodeWithSignature(\"Panic(uint256)\", 0x21);\n bytes public constant encodeStorageError = abi.encodeWithSignature(\"Panic(uint256)\", 0x22);\n bytes public constant popError = abi.encodeWithSignature(\"Panic(uint256)\", 0x31);\n bytes public constant indexOOBError = abi.encodeWithSignature(\"Panic(uint256)\", 0x32);\n bytes public constant memOverflowError = abi.encodeWithSignature(\"Panic(uint256)\", 0x41);\n bytes public constant zeroVarError = abi.encodeWithSignature(\"Panic(uint256)\", 0x51);\n}\n" + }, + "forge-std/StdInvariant.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\ncontract StdInvariant {\n struct FuzzSelector {\n address addr;\n bytes4[] selectors;\n }\n\n address[] private _excludedContracts;\n address[] private _excludedSenders;\n address[] private _targetedContracts;\n address[] private _targetedSenders;\n\n string[] private _excludedArtifacts;\n string[] private _targetedArtifacts;\n\n FuzzSelector[] private _targetedArtifactSelectors;\n FuzzSelector[] private _targetedSelectors;\n\n // Functions for users:\n // These are intended to be called in tests.\n\n function excludeContract(address newExcludedContract_) internal {\n _excludedContracts.push(newExcludedContract_);\n }\n\n function excludeSender(address newExcludedSender_) internal {\n _excludedSenders.push(newExcludedSender_);\n }\n\n function excludeArtifact(string memory newExcludedArtifact_) internal {\n _excludedArtifacts.push(newExcludedArtifact_);\n }\n\n function targetArtifact(string memory newTargetedArtifact_) internal {\n _targetedArtifacts.push(newTargetedArtifact_);\n }\n\n function targetArtifactSelector(FuzzSelector memory newTargetedArtifactSelector_) internal {\n _targetedArtifactSelectors.push(newTargetedArtifactSelector_);\n }\n\n function targetContract(address newTargetedContract_) internal {\n _targetedContracts.push(newTargetedContract_);\n }\n\n function targetSelector(FuzzSelector memory newTargetedSelector_) internal {\n _targetedSelectors.push(newTargetedSelector_);\n }\n\n function targetSender(address newTargetedSender_) internal {\n _targetedSenders.push(newTargetedSender_);\n }\n\n // Functions for forge:\n // These are called by forge to run invariant tests and don't need to be called in tests.\n\n function excludeArtifacts() public view returns (string[] memory excludedArtifacts_) {\n excludedArtifacts_ = _excludedArtifacts;\n }\n\n function excludeContracts() public view returns (address[] memory excludedContracts_) {\n excludedContracts_ = _excludedContracts;\n }\n\n function excludeSenders() public view returns (address[] memory excludedSenders_) {\n excludedSenders_ = _excludedSenders;\n }\n\n function targetArtifacts() public view returns (string[] memory targetedArtifacts_) {\n targetedArtifacts_ = _targetedArtifacts;\n }\n\n function targetArtifactSelectors() public view returns (FuzzSelector[] memory targetedArtifactSelectors_) {\n targetedArtifactSelectors_ = _targetedArtifactSelectors;\n }\n\n function targetContracts() public view returns (address[] memory targetedContracts_) {\n targetedContracts_ = _targetedContracts;\n }\n\n function targetSelectors() public view returns (FuzzSelector[] memory targetedSelectors_) {\n targetedSelectors_ = _targetedSelectors;\n }\n\n function targetSenders() public view returns (address[] memory targetedSenders_) {\n targetedSenders_ = _targetedSenders;\n }\n}\n" + }, + "forge-std/StdJson.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.0 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\nimport {VmSafe} from \"./Vm.sol\";\n\n// Helpers for parsing and writing JSON files\n// To parse:\n// ```\n// using stdJson for string;\n// string memory json = vm.readFile(\"some_peth\");\n// json.parseUint(\"\");\n// ```\n// To write:\n// ```\n// using stdJson for string;\n// string memory json = \"deploymentArtifact\";\n// Contract contract = new Contract();\n// json.serialize(\"contractAddress\", address(contract));\n// json = json.serialize(\"deploymentTimes\", uint(1));\n// // store the stringified JSON to the 'json' variable we have been using as a key\n// // as we won't need it any longer\n// string memory json2 = \"finalArtifact\";\n// string memory final = json2.serialize(\"depArtifact\", json);\n// final.write(\"\");\n// ```\n\nlibrary stdJson {\n VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256(\"hevm cheat code\")))));\n\n function parseRaw(string memory json, string memory key) internal pure returns (bytes memory) {\n return vm.parseJson(json, key);\n }\n\n function readUint(string memory json, string memory key) internal returns (uint256) {\n return vm.parseJsonUint(json, key);\n }\n\n function readUintArray(string memory json, string memory key) internal returns (uint256[] memory) {\n return vm.parseJsonUintArray(json, key);\n }\n\n function readInt(string memory json, string memory key) internal returns (int256) {\n return vm.parseJsonInt(json, key);\n }\n\n function readIntArray(string memory json, string memory key) internal returns (int256[] memory) {\n return vm.parseJsonIntArray(json, key);\n }\n\n function readBytes32(string memory json, string memory key) internal returns (bytes32) {\n return vm.parseJsonBytes32(json, key);\n }\n\n function readBytes32Array(string memory json, string memory key) internal returns (bytes32[] memory) {\n return vm.parseJsonBytes32Array(json, key);\n }\n\n function readString(string memory json, string memory key) internal returns (string memory) {\n return vm.parseJsonString(json, key);\n }\n\n function readStringArray(string memory json, string memory key) internal returns (string[] memory) {\n return vm.parseJsonStringArray(json, key);\n }\n\n function readAddress(string memory json, string memory key) internal returns (address) {\n return vm.parseJsonAddress(json, key);\n }\n\n function readAddressArray(string memory json, string memory key) internal returns (address[] memory) {\n return vm.parseJsonAddressArray(json, key);\n }\n\n function readBool(string memory json, string memory key) internal returns (bool) {\n return vm.parseJsonBool(json, key);\n }\n\n function readBoolArray(string memory json, string memory key) internal returns (bool[] memory) {\n return vm.parseJsonBoolArray(json, key);\n }\n\n function readBytes(string memory json, string memory key) internal returns (bytes memory) {\n return vm.parseJsonBytes(json, key);\n }\n\n function readBytesArray(string memory json, string memory key) internal returns (bytes[] memory) {\n return vm.parseJsonBytesArray(json, key);\n }\n\n function serialize(string memory jsonKey, string memory key, bool value) internal returns (string memory) {\n return vm.serializeBool(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, bool[] memory value)\n internal\n returns (string memory)\n {\n return vm.serializeBool(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, uint256 value) internal returns (string memory) {\n return vm.serializeUint(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, uint256[] memory value)\n internal\n returns (string memory)\n {\n return vm.serializeUint(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, int256 value) internal returns (string memory) {\n return vm.serializeInt(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, int256[] memory value)\n internal\n returns (string memory)\n {\n return vm.serializeInt(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, address value) internal returns (string memory) {\n return vm.serializeAddress(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, address[] memory value)\n internal\n returns (string memory)\n {\n return vm.serializeAddress(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, bytes32 value) internal returns (string memory) {\n return vm.serializeBytes32(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, bytes32[] memory value)\n internal\n returns (string memory)\n {\n return vm.serializeBytes32(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, bytes memory value) internal returns (string memory) {\n return vm.serializeBytes(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, bytes[] memory value)\n internal\n returns (string memory)\n {\n return vm.serializeBytes(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, string memory value)\n internal\n returns (string memory)\n {\n return vm.serializeString(jsonKey, key, value);\n }\n\n function serialize(string memory jsonKey, string memory key, string[] memory value)\n internal\n returns (string memory)\n {\n return vm.serializeString(jsonKey, key, value);\n }\n\n function write(string memory jsonKey, string memory path) internal {\n vm.writeJson(jsonKey, path);\n }\n\n function write(string memory jsonKey, string memory path, string memory valueKey) internal {\n vm.writeJson(jsonKey, path, valueKey);\n }\n}\n" + }, + "forge-std/StdMath.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\nlibrary stdMath {\n int256 private constant INT256_MIN = -57896044618658097711785492504343953926634992332820282019728792003956564819968;\n\n function abs(int256 a) internal pure returns (uint256) {\n // Required or it will fail when `a = type(int256).min`\n if (a == INT256_MIN) {\n return 57896044618658097711785492504343953926634992332820282019728792003956564819968;\n }\n\n return uint256(a > 0 ? a : -a);\n }\n\n function delta(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a - b : b - a;\n }\n\n function delta(int256 a, int256 b) internal pure returns (uint256) {\n // a and b are of the same sign\n // this works thanks to two's complement, the left-most bit is the sign bit\n if ((a ^ b) > -1) {\n return delta(abs(a), abs(b));\n }\n\n // a and b are of opposite signs\n return abs(a) + abs(b);\n }\n\n function percentDelta(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 absDelta = delta(a, b);\n\n return absDelta * 1e18 / b;\n }\n\n function percentDelta(int256 a, int256 b) internal pure returns (uint256) {\n uint256 absDelta = delta(a, b);\n uint256 absB = abs(b);\n\n return absDelta * 1e18 / absB;\n }\n}\n" + }, + "forge-std/StdStorage.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\nimport {Vm} from \"./Vm.sol\";\n\nstruct StdStorage {\n mapping(address => mapping(bytes4 => mapping(bytes32 => uint256))) slots;\n mapping(address => mapping(bytes4 => mapping(bytes32 => bool))) finds;\n bytes32[] _keys;\n bytes4 _sig;\n uint256 _depth;\n address _target;\n bytes32 _set;\n}\n\nlibrary stdStorageSafe {\n event SlotFound(address who, bytes4 fsig, bytes32 keysHash, uint256 slot);\n event WARNING_UninitedSlot(address who, uint256 slot);\n\n Vm private constant vm = Vm(address(uint160(uint256(keccak256(\"hevm cheat code\")))));\n\n function sigs(string memory sigStr) internal pure returns (bytes4) {\n return bytes4(keccak256(bytes(sigStr)));\n }\n\n /// @notice find an arbitrary storage slot given a function sig, input data, address of the contract and a value to check against\n // slot complexity:\n // if flat, will be bytes32(uint256(uint));\n // if map, will be keccak256(abi.encode(key, uint(slot)));\n // if deep map, will be keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))));\n // if map struct, will be bytes32(uint256(keccak256(abi.encode(key1, keccak256(abi.encode(key0, uint(slot)))))) + structFieldDepth);\n function find(StdStorage storage self) internal returns (uint256) {\n address who = self._target;\n bytes4 fsig = self._sig;\n uint256 field_depth = self._depth;\n bytes32[] memory ins = self._keys;\n\n // calldata to test against\n if (self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]) {\n return self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))];\n }\n bytes memory cald = abi.encodePacked(fsig, flatten(ins));\n vm.record();\n bytes32 fdat;\n {\n (, bytes memory rdat) = who.staticcall(cald);\n fdat = bytesToBytes32(rdat, 32 * field_depth);\n }\n\n (bytes32[] memory reads,) = vm.accesses(address(who));\n if (reads.length == 1) {\n bytes32 curr = vm.load(who, reads[0]);\n if (curr == bytes32(0)) {\n emit WARNING_UninitedSlot(who, uint256(reads[0]));\n }\n if (fdat != curr) {\n require(\n false,\n \"stdStorage find(StdStorage): Packed slot. This would cause dangerous overwriting and currently isn't supported.\"\n );\n }\n emit SlotFound(who, fsig, keccak256(abi.encodePacked(ins, field_depth)), uint256(reads[0]));\n self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = uint256(reads[0]);\n self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = true;\n } else if (reads.length > 1) {\n for (uint256 i = 0; i < reads.length; i++) {\n bytes32 prev = vm.load(who, reads[i]);\n if (prev == bytes32(0)) {\n emit WARNING_UninitedSlot(who, uint256(reads[i]));\n }\n // store\n vm.store(who, reads[i], bytes32(hex\"1337\"));\n bool success;\n bytes memory rdat;\n {\n (success, rdat) = who.staticcall(cald);\n fdat = bytesToBytes32(rdat, 32 * field_depth);\n }\n\n if (success && fdat == bytes32(hex\"1337\")) {\n // we found which of the slots is the actual one\n emit SlotFound(who, fsig, keccak256(abi.encodePacked(ins, field_depth)), uint256(reads[i]));\n self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = uint256(reads[i]);\n self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))] = true;\n vm.store(who, reads[i], prev);\n break;\n }\n vm.store(who, reads[i], prev);\n }\n } else {\n revert(\"stdStorage find(StdStorage): No storage use detected for target.\");\n }\n\n require(\n self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))],\n \"stdStorage find(StdStorage): Slot(s) not found.\"\n );\n\n delete self._target;\n delete self._sig;\n delete self._keys;\n delete self._depth;\n\n return self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))];\n }\n\n function target(StdStorage storage self, address _target) internal returns (StdStorage storage) {\n self._target = _target;\n return self;\n }\n\n function sig(StdStorage storage self, bytes4 _sig) internal returns (StdStorage storage) {\n self._sig = _sig;\n return self;\n }\n\n function sig(StdStorage storage self, string memory _sig) internal returns (StdStorage storage) {\n self._sig = sigs(_sig);\n return self;\n }\n\n function with_key(StdStorage storage self, address who) internal returns (StdStorage storage) {\n self._keys.push(bytes32(uint256(uint160(who))));\n return self;\n }\n\n function with_key(StdStorage storage self, uint256 amt) internal returns (StdStorage storage) {\n self._keys.push(bytes32(amt));\n return self;\n }\n\n function with_key(StdStorage storage self, bytes32 key) internal returns (StdStorage storage) {\n self._keys.push(key);\n return self;\n }\n\n function depth(StdStorage storage self, uint256 _depth) internal returns (StdStorage storage) {\n self._depth = _depth;\n return self;\n }\n\n function read(StdStorage storage self) private returns (bytes memory) {\n address t = self._target;\n uint256 s = find(self);\n return abi.encode(vm.load(t, bytes32(s)));\n }\n\n function read_bytes32(StdStorage storage self) internal returns (bytes32) {\n return abi.decode(read(self), (bytes32));\n }\n\n function read_bool(StdStorage storage self) internal returns (bool) {\n int256 v = read_int(self);\n if (v == 0) return false;\n if (v == 1) return true;\n revert(\"stdStorage read_bool(StdStorage): Cannot decode. Make sure you are reading a bool.\");\n }\n\n function read_address(StdStorage storage self) internal returns (address) {\n return abi.decode(read(self), (address));\n }\n\n function read_uint(StdStorage storage self) internal returns (uint256) {\n return abi.decode(read(self), (uint256));\n }\n\n function read_int(StdStorage storage self) internal returns (int256) {\n return abi.decode(read(self), (int256));\n }\n\n function bytesToBytes32(bytes memory b, uint256 offset) private pure returns (bytes32) {\n bytes32 out;\n\n uint256 max = b.length > 32 ? 32 : b.length;\n for (uint256 i = 0; i < max; i++) {\n out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);\n }\n return out;\n }\n\n function flatten(bytes32[] memory b) private pure returns (bytes memory) {\n bytes memory result = new bytes(b.length * 32);\n for (uint256 i = 0; i < b.length; i++) {\n bytes32 k = b[i];\n /// @solidity memory-safe-assembly\n assembly {\n mstore(add(result, add(32, mul(32, i))), k)\n }\n }\n\n return result;\n }\n}\n\nlibrary stdStorage {\n Vm private constant vm = Vm(address(uint160(uint256(keccak256(\"hevm cheat code\")))));\n\n function sigs(string memory sigStr) internal pure returns (bytes4) {\n return stdStorageSafe.sigs(sigStr);\n }\n\n function find(StdStorage storage self) internal returns (uint256) {\n return stdStorageSafe.find(self);\n }\n\n function target(StdStorage storage self, address _target) internal returns (StdStorage storage) {\n return stdStorageSafe.target(self, _target);\n }\n\n function sig(StdStorage storage self, bytes4 _sig) internal returns (StdStorage storage) {\n return stdStorageSafe.sig(self, _sig);\n }\n\n function sig(StdStorage storage self, string memory _sig) internal returns (StdStorage storage) {\n return stdStorageSafe.sig(self, _sig);\n }\n\n function with_key(StdStorage storage self, address who) internal returns (StdStorage storage) {\n return stdStorageSafe.with_key(self, who);\n }\n\n function with_key(StdStorage storage self, uint256 amt) internal returns (StdStorage storage) {\n return stdStorageSafe.with_key(self, amt);\n }\n\n function with_key(StdStorage storage self, bytes32 key) internal returns (StdStorage storage) {\n return stdStorageSafe.with_key(self, key);\n }\n\n function depth(StdStorage storage self, uint256 _depth) internal returns (StdStorage storage) {\n return stdStorageSafe.depth(self, _depth);\n }\n\n function checked_write(StdStorage storage self, address who) internal {\n checked_write(self, bytes32(uint256(uint160(who))));\n }\n\n function checked_write(StdStorage storage self, uint256 amt) internal {\n checked_write(self, bytes32(amt));\n }\n\n function checked_write(StdStorage storage self, bool write) internal {\n bytes32 t;\n /// @solidity memory-safe-assembly\n assembly {\n t := write\n }\n checked_write(self, t);\n }\n\n function checked_write(StdStorage storage self, bytes32 set) internal {\n address who = self._target;\n bytes4 fsig = self._sig;\n uint256 field_depth = self._depth;\n bytes32[] memory ins = self._keys;\n\n bytes memory cald = abi.encodePacked(fsig, flatten(ins));\n if (!self.finds[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]) {\n find(self);\n }\n bytes32 slot = bytes32(self.slots[who][fsig][keccak256(abi.encodePacked(ins, field_depth))]);\n\n bytes32 fdat;\n {\n (, bytes memory rdat) = who.staticcall(cald);\n fdat = bytesToBytes32(rdat, 32 * field_depth);\n }\n bytes32 curr = vm.load(who, slot);\n\n if (fdat != curr) {\n require(\n false,\n \"stdStorage find(StdStorage): Packed slot. This would cause dangerous overwriting and currently isn't supported.\"\n );\n }\n vm.store(who, slot, set);\n delete self._target;\n delete self._sig;\n delete self._keys;\n delete self._depth;\n }\n\n function read_bytes32(StdStorage storage self) internal returns (bytes32) {\n return stdStorageSafe.read_bytes32(self);\n }\n\n function read_bool(StdStorage storage self) internal returns (bool) {\n return stdStorageSafe.read_bool(self);\n }\n\n function read_address(StdStorage storage self) internal returns (address) {\n return stdStorageSafe.read_address(self);\n }\n\n function read_uint(StdStorage storage self) internal returns (uint256) {\n return stdStorageSafe.read_uint(self);\n }\n\n function read_int(StdStorage storage self) internal returns (int256) {\n return stdStorageSafe.read_int(self);\n }\n\n // Private function so needs to be copied over\n function bytesToBytes32(bytes memory b, uint256 offset) private pure returns (bytes32) {\n bytes32 out;\n\n uint256 max = b.length > 32 ? 32 : b.length;\n for (uint256 i = 0; i < max; i++) {\n out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);\n }\n return out;\n }\n\n // Private function so needs to be copied over\n function flatten(bytes32[] memory b) private pure returns (bytes memory) {\n bytes memory result = new bytes(b.length * 32);\n for (uint256 i = 0; i < b.length; i++) {\n bytes32 k = b[i];\n /// @solidity memory-safe-assembly\n assembly {\n mstore(add(result, add(32, mul(32, i))), k)\n }\n }\n\n return result;\n }\n}\n" + }, + "forge-std/StdStyle.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.4.22 <0.9.0;\n\nimport {Vm} from \"./Vm.sol\";\n\nlibrary StdStyle {\n Vm private constant vm = Vm(address(uint160(uint256(keccak256(\"hevm cheat code\")))));\n\n string constant RED = \"\\u001b[91m\";\n string constant GREEN = \"\\u001b[92m\";\n string constant YELLOW = \"\\u001b[93m\";\n string constant BLUE = \"\\u001b[94m\";\n string constant MAGENTA = \"\\u001b[95m\";\n string constant CYAN = \"\\u001b[96m\";\n string constant BOLD = \"\\u001b[1m\";\n string constant DIM = \"\\u001b[2m\";\n string constant ITALIC = \"\\u001b[3m\";\n string constant UNDERLINE = \"\\u001b[4m\";\n string constant INVERSE = \"\\u001b[7m\";\n string constant RESET = \"\\u001b[0m\";\n\n function styleConcat(string memory style, string memory self) private pure returns (string memory) {\n return string(abi.encodePacked(style, self, RESET));\n }\n\n function red(string memory self) internal pure returns (string memory) {\n return styleConcat(RED, self);\n }\n\n function red(uint256 self) internal pure returns (string memory) {\n return red(vm.toString(self));\n }\n\n function red(int256 self) internal pure returns (string memory) {\n return red(vm.toString(self));\n }\n\n function red(address self) internal pure returns (string memory) {\n return red(vm.toString(self));\n }\n\n function red(bool self) internal pure returns (string memory) {\n return red(vm.toString(self));\n }\n\n function redBytes(bytes memory self) internal pure returns (string memory) {\n return red(vm.toString(self));\n }\n\n function redBytes32(bytes32 self) internal pure returns (string memory) {\n return red(vm.toString(self));\n }\n\n function green(string memory self) internal pure returns (string memory) {\n return styleConcat(GREEN, self);\n }\n\n function green(uint256 self) internal pure returns (string memory) {\n return green(vm.toString(self));\n }\n\n function green(int256 self) internal pure returns (string memory) {\n return green(vm.toString(self));\n }\n\n function green(address self) internal pure returns (string memory) {\n return green(vm.toString(self));\n }\n\n function green(bool self) internal pure returns (string memory) {\n return green(vm.toString(self));\n }\n\n function greenBytes(bytes memory self) internal pure returns (string memory) {\n return green(vm.toString(self));\n }\n\n function greenBytes32(bytes32 self) internal pure returns (string memory) {\n return green(vm.toString(self));\n }\n\n function yellow(string memory self) internal pure returns (string memory) {\n return styleConcat(YELLOW, self);\n }\n\n function yellow(uint256 self) internal pure returns (string memory) {\n return yellow(vm.toString(self));\n }\n\n function yellow(int256 self) internal pure returns (string memory) {\n return yellow(vm.toString(self));\n }\n\n function yellow(address self) internal pure returns (string memory) {\n return yellow(vm.toString(self));\n }\n\n function yellow(bool self) internal pure returns (string memory) {\n return yellow(vm.toString(self));\n }\n\n function yellowBytes(bytes memory self) internal pure returns (string memory) {\n return yellow(vm.toString(self));\n }\n\n function yellowBytes32(bytes32 self) internal pure returns (string memory) {\n return yellow(vm.toString(self));\n }\n\n function blue(string memory self) internal pure returns (string memory) {\n return styleConcat(BLUE, self);\n }\n\n function blue(uint256 self) internal pure returns (string memory) {\n return blue(vm.toString(self));\n }\n\n function blue(int256 self) internal pure returns (string memory) {\n return blue(vm.toString(self));\n }\n\n function blue(address self) internal pure returns (string memory) {\n return blue(vm.toString(self));\n }\n\n function blue(bool self) internal pure returns (string memory) {\n return blue(vm.toString(self));\n }\n\n function blueBytes(bytes memory self) internal pure returns (string memory) {\n return blue(vm.toString(self));\n }\n\n function blueBytes32(bytes32 self) internal pure returns (string memory) {\n return blue(vm.toString(self));\n }\n\n function magenta(string memory self) internal pure returns (string memory) {\n return styleConcat(MAGENTA, self);\n }\n\n function magenta(uint256 self) internal pure returns (string memory) {\n return magenta(vm.toString(self));\n }\n\n function magenta(int256 self) internal pure returns (string memory) {\n return magenta(vm.toString(self));\n }\n\n function magenta(address self) internal pure returns (string memory) {\n return magenta(vm.toString(self));\n }\n\n function magenta(bool self) internal pure returns (string memory) {\n return magenta(vm.toString(self));\n }\n\n function magentaBytes(bytes memory self) internal pure returns (string memory) {\n return magenta(vm.toString(self));\n }\n\n function magentaBytes32(bytes32 self) internal pure returns (string memory) {\n return magenta(vm.toString(self));\n }\n\n function cyan(string memory self) internal pure returns (string memory) {\n return styleConcat(CYAN, self);\n }\n\n function cyan(uint256 self) internal pure returns (string memory) {\n return cyan(vm.toString(self));\n }\n\n function cyan(int256 self) internal pure returns (string memory) {\n return cyan(vm.toString(self));\n }\n\n function cyan(address self) internal pure returns (string memory) {\n return cyan(vm.toString(self));\n }\n\n function cyan(bool self) internal pure returns (string memory) {\n return cyan(vm.toString(self));\n }\n\n function cyanBytes(bytes memory self) internal pure returns (string memory) {\n return cyan(vm.toString(self));\n }\n\n function cyanBytes32(bytes32 self) internal pure returns (string memory) {\n return cyan(vm.toString(self));\n }\n\n function bold(string memory self) internal pure returns (string memory) {\n return styleConcat(BOLD, self);\n }\n\n function bold(uint256 self) internal pure returns (string memory) {\n return bold(vm.toString(self));\n }\n\n function bold(int256 self) internal pure returns (string memory) {\n return bold(vm.toString(self));\n }\n\n function bold(address self) internal pure returns (string memory) {\n return bold(vm.toString(self));\n }\n\n function bold(bool self) internal pure returns (string memory) {\n return bold(vm.toString(self));\n }\n\n function boldBytes(bytes memory self) internal pure returns (string memory) {\n return bold(vm.toString(self));\n }\n\n function boldBytes32(bytes32 self) internal pure returns (string memory) {\n return bold(vm.toString(self));\n }\n\n function dim(string memory self) internal pure returns (string memory) {\n return styleConcat(DIM, self);\n }\n\n function dim(uint256 self) internal pure returns (string memory) {\n return dim(vm.toString(self));\n }\n\n function dim(int256 self) internal pure returns (string memory) {\n return dim(vm.toString(self));\n }\n\n function dim(address self) internal pure returns (string memory) {\n return dim(vm.toString(self));\n }\n\n function dim(bool self) internal pure returns (string memory) {\n return dim(vm.toString(self));\n }\n\n function dimBytes(bytes memory self) internal pure returns (string memory) {\n return dim(vm.toString(self));\n }\n\n function dimBytes32(bytes32 self) internal pure returns (string memory) {\n return dim(vm.toString(self));\n }\n\n function italic(string memory self) internal pure returns (string memory) {\n return styleConcat(ITALIC, self);\n }\n\n function italic(uint256 self) internal pure returns (string memory) {\n return italic(vm.toString(self));\n }\n\n function italic(int256 self) internal pure returns (string memory) {\n return italic(vm.toString(self));\n }\n\n function italic(address self) internal pure returns (string memory) {\n return italic(vm.toString(self));\n }\n\n function italic(bool self) internal pure returns (string memory) {\n return italic(vm.toString(self));\n }\n\n function italicBytes(bytes memory self) internal pure returns (string memory) {\n return italic(vm.toString(self));\n }\n\n function italicBytes32(bytes32 self) internal pure returns (string memory) {\n return italic(vm.toString(self));\n }\n\n function underline(string memory self) internal pure returns (string memory) {\n return styleConcat(UNDERLINE, self);\n }\n\n function underline(uint256 self) internal pure returns (string memory) {\n return underline(vm.toString(self));\n }\n\n function underline(int256 self) internal pure returns (string memory) {\n return underline(vm.toString(self));\n }\n\n function underline(address self) internal pure returns (string memory) {\n return underline(vm.toString(self));\n }\n\n function underline(bool self) internal pure returns (string memory) {\n return underline(vm.toString(self));\n }\n\n function underlineBytes(bytes memory self) internal pure returns (string memory) {\n return underline(vm.toString(self));\n }\n\n function underlineBytes32(bytes32 self) internal pure returns (string memory) {\n return underline(vm.toString(self));\n }\n\n function inverse(string memory self) internal pure returns (string memory) {\n return styleConcat(INVERSE, self);\n }\n\n function inverse(uint256 self) internal pure returns (string memory) {\n return inverse(vm.toString(self));\n }\n\n function inverse(int256 self) internal pure returns (string memory) {\n return inverse(vm.toString(self));\n }\n\n function inverse(address self) internal pure returns (string memory) {\n return inverse(vm.toString(self));\n }\n\n function inverse(bool self) internal pure returns (string memory) {\n return inverse(vm.toString(self));\n }\n\n function inverseBytes(bytes memory self) internal pure returns (string memory) {\n return inverse(vm.toString(self));\n }\n\n function inverseBytes32(bytes32 self) internal pure returns (string memory) {\n return inverse(vm.toString(self));\n }\n}\n" + }, + "forge-std/StdUtils.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\nimport {IMulticall3} from \"./interfaces/IMulticall3.sol\";\n// TODO Remove import.\nimport {VmSafe} from \"./Vm.sol\";\n\nabstract contract StdUtils {\n /*//////////////////////////////////////////////////////////////////////////\n CONSTANTS\n //////////////////////////////////////////////////////////////////////////*/\n\n IMulticall3 private constant multicall = IMulticall3(0xcA11bde05977b3631167028862bE2a173976CA11);\n VmSafe private constant vm = VmSafe(address(uint160(uint256(keccak256(\"hevm cheat code\")))));\n address private constant CONSOLE2_ADDRESS = 0x000000000000000000636F6e736F6c652e6c6f67;\n uint256 private constant INT256_MIN_ABS =\n 57896044618658097711785492504343953926634992332820282019728792003956564819968;\n uint256 private constant UINT256_MAX =\n 115792089237316195423570985008687907853269984665640564039457584007913129639935;\n\n // Used by default when deploying with create2, https://github.com/Arachnid/deterministic-deployment-proxy.\n address private constant CREATE2_FACTORY = 0x4e59b44847b379578588920cA78FbF26c0B4956C;\n\n /*//////////////////////////////////////////////////////////////////////////\n INTERNAL FUNCTIONS\n //////////////////////////////////////////////////////////////////////////*/\n\n function _bound(uint256 x, uint256 min, uint256 max) internal pure virtual returns (uint256 result) {\n require(min <= max, \"StdUtils bound(uint256,uint256,uint256): Max is less than min.\");\n // If x is between min and max, return x directly. This is to ensure that dictionary values\n // do not get shifted if the min is nonzero. More info: https://github.com/foundry-rs/forge-std/issues/188\n if (x >= min && x <= max) return x;\n\n uint256 size = max - min + 1;\n\n // If the value is 0, 1, 2, 3, warp that to min, min+1, min+2, min+3. Similarly for the UINT256_MAX side.\n // This helps ensure coverage of the min/max values.\n if (x <= 3 && size > x) return min + x;\n if (x >= UINT256_MAX - 3 && size > UINT256_MAX - x) return max - (UINT256_MAX - x);\n\n // Otherwise, wrap x into the range [min, max], i.e. the range is inclusive.\n if (x > max) {\n uint256 diff = x - max;\n uint256 rem = diff % size;\n if (rem == 0) return max;\n result = min + rem - 1;\n } else if (x < min) {\n uint256 diff = min - x;\n uint256 rem = diff % size;\n if (rem == 0) return min;\n result = max - rem + 1;\n }\n }\n\n function bound(uint256 x, uint256 min, uint256 max) internal view virtual returns (uint256 result) {\n result = _bound(x, min, max);\n console2_log(\"Bound Result\", result);\n }\n\n function bound(int256 x, int256 min, int256 max) internal view virtual returns (int256 result) {\n require(min <= max, \"StdUtils bound(int256,int256,int256): Max is less than min.\");\n\n // Shifting all int256 values to uint256 to use _bound function. The range of two types are:\n // int256 : -(2**255) ~ (2**255 - 1)\n // uint256: 0 ~ (2**256 - 1)\n // So, add 2**255, INT256_MIN_ABS to the integer values.\n //\n // If the given integer value is -2**255, we cannot use `-uint256(-x)` because of the overflow.\n // So, use `~uint256(x) + 1` instead.\n uint256 _x = x < 0 ? (INT256_MIN_ABS - ~uint256(x) - 1) : (uint256(x) + INT256_MIN_ABS);\n uint256 _min = min < 0 ? (INT256_MIN_ABS - ~uint256(min) - 1) : (uint256(min) + INT256_MIN_ABS);\n uint256 _max = max < 0 ? (INT256_MIN_ABS - ~uint256(max) - 1) : (uint256(max) + INT256_MIN_ABS);\n\n uint256 y = _bound(_x, _min, _max);\n\n // To move it back to int256 value, subtract INT256_MIN_ABS at here.\n result = y < INT256_MIN_ABS ? int256(~(INT256_MIN_ABS - y) + 1) : int256(y - INT256_MIN_ABS);\n console2_log(\"Bound result\", vm.toString(result));\n }\n\n function bytesToUint(bytes memory b) internal pure virtual returns (uint256) {\n require(b.length <= 32, \"StdUtils bytesToUint(bytes): Bytes length exceeds 32.\");\n return abi.decode(abi.encodePacked(new bytes(32 - b.length), b), (uint256));\n }\n\n /// @dev Compute the address a contract will be deployed at for a given deployer address and nonce\n /// @notice adapted from Solmate implementation (https://github.com/Rari-Capital/solmate/blob/main/src/utils/LibRLP.sol)\n function computeCreateAddress(address deployer, uint256 nonce) internal pure virtual returns (address) {\n // forgefmt: disable-start\n // The integer zero is treated as an empty byte string, and as a result it only has a length prefix, 0x80, computed via 0x80 + 0.\n // A one byte integer uses its own value as its length prefix, there is no additional \"0x80 + length\" prefix that comes before it.\n if (nonce == 0x00) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd6), bytes1(0x94), deployer, bytes1(0x80))));\n if (nonce <= 0x7f) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd6), bytes1(0x94), deployer, uint8(nonce))));\n\n // Nonces greater than 1 byte all follow a consistent encoding scheme, where each value is preceded by a prefix of 0x80 + length.\n if (nonce <= 2**8 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd7), bytes1(0x94), deployer, bytes1(0x81), uint8(nonce))));\n if (nonce <= 2**16 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd8), bytes1(0x94), deployer, bytes1(0x82), uint16(nonce))));\n if (nonce <= 2**24 - 1) return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xd9), bytes1(0x94), deployer, bytes1(0x83), uint24(nonce))));\n // forgefmt: disable-end\n\n // More details about RLP encoding can be found here: https://eth.wiki/fundamentals/rlp\n // 0xda = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x84 ++ nonce)\n // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex)\n // 0x84 = 0x80 + 0x04 (0x04 = the bytes length of the nonce, 4 bytes, in hex)\n // We assume nobody can have a nonce large enough to require more than 32 bytes.\n return addressFromLast20Bytes(\n keccak256(abi.encodePacked(bytes1(0xda), bytes1(0x94), deployer, bytes1(0x84), uint32(nonce)))\n );\n }\n\n function computeCreate2Address(bytes32 salt, bytes32 initcodeHash, address deployer)\n internal\n pure\n virtual\n returns (address)\n {\n return addressFromLast20Bytes(keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, initcodeHash)));\n }\n\n /// @dev returns the address of a contract created with CREATE2 using the default CREATE2 deployer\n function computeCreate2Address(bytes32 salt, bytes32 initCodeHash) internal pure returns (address) {\n return computeCreate2Address(salt, initCodeHash, CREATE2_FACTORY);\n }\n\n /// @dev returns the hash of the init code (creation code + no args) used in CREATE2 with no constructor arguments\n /// @param creationCode the creation code of a contract C, as returned by type(C).creationCode\n function hashInitCode(bytes memory creationCode) internal pure returns (bytes32) {\n return hashInitCode(creationCode, \"\");\n }\n\n /// @dev returns the hash of the init code (creation code + ABI-encoded args) used in CREATE2\n /// @param creationCode the creation code of a contract C, as returned by type(C).creationCode\n /// @param args the ABI-encoded arguments to the constructor of C\n function hashInitCode(bytes memory creationCode, bytes memory args) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(creationCode, args));\n }\n\n // Performs a single call with Multicall3 to query the ERC-20 token balances of the given addresses.\n function getTokenBalances(address token, address[] memory addresses)\n internal\n virtual\n returns (uint256[] memory balances)\n {\n uint256 tokenCodeSize;\n assembly {\n tokenCodeSize := extcodesize(token)\n }\n require(tokenCodeSize > 0, \"StdUtils getTokenBalances(address,address[]): Token address is not a contract.\");\n\n // ABI encode the aggregate call to Multicall3.\n uint256 length = addresses.length;\n IMulticall3.Call[] memory calls = new IMulticall3.Call[](length);\n for (uint256 i = 0; i < length; ++i) {\n // 0x70a08231 = bytes4(\"balanceOf(address)\"))\n calls[i] = IMulticall3.Call({target: token, callData: abi.encodeWithSelector(0x70a08231, (addresses[i]))});\n }\n\n // Make the aggregate call.\n (, bytes[] memory returnData) = multicall.aggregate(calls);\n\n // ABI decode the return data and return the balances.\n balances = new uint256[](length);\n for (uint256 i = 0; i < length; ++i) {\n balances[i] = abi.decode(returnData[i], (uint256));\n }\n }\n\n /*//////////////////////////////////////////////////////////////////////////\n PRIVATE FUNCTIONS\n //////////////////////////////////////////////////////////////////////////*/\n\n function addressFromLast20Bytes(bytes32 bytesValue) private pure returns (address) {\n return address(uint160(uint256(bytesValue)));\n }\n\n // Used to prevent the compilation of console, which shortens the compilation time when console is not used elsewhere.\n\n function console2_log(string memory p0, uint256 p1) private view {\n (bool status,) = address(CONSOLE2_ADDRESS).staticcall(abi.encodeWithSignature(\"log(string,uint256)\", p0, p1));\n status;\n }\n\n function console2_log(string memory p0, string memory p1) private view {\n (bool status,) = address(CONSOLE2_ADDRESS).staticcall(abi.encodeWithSignature(\"log(string,string)\", p0, p1));\n status;\n }\n}\n" + }, + "forge-std/Test.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\n// 💬 ABOUT\n// Standard Library's default Test\n\n// 🧩 MODULES\nimport {console} from \"./console.sol\";\nimport {console2} from \"./console2.sol\";\nimport {StdAssertions} from \"./StdAssertions.sol\";\nimport {StdChains} from \"./StdChains.sol\";\nimport {StdCheats} from \"./StdCheats.sol\";\nimport {stdError} from \"./StdError.sol\";\nimport {StdInvariant} from \"./StdInvariant.sol\";\nimport {stdJson} from \"./StdJson.sol\";\nimport {stdMath} from \"./StdMath.sol\";\nimport {StdStorage, stdStorage} from \"./StdStorage.sol\";\nimport {StdUtils} from \"./StdUtils.sol\";\nimport {Vm} from \"./Vm.sol\";\nimport {StdStyle} from \"./StdStyle.sol\";\n\n// 📦 BOILERPLATE\nimport {TestBase} from \"./Base.sol\";\nimport {DSTest} from \"ds-test/test.sol\";\n\n// ⭐️ TEST\nabstract contract Test is DSTest, StdAssertions, StdChains, StdCheats, StdInvariant, StdUtils, TestBase {\n// Note: IS_TEST() must return true.\n// Note: Must have failure system, https://github.com/dapphub/ds-test/blob/cd98eff28324bfac652e63a239a60632a761790b/src/test.sol#L39-L76.\n}\n" + }, + "forge-std/Vm.sol": { + "content": "// SPDX-License-Identifier: MIT\npragma solidity >=0.6.2 <0.9.0;\n\npragma experimental ABIEncoderV2;\n\n// Cheatcodes are marked as view/pure/none using the following rules:\n// 0. A call's observable behaviour includes its return value, logs, reverts and state writes,\n// 1. If you can influence a later call's observable behaviour, you're neither `view` nor `pure (you are modifying some state be it the EVM, interpreter, filesystem, etc),\n// 2. Otherwise if you can be influenced by an earlier call, or if reading some state, you're `view`,\n// 3. Otherwise you're `pure`.\n\ninterface VmSafe {\n struct Log {\n bytes32[] topics;\n bytes data;\n address emitter;\n }\n\n struct Rpc {\n string key;\n string url;\n }\n\n struct FsMetadata {\n bool isDir;\n bool isSymlink;\n uint256 length;\n bool readOnly;\n uint256 modified;\n uint256 accessed;\n uint256 created;\n }\n\n // Loads a storage slot from an address\n function load(address target, bytes32 slot) external view returns (bytes32 data);\n // Signs data\n function sign(uint256 privateKey, bytes32 digest) external pure returns (uint8 v, bytes32 r, bytes32 s);\n // Gets the address for a given private key\n function addr(uint256 privateKey) external pure returns (address keyAddr);\n // Gets the nonce of an account\n function getNonce(address account) external view returns (uint64 nonce);\n // Performs a foreign function call via the terminal\n function ffi(string[] calldata commandInput) external returns (bytes memory result);\n // Sets environment variables\n function setEnv(string calldata name, string calldata value) external;\n // Reads environment variables, (name) => (value)\n function envBool(string calldata name) external view returns (bool value);\n function envUint(string calldata name) external view returns (uint256 value);\n function envInt(string calldata name) external view returns (int256 value);\n function envAddress(string calldata name) external view returns (address value);\n function envBytes32(string calldata name) external view returns (bytes32 value);\n function envString(string calldata name) external view returns (string memory value);\n function envBytes(string calldata name) external view returns (bytes memory value);\n // Reads environment variables as arrays\n function envBool(string calldata name, string calldata delim) external view returns (bool[] memory value);\n function envUint(string calldata name, string calldata delim) external view returns (uint256[] memory value);\n function envInt(string calldata name, string calldata delim) external view returns (int256[] memory value);\n function envAddress(string calldata name, string calldata delim) external view returns (address[] memory value);\n function envBytes32(string calldata name, string calldata delim) external view returns (bytes32[] memory value);\n function envString(string calldata name, string calldata delim) external view returns (string[] memory value);\n function envBytes(string calldata name, string calldata delim) external view returns (bytes[] memory value);\n // Read environment variables with default value\n function envOr(string calldata name, bool defaultValue) external returns (bool value);\n function envOr(string calldata name, uint256 defaultValue) external returns (uint256 value);\n function envOr(string calldata name, int256 defaultValue) external returns (int256 value);\n function envOr(string calldata name, address defaultValue) external returns (address value);\n function envOr(string calldata name, bytes32 defaultValue) external returns (bytes32 value);\n function envOr(string calldata name, string calldata defaultValue) external returns (string memory value);\n function envOr(string calldata name, bytes calldata defaultValue) external returns (bytes memory value);\n // Read environment variables as arrays with default value\n function envOr(string calldata name, string calldata delim, bool[] calldata defaultValue)\n external\n returns (bool[] memory value);\n function envOr(string calldata name, string calldata delim, uint256[] calldata defaultValue)\n external\n returns (uint256[] memory value);\n function envOr(string calldata name, string calldata delim, int256[] calldata defaultValue)\n external\n returns (int256[] memory value);\n function envOr(string calldata name, string calldata delim, address[] calldata defaultValue)\n external\n returns (address[] memory value);\n function envOr(string calldata name, string calldata delim, bytes32[] calldata defaultValue)\n external\n returns (bytes32[] memory value);\n function envOr(string calldata name, string calldata delim, string[] calldata defaultValue)\n external\n returns (string[] memory value);\n function envOr(string calldata name, string calldata delim, bytes[] calldata defaultValue)\n external\n returns (bytes[] memory value);\n // Records all storage reads and writes\n function record() external;\n // Gets all accessed reads and write slot from a recording session, for a given address\n function accesses(address target) external returns (bytes32[] memory readSlots, bytes32[] memory writeSlots);\n // Gets the _creation_ bytecode from an artifact file. Takes in the relative path to the json file\n function getCode(string calldata artifactPath) external view returns (bytes memory creationBytecode);\n // Gets the _deployed_ bytecode from an artifact file. Takes in the relative path to the json file\n function getDeployedCode(string calldata artifactPath) external view returns (bytes memory runtimeBytecode);\n // Labels an address in call traces\n function label(address account, string calldata newLabel) external;\n // Using the address that calls the test contract, has the next call (at this call depth only) create a transaction that can later be signed and sent onchain\n function broadcast() external;\n // Has the next call (at this call depth only) create a transaction with the address provided as the sender that can later be signed and sent onchain\n function broadcast(address signer) external;\n // Has the next call (at this call depth only) create a transaction with the private key provided as the sender that can later be signed and sent onchain\n function broadcast(uint256 privateKey) external;\n // Using the address that calls the test contract, has all subsequent calls (at this call depth only) create transactions that can later be signed and sent onchain\n function startBroadcast() external;\n // Has all subsequent calls (at this call depth only) create transactions with the address provided that can later be signed and sent onchain\n function startBroadcast(address signer) external;\n // Has all subsequent calls (at this call depth only) create transactions with the private key provided that can later be signed and sent onchain\n function startBroadcast(uint256 privateKey) external;\n // Stops collecting onchain transactions\n function stopBroadcast() external;\n // Reads the entire content of file to string\n function readFile(string calldata path) external view returns (string memory data);\n // Reads the entire content of file as binary. Path is relative to the project root.\n function readFileBinary(string calldata path) external view returns (bytes memory data);\n // Get the path of the current project root\n function projectRoot() external view returns (string memory path);\n // Get the metadata for a file/directory\n function fsMetadata(string calldata fileOrDir) external returns (FsMetadata memory metadata);\n // Reads next line of file to string\n function readLine(string calldata path) external view returns (string memory line);\n // Writes data to file, creating a file if it does not exist, and entirely replacing its contents if it does.\n function writeFile(string calldata path, string calldata data) external;\n // Writes binary data to a file, creating a file if it does not exist, and entirely replacing its contents if it does.\n // Path is relative to the project root.\n function writeFileBinary(string calldata path, bytes calldata data) external;\n // Writes line to file, creating a file if it does not exist.\n function writeLine(string calldata path, string calldata data) external;\n // Closes file for reading, resetting the offset and allowing to read it from beginning with readLine.\n function closeFile(string calldata path) external;\n // Removes file. This cheatcode will revert in the following situations, but is not limited to just these cases:\n // - Path points to a directory.\n // - The file doesn't exist.\n // - The user lacks permissions to remove the file.\n function removeFile(string calldata path) external;\n // Convert values to a string\n function toString(address value) external pure returns (string memory stringifiedValue);\n function toString(bytes calldata value) external pure returns (string memory stringifiedValue);\n function toString(bytes32 value) external pure returns (string memory stringifiedValue);\n function toString(bool value) external pure returns (string memory stringifiedValue);\n function toString(uint256 value) external pure returns (string memory stringifiedValue);\n function toString(int256 value) external pure returns (string memory stringifiedValue);\n // Convert values from a string\n function parseBytes(string calldata stringifiedValue) external pure returns (bytes memory parsedValue);\n function parseAddress(string calldata stringifiedValue) external pure returns (address parsedValue);\n function parseUint(string calldata stringifiedValue) external pure returns (uint256 parsedValue);\n function parseInt(string calldata stringifiedValue) external pure returns (int256 parsedValue);\n function parseBytes32(string calldata stringifiedValue) external pure returns (bytes32 parsedValue);\n function parseBool(string calldata stringifiedValue) external pure returns (bool parsedValue);\n // Record all the transaction logs\n function recordLogs() external;\n // Gets all the recorded logs\n function getRecordedLogs() external returns (Log[] memory logs);\n // Derive a private key from a provided mnenomic string (or mnenomic file path) at the derivation path m/44'/60'/0'/0/{index}\n function deriveKey(string calldata mnemonic, uint32 index) external pure returns (uint256 privateKey);\n // Derive a private key from a provided mnenomic string (or mnenomic file path) at {derivationPath}{index}\n function deriveKey(string calldata mnemonic, string calldata derivationPath, uint32 index)\n external\n pure\n returns (uint256 privateKey);\n // Adds a private key to the local forge wallet and returns the address\n function rememberKey(uint256 privateKey) external returns (address keyAddr);\n //\n // parseJson\n //\n // ----\n // In case the returned value is a JSON object, it's encoded as a ABI-encoded tuple. As JSON objects\n // don't have the notion of ordered, but tuples do, they JSON object is encoded with it's fields ordered in\n // ALPHABETICAL order. That means that in order to successfully decode the tuple, we need to define a tuple that\n // encodes the fields in the same order, which is alphabetical. In the case of Solidity structs, they are encoded\n // as tuples, with the attributes in the order in which they are defined.\n // For example: json = { 'a': 1, 'b': 0xa4tb......3xs}\n // a: uint256\n // b: address\n // To decode that json, we need to define a struct or a tuple as follows:\n // struct json = { uint256 a; address b; }\n // If we defined a json struct with the opposite order, meaning placing the address b first, it would try to\n // decode the tuple in that order, and thus fail.\n // ----\n // Given a string of JSON, return it as ABI-encoded\n function parseJson(string calldata json, string calldata key) external pure returns (bytes memory abiEncodedData);\n function parseJson(string calldata json) external pure returns (bytes memory abiEncodedData);\n\n // The following parseJson cheatcodes will do type coercion, for the type that they indicate.\n // For example, parseJsonUint will coerce all values to a uint256. That includes stringified numbers '12'\n // and hex numbers '0xEF'.\n // Type coercion works ONLY for discrete values or arrays. That means that the key must return a value or array, not\n // a JSON object.\n function parseJsonUint(string calldata, string calldata) external returns (uint256);\n function parseJsonUintArray(string calldata, string calldata) external returns (uint256[] memory);\n function parseJsonInt(string calldata, string calldata) external returns (int256);\n function parseJsonIntArray(string calldata, string calldata) external returns (int256[] memory);\n function parseJsonBool(string calldata, string calldata) external returns (bool);\n function parseJsonBoolArray(string calldata, string calldata) external returns (bool[] memory);\n function parseJsonAddress(string calldata, string calldata) external returns (address);\n function parseJsonAddressArray(string calldata, string calldata) external returns (address[] memory);\n function parseJsonString(string calldata, string calldata) external returns (string memory);\n function parseJsonStringArray(string calldata, string calldata) external returns (string[] memory);\n function parseJsonBytes(string calldata, string calldata) external returns (bytes memory);\n function parseJsonBytesArray(string calldata, string calldata) external returns (bytes[] memory);\n function parseJsonBytes32(string calldata, string calldata) external returns (bytes32);\n function parseJsonBytes32Array(string calldata, string calldata) external returns (bytes32[] memory);\n\n // Serialize a key and value to a JSON object stored in-memory that can be later written to a file\n // It returns the stringified version of the specific JSON file up to that moment.\n function serializeBool(string calldata objectKey, string calldata valueKey, bool value)\n external\n returns (string memory json);\n function serializeUint(string calldata objectKey, string calldata valueKey, uint256 value)\n external\n returns (string memory json);\n function serializeInt(string calldata objectKey, string calldata valueKey, int256 value)\n external\n returns (string memory json);\n function serializeAddress(string calldata objectKey, string calldata valueKey, address value)\n external\n returns (string memory json);\n function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32 value)\n external\n returns (string memory json);\n function serializeString(string calldata objectKey, string calldata valueKey, string calldata value)\n external\n returns (string memory json);\n function serializeBytes(string calldata objectKey, string calldata valueKey, bytes calldata value)\n external\n returns (string memory json);\n\n function serializeBool(string calldata objectKey, string calldata valueKey, bool[] calldata values)\n external\n returns (string memory json);\n function serializeUint(string calldata objectKey, string calldata valueKey, uint256[] calldata values)\n external\n returns (string memory json);\n function serializeInt(string calldata objectKey, string calldata valueKey, int256[] calldata values)\n external\n returns (string memory json);\n function serializeAddress(string calldata objectKey, string calldata valueKey, address[] calldata values)\n external\n returns (string memory json);\n function serializeBytes32(string calldata objectKey, string calldata valueKey, bytes32[] calldata values)\n external\n returns (string memory json);\n function serializeString(string calldata objectKey, string calldata valueKey, string[] calldata values)\n external\n returns (string memory json);\n function serializeBytes(string calldata objectKey, string calldata valueKey, bytes[] calldata values)\n external\n returns (string memory json);\n\n //\n // writeJson\n //\n // ----\n // Write a serialized JSON object to a file. If the file exists, it will be overwritten.\n // Let's assume we want to write the following JSON to a file:\n //\n // { \"boolean\": true, \"number\": 342, \"object\": { \"title\": \"finally json serialization\" } }\n //\n // ```\n // string memory json1 = \"some key\";\n // vm.serializeBool(json1, \"boolean\", true);\n // vm.serializeBool(json1, \"number\", uint256(342));\n // json2 = \"some other key\";\n // string memory output = vm.serializeString(json2, \"title\", \"finally json serialization\");\n // string memory finalJson = vm.serialize(json1, \"object\", output);\n // vm.writeJson(finalJson, \"./output/example.json\");\n // ```\n // The critical insight is that every invocation of serialization will return the stringified version of the JSON\n // up to that point. That means we can construct arbitrary JSON objects and then use the return stringified version\n // to serialize them as values to another JSON object.\n //\n // json1 and json2 are simply keys used by the backend to keep track of the objects. So vm.serializeJson(json1,..)\n // will find the object in-memory that is keyed by \"some key\".\n function writeJson(string calldata json, string calldata path) external;\n // Write a serialized JSON object to an **existing** JSON file, replacing a value with key = \n // This is useful to replace a specific value of a JSON file, without having to parse the entire thing\n function writeJson(string calldata json, string calldata path, string calldata valueKey) external;\n // Returns the RPC url for the given alias\n function rpcUrl(string calldata rpcAlias) external view returns (string memory json);\n // Returns all rpc urls and their aliases `[alias, url][]`\n function rpcUrls() external view returns (string[2][] memory urls);\n // Returns all rpc urls and their aliases as structs.\n function rpcUrlStructs() external view returns (Rpc[] memory urls);\n // If the condition is false, discard this run's fuzz inputs and generate new ones.\n function assume(bool condition) external pure;\n // Pauses gas metering (i.e. gas usage is not counted). Noop if already paused.\n function pauseGasMetering() external;\n // Resumes gas metering (i.e. gas usage is counted again). Noop if already on.\n function resumeGasMetering() external;\n}\n\ninterface Vm is VmSafe {\n // Sets block.timestamp\n function warp(uint256 newTimestamp) external;\n // Sets block.height\n function roll(uint256 newHeight) external;\n // Sets block.basefee\n function fee(uint256 newBasefee) external;\n // Sets block.difficulty\n function difficulty(uint256 newDifficulty) external;\n // Sets block.chainid\n function chainId(uint256 newChainId) external;\n // Stores a value to an address' storage slot.\n function store(address target, bytes32 slot, bytes32 value) external;\n // Sets the nonce of an account; must be higher than the current nonce of the account\n function setNonce(address account, uint64 newNonce) external;\n // Sets the *next* call's msg.sender to be the input address\n function prank(address msgSender) external;\n // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called\n function startPrank(address msgSender) external;\n // Sets the *next* call's msg.sender to be the input address, and the tx.origin to be the second input\n function prank(address msgSender, address txOrigin) external;\n // Sets all subsequent calls' msg.sender to be the input address until `stopPrank` is called, and the tx.origin to be the second input\n function startPrank(address msgSender, address txOrigin) external;\n // Resets subsequent calls' msg.sender to be `address(this)`\n function stopPrank() external;\n // Sets an address' balance\n function deal(address account, uint256 newBalance) external;\n // Sets an address' code\n function etch(address target, bytes calldata newRuntimeBytecode) external;\n // Expects an error on next call\n function expectRevert(bytes calldata revertData) external;\n function expectRevert(bytes4 revertData) external;\n function expectRevert() external;\n // Prepare an expected log with (bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData).\n // Call this function, then emit an event, then call a function. Internally after the call, we check if\n // logs were emitted in the expected order with the expected topics and data (as specified by the booleans)\n function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData) external;\n function expectEmit(bool checkTopic1, bool checkTopic2, bool checkTopic3, bool checkData, address emitter)\n external;\n // Mocks a call to an address, returning specified data.\n // Calldata can either be strict or a partial match, e.g. if you only\n // pass a Solidity selector to the expected calldata, then the entire Solidity\n // function will be mocked.\n function mockCall(address callee, bytes calldata data, bytes calldata returnData) external;\n // Mocks a call to an address with a specific msg.value, returning specified data.\n // Calldata match takes precedence over msg.value in case of ambiguity.\n function mockCall(address callee, uint256 msgValue, bytes calldata data, bytes calldata returnData) external;\n // Clears all mocked calls\n function clearMockedCalls() external;\n // Expects a call to an address with the specified calldata.\n // Calldata can either be a strict or a partial match\n function expectCall(address callee, bytes calldata data) external;\n // Expects a call to an address with the specified msg.value and calldata\n function expectCall(address callee, uint256 msgValue, bytes calldata data) external;\n // Expect a call to an address with the specified msg.value, gas, and calldata.\n function expectCall(address callee, uint256 msgValue, uint64 gas, bytes calldata data) external;\n // Expect a call to an address with the specified msg.value and calldata, and a *minimum* amount of gas.\n function expectCallMinGas(address callee, uint256 msgValue, uint64 minGas, bytes calldata data) external;\n // Sets block.coinbase\n function coinbase(address newCoinbase) external;\n // Snapshot the current state of the evm.\n // Returns the id of the snapshot that was created.\n // To revert a snapshot use `revertTo`\n function snapshot() external returns (uint256 snapshotId);\n // Revert the state of the EVM to a previous snapshot\n // Takes the snapshot id to revert to.\n // This deletes the snapshot and all snapshots taken after the given snapshot id.\n function revertTo(uint256 snapshotId) external returns (bool success);\n // Creates a new fork with the given endpoint and block and returns the identifier of the fork\n function createFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId);\n // Creates a new fork with the given endpoint and the _latest_ block and returns the identifier of the fork\n function createFork(string calldata urlOrAlias) external returns (uint256 forkId);\n // Creates a new fork with the given endpoint and at the block the given transaction was mined in, replays all transaction mined in the block before the transaction,\n // and returns the identifier of the fork\n function createFork(string calldata urlOrAlias, bytes32 txHash) external returns (uint256 forkId);\n // Creates _and_ also selects a new fork with the given endpoint and block and returns the identifier of the fork\n function createSelectFork(string calldata urlOrAlias, uint256 blockNumber) external returns (uint256 forkId);\n // Creates _and_ also selects new fork with the given endpoint and at the block the given transaction was mined in, replays all transaction mined in the block before\n // the transaction, returns the identifier of the fork\n function createSelectFork(string calldata urlOrAlias, bytes32 txHash) external returns (uint256 forkId);\n // Creates _and_ also selects a new fork with the given endpoint and the latest block and returns the identifier of the fork\n function createSelectFork(string calldata urlOrAlias) external returns (uint256 forkId);\n // Takes a fork identifier created by `createFork` and sets the corresponding forked state as active.\n function selectFork(uint256 forkId) external;\n /// Returns the identifier of the currently active fork. Reverts if no fork is currently active.\n function activeFork() external view returns (uint256 forkId);\n // Updates the currently active fork to given block number\n // This is similar to `roll` but for the currently active fork\n function rollFork(uint256 blockNumber) external;\n // Updates the currently active fork to given transaction\n // this will `rollFork` with the number of the block the transaction was mined in and replays all transaction mined before it in the block\n function rollFork(bytes32 txHash) external;\n // Updates the given fork to given block number\n function rollFork(uint256 forkId, uint256 blockNumber) external;\n // Updates the given fork to block number of the given transaction and replays all transaction mined before it in the block\n function rollFork(uint256 forkId, bytes32 txHash) external;\n // Marks that the account(s) should use persistent storage across fork swaps in a multifork setup\n // Meaning, changes made to the state of this account will be kept when switching forks\n function makePersistent(address account) external;\n function makePersistent(address account0, address account1) external;\n function makePersistent(address account0, address account1, address account2) external;\n function makePersistent(address[] calldata accounts) external;\n // Revokes persistent status from the address, previously added via `makePersistent`\n function revokePersistent(address account) external;\n function revokePersistent(address[] calldata accounts) external;\n // Returns true if the account is marked as persistent\n function isPersistent(address account) external view returns (bool persistent);\n // In forking mode, explicitly grant the given address cheatcode access\n function allowCheatcodes(address account) external;\n // Fetches the given transaction from the active fork and executes it on the current state\n function transact(bytes32 txHash) external;\n // Fetches the given transaction from the given fork and executes it on the current state\n function transact(uint256 forkId, bytes32 txHash) external;\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/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/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/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/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" + }, + "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/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/tokens/WETH.sol": { + "content": "// SPDX-License-Identifier: AGPL-3.0-only\npragma solidity >=0.8.0;\n\nimport {ERC20} from \"./ERC20.sol\";\n\nimport {SafeTransferLib} from \"../utils/SafeTransferLib.sol\";\n\n/// @notice Minimalist and modern Wrapped Ether implementation.\n/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/WETH.sol)\n/// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)\ncontract WETH is ERC20(\"Wrapped Ether\", \"WETH\", 18) {\n using SafeTransferLib for address;\n\n event Deposit(address indexed from, uint256 amount);\n\n event Withdrawal(address indexed to, uint256 amount);\n\n function deposit() public payable virtual {\n _mint(msg.sender, msg.value);\n\n emit Deposit(msg.sender, msg.value);\n }\n\n function withdraw(uint256 amount) public virtual {\n _burn(msg.sender, amount);\n\n emit Withdrawal(msg.sender, amount);\n\n msg.sender.safeTransferETH(amount);\n }\n\n receive() external payable virtual {\n deposit();\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/tasks/chain-specific/index.ts b/packages/contracts/tasks/chain-specific/index.ts index 2ea5e60b3..98a920829 100644 --- a/packages/contracts/tasks/chain-specific/index.ts +++ b/packages/contracts/tasks/chain-specific/index.ts @@ -1,4 +1,5 @@ import "./bob"; import "./base"; import "./mode"; -import "./fraxtal"; \ No newline at end of file +import "./fraxtal"; +import "./optimism"; \ No newline at end of file diff --git a/packages/contracts/tasks/chain-specific/optimism/index.ts b/packages/contracts/tasks/chain-specific/optimism/index.ts new file mode 100644 index 000000000..11a8328b8 --- /dev/null +++ b/packages/contracts/tasks/chain-specific/optimism/index.ts @@ -0,0 +1,3 @@ +import "./market"; + +export const COMPTROLLER_MAIN = "0xaFB4A254D125B0395610fdc8f1D022936c7b166B"; diff --git a/packages/contracts/tasks/chain-specific/optimism/market.ts b/packages/contracts/tasks/chain-specific/optimism/market.ts new file mode 100644 index 000000000..fd4261580 --- /dev/null +++ b/packages/contracts/tasks/chain-specific/optimism/market.ts @@ -0,0 +1,55 @@ +import { task } from "hardhat/config"; +import { zeroAddress } from "viem"; +import { assetSymbols } from "@ionicprotocol/types"; +import { COMPTROLLER_MAIN } from "."; +import { optimism } from "@ionicprotocol/chains"; + +task("markets:deploy:optimism:new", "deploy new mode assets").setAction(async (_, { viem, run }) => { + const assetsToDeploy: string[] = [assetSymbols.wUSDM]; + for (const asset of optimism.assets.filter((asset) => assetsToDeploy.includes(asset.symbol))) { + if (!asset.name || !asset.symbol || !asset.underlying) { + throw new Error(`Asset ${asset.symbol} has no name, symbol or underlying`); + } + const name = `Ionic ${asset.name}`; + const symbol = "ion" + asset.symbol; + console.log(`Deploying ctoken ${name} with symbol ${symbol}`); + await run("market:deploy", { + signer: "deployer", + cf: "0", + underlying: asset.underlying, + comptroller: COMPTROLLER_MAIN, + symbol, + name + }); + const pool = await viem.getContractAt("IonicComptroller", COMPTROLLER_MAIN); + const cToken = await pool.read.cTokensByUnderlying([asset.underlying]); + console.log(`Deployed ${asset.symbol} at ${cToken}`); + + if (cToken !== zeroAddress) { + await run("market:set-supply-cap", { + market: cToken, + maxSupply: asset.initialSupplyCap + }); + + await run("market:set-borrow-cap", { + market: cToken, + maxBorrow: asset.initialBorrowCap + }); + } + } +}); + +task("market:set-cf:optimism:new", "Sets CF on a market").setAction(async (_, { viem, run }) => { + for (const asset of optimism.assets.filter((asset) => asset.symbol === assetSymbols.wsuperOETHb)) { + const pool = await viem.getContractAt("IonicComptroller", COMPTROLLER_MAIN); + const cToken = await pool.read.cTokensByUnderlying([asset.underlying]); + console.log("cToken: ", cToken, asset.symbol); + + if (asset.initialCf) { + await run("market:set:ltv", { + marketAddress: cToken, + ltv: asset.initialCf + }); + } + } +}); diff --git a/packages/ui/constants/index.ts b/packages/ui/constants/index.ts index ba5d678db..4ad5ad7f9 100644 --- a/packages/ui/constants/index.ts +++ b/packages/ui/constants/index.ts @@ -209,7 +209,17 @@ export const pools: Record = { { id: '0', name: 'Main Pool', - assets: ['USDC', 'USDT', 'WETH', 'OP', 'wstETH', 'SNX', 'WBTC', 'LUSD'] + assets: [ + 'USDC', + 'USDT', + 'WETH', + 'wUSDM', + 'OP', + 'wstETH', + 'SNX', + 'WBTC', + 'LUSD' + ] } ] },