File size: 81,700 Bytes
f998fcd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
{
"language": "Solidity",
"settings": {
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs",
"useLiteralContent": true
},
"optimizer": {
"enabled": true,
"runs": 1000000
},
"remappings": [],
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
}
},
"sources": {
"@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol": {
"content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\ninterface AggregatorV3Interface {\n\n function decimals()\n external\n view\n returns (\n uint8\n );\n\n function description()\n external\n view\n returns (\n string memory\n );\n\n function version()\n external\n view\n returns (\n uint256\n );\n\n // getRoundData and latestRoundData should both raise \"No data present\"\n // if they do not have data to report, instead of returning unset values\n // which could be misinterpreted as actual reported values.\n function getRoundData(\n uint80 _roundId\n )\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n function latestRoundData()\n external\n view\n returns (\n uint80 roundId,\n int256 answer,\n uint256 startedAt,\n uint256 updatedAt,\n uint80 answeredInRound\n );\n\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\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 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 `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, 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 `sender` to `recipient` 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 sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\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"
},
"@openzeppelin/contracts/token/ERC20/IERC20.sol": {
"content": "// SPDX-License-Identifier: MIT\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 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 `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, 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 `sender` to `recipient` 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 sender,\n address recipient,\n uint256 amount\n ) external returns (bool);\n\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"
},
"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol": {
"content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\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"
},
"@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\nimport './pool/IUniswapV3PoolImmutables.sol';\nimport './pool/IUniswapV3PoolState.sol';\nimport './pool/IUniswapV3PoolDerivedState.sol';\nimport './pool/IUniswapV3PoolActions.sol';\nimport './pool/IUniswapV3PoolOwnerActions.sol';\nimport './pool/IUniswapV3PoolEvents.sol';\n\n/// @title The interface for a Uniswap V3 Pool\n/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform\n/// to the ERC20 specification\n/// @dev The pool interface is broken up into many smaller pieces\ninterface IUniswapV3Pool is\n IUniswapV3PoolImmutables,\n IUniswapV3PoolState,\n IUniswapV3PoolDerivedState,\n IUniswapV3PoolActions,\n IUniswapV3PoolOwnerActions,\n IUniswapV3PoolEvents\n{\n\n}\n"
},
"@uniswap/v3-core/contracts/interfaces/pool/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"
},
"@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that is not stored\n/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the\n/// blockchain. The functions here may have variable gas costs.\ninterface IUniswapV3PoolDerivedState {\n /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp\n /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing\n /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,\n /// you must call it with secondsAgos = [3600, 0].\n /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in\n /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.\n /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned\n /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp\n /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block\n /// timestamp\n function observe(uint32[] calldata secondsAgos)\n external\n view\n returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);\n\n /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range\n /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.\n /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first\n /// snapshot is taken and the second snapshot is taken.\n /// @param tickLower The lower tick of the range\n /// @param tickUpper The upper tick of the range\n /// @return tickCumulativeInside The snapshot of the tick accumulator for the range\n /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range\n /// @return secondsInside The snapshot of seconds per liquidity for the range\n function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)\n external\n view\n returns (\n int56 tickCumulativeInside,\n uint160 secondsPerLiquidityInsideX128,\n uint32 secondsInside\n );\n}\n"
},
"@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Events emitted by a pool\n/// @notice Contains all events emitted by the pool\ninterface IUniswapV3PoolEvents {\n /// @notice Emitted exactly once by a pool when #initialize is first called on the pool\n /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize\n /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96\n /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool\n event Initialize(uint160 sqrtPriceX96, int24 tick);\n\n /// @notice Emitted when liquidity is minted for a given position\n /// @param sender The address that minted the liquidity\n /// @param owner The owner of the position and recipient of any minted liquidity\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity minted to the position range\n /// @param amount0 How much token0 was required for the minted liquidity\n /// @param amount1 How much token1 was required for the minted liquidity\n event Mint(\n address sender,\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted when fees are collected by the owner of a position\n /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees\n /// @param owner The owner of the position for which fees are collected\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount0 The amount of token0 fees collected\n /// @param amount1 The amount of token1 fees collected\n event Collect(\n address indexed owner,\n address recipient,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount0,\n uint128 amount1\n );\n\n /// @notice Emitted when a position's liquidity is removed\n /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect\n /// @param owner The owner of the position for which liquidity is removed\n /// @param tickLower The lower tick of the position\n /// @param tickUpper The upper tick of the position\n /// @param amount The amount of liquidity to remove\n /// @param amount0 The amount of token0 withdrawn\n /// @param amount1 The amount of token1 withdrawn\n event Burn(\n address indexed owner,\n int24 indexed tickLower,\n int24 indexed tickUpper,\n uint128 amount,\n uint256 amount0,\n uint256 amount1\n );\n\n /// @notice Emitted by the pool for any swaps between token0 and token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the output of the swap\n /// @param amount0 The delta of the token0 balance of the pool\n /// @param amount1 The delta of the token1 balance of the pool\n /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96\n /// @param liquidity The liquidity of the pool after the swap\n /// @param tick The log base 1.0001 of price of the pool after the swap\n event Swap(\n address indexed sender,\n address indexed recipient,\n int256 amount0,\n int256 amount1,\n uint160 sqrtPriceX96,\n uint128 liquidity,\n int24 tick\n );\n\n /// @notice Emitted by the pool for any flashes of token0/token1\n /// @param sender The address that initiated the swap call, and that received the callback\n /// @param recipient The address that received the tokens from flash\n /// @param amount0 The amount of token0 that was flashed\n /// @param amount1 The amount of token1 that was flashed\n /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee\n /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee\n event Flash(\n address indexed sender,\n address indexed recipient,\n uint256 amount0,\n uint256 amount1,\n uint256 paid0,\n uint256 paid1\n );\n\n /// @notice Emitted by the pool for increases to the number of observations that can be stored\n /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index\n /// just before a mint/swap/burn.\n /// @param observationCardinalityNextOld The previous value of the next observation cardinality\n /// @param observationCardinalityNextNew The updated value of the next observation cardinality\n event IncreaseObservationCardinalityNext(\n uint16 observationCardinalityNextOld,\n uint16 observationCardinalityNextNew\n );\n\n /// @notice Emitted when the protocol fee is changed by the pool\n /// @param feeProtocol0Old The previous value of the token0 protocol fee\n /// @param feeProtocol1Old The previous value of the token1 protocol fee\n /// @param feeProtocol0New The updated value of the token0 protocol fee\n /// @param feeProtocol1New The updated value of the token1 protocol fee\n event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);\n\n /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner\n /// @param sender The address that collects the protocol fees\n /// @param recipient The address that receives the collected protocol fees\n /// @param amount0 The amount of token0 protocol fees that is withdrawn\n /// @param amount0 The amount of token1 protocol fees that is withdrawn\n event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);\n}\n"
},
"@uniswap/v3-core/contracts/interfaces/pool/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"
},
"@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Permissioned pool actions\n/// @notice Contains pool methods that may only be called by the factory owner\ninterface IUniswapV3PoolOwnerActions {\n /// @notice Set the denominator of the protocol's % share of the fees\n /// @param feeProtocol0 new protocol fee for token0 of the pool\n /// @param feeProtocol1 new protocol fee for token1 of the pool\n function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;\n\n /// @notice Collect the protocol fee accrued to the pool\n /// @param recipient The address to which collected protocol fees should be sent\n /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1\n /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0\n /// @return amount0 The protocol fee collected in token0\n /// @return amount1 The protocol fee collected in token1\n function collectProtocol(\n address recipient,\n uint128 amount0Requested,\n uint128 amount1Requested\n ) external returns (uint128 amount0, uint128 amount1);\n}\n"
},
"@uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol": {
"content": "// SPDX-License-Identifier: GPL-2.0-or-later\npragma solidity >=0.5.0;\n\n/// @title Pool state that can change\n/// @notice These methods compose the pool's state, and can change with any frequency including multiple times\n/// per transaction\ninterface IUniswapV3PoolState {\n /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas\n /// when accessed externally.\n /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value\n /// tick The current tick of the pool, i.e. according to the last tick transition that was run.\n /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick\n /// boundary.\n /// observationIndex The index of the last oracle observation that was written,\n /// observationCardinality The current maximum number of observations stored in the pool,\n /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.\n /// feeProtocol The protocol fee for both tokens of the pool.\n /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0\n /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.\n /// unlocked Whether the pool is currently locked to reentrancy\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 /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal0X128() external view returns (uint256);\n\n /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool\n /// @dev This value can overflow the uint256\n function feeGrowthGlobal1X128() external view returns (uint256);\n\n /// @notice The amounts of token0 and token1 that are owed to the protocol\n /// @dev Protocol fees will never exceed uint128 max in either token\n function protocolFees() external view returns (uint128 token0, uint128 token1);\n\n /// @notice The currently in range liquidity available to the pool\n /// @dev This value has no relationship to the total liquidity across all ticks\n function liquidity() external view returns (uint128);\n\n /// @notice Look up information about a specific tick in the pool\n /// @param tick The tick to look up\n /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or\n /// tick upper,\n /// liquidityNet how much liquidity changes when the pool price crosses the tick,\n /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,\n /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,\n /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick\n /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,\n /// secondsOutside the seconds spent on the other side of the tick from the current tick,\n /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.\n /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.\n /// In addition, these values are only relative and must be used only in comparison to previous snapshots for\n /// a specific position.\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 /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information\n function tickBitmap(int16 wordPosition) external view returns (uint256);\n\n /// @notice Returns the information about a position by the position's key\n /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper\n /// @return _liquidity The amount of liquidity in the position,\n /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,\n /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,\n /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,\n /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke\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 /// @notice Returns data about a specific observation index\n /// @param index The element of the observations array to fetch\n /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time\n /// ago, rather than at a specific index in the array.\n /// @return blockTimestamp The timestamp of the observation,\n /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,\n /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,\n /// Returns initialized whether the observation has been initialized and the values are safe to use\n function observations(uint256 index)\n external\n view\n returns (\n uint32 blockTimestamp,\n int56 tickCumulative,\n uint160 secondsPerLiquidityCumulativeX128,\n bool initialized\n );\n}\n"
},
"contracts/external/FullMath.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity >=0.4.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\n/// @dev This contract was forked from Uniswap V3's contract `FullMath.sol` available here\n/// https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/FullMath.sol\nabstract contract 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 // 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 // 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"
},
"contracts/interfaces/ICoreBorrow.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\n/// @title ICoreBorrow\n/// @author Angle Core Team\n/// @notice Interface for the `CoreBorrow` contract\n/// @dev This interface only contains functions of the `CoreBorrow` contract which are called by other contracts\n/// of this module\ninterface ICoreBorrow {\n /// @notice Checks if an address corresponds to a treasury of a stablecoin with a flash loan\n /// module initialized on it\n /// @param treasury Address to check\n /// @return Whether the address has the `FLASHLOANER_TREASURY_ROLE` or not\n function isFlashLoanerTreasury(address treasury) external view returns (bool);\n\n /// @notice Checks whether an address is governor of the Angle Protocol or not\n /// @param admin Address to check\n /// @return Whether the address has the `GOVERNOR_ROLE` or not\n function isGovernor(address admin) external view returns (bool);\n\n /// @notice Checks whether an address is governor or a guardian of the Angle Protocol or not\n /// @param admin Address to check\n /// @return Whether the address has the `GUARDIAN_ROLE` or not\n /// @dev Governance should make sure when adding a governor to also give this governor the guardian\n /// role by calling the `addGovernor` function\n function isGovernorOrGuardian(address admin) external view returns (bool);\n}\n"
},
"contracts/interfaces/IKeeperRegistry.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol\";\n\n/// @title IKeeperRegistry\n/// @author Angle Core Team\ninterface IKeeperRegistry {\n /// @notice Checks whether an address is whitelisted during oracle updates\n /// @param caller Address for which the whitelist should be checked\n /// @return Whether if the address is trusted\n function isTrusted(address caller) external view returns (bool);\n}\n"
},
"contracts/interfaces/IOracle.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\n/// @title IOracle\n/// @author Angle Core Team\n/// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink\n/// from just UniswapV3 or from just Chainlink\ninterface IOracle {\n function read() external view returns (uint256);\n\n function readAll() external view returns (uint256 lowerRate, uint256 upperRate);\n\n function readLower() external view returns (uint256);\n\n function readUpper() external view returns (uint256);\n\n function readQuote(uint256 baseAmount) external view returns (uint256);\n\n function readQuoteLower(uint256 baseAmount) external view returns (uint256);\n\n function inBase() external view returns (uint256);\n}\n"
},
"contracts/oracle/OracleAbstractWithKeeper.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\nimport \"../interfaces/IOracle.sol\";\n\n/// @title OracleAbstractWithKeeper\n/// @author Angle Core Team\n/// @notice Abstract Oracle contract that contains some of the functions that are used across all oracle contracts\n/// @dev This is the most generic form of oracle contract\n/// @dev A rate gives the price of the out-currency with respect to the in-currency in base `BASE`. For instance\n/// if the out-currency is ETH worth 1000 USD, then the rate ETH-USD is 10**21\nabstract contract OracleAbstractWithKeeper is IOracle {\n /// @notice Base used for computation\n uint256 public constant BASE = 10**18;\n /// @notice Unit of the in-currency\n uint256 public override inBase;\n /// @notice Description of the assets concerned by the oracle and the price outputted\n string public description;\n\n /// @notice Reads one of the rates from the circuits given\n /// @return rate The current rate between the in-currency and out-currency\n /// @dev By default if the oracle involves a Uniswap price and a Chainlink price\n /// this function will return the Uniswap price\n /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)\n function read() external view virtual override returns (uint256 rate);\n\n /// @notice Read rates from the circuit of both Uniswap and Chainlink if there are both circuits\n /// else returns twice the same price\n /// @return Return all available rates (Chainlink and Uniswap) with the lowest rate returned first.\n /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)\n function readAll() external view override returns (uint256, uint256) {\n return _readAll(inBase);\n }\n\n /// @notice Reads rates from the circuit of both Uniswap and Chainlink if there are both circuits\n /// and returns either the highest of both rates or the lowest\n /// @return rate The lower rate between Chainlink and Uniswap\n /// @dev If there is only one rate computed in an oracle contract, then the only rate is returned\n /// regardless of the value of the `lower` parameter\n /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)\n function readLower() external view override returns (uint256 rate) {\n (rate, ) = _readAll(inBase);\n }\n\n /// @notice Reads rates from the circuit of both Uniswap and Chainlink if there are both circuits\n /// and returns either the highest of both rates or the lowest\n /// @return rate The upper rate between Chainlink and Uniswap\n /// @dev If there is only one rate computed in an oracle contract, then the only rate is returned\n /// regardless of the value of the `lower` parameter\n /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)\n function readUpper() external view override returns (uint256 rate) {\n (, rate) = _readAll(inBase);\n }\n\n /// @notice Converts an in-currency quote amount to out-currency using one of the rates available in the oracle\n /// contract\n /// @param quoteAmount Amount (in the input collateral) to be converted to be converted in out-currency\n /// @return Quote amount in out-currency from the base amount in in-currency\n /// @dev Like in the read function, if the oracle involves a Uniswap and a Chainlink price, this function\n /// will use the Uniswap price to compute the out quoteAmount\n /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)\n function readQuote(uint256 quoteAmount) external view virtual override returns (uint256);\n\n /// @notice Returns the lowest quote amount between Uniswap and Chainlink circuits (if possible). If the oracle\n /// contract only involves a single feed, then this returns the value of this feed\n /// @param quoteAmount Amount (in the input collateral) to be converted\n /// @return The lowest quote amount from the quote amount in in-currency\n /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)\n function readQuoteLower(uint256 quoteAmount) external view override returns (uint256) {\n (uint256 quoteSmall, ) = _readAll(quoteAmount);\n return quoteSmall;\n }\n\n /// @notice Returns Uniswap and Chainlink values (with the first one being the smallest one) or twice the same value\n /// if just Uniswap or just Chainlink is used\n /// @param quoteAmount Amount expressed in the in-currency base.\n /// @dev If `quoteAmount` is `inBase`, rates are returned\n /// @return The first return value is the lowest value and the second parameter is the highest\n /// @dev The rate returned is expressed with base `BASE` (and not the base of the out-currency)\n function _readAll(uint256 quoteAmount) internal view virtual returns (uint256, uint256) {}\n}\n"
},
"contracts/oracle/OracleMultiUSDWithKeeper.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\nimport \"./OracleAbstractWithKeeper.sol\";\n\nimport \"./modules/ModuleChainlinkMultiWithKeeper.sol\";\nimport \"./modules/ModuleUniswapMultiWithKeeper.sol\";\n\n// To avoid a stack too deep\nstruct ChainlinkParameters {\n address[] circuitChainlink;\n uint8[] circuitChainlinkIsPausable;\n uint8[] circuitChainIsMultiplied;\n uint32 stalePeriod;\n uint32 pausingPeriod;\n}\n\n/// @title OracleMultiUSDWithKeeper\n/// @author Angle Core Team\n/// @notice Oracle contract that uses both Chainlink prices and Uniswap TWAPs with the possibility to have\n/// some Chainlink feeds paused after an update\n/// @dev This oracle is built specifically for USD stablecoins\ncontract OracleMultiUSDWithKeeper is\n OracleAbstractWithKeeper,\n ModuleChainlinkMultiWithKeeper,\n ModuleUniswapMultiWithKeeper\n{\n /// @notice Whether the final rate obtained with Uniswap should be multiplied to last rate from Chainlink\n uint8 public immutable uniFinalCurrency;\n\n /// @notice Unit out Uniswap currency\n uint256 public immutable outBase;\n\n /// @notice Constructor for an oracle using both Uniswap and Chainlink with multiple pools to read from\n /// @param addressInAndOutUni List of 2 addresses representing the in-currency address and the out-currency address\n /// @param _circuitUniswap Path of the Uniswap pools\n /// @param _circuitUniIsMultiplied Whether we should multiply or divide by this rate in the path\n /// @param _twapPeriod Time weighted average window for all Uniswap pools\n /// @param observationLength Number of observations that each pool should have stored\n /// @param _uniFinalCurrency Whether we need to use the last Chainlink oracle to convert to another\n /// currency / asset (Forex for instance)\n /// @param chainLinkParameters Parameters of the Chainlink feeds\n /// @param _coreBorrow List of governor or guardian addresses\n /// @param _keeperRegistry Contract holding keeper whitelisting\n /// @param _description Description of the assets concerned by the oracle\n /// @dev When deploying this contract, it is important to check in the case where Uniswap circuit is not final whether\n /// Chainlink and Uniswap circuits are compatible. If Chainlink is UNI-WBTC and WBTC-USD and Uniswap is just UNI-WETH,\n /// then Uniswap cannot be the final circuit\n constructor(\n address[] memory addressInAndOutUni,\n IUniswapV3Pool[] memory _circuitUniswap,\n uint8[] memory _circuitUniIsMultiplied,\n uint32 _twapPeriod,\n uint16 observationLength,\n uint8 _uniFinalCurrency,\n ChainlinkParameters memory chainLinkParameters,\n ICoreBorrow _coreBorrow,\n IKeeperRegistry _keeperRegistry,\n string memory _description\n )\n ModuleUniswapMultiWithKeeper(_circuitUniswap, _circuitUniIsMultiplied, _twapPeriod, observationLength)\n ModuleChainlinkMultiWithKeeper(\n chainLinkParameters.circuitChainlink,\n chainLinkParameters.circuitChainlinkIsPausable,\n chainLinkParameters.circuitChainIsMultiplied,\n chainLinkParameters.stalePeriod,\n chainLinkParameters.pausingPeriod,\n _coreBorrow,\n _keeperRegistry\n )\n {\n if (addressInAndOutUni.length != 2) revert InvalidLength();\n // Using the tokens' metadata to get the in and out currencies decimals\n {\n IERC20Metadata inCur = IERC20Metadata(addressInAndOutUni[0]);\n IERC20Metadata outCur = IERC20Metadata(addressInAndOutUni[1]);\n inBase = 10**(inCur.decimals());\n outBase = 10**(outCur.decimals());\n }\n\n uniFinalCurrency = _uniFinalCurrency;\n description = _description;\n }\n\n /// @inheritdoc UniswapUtilsWithKeeper\n function _getCoreBorrow() internal view override returns (ICoreBorrow) {\n return coreBorrow;\n }\n\n /// @inheritdoc OracleAbstractWithKeeper\n function read() external view override returns (uint256) {\n return _readUniswapQuote(inBase);\n }\n\n /// @inheritdoc OracleAbstractWithKeeper\n function readQuote(uint256 quoteAmount) external view override returns (uint256) {\n return _readUniswapQuote(quoteAmount);\n }\n\n /// @inheritdoc OracleAbstractWithKeeper\n function _readAll(uint256 quoteAmount) internal view override returns (uint256, uint256) {\n uint256 quoteAmountUni = _quoteUniswap(quoteAmount);\n\n // The current uni rate is in `outBase` we want our rate to all be in base `BASE`\n quoteAmountUni = (quoteAmountUni * BASE) / outBase;\n // The current amount is in `inBase` we want our rate to all be in base `BASE`\n uint256 quoteAmountCL = (quoteAmount * BASE) / inBase;\n uint256 ratio;\n\n (quoteAmountCL, ratio) = _quoteChainlink(quoteAmountCL);\n\n if (uniFinalCurrency > 0) {\n quoteAmountUni = _changeUniswapNotFinal(ratio, quoteAmountUni);\n }\n\n // As the asset is made to be a stablecoin, compute the rate as if Uniswap returned `BASE * quoteAmount / inBase`\n ratio = _changeUniswapNotFinal(ratio, (quoteAmount * BASE) / inBase);\n\n if (quoteAmountCL <= quoteAmountUni) {\n if (ratio <= quoteAmountCL) {\n return (ratio, quoteAmountUni);\n } else if (quoteAmountUni <= ratio) {\n return (quoteAmountCL, ratio);\n }\n return (quoteAmountCL, quoteAmountUni);\n } else {\n if (ratio <= quoteAmountUni) {\n return (ratio, quoteAmountCL);\n } else if (quoteAmountCL <= ratio) {\n return (quoteAmountUni, ratio);\n }\n return (quoteAmountUni, quoteAmountCL);\n }\n }\n\n /// @notice Uses Chainlink's value to change Uniswap's rate\n /// @param ratio Value of the last oracle rate of Chainlink\n /// @param quoteAmountUni End quote computed from Uniswap's circuit\n /// @dev We use the last Chainlink rate to correct the value obtained with Uniswap. It may for instance be used\n /// to get a Uniswap price in EUR (ex: ETH -> USDC and we use this to do USDC -> EUR)\n function _changeUniswapNotFinal(uint256 ratio, uint256 quoteAmountUni) internal view returns (uint256) {\n uint256 idxLastPoolCL = circuitChainlink.length - 1;\n (quoteAmountUni, ) = _readChainlinkFeed(\n quoteAmountUni,\n circuitChainlink[idxLastPoolCL],\n circuitChainlinkIsPausable[idxLastPoolCL],\n circuitChainIsMultiplied[idxLastPoolCL],\n chainlinkDecimals[idxLastPoolCL],\n ratio\n );\n return quoteAmountUni;\n }\n\n /// @notice Internal function to convert an in-currency quote amount to out-currency using only the Uniswap rate\n /// and by correcting it if needed from Chainlink last rate\n /// @param quoteAmount Amount (in the input collateral) to be converted in out-currency using Uniswap (and Chainlink)\n /// at the end of the funnel\n /// @return uniAmount Quote amount in out-currency from the base amount in in-currency\n /// @dev The amount returned is expressed with base `BASE` (and not the base of the out-currency)\n function _readUniswapQuote(uint256 quoteAmount) internal view returns (uint256 uniAmount) {\n uniAmount = _quoteUniswap(quoteAmount);\n // The current uni rate is in outBase we want our rate to all be in base\n uniAmount = (uniAmount * BASE) / outBase;\n if (uniFinalCurrency > 0) {\n uniAmount = _changeUniswapNotFinal(0, uniAmount);\n }\n }\n}\n"
},
"contracts/oracle/OracleMultiWithKeeper.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\n\nimport \"./OracleAbstractWithKeeper.sol\";\nimport \"./OracleMultiUSDWithKeeper.sol\";\n\nimport \"./modules/ModuleChainlinkMultiWithKeeper.sol\";\nimport \"./modules/ModuleUniswapMultiWithKeeper.sol\";\n\n/// @title OracleMultiWithKeeper\n/// @author Angle Core Team\n/// @notice Oracle contract that uses both Chainlink prices and Uniswap TWAPs with the possibility to have\n/// some Chainlink feeds paused after an update\ncontract OracleMultiWithKeeper is\n OracleAbstractWithKeeper,\n ModuleChainlinkMultiWithKeeper,\n ModuleUniswapMultiWithKeeper\n{\n /// @notice Whether the final rate obtained with Uniswap should be multiplied to last rate from Chainlink\n uint8 public immutable uniFinalCurrency;\n\n /// @notice Unit out Uniswap currency\n uint256 public immutable outBase;\n\n /// @notice Constructor for an oracle using both Uniswap and Chainlink with multiple pools to read from\n /// @param addressInAndOutUni List of 2 addresses representing the in-currency address and the out-currency address\n /// @param _circuitUniswap Path of the Uniswap pools\n /// @param _circuitUniIsMultiplied Whether we should multiply or divide by this rate in the path\n /// @param _twapPeriod Time weighted average window for all Uniswap pools\n /// @param observationLength Number of observations that each pool should have stored\n /// @param _uniFinalCurrency Whether we need to use the last Chainlink oracle to convert to another\n /// currency / asset (Forex for instance)\n /// @param chainLinkParameters Parameters of the Chainlink feeds\n /// @param _coreBorrow List of governor or guardian addresses\n /// @param _keeperRegistry Contract holding keeper whitelisting\n /// @param _description Description of the assets concerned by the oracle\n /// @dev When deploying this contract, it is important to check in the case where Uniswap circuit is not final whether\n /// Chainlink and Uniswap circuits are compatible. If Chainlink is UNI-WBTC and WBTC-USD and Uniswap is just UNI-WETH,\n /// then Uniswap cannot be the final circuit\n constructor(\n address[] memory addressInAndOutUni,\n IUniswapV3Pool[] memory _circuitUniswap,\n uint8[] memory _circuitUniIsMultiplied,\n uint32 _twapPeriod,\n uint16 observationLength,\n uint8 _uniFinalCurrency,\n ChainlinkParameters memory chainLinkParameters,\n ICoreBorrow _coreBorrow,\n IKeeperRegistry _keeperRegistry,\n string memory _description\n )\n ModuleUniswapMultiWithKeeper(_circuitUniswap, _circuitUniIsMultiplied, _twapPeriod, observationLength)\n ModuleChainlinkMultiWithKeeper(\n chainLinkParameters.circuitChainlink,\n chainLinkParameters.circuitChainlinkIsPausable,\n chainLinkParameters.circuitChainIsMultiplied,\n chainLinkParameters.stalePeriod,\n chainLinkParameters.pausingPeriod,\n _coreBorrow,\n _keeperRegistry\n )\n {\n if (addressInAndOutUni.length != 2) revert InvalidLength();\n // Using the tokens' metadata to get the in and out currencies decimals\n {\n IERC20Metadata inCur = IERC20Metadata(addressInAndOutUni[0]);\n IERC20Metadata outCur = IERC20Metadata(addressInAndOutUni[1]);\n inBase = 10**(inCur.decimals());\n outBase = 10**(outCur.decimals());\n }\n\n uniFinalCurrency = _uniFinalCurrency;\n description = _description;\n }\n\n /// @inheritdoc UniswapUtilsWithKeeper\n function _getCoreBorrow() internal view override returns (ICoreBorrow) {\n return coreBorrow;\n }\n\n /// @inheritdoc OracleAbstractWithKeeper\n function read() external view override returns (uint256) {\n return _readUniswapQuote(inBase);\n }\n\n /// @inheritdoc OracleAbstractWithKeeper\n function readQuote(uint256 quoteAmount) external view override returns (uint256) {\n return _readUniswapQuote(quoteAmount);\n }\n\n /// @inheritdoc OracleAbstractWithKeeper\n function _readAll(uint256 quoteAmount) internal view override returns (uint256, uint256) {\n uint256 quoteAmountUni = _quoteUniswap(quoteAmount);\n\n // The current uni rate is in `outBase` we want our rate to all be in base `BASE`\n quoteAmountUni = (quoteAmountUni * BASE) / outBase;\n // The current amount is in `inBase` we want our rate to all be in base `BASE`\n uint256 quoteAmountCL = (quoteAmount * BASE) / inBase;\n uint256 ratio;\n\n (quoteAmountCL, ratio) = _quoteChainlink(quoteAmountCL);\n\n if (uniFinalCurrency > 0) {\n quoteAmountUni = _changeUniswapNotFinal(ratio, quoteAmountUni);\n }\n\n if (quoteAmountCL <= quoteAmountUni) {\n return (quoteAmountCL, quoteAmountUni);\n } else return (quoteAmountUni, quoteAmountCL);\n }\n\n /// @notice Uses Chainlink's value to change Uniswap's rate\n /// @param ratio Value of the last oracle rate of Chainlink\n /// @param quoteAmountUni End quote computed from Uniswap's circuit\n /// @dev We use the last Chainlink rate to correct the value obtained with Uniswap. It may for instance be used\n /// to get a Uniswap price in EUR (ex: ETH -> USDC and we use this to do USDC -> EUR)\n function _changeUniswapNotFinal(uint256 ratio, uint256 quoteAmountUni) internal view returns (uint256) {\n uint256 idxLastPoolCL = circuitChainlink.length - 1;\n (quoteAmountUni, ) = _readChainlinkFeed(\n quoteAmountUni,\n circuitChainlink[idxLastPoolCL],\n circuitChainlinkIsPausable[idxLastPoolCL],\n circuitChainIsMultiplied[idxLastPoolCL],\n chainlinkDecimals[idxLastPoolCL],\n ratio\n );\n return quoteAmountUni;\n }\n\n /// @notice Internal function to convert an in-currency quote amount to out-currency using only the Uniswap rate\n /// and by correcting it if needed from Chainlink last rate\n /// @param quoteAmount Amount (in the input collateral) to be converted in out-currency using Uniswap (and Chainlink)\n /// at the end of the funnel\n /// @return uniAmount Quote amount in out-currency from the base amount in in-currency\n /// @dev The amount returned is expressed with base `BASE` (and not the base of the out-currency)\n function _readUniswapQuote(uint256 quoteAmount) internal view returns (uint256 uniAmount) {\n uniAmount = _quoteUniswap(quoteAmount);\n // The current uni rate is in outBase we want our rate to all be in base\n uniAmount = (uniAmount * BASE) / outBase;\n if (uniFinalCurrency > 0) {\n uniAmount = _changeUniswapNotFinal(0, uniAmount);\n }\n }\n}\n"
},
"contracts/oracle/modules/ModuleChainlinkMultiWithKeeper.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\nimport \"../utils/ChainlinkUtilsWithKeeper.sol\";\n\n/// @title ModuleChainlinkMultiWithKeeper\n/// @author Angle Core Team\n/// @notice Module Contract to help compute Chainlink prices\n/// @dev This contract helps for an oracle using a Chainlink circuit composed of multiple pools and for which some\n/// feeds can potentially be paused right after an update\nabstract contract ModuleChainlinkMultiWithKeeper is ChainlinkUtilsWithKeeper {\n /// @notice Chanlink pools, the order of the pools has to be the order in which they are read for the computation\n /// of the price\n AggregatorV3Interface[] public circuitChainlink;\n /// @notice Whether each rate for the pairs in `circuitChainlink` should be multiplied or divided\n uint8[] public circuitChainIsMultiplied;\n /// @notice Whether the oracle needs to to be paused after an update\n uint8[] public circuitChainlinkIsPausable;\n /// @notice Decimals for each Chainlink pairs\n uint8[] public chainlinkDecimals;\n\n error InvalidLength();\n error ZeroAddress();\n\n /// @notice Constructor for an oracle using only Chainlink with multiple pools to read from\n /// @param _circuitChainlink Chainlink pool addresses (in order)\n /// @param _circuitChainlinkIsPausable Whether the oracle needs to to be paused after an update\n /// @param _circuitChainIsMultiplied Whether we should multiply or divide by this rate when computing Chainlink price\n /// @param _keeperRegistry Contract holding keeper whitelisting\n constructor(\n address[] memory _circuitChainlink,\n uint8[] memory _circuitChainlinkIsPausable,\n uint8[] memory _circuitChainIsMultiplied,\n uint32 _stalePeriod,\n uint32 _pausingPeriod,\n ICoreBorrow _coreBorrow,\n IKeeperRegistry _keeperRegistry\n ) {\n uint256 circuitLength = _circuitChainlink.length;\n if (\n (circuitLength == 0) ||\n (circuitLength != _circuitChainIsMultiplied.length) ||\n (circuitLength != _circuitChainlinkIsPausable.length)\n ) revert InvalidLength();\n\n for (uint256 i = 0; i < circuitLength; i++) {\n AggregatorV3Interface _pool = AggregatorV3Interface(_circuitChainlink[i]);\n circuitChainlink.push(_pool);\n chainlinkDecimals.push(_pool.decimals());\n }\n\n stalePeriod = _stalePeriod;\n pausingPeriod = _pausingPeriod;\n circuitChainIsMultiplied = _circuitChainIsMultiplied;\n circuitChainlinkIsPausable = _circuitChainlinkIsPausable;\n keeperRegistry = _keeperRegistry;\n coreBorrow = _coreBorrow;\n }\n\n /// @notice Reads oracle price using Chainlink circuit\n /// @param quoteAmount The amount for which to compute the price expressed with base decimal\n /// @return The `quoteAmount` converted in `out-currency`\n /// @return The value obtained with the last Chainlink feed queried casted to uint\n /// @dev If `quoteAmount` is `BASE_TOKENS`, the output is the oracle rate\n function _quoteChainlink(uint256 quoteAmount) internal view returns (uint256, uint256) {\n uint256 castedRatio;\n // An invariant should be that `circuitChainlink.length > 0` otherwise `castedRatio = 0`\n for (uint256 i = 0; i < circuitChainlink.length; i++) {\n (quoteAmount, castedRatio) = _readChainlinkFeed(\n quoteAmount,\n circuitChainlink[i],\n circuitChainlinkIsPausable[i],\n circuitChainIsMultiplied[i],\n chainlinkDecimals[i],\n 0\n );\n }\n return (quoteAmount, castedRatio);\n }\n}\n"
},
"contracts/oracle/modules/ModuleUniswapMultiWithKeeper.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\nimport \"../utils/UniswapUtilsWithKeeper.sol\";\n\n/// @title ModuleUniswapMulti\n/// @author Angle Core Team\n/// @notice Module Contract that is going to be used to help compute Uniswap prices\n/// @dev This contract will help for an oracle using multiple UniswapV3 pools\n/// @dev An oracle using Uniswap is either going to be a `ModuleUniswapSingle` or a `ModuleUniswapMulti`\nabstract contract ModuleUniswapMultiWithKeeper is UniswapUtilsWithKeeper {\n /// @notice Uniswap pools, the order of the pools to arrive to the final price should be respected\n IUniswapV3Pool[] public circuitUniswap;\n /// @notice Whether the rate obtained with each pool should be multiplied or divided to the current amount\n uint8[] public circuitUniIsMultiplied;\n\n error ZeroParameter();\n\n /// @notice Constructor for an oracle using multiple Uniswap pool\n /// @param _circuitUniswap Path of the Uniswap pools\n /// @param _circuitUniIsMultiplied Whether we should multiply or divide by this rate in the path\n /// @param _twapPeriod Time weighted average window, it is common for all Uniswap pools\n /// @param observationLength Number of observations that each pool should have stored\n constructor(\n IUniswapV3Pool[] memory _circuitUniswap,\n uint8[] memory _circuitUniIsMultiplied,\n uint32 _twapPeriod,\n uint16 observationLength\n ) {\n if (int32(_twapPeriod) == 0) revert ZeroParameter();\n uint256 circuitUniLength = _circuitUniswap.length;\n require(circuitUniLength > 0, \"103\");\n require(circuitUniLength == _circuitUniIsMultiplied.length, \"104\");\n\n twapPeriod = _twapPeriod;\n\n circuitUniswap = _circuitUniswap;\n circuitUniIsMultiplied = _circuitUniIsMultiplied;\n\n for (uint256 i = 0; i < circuitUniLength; i++) {\n circuitUniswap[i].increaseObservationCardinalityNext(observationLength);\n }\n }\n\n /// @notice Reads Uniswap current block oracle rate\n /// @param quoteAmount The amount in the in-currency base to convert using the Uniswap oracle\n /// @return The value of the oracle of the initial amount is then expressed in the decimal from\n /// the end currency\n function _quoteUniswap(uint256 quoteAmount) internal view returns (uint256) {\n for (uint256 i = 0; i < circuitUniswap.length; i++) {\n quoteAmount = _readUniswapPool(quoteAmount, circuitUniswap[i], circuitUniIsMultiplied[i]);\n }\n // The decimal here is the one from the end currency\n return quoteAmount;\n }\n\n /// @notice Increases the number of observations for each Uniswap pools\n /// @param newLengthStored Size asked for\n /// @dev newLengthStored should be larger than all previous pools observations length\n function increaseTWAPStore(uint16 newLengthStored) external {\n for (uint256 i = 0; i < circuitUniswap.length; i++) {\n circuitUniswap[i].increaseObservationCardinalityNext(newLengthStored);\n }\n }\n}\n"
},
"contracts/oracle/utils/ChainlinkUtilsWithKeeper.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\nimport \"@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol\";\nimport \"../../interfaces/IKeeperRegistry.sol\";\nimport \"../../interfaces/ICoreBorrow.sol\";\n\n/// @title ChainlinkUtilsWithKeeper\n/// @author Angle Core Team\n/// @notice Utility contract that is used to read for Chainlink feeds with the possibility to pause\n/// the oracle after each oracle update\nabstract contract ChainlinkUtilsWithKeeper {\n /// @notice Maximum amount of time (in seconds) between each Chainlink update\n /// before the price feed is considered stale\n uint32 public stalePeriod;\n\n /// @notice Number of seconds during which the oracle needs to be paused after each update\n uint32 public pausingPeriod;\n\n /// @notice Holds the mapping of whitelisted keepers\n IKeeperRegistry public keeperRegistry;\n\n /// @notice Contract handling access control\n ICoreBorrow public coreBorrow;\n\n error InvalidChainlinkRate();\n error NotGovernorOrGuardianChainlink();\n error NotGovernor();\n error OraclePaused();\n\n /// @notice Checks whether the `msg.sender` has the governor role or the guardian role\n modifier onlyGovernorOrGuardian() {\n if (!coreBorrow.isGovernorOrGuardian(msg.sender)) revert NotGovernorOrGuardianChainlink();\n _;\n }\n\n /// @notice Checks whether the `msg.sender` has the governor role\n modifier onlyGovernor() {\n if (!coreBorrow.isGovernor(msg.sender)) revert NotGovernor();\n _;\n }\n\n /// @notice Reads a Chainlink feed using a quote amount and converts the quote amount to\n /// the out-currency\n /// @param quoteAmount The amount for which to compute the price expressed with base decimal\n /// @param feed Chainlink feed to query\n /// @param pauseAfterUpdate Whether to pause the oracle after each update\n /// @param multiplied Whether the ratio outputted by Chainlink should be multiplied or divided\n /// to the `quoteAmount`\n /// @param decimals Number of decimals of the corresponding Chainlink pair\n /// @param castedRatio Whether a previous rate has already been computed for this feed\n /// This is mostly used in the `_changeUniswapNotFinal` function of the oracles\n /// @return The `quoteAmount` converted in out-currency (computed using the second return value)\n /// @return The value obtained with the Chainlink feed queried casted to uint\n /// @dev In this implementation, the Chainlink feed can be paused for unregistered addresses after\n /// an oracle update is `pauseAfterUpdate` is true\n function _readChainlinkFeed(\n uint256 quoteAmount,\n AggregatorV3Interface feed,\n uint8 pauseAfterUpdate,\n uint8 multiplied,\n uint256 decimals,\n uint256 castedRatio\n ) internal view returns (uint256, uint256) {\n if (castedRatio == 0) {\n (uint80 roundId, int256 ratio, , uint256 updatedAt, uint80 answeredInRound) = feed.latestRoundData();\n if (\n pauseAfterUpdate == 1 &&\n updatedAt + pausingPeriod > block.timestamp &&\n //solhint-disable-next-line\n !keeperRegistry.isTrusted(tx.origin)\n ) revert OraclePaused();\n if (ratio <= 0 || roundId > answeredInRound || block.timestamp - updatedAt > stalePeriod)\n revert InvalidChainlinkRate();\n castedRatio = uint256(ratio);\n }\n // Checking whether we should multiply or divide by the ratio computed\n if (multiplied == 1) quoteAmount = (quoteAmount * castedRatio) / (10**decimals);\n else quoteAmount = (quoteAmount * (10**decimals)) / castedRatio;\n return (quoteAmount, castedRatio);\n }\n\n /// @notice Changes the `stalePeriod`\n /// @param _stalePeriod New stale period (in seconds)\n function changeStalePeriod(uint32 _stalePeriod) external onlyGovernorOrGuardian {\n stalePeriod = _stalePeriod;\n }\n\n /// @notice Changes the `pausingPeriod`\n /// @param _pausingPeriod New period\n function changePausingPeriod(uint32 _pausingPeriod) external onlyGovernorOrGuardian {\n pausingPeriod = _pausingPeriod;\n }\n\n /// @notice Changes the `keeperRegistry` address\n /// @param _keeperRegistry New registry\n function changeKeeperRegistry(IKeeperRegistry _keeperRegistry) external onlyGovernorOrGuardian {\n keeperRegistry = _keeperRegistry;\n }\n\n /// @notice Changes the `coreBorrow` address\n /// @param _coreBorrow New CoreBorrow\n function changeCoreBorrow(ICoreBorrow _coreBorrow) external onlyGovernor {\n coreBorrow = _coreBorrow;\n }\n}\n"
},
"contracts/oracle/utils/UniswapUtilsWithKeeper.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\nimport \"@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol\";\n\nimport \"../../utils/OracleMath.sol\";\nimport \"../../interfaces/ICoreBorrow.sol\";\n\n/// @title UniswapUtils\n/// @author Angle Core Team\n/// @notice Utility contract that is used in the Uniswap module contract\nabstract contract UniswapUtilsWithKeeper is OracleMath {\n // The parameters below are common among the different Uniswap modules contracts\n\n /// @notice Time weigthed average window that should be used for each Uniswap rate\n /// It is mainly going to be 5 minutes in the protocol\n uint32 public twapPeriod;\n\n error NotGovernorOrGuardianUniswap();\n\n /// @notice Returns the `coreBorrow` address\n function _getCoreBorrow() internal view virtual returns (ICoreBorrow) {}\n\n /// @notice Gets a quote for an amount of in-currency using UniswapV3 TWAP and converts this\n /// amount to out-currency\n /// @param quoteAmount The amount to convert in the out-currency\n /// @param pool UniswapV3 pool to query\n /// @param isUniMultiplied Whether the rate corresponding to the Uniswap pool should be multiplied or divided\n /// @return The value of the `quoteAmount` expressed in out-currency\n function _readUniswapPool(\n uint256 quoteAmount,\n IUniswapV3Pool pool,\n uint8 isUniMultiplied\n ) internal view returns (uint256) {\n uint32[] memory secondAgos = new uint32[](2);\n\n secondAgos[0] = twapPeriod;\n secondAgos[1] = 0;\n\n (int56[] memory tickCumulatives, ) = pool.observe(secondAgos);\n int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];\n\n int24 timeWeightedAverageTick = int24(tickCumulativesDelta / int32(twapPeriod));\n\n // Always round to negative infinity\n if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int56(int32(twapPeriod)) != 0))\n timeWeightedAverageTick--;\n\n // Computing the `quoteAmount` from the ticks obtained from Uniswap\n return _getQuoteAtTick(timeWeightedAverageTick, quoteAmount, isUniMultiplied);\n }\n\n /// @notice Changes the TWAP period\n /// @param _twapPeriod New window to compute the TWAP\n function changeTwapPeriod(uint32 _twapPeriod) external {\n if (!_getCoreBorrow().isGovernorOrGuardian(msg.sender)) revert NotGovernorOrGuardianUniswap();\n require(int32(_twapPeriod) > 0, \"99\");\n twapPeriod = _twapPeriod;\n }\n}\n"
},
"contracts/utils/OracleMath.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\n\npragma solidity ^0.8.7;\n\nimport \"../external/FullMath.sol\";\n\n/// @title OracleMath\n/// @author Forked and adapted by Angle Core Team from https://github.com/Uniswap/uniswap-v3-core/blob/main/contracts/libraries/TickMath.sol\n/// @notice Math library for computing prices from ticks\n/// @dev Computes price for ticks of size 1.0001, i.e. sqrt(1.0001^tick). Supports\n/// prices between 2**-128 and 2**128\ncontract OracleMath is FullMath {\n /// @dev Maximum tick that may be passed to `_getSqrtRatioAtTick` computed from log base 1.0001 of 2**128\n int24 internal constant _MAX_TICK = 887272;\n\n /// @notice Given a tick and a token amount, calculates the amount of token received in exchange\n /// @param tick Tick value used to calculate the quote\n /// @param baseAmount Amount of token to be converted\n /// @param multiply Boolean representing whether the `baseToken` has a lower address than the `quoteToken`\n /// @return quoteAmount Amount of `quoteToken` received for `baseAmount` of `baseToken`\n function _getQuoteAtTick(\n int24 tick,\n uint256 baseAmount,\n uint256 multiply\n ) internal pure returns (uint256 quoteAmount) {\n uint256 ratio = _getRatioAtTick(tick);\n\n quoteAmount = (multiply == 1) ? _mulDiv(ratio, baseAmount, 1e18) : _mulDiv(1e18, baseAmount, ratio);\n }\n\n /// @notice Calculates 1.0001^tick * in out ERC20 decimals\n /// @dev Adapted from Uniswap `_getSqrtRatioAtTick` but we don't consider the square root\n /// anymore but directly the full rate\n /// @dev Throws if `|tick| > max tick`\n /// @param tick The input tick for the above formula\n /// @return rate uint256 representing the ratio of the two assets `(token1/token0) * 10**decimals(token1)`\n /// at the given tick\n function _getRatioAtTick(int24 tick) internal pure returns (uint256 rate) {\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 ? 0xfff97272373d413259a46990580e213a : 0x100000000000000000000000000000000;\n if (absTick & 0x2 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;\n if (absTick & 0x4 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;\n if (absTick & 0x8 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;\n if (absTick & 0x10 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;\n if (absTick & 0x20 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;\n if (absTick & 0x40 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;\n if (absTick & 0x80 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;\n if (absTick & 0x100 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;\n if (absTick & 0x200 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;\n if (absTick & 0x400 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;\n if (absTick & 0x800 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;\n if (absTick & 0x1000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;\n if (absTick & 0x2000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;\n if (absTick & 0x4000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;\n if (absTick & 0x8000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;\n if (absTick & 0x10000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;\n if (absTick & 0x20000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;\n if (absTick & 0x40000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;\n if (absTick & 0x80000 != 0) ratio = (ratio * 0x149b34ee7ac262) >> 128;\n\n if (tick > 0) ratio = type(uint256).max / ratio;\n\n // We need to modify the 96 decimal to be able to convert it to a D256\n // 2**59 ~ 10**18 (thus we guarantee the same precision) and 128-59 = 69\n // We retrieve a Q128.59 decimal. --> we have 69 bits free to reach the uint256 limit.\n // Now, 2**69 >> 10**18 so we are safe in the Decimal conversion.\n\n uint256 price = uint256((ratio >> 69) + (ratio % (1 << 69) == 0 ? 0 : 1));\n rate = ((price * 1e18) >> 59);\n }\n}\n"
}
}
} |