Overview
ETH Balance
0 ETH
Eth Value
$0.00More Info
Private Name Tags
ContractCreator
Latest 1 from a total of 1 transactions
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
0x60806040 | 13982498 | 1033 days ago | IN | 0 ETH | 0.14863909 |
View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Loading...
Loading
Contract Name:
Oracle
Compiler Version
v0.7.6+commit.7338295f
Optimization Enabled:
Yes with 825 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-2.0-or-later // uniswap Library only works under 0.7.6 pragma solidity =0.7.6; //interface import {IUniswapV3Pool} from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol"; //library import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Uint256Casting} from "../libs/Uint256Casting.sol"; import {OracleLibrary} from "../libs/OracleLibrary.sol"; /** * @notice read UniswapV3 pool TWAP prices, and convert to human readable term with (18 decimals) * @dev if ETH price is $3000, both ETH/USDC price and ETH/DAI price will be reported as 3000 * 1e18 by this oracle */ contract Oracle { using SafeMath for uint256; using Uint256Casting for uint256; uint128 private constant ONE = 1e18; /** * @notice get twap converted with base & quote token decimals * @dev if period is longer than the current timestamp - first timestamp stored in the pool, this will revert with "OLD" * @param _pool uniswap pool address * @param _base base currency. to get eth/usd price, eth is base token * @param _quote quote currency. to get eth/usd price, usd is the quote currency * @param _period number of seconds in the past to start calculating time-weighted average * @return price of 1 base currency in quote currency. scaled by 1e18 */ function getTwap( address _pool, address _base, address _quote, uint32 _period, bool _checkPeriod ) external view returns (uint256) { // if the period is already checked, request TWAP directly. Will revert if period is too long. if (!_checkPeriod) return _fetchTwap(_pool, _base, _quote, _period); // make sure the requested period < maxPeriod the pool recorded. uint32 maxPeriod = _getMaxPeriod(_pool); uint32 requestPeriod = _period > maxPeriod ? maxPeriod : _period; return _fetchTwap(_pool, _base, _quote, requestPeriod); } /** * @notice get twap for a specific period of time, converted with base & quote token decimals * @dev if the _secondsAgoToStartOfTwap period is longer than the current timestamp - first timestamp stored in the pool, this will revert with "OLD" * @param _pool uniswap pool address * @param _base base currency. to get eth/usd price, eth is base token * @param _quote quote currency. to get eth/usd price, usd is the quote currency * @param _secondsAgoToStartOfTwap amount of seconds in the past to start calculating time-weighted average * @param _secondsAgoToEndOfTwap amount of seconds in the past to end calculating time-weighted average * @return price of 1 base currency in quote currency. scaled by 1e18 */ function getHistoricalTwap( address _pool, address _base, address _quote, uint32 _secondsAgoToStartOfTwap, uint32 _secondsAgoToEndOfTwap ) external view returns (uint256) { return _fetchHistoricTwap(_pool, _base, _quote, _secondsAgoToStartOfTwap, _secondsAgoToEndOfTwap); } /** * @notice get the max period that can be used to request twap * @param _pool uniswap pool address * @return max period can be used to request twap */ function getMaxPeriod(address _pool) external view returns (uint32) { return _getMaxPeriod(_pool); } /** * @notice get time weighed average tick, not converted to price * @dev this function will not revert * @param _pool address of the pool * @param _period period in second that we want to calculate average on * @return timeWeightedAverageTick the time weighted average tick */ function getTimeWeightedAverageTickSafe(address _pool, uint32 _period) external view returns (int24 timeWeightedAverageTick) { uint32 maxPeriod = _getMaxPeriod(_pool); uint32 requestPeriod = _period > maxPeriod ? maxPeriod : _period; return OracleLibrary.consultAtHistoricTime(_pool, requestPeriod, 0); } /** * @notice get twap converted with base & quote token decimals * @dev if period is longer than the current timestamp - first timestamp stored in the pool, this will revert with "OLD" * @param _pool uniswap pool address * @param _base base currency. to get eth/usd price, eth is base token * @param _quote quote currency. to get eth/usd price, usd is the quote currency * @param _period number of seconds in the past to start calculating time-weighted average * @return twap price which is scaled */ function _fetchTwap( address _pool, address _base, address _quote, uint32 _period ) internal view returns (uint256) { uint256 quoteAmountOut = _fetchRawTwap(_pool, _base, _quote, _period); uint8 baseDecimals = IERC20Detailed(_base).decimals(); uint8 quoteDecimals = IERC20Detailed(_quote).decimals(); if (baseDecimals == quoteDecimals) return quoteAmountOut; // if quote token has less decimals, the returned quoteAmountOut will be lower, need to scale up by decimal difference if (baseDecimals > quoteDecimals) return quoteAmountOut.mul(10**(baseDecimals - quoteDecimals)); // if quote token has more decimals, the returned quoteAmountOut will be higher, need to scale down by decimal difference return quoteAmountOut.div(10**(quoteDecimals - baseDecimals)); } /** * @notice get raw twap from the uniswap pool * @dev if period is longer than the current timestamp - first timestamp stored in the pool, this will revert with "OLD". * @param _pool uniswap pool address * @param _base base currency. to get eth/usd price, eth is base token * @param _quote quote currency. to get eth/usd price, usd is the quote currency * @param _period number of seconds in the past to start calculating time-weighted average * @return amount of quote currency received for _amountIn of base currency */ function _fetchRawTwap( address _pool, address _base, address _quote, uint32 _period ) internal view returns (uint256) { int24 twapTick = OracleLibrary.consultAtHistoricTime(_pool, _period, 0); return OracleLibrary.getQuoteAtTick(twapTick, ONE, _base, _quote); } /** * @notice get twap for a specific period of time, converted with base & quote token decimals * @dev if the _secondsAgoToStartOfTwap period is longer than the current timestamp - first timestamp stored in the pool, this will revert with "OLD" * @param _pool uniswap pool address * @param _base base currency. to get eth/usd price, eth is base token * @param _quote quote currency. to get eth/usd price, usd is the quote currency * @param _secondsAgoToStartOfTwap amount of seconds in the past to start calculating time-weighted average * @param _secondsAgoToEndOfTwap amount of seconds in the past to end calculating time-weighted average * @return price of 1 base currency in quote currency. scaled by 1e18 */ function _fetchHistoricTwap( address _pool, address _base, address _quote, uint32 _secondsAgoToStartOfTwap, uint32 _secondsAgoToEndOfTwap ) internal view returns (uint256) { int24 twapTick = OracleLibrary.consultAtHistoricTime(_pool, _secondsAgoToStartOfTwap, _secondsAgoToEndOfTwap); return OracleLibrary.getQuoteAtTick(twapTick, ONE, _base, _quote); } /** * @notice get the max period that can be used to request twap * @param _pool uniswap pool address * @return max period can be used to request twap */ function _getMaxPeriod(address _pool) internal view returns (uint32) { IUniswapV3Pool pool = IUniswapV3Pool(_pool); // observationIndex: the index of the last oracle observation that was written // cardinality: the current maximum number of observations stored in the pool (, , uint16 observationIndex, uint16 cardinality, , , ) = pool.slot0(); // first observation index // it's safe to use % without checking cardinality = 0 because cardinality is always >= 1 uint16 oldestObservationIndex = (observationIndex + 1) % cardinality; (uint32 oldestObservationTimestamp, , , bool initialized) = pool.observations(oldestObservationIndex); if (initialized) return uint32(block.timestamp) - oldestObservationTimestamp; // (index + 1) % cardinality is not the oldest index, // probably because cardinality is increased after last observation. // in this case, observation at index 0 should be the oldest. (oldestObservationTimestamp, , , ) = pool.observations(0); return uint32(block.timestamp) - oldestObservationTimestamp; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { }
// SPDX-License-Identifier: MIT // uniswap Library only works under 0.7.6 pragma solidity =0.7.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Detailed is IERC20 { function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
//SPDX-License-Identifier: MIT pragma solidity =0.7.6; library Uint256Casting { /** * @notice cast a uint256 to a uint128, revert on overflow * @param y the uint256 to be downcasted * @return z the downcasted integer, now type uint128 */ function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y, "OF128"); } /** * @notice cast a uint256 to a uint96, revert on overflow * @param y the uint256 to be downcasted * @return z the downcasted integer, now type uint96 */ function toUint96(uint256 y) internal pure returns (uint96 z) { require((z = uint96(y)) == y, "OF96"); } /** * @notice cast a uint256 to a uint32, revert on overflow * @param y the uint256 to be downcasted * @return z the downcasted integer, now type uint32 */ function toUint32(uint256 y) internal pure returns (uint32 z) { require((z = uint32(y)) == y, "OF32"); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.0; //interface import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; //lib import "@uniswap/v3-core/contracts/libraries/FullMath.sol"; import "@uniswap/v3-core/contracts/libraries/TickMath.sol"; /// @title oracle library /// @notice provides functions to integrate with uniswap v3 oracle /// @author uniswap team other than consultAtHistoricTime(), built by opyn library OracleLibrary { /// @notice fetches time-weighted average tick using uniswap v3 oracle /// @dev written by opyn team /// @param pool Address of uniswap v3 pool that we want to observe /// @param _secondsAgoToStartOfTwap number of seconds to start of TWAP period /// @param _secondsAgoToEndOfTwap number of seconds to end of TWAP period /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - _secondsAgoToStartOfTwap) to _secondsAgoToEndOfTwap function consultAtHistoricTime( address pool, uint32 _secondsAgoToStartOfTwap, uint32 _secondsAgoToEndOfTwap ) internal view returns (int24) { require(_secondsAgoToStartOfTwap > _secondsAgoToEndOfTwap, "BP"); int24 timeWeightedAverageTick; uint32[] memory secondAgos = new uint32[](2); uint32 twapDuration = _secondsAgoToStartOfTwap - _secondsAgoToEndOfTwap; // get TWAP from (now - _secondsAgoToStartOfTwap) -> (now - _secondsAgoToEndOfTwap) secondAgos[0] = _secondsAgoToStartOfTwap; secondAgos[1] = _secondsAgoToEndOfTwap; (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; timeWeightedAverageTick = int24(tickCumulativesDelta / (twapDuration)); // Always round to negative infinity if (tickCumulativesDelta < 0 && (tickCumulativesDelta % (twapDuration) != 0)) timeWeightedAverageTick--; return timeWeightedAverageTick; } /// @notice given a tick and a token amount, calculates the amount of token received in exchange /// @param tick tick value used to calculate the quote /// @param baseAmount amount of token to be converted /// @param baseToken address of an ERC20 token contract used as the baseAmount denomination /// @param quoteToken address of an ERC20 token contract used as the quoteAmount denomination /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken function getQuoteAtTick( int24 tick, uint128 baseAmount, address baseToken, address quoteToken ) internal pure returns (uint256 quoteAmount) { uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself if (sqrtRatioX96 <= type(uint128).max) { uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); } else { uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); quoteAmount = baseToken < quoteToken ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); }
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
// SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } }
{ "optimizer": { "enabled": true, "runs": 825 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"internalType":"address","name":"_pool","type":"address"},{"internalType":"address","name":"_base","type":"address"},{"internalType":"address","name":"_quote","type":"address"},{"internalType":"uint32","name":"_secondsAgoToStartOfTwap","type":"uint32"},{"internalType":"uint32","name":"_secondsAgoToEndOfTwap","type":"uint32"}],"name":"getHistoricalTwap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_pool","type":"address"}],"name":"getMaxPeriod","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_pool","type":"address"},{"internalType":"uint32","name":"_period","type":"uint32"}],"name":"getTimeWeightedAverageTickSafe","outputs":[{"internalType":"int24","name":"timeWeightedAverageTick","type":"int24"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_pool","type":"address"},{"internalType":"address","name":"_base","type":"address"},{"internalType":"address","name":"_quote","type":"address"},{"internalType":"uint32","name":"_period","type":"uint32"},{"internalType":"bool","name":"_checkPeriod","type":"bool"}],"name":"getTwap","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
608060405234801561001057600080fd5b50610edc806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c80634a0a96eb146100515780634ac78d111461009a578063cce79bd5146100f6578063de5a6e2214610140575b600080fd5b6100836004803603604081101561006757600080fd5b5080356001600160a01b0316906020013563ffffffff1661017f565b6040805160029290920b8252519081900360200190f35b6100e4600480360360a08110156100b057600080fd5b506001600160a01b03813581169160208101358216916040820135169063ffffffff606082013581169160800135166101c3565b60408051918252519081900360200190f35b6100e4600480360360a081101561010c57600080fd5b506001600160a01b03813581169160208101358216916040820135169063ffffffff606082013516906080013515156101de565b6101666004803603602081101561015657600080fd5b50356001600160a01b031661023c565b6040805163ffffffff9092168252519081900360200190f35b60008061018b8461024f565b905060008163ffffffff168463ffffffff16116101a857836101aa565b815b90506101b8858260006103fb565b925050505b92915050565b60006101d28686868686610713565b90505b95945050505050565b6000816101f8576101f186868686610742565b90506101d5565b60006102038761024f565b905060008163ffffffff168563ffffffff16116102205784610222565b815b905061023088888884610742565b98975050505050505050565b60006102478261024f565b90505b919050565b600080829050600080826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e06040518083038186803b15801561029157600080fd5b505afa1580156102a5573d6000803e3d6000fd5b505050506040513d60e08110156102bb57600080fd5b5060408101516060909101519092509050600061ffff808316906001850116816102e157fe5b069050600080856001600160a01b031663252c09d7846040518263ffffffff1660e01b8152600401808261ffff16815260200191505060806040518083038186803b15801561032f57600080fd5b505afa158015610343573d6000803e3d6000fd5b505050506040513d608081101561035957600080fd5b5080516060909101519092509050801561037c57504203945061024a9350505050565b856001600160a01b031663252c09d760006040518263ffffffff1660e01b81526004018082815260200191505060806040518083038186803b1580156103c157600080fd5b505afa1580156103d5573d6000803e3d6000fd5b505050506040513d60808110156103eb57600080fd5b5051420398975050505050505050565b60008163ffffffff168363ffffffff1611610442576040805162461bcd60e51b8152602060048201526002602482015261042560f41b604482015290519081900360640190fd5b6040805160028082526060820183526000928392919060208301908036833701905050905060008486039050858260008151811061047c57fe5b602002602001019063ffffffff16908163ffffffff168152505084826001815181106104a457fe5b63ffffffff90921660209283029190910182015260405163883bdbfd60e01b8152600481018281528451602483015284516000936001600160a01b038c169363883bdbfd938893909283926044019185820191028083838b5b838110156105155781810151838201526020016104fd565b505050509050019250505060006040518083038186803b15801561053857600080fd5b505afa15801561054c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604090815281101561057557600080fd5b810190808051604051939291908464010000000082111561059557600080fd5b9083019060208201858111156105aa57600080fd5b82518660208202830111640100000000821117156105c757600080fd5b82525081516020918201928201910280838360005b838110156105f45781810151838201526020016105dc565b505050509050016040526020018051604051939291908464010000000082111561061d57600080fd5b90830190602082018581111561063257600080fd5b825186602082028301116401000000008211171561064f57600080fd5b82525081516020918201928201910280838360005b8381101561067c578181015183820152602001610664565b5050505090500160405250505050905060008160008151811061069b57fe5b6020026020010151826001815181106106b057fe5b60200260200101510390508263ffffffff168160060b816106cd57fe5b05945060008160060b1280156106f757508263ffffffff168160060b816106f057fe5b0760060b15155b1561070457600019909401935b509293505050505b9392505050565b6000806107218785856103fb565b905061073781670de0b6b3a76400008888610891565b979650505050505050565b600080610751868686866109b5565b90506000856001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561078e57600080fd5b505afa1580156107a2573d6000803e3d6000fd5b505050506040513d60208110156107b857600080fd5b50516040805163313ce56760e01b815290519192506000916001600160a01b0388169163313ce567916004808301926020929190829003018186803b15801561080057600080fd5b505afa158015610814573d6000803e3d6000fd5b505050506040513d602081101561082a57600080fd5b5051905060ff828116908216141561084757829350505050610889565b8060ff168260ff161115610871576108678360ff83850316600a0a6109e4565b9350505050610889565b6108838360ff84840316600a0a610a3d565b93505050505b949350505050565b60008061089d86610aa4565b90506fffffffffffffffffffffffffffffffff6001600160a01b03821611610927576001600160a01b03808216800290848116908616106108fe576108f9600160c01b876fffffffffffffffffffffffffffffffff1683610dd6565b61091f565b61091f81876fffffffffffffffffffffffffffffffff16600160c01b610dd6565b9250506109ac565b60006109466001600160a01b0383168068010000000000000000610dd6565b9050836001600160a01b0316856001600160a01b03161061098757610982600160801b876fffffffffffffffffffffffffffffffff1683610dd6565b6109a8565b6109a881876fffffffffffffffffffffffffffffffff16600160801b610dd6565b9250505b50949350505050565b6000806109c4868460006103fb565b90506109da81670de0b6b3a76400008787610891565b9695505050505050565b6000826109f3575060006101bd565b82820282848281610a0057fe5b041461070c5760405162461bcd60e51b8152600401808060200182810382526021815260200180610e866021913960400191505060405180910390fd5b6000808211610a93576040805162461bcd60e51b815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b818381610a9c57fe5b049392505050565b60008060008360020b12610abb578260020b610ac3565b8260020b6000035b9050620d89e8811115610b01576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216610b1557600160801b610b27565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610b5b576ffff97272373d413259a46990580e213a0260801c5b6004821615610b7a576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615610b99576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615610bb8576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615610bd7576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615610bf6576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615610c15576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615610c35576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615610c55576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615610c75576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615610c95576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615610cb5576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615610cd5576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615610cf5576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615610d15576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615610d36576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615610d56576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615610d75576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615610d92576b048a170391f7dc42444e8fa20260801c5b60008460020b1315610dad578060001981610da957fe5b0490505b640100000000810615610dc1576001610dc4565b60005b60ff16602082901c0192505050919050565b6000808060001985870986860292508281109083900303905080610e0c5760008411610e0157600080fd5b50829004905061070c565b808411610e1857600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a0290910302918190038190046001018684119095039490940291909403929092049190911791909102915050939250505056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a2646970667358221220b1a443112ea45879a00fbc518b3cc36f190c9940d1022cd43a38928e460276ce64736f6c63430007060033
Deployed Bytecode
0x608060405234801561001057600080fd5b506004361061004c5760003560e01c80634a0a96eb146100515780634ac78d111461009a578063cce79bd5146100f6578063de5a6e2214610140575b600080fd5b6100836004803603604081101561006757600080fd5b5080356001600160a01b0316906020013563ffffffff1661017f565b6040805160029290920b8252519081900360200190f35b6100e4600480360360a08110156100b057600080fd5b506001600160a01b03813581169160208101358216916040820135169063ffffffff606082013581169160800135166101c3565b60408051918252519081900360200190f35b6100e4600480360360a081101561010c57600080fd5b506001600160a01b03813581169160208101358216916040820135169063ffffffff606082013516906080013515156101de565b6101666004803603602081101561015657600080fd5b50356001600160a01b031661023c565b6040805163ffffffff9092168252519081900360200190f35b60008061018b8461024f565b905060008163ffffffff168463ffffffff16116101a857836101aa565b815b90506101b8858260006103fb565b925050505b92915050565b60006101d28686868686610713565b90505b95945050505050565b6000816101f8576101f186868686610742565b90506101d5565b60006102038761024f565b905060008163ffffffff168563ffffffff16116102205784610222565b815b905061023088888884610742565b98975050505050505050565b60006102478261024f565b90505b919050565b600080829050600080826001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e06040518083038186803b15801561029157600080fd5b505afa1580156102a5573d6000803e3d6000fd5b505050506040513d60e08110156102bb57600080fd5b5060408101516060909101519092509050600061ffff808316906001850116816102e157fe5b069050600080856001600160a01b031663252c09d7846040518263ffffffff1660e01b8152600401808261ffff16815260200191505060806040518083038186803b15801561032f57600080fd5b505afa158015610343573d6000803e3d6000fd5b505050506040513d608081101561035957600080fd5b5080516060909101519092509050801561037c57504203945061024a9350505050565b856001600160a01b031663252c09d760006040518263ffffffff1660e01b81526004018082815260200191505060806040518083038186803b1580156103c157600080fd5b505afa1580156103d5573d6000803e3d6000fd5b505050506040513d60808110156103eb57600080fd5b5051420398975050505050505050565b60008163ffffffff168363ffffffff1611610442576040805162461bcd60e51b8152602060048201526002602482015261042560f41b604482015290519081900360640190fd5b6040805160028082526060820183526000928392919060208301908036833701905050905060008486039050858260008151811061047c57fe5b602002602001019063ffffffff16908163ffffffff168152505084826001815181106104a457fe5b63ffffffff90921660209283029190910182015260405163883bdbfd60e01b8152600481018281528451602483015284516000936001600160a01b038c169363883bdbfd938893909283926044019185820191028083838b5b838110156105155781810151838201526020016104fd565b505050509050019250505060006040518083038186803b15801561053857600080fd5b505afa15801561054c573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f19168201604090815281101561057557600080fd5b810190808051604051939291908464010000000082111561059557600080fd5b9083019060208201858111156105aa57600080fd5b82518660208202830111640100000000821117156105c757600080fd5b82525081516020918201928201910280838360005b838110156105f45781810151838201526020016105dc565b505050509050016040526020018051604051939291908464010000000082111561061d57600080fd5b90830190602082018581111561063257600080fd5b825186602082028301116401000000008211171561064f57600080fd5b82525081516020918201928201910280838360005b8381101561067c578181015183820152602001610664565b5050505090500160405250505050905060008160008151811061069b57fe5b6020026020010151826001815181106106b057fe5b60200260200101510390508263ffffffff168160060b816106cd57fe5b05945060008160060b1280156106f757508263ffffffff168160060b816106f057fe5b0760060b15155b1561070457600019909401935b509293505050505b9392505050565b6000806107218785856103fb565b905061073781670de0b6b3a76400008888610891565b979650505050505050565b600080610751868686866109b5565b90506000856001600160a01b031663313ce5676040518163ffffffff1660e01b815260040160206040518083038186803b15801561078e57600080fd5b505afa1580156107a2573d6000803e3d6000fd5b505050506040513d60208110156107b857600080fd5b50516040805163313ce56760e01b815290519192506000916001600160a01b0388169163313ce567916004808301926020929190829003018186803b15801561080057600080fd5b505afa158015610814573d6000803e3d6000fd5b505050506040513d602081101561082a57600080fd5b5051905060ff828116908216141561084757829350505050610889565b8060ff168260ff161115610871576108678360ff83850316600a0a6109e4565b9350505050610889565b6108838360ff84840316600a0a610a3d565b93505050505b949350505050565b60008061089d86610aa4565b90506fffffffffffffffffffffffffffffffff6001600160a01b03821611610927576001600160a01b03808216800290848116908616106108fe576108f9600160c01b876fffffffffffffffffffffffffffffffff1683610dd6565b61091f565b61091f81876fffffffffffffffffffffffffffffffff16600160c01b610dd6565b9250506109ac565b60006109466001600160a01b0383168068010000000000000000610dd6565b9050836001600160a01b0316856001600160a01b03161061098757610982600160801b876fffffffffffffffffffffffffffffffff1683610dd6565b6109a8565b6109a881876fffffffffffffffffffffffffffffffff16600160801b610dd6565b9250505b50949350505050565b6000806109c4868460006103fb565b90506109da81670de0b6b3a76400008787610891565b9695505050505050565b6000826109f3575060006101bd565b82820282848281610a0057fe5b041461070c5760405162461bcd60e51b8152600401808060200182810382526021815260200180610e866021913960400191505060405180910390fd5b6000808211610a93576040805162461bcd60e51b815260206004820152601a60248201527f536166654d6174683a206469766973696f6e206279207a65726f000000000000604482015290519081900360640190fd5b818381610a9c57fe5b049392505050565b60008060008360020b12610abb578260020b610ac3565b8260020b6000035b9050620d89e8811115610b01576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b600060018216610b1557600160801b610b27565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff1690506002821615610b5b576ffff97272373d413259a46990580e213a0260801c5b6004821615610b7a576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615610b99576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615610bb8576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615610bd7576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615610bf6576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615610c15576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615610c35576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615610c55576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615610c75576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615610c95576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615610cb5576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615610cd5576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615610cf5576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615610d15576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615610d36576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615610d56576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615610d75576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615610d92576b048a170391f7dc42444e8fa20260801c5b60008460020b1315610dad578060001981610da957fe5b0490505b640100000000810615610dc1576001610dc4565b60005b60ff16602082901c0192505050919050565b6000808060001985870986860292508281109083900303905080610e0c5760008411610e0157600080fd5b50829004905061070c565b808411610e1857600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a0290910302918190038190046001018684119095039490940291909403929092049190911791909102915050939250505056fe536166654d6174683a206d756c7469706c69636174696f6e206f766572666c6f77a2646970667358221220b1a443112ea45879a00fbc518b3cc36f190c9940d1022cd43a38928e460276ce64736f6c63430007060033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.