Overview
ETH Balance
0 ETH
ETH Value
$0.00More Info
Private Name Tags
ContractCreator
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 25 internal transactions (View All)
Parent Transaction Hash | Block | From | To | |||
---|---|---|---|---|---|---|
14995484 | 13 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14995112 | 28 mins ago | 0 ETH | ||||
14994866 | 39 mins ago | 0 ETH | ||||
14994866 | 39 mins ago | 0 ETH | ||||
14994866 | 39 mins ago | 0 ETH | ||||
14994689 | 46 mins ago | 0 ETH | ||||
14994604 | 50 mins ago | 0 ETH | ||||
14994604 | 50 mins ago | 0 ETH | ||||
14994604 | 50 mins ago | 0 ETH | ||||
14994604 | 50 mins ago | 0 ETH | ||||
14994550 | 52 mins ago | 0 ETH | ||||
14994490 | 54 mins ago | 0 ETH | ||||
14994490 | 54 mins ago | 0 ETH | ||||
14994456 | 55 mins ago | 0 ETH | ||||
14994456 | 55 mins ago | 0 ETH | ||||
14994456 | 55 mins ago | 0 ETH |
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Contract Name:
Position
Compiler Version
v0.7.6+commit.7338295f
Optimization Enabled:
Yes with 800 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.0; pragma abicoder v2; import './FullMath.sol'; import './FixedPoint128.sol'; import './FixedPoint32.sol'; import './LiquidityMath.sol'; import './SqrtPriceMath.sol'; import './States.sol'; import './Tick.sol'; import './TickMath.sol'; import './TickBitmap.sol'; import './Oracle.sol'; import '../../v2-periphery/libraries/LiquidityAmounts.sol'; import '../../interfaces/IVotingEscrow.sol'; import '../../interfaces/IVoter.sol'; /// @title Position /// @notice Positions represent an owner address' liquidity between a lower and upper tick boundary /// @dev Positions store additional state for tracking fees owed to the position library Position { // no limit if a your veNFT reaches a threshold // if veNFTRatio is more than 2.5% of total (2.5% * 1.5e18 = 3.75e+16) uint256 internal constant veNftUncapThreshold = 37500000000000000; /// @notice Returns the hash used to store positions in a mapping /// @param owner The address of the position owner /// @param index The index of the position /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @return _hash The hash used to store positions in a mapping function positionHash( address owner, uint256 index, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(owner, index, tickLower, tickUpper)); } /// @notice Returns the Info struct of a position, given an owner and position boundaries /// @param self The mapping containing all user positions /// @param owner The address of the position owner /// @param index The index of the position /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @return position The position info struct of the given owners' position function get( mapping(bytes32 => PositionInfo) storage self, address owner, uint256 index, int24 tickLower, int24 tickUpper ) public view returns (PositionInfo storage position) { position = self[positionHash(owner, index, tickLower, tickUpper)]; } /// @notice Returns the BoostInfo struct of a position, given an owner, index, and position boundaries /// @param self The mapping containing all user boosted positions within the period /// @param owner The address of the position owner /// @param index The index of the position /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @return position The position BoostInfo struct of the given owners' position within the period function get( PeriodBoostInfo storage self, address owner, uint256 index, int24 tickLower, int24 tickUpper ) public view returns (BoostInfo storage position) { position = self.positions[positionHash(owner, index, tickLower, tickUpper)]; } /// @notice Credits accumulated fees to a user's position /// @param self The individual position to update /// @param liquidityDelta The change in pool liquidity as a result of the position update /// @param feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries /// @param feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries function _updatePositionLiquidity( PositionInfo storage self, States.PoolStates storage states, uint256 period, bytes32 _positionHash, int128 liquidityDelta, uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128 ) internal { PositionInfo memory _self = self; uint128 liquidityNext; if (liquidityDelta == 0) { require(_self.liquidity > 0, 'NP'); // disallow pokes for 0 liquidity positions liquidityNext = _self.liquidity; } else { liquidityNext = LiquidityMath.addDelta(_self.liquidity, liquidityDelta); } // calculate accumulated fees uint128 tokensOwed0 = uint128( FullMath.mulDiv(feeGrowthInside0X128 - _self.feeGrowthInside0LastX128, _self.liquidity, FixedPoint128.Q128) ); uint128 tokensOwed1 = uint128( FullMath.mulDiv(feeGrowthInside1X128 - _self.feeGrowthInside1LastX128, _self.liquidity, FixedPoint128.Q128) ); // update the position if (liquidityDelta != 0) { self.liquidity = liquidityNext; } self.feeGrowthInside0LastX128 = feeGrowthInside0X128; self.feeGrowthInside1LastX128 = feeGrowthInside1X128; if (tokensOwed0 > 0 || tokensOwed1 > 0) { // overflow is acceptable, have to withdraw before you hit type(uint128).max fees self.tokensOwed0 += tokensOwed0; self.tokensOwed1 += tokensOwed1; } // write checkpoint, push a checkpoint if the last period is different, overwrite if not uint256 checkpointLength = states.positionCheckpoints[_positionHash].length; if (checkpointLength == 0 || states.positionCheckpoints[_positionHash][checkpointLength - 1].period != period) { states.positionCheckpoints[_positionHash].push( PositionCheckpoint({period: period, liquidity: liquidityNext}) ); } else { states.positionCheckpoints[_positionHash][checkpointLength - 1].liquidity = liquidityNext; } } /// @notice Updates boosted balances to a user's position /// @param self The individual boosted position to update /// @param boostedLiquidityDelta The change in pool liquidity as a result of the position update /// @param secondsPerBoostedLiquidityPeriodX128 The seconds in range gained per unit of liquidity, inside the position's tick boundaries for this period function _updateBoostedPosition( BoostInfo storage self, int128 liquidityDelta, int128 boostedLiquidityDelta, uint160 secondsPerLiquidityPeriodX128, uint160 secondsPerBoostedLiquidityPeriodX128 ) internal { // negative expected sometimes, which is allowed int160 secondsPerLiquidityPeriodIntX128 = int160(secondsPerLiquidityPeriodX128); int160 secondsPerBoostedLiquidityPeriodIntX128 = int160(secondsPerBoostedLiquidityPeriodX128); self.boostAmount = LiquidityMath.addDelta(self.boostAmount, boostedLiquidityDelta); int160 secondsPerLiquidityPeriodStartX128 = self.secondsPerLiquidityPeriodStartX128; int160 secondsPerBoostedLiquidityPeriodStartX128 = self.secondsPerBoostedLiquidityPeriodStartX128; // take the difference to make the delta positive or zero secondsPerLiquidityPeriodIntX128 -= secondsPerLiquidityPeriodStartX128; secondsPerBoostedLiquidityPeriodIntX128 -= secondsPerBoostedLiquidityPeriodStartX128; // these int should never be negative if (secondsPerLiquidityPeriodIntX128 < 0) { secondsPerLiquidityPeriodIntX128 = 0; } if (secondsPerBoostedLiquidityPeriodIntX128 < 0) { secondsPerBoostedLiquidityPeriodIntX128 = 0; } int256 secondsDebtDeltaX96 = SafeCast.toInt256( FullMath.mulDivRoundingUp( liquidityDelta > 0 ? uint256(liquidityDelta) : uint256(-liquidityDelta), uint256(secondsPerLiquidityPeriodIntX128), FixedPoint32.Q32 ) ); int256 boostedSecondsDebtDeltaX96 = SafeCast.toInt256( FullMath.mulDivRoundingUp( boostedLiquidityDelta > 0 ? uint256(boostedLiquidityDelta) : uint256(-boostedLiquidityDelta), uint256(secondsPerBoostedLiquidityPeriodIntX128), FixedPoint32.Q32 ) ); self.boostedSecondsDebtX96 = boostedLiquidityDelta > 0 ? self.boostedSecondsDebtX96 + boostedSecondsDebtDeltaX96 : self.boostedSecondsDebtX96 - boostedSecondsDebtDeltaX96; // can't overflow since each period is way less than uint31 self.secondsDebtX96 = liquidityDelta > 0 ? self.secondsDebtX96 + secondsDebtDeltaX96 : self.secondsDebtX96 - secondsDebtDeltaX96; // can't overflow since each period is way less than uint31 } /// @notice Initializes secondsPerLiquidityPeriodStartX128 for a position /// @param self The individual boosted position to update /// @param position The individual position /// @param secondsInRangeParams Parameters used to find the seconds in range /// @param secondsPerLiquidityPeriodX128 The seconds in range gained per unit of liquidity, inside the position's tick boundaries for this period /// @param secondsPerBoostedLiquidityPeriodX128 The seconds in range gained per unit of liquidity, inside the position's tick boundaries for this period function initializeSecondsStart( BoostInfo storage self, PositionInfo storage position, PositionPeriodSecondsInRangeParams memory secondsInRangeParams, uint160 secondsPerLiquidityPeriodX128, uint160 secondsPerBoostedLiquidityPeriodX128 ) internal { // record initialized self.initialized = true; // record owed tokens if liquidity > 0 (means position existed before period change) if (position.liquidity > 0) { (uint256 periodSecondsInsideX96, uint256 periodBoostedSecondsInsideX96) = positionPeriodSecondsInRange( secondsInRangeParams ); self.secondsDebtX96 = -int256(periodSecondsInsideX96); self.boostedSecondsDebtX96 = -int256(periodBoostedSecondsInsideX96); } // convert uint to int // negative expected sometimes, which is allowed int160 secondsPerLiquidityPeriodIntX128 = int160(secondsPerLiquidityPeriodX128); int160 secondsPerBoostedLiquidityPeriodIntX128 = int160(secondsPerBoostedLiquidityPeriodX128); self.secondsPerLiquidityPeriodStartX128 = secondsPerLiquidityPeriodIntX128; self.secondsPerBoostedLiquidityPeriodStartX128 = secondsPerBoostedLiquidityPeriodIntX128; } struct ModifyPositionParams { // the address that owns the position address owner; uint256 index; // the lower and upper tick of the position int24 tickLower; int24 tickUpper; // any change in liquidity int128 liquidityDelta; uint256 veNftTokenId; } /// @dev Effect some changes to a position /// @param params the position details and the change to the position's liquidity to effect /// @return position a storage pointer referencing the position with the given owner and tick range /// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient /// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient function _modifyPosition( ModifyPositionParams memory params ) external returns (PositionInfo storage position, int256 amount0, int256 amount1) { States.PoolStates storage states = States.getStorage(); // check ticks require(params.tickLower < params.tickUpper, 'TLU'); require(params.tickLower >= TickMath.MIN_TICK, 'TLM'); require(params.tickUpper <= TickMath.MAX_TICK, 'TUM'); Slot0 memory _slot0 = states.slot0; // SLOAD for gas optimization int128 boostedLiquidityDelta; (position, boostedLiquidityDelta) = _updatePosition( UpdatePositionParams({ owner: params.owner, index: params.index, tickLower: params.tickLower, tickUpper: params.tickUpper, liquidityDelta: params.liquidityDelta, tick: _slot0.tick, veNftTokenId: params.veNftTokenId }) ); if (params.liquidityDelta != 0 || boostedLiquidityDelta != 0) { if (_slot0.tick < params.tickLower) { // current tick is below the passed range; liquidity can only become in range by crossing from left to // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it amount0 = SqrtPriceMath.getAmount0Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); } else if (_slot0.tick < params.tickUpper) { // current tick is inside the passed range uint128 liquidityBefore = states.liquidity; // SLOAD for gas optimization uint128 boostedLiquidityBefore = states.boostedLiquidity; // write an oracle entry (states.slot0.observationIndex, states.slot0.observationCardinality) = Oracle.write( states.observations, _slot0.observationIndex, States._blockTimestamp(), _slot0.tick, liquidityBefore, boostedLiquidityBefore, _slot0.observationCardinality, _slot0.observationCardinalityNext ); amount0 = SqrtPriceMath.getAmount0Delta( _slot0.sqrtPriceX96, TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); amount1 = SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), _slot0.sqrtPriceX96, params.liquidityDelta ); states.liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta); states.boostedLiquidity = LiquidityMath.addDelta(boostedLiquidityBefore, boostedLiquidityDelta); } else { // current tick is above the passed range; liquidity can only become in range by crossing from right to // left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it amount1 = SqrtPriceMath.getAmount1Delta( TickMath.getSqrtRatioAtTick(params.tickLower), TickMath.getSqrtRatioAtTick(params.tickUpper), params.liquidityDelta ); } } } struct UpdatePositionParams { // the owner of the position address owner; // the index of the position uint256 index; // the lower tick of the position's tick range int24 tickLower; // the upper tick of the position's tick range int24 tickUpper; // the amount liquidity changes by int128 liquidityDelta; // the current tick, passed to avoid sloads int24 tick; // the veNFTTokenId to be attached uint256 veNftTokenId; } struct UpdatePositionCache { uint256 feeGrowthGlobal0X128; uint256 feeGrowthGlobal1X128; bool flippedUpper; bool flippedLower; uint256 feeGrowthInside0X128; uint256 feeGrowthInside1X128; } struct ObservationCache { int56 tickCumulative; uint160 secondsPerLiquidityCumulativeX128; uint160 secondsPerBoostedLiquidityPeriodX128; } struct PoolBalanceCache { uint256 hypBalance0; uint256 hypBalance1; uint256 poolBalance0; uint256 poolBalance1; } struct BoostedLiquidityCache { uint256 veNftRatio; uint256 newBoostedLiquidity; uint160 lowerSqrtRatioX96; uint160 upperSqrtRatioX96; uint160 currentSqrtRatioX96; } struct VeNftBoostCache { uint256 veNftBoostUsedRatio; uint256 positionBoostUsedRatio; } /// @dev Gets and updates a position with the given liquidity delta /// @param params the position details and the change to the position's liquidity to effect function _updatePosition( UpdatePositionParams memory params ) private returns (PositionInfo storage position, int128 boostedLiquidityDelta) { States.PoolStates storage states = States.getStorage(); uint256 period = States._blockTimestamp() / 1 weeks; bytes32 _positionHash = positionHash(params.owner, params.index, params.tickLower, params.tickUpper); position = states.positions[_positionHash]; BoostInfo storage boostedPosition = states.boostInfos[period].positions[_positionHash]; { // this is needed to determine attachment and newBoostedLiquidity uint128 newLiquidity = LiquidityMath.addDelta(position.liquidity, params.liquidityDelta); // detach if new liquidity is 0 if (newLiquidity == 0) { _switchAttached(position, boostedPosition, 0, period, _positionHash); params.veNftTokenId = 0; } // type(uint256).max serves as a signal to not switch attachment if (params.veNftTokenId != type(uint256).max) { _switchAttached(position, boostedPosition, params.veNftTokenId, period, _positionHash); } { BoostedLiquidityCache memory boostedLiquidityCache; (boostedLiquidityCache.veNftRatio, boostedLiquidityCache.newBoostedLiquidity) = LiquidityMath .calculateBoostedLiquidity( newLiquidity, boostedPosition.veNftAmount, states.boostInfos[period].totalVeNftAmount ); if (boostedLiquidityCache.newBoostedLiquidity > 0) { PoolBalanceCache memory poolBalanceCache; poolBalanceCache.poolBalance0 = States.balance0(); poolBalanceCache.poolBalance1 = States.balance1(); boostedLiquidityCache.lowerSqrtRatioX96 = TickMath.getSqrtRatioAtTick(params.tickLower); boostedLiquidityCache.upperSqrtRatioX96 = TickMath.getSqrtRatioAtTick(params.tickUpper); boostedLiquidityCache.currentSqrtRatioX96 = states.slot0.sqrtPriceX96; // boosted liquidity cap // no limit if a your veNFT reaches a threshold if (boostedLiquidityCache.veNftRatio < veNftUncapThreshold) { uint160 midSqrtRatioX96 = TickMath.getSqrtRatioAtTick( (params.tickLower + params.tickUpper) / 2 ); // check max balance allowed { uint256 maxBalance0 = LiquidityAmounts.getAmount0ForLiquidity( midSqrtRatioX96, boostedLiquidityCache.upperSqrtRatioX96, type(uint128).max ); uint256 maxBalance1 = LiquidityAmounts.getAmount1ForLiquidity( boostedLiquidityCache.lowerSqrtRatioX96, midSqrtRatioX96, type(uint128).max ); if (poolBalanceCache.poolBalance0 > maxBalance0) { poolBalanceCache.hypBalance0 = maxBalance0; } else { poolBalanceCache.hypBalance0 = poolBalanceCache.poolBalance0; } if (poolBalanceCache.poolBalance1 > maxBalance1) { poolBalanceCache.hypBalance1 = maxBalance1; } else { poolBalanceCache.hypBalance1 = poolBalanceCache.poolBalance1; } } // hypothetical liquidity is found by using all of balance0 and balance1 // at this position's midpoint and range // using midpoint to discourage making out of range positions uint256 hypotheticalLiquidity = LiquidityAmounts.getLiquidityForAmounts( midSqrtRatioX96, boostedLiquidityCache.lowerSqrtRatioX96, boostedLiquidityCache.upperSqrtRatioX96, poolBalanceCache.hypBalance0, poolBalanceCache.hypBalance1 ); // limit newBoostedLiquidity to a portion of hypotheticalLiquidity based on how much veNFT is attached uint256 boostedLiquidityCap = FullMath.mulDiv( hypotheticalLiquidity, boostedLiquidityCache.veNftRatio, 1e18 ); if (boostedLiquidityCache.newBoostedLiquidity > boostedLiquidityCap) { boostedLiquidityCache.newBoostedLiquidity = boostedLiquidityCap; } } // veNFT boost available uint256 veNftBoostAvailable; VeNftBoostCache memory veNftBoostCache; { // fetch existing data veNftBoostCache.positionBoostUsedRatio = states .boostInfos[period] .veNftInfos[params.veNftTokenId] .positionBoostUsedRatio[_positionHash]; veNftBoostCache.veNftBoostUsedRatio = states .boostInfos[period] .veNftInfos[params.veNftTokenId] .veNftBoostUsedRatio; // prevents underflows veNftBoostCache.veNftBoostUsedRatio = veNftBoostCache.veNftBoostUsedRatio > veNftBoostCache.positionBoostUsedRatio ? veNftBoostCache.veNftBoostUsedRatio - veNftBoostCache.positionBoostUsedRatio : 0; uint256 veNftBoostAvailableRatio = 1e18 > veNftBoostCache.veNftBoostUsedRatio ? 1e18 - veNftBoostCache.veNftBoostUsedRatio : 0; // no limit if a your veNFT reaches a threshold // hypothetical balances still have to be calculated in case // the veNFT falls below threshold later if (boostedLiquidityCache.veNftRatio >= veNftUncapThreshold) { veNftBoostAvailableRatio = 1e18; } // assign hypBalances { uint256 maxBalance0 = 0; uint256 maxBalance1 = 0; if (boostedLiquidityCache.currentSqrtRatioX96 < boostedLiquidityCache.lowerSqrtRatioX96) { maxBalance0 = LiquidityAmounts.getAmount0ForLiquidity( boostedLiquidityCache.lowerSqrtRatioX96, boostedLiquidityCache.upperSqrtRatioX96, type(uint128).max ); } else if ( boostedLiquidityCache.currentSqrtRatioX96 < boostedLiquidityCache.upperSqrtRatioX96 ) { maxBalance0 = LiquidityAmounts.getAmount0ForLiquidity( boostedLiquidityCache.currentSqrtRatioX96, boostedLiquidityCache.upperSqrtRatioX96, type(uint128).max ); maxBalance1 = LiquidityAmounts.getAmount1ForLiquidity( boostedLiquidityCache.lowerSqrtRatioX96, boostedLiquidityCache.currentSqrtRatioX96, type(uint128).max ); } else { maxBalance1 = LiquidityAmounts.getAmount1ForLiquidity( boostedLiquidityCache.lowerSqrtRatioX96, boostedLiquidityCache.upperSqrtRatioX96, type(uint128).max ); } if (poolBalanceCache.poolBalance0 > maxBalance0) { poolBalanceCache.hypBalance0 = maxBalance0; } else { poolBalanceCache.hypBalance0 = poolBalanceCache.poolBalance0; } if (poolBalanceCache.poolBalance1 > maxBalance1) { poolBalanceCache.hypBalance1 = maxBalance1; } else { poolBalanceCache.hypBalance1 = poolBalanceCache.poolBalance1; } } // hypothetical liquidity is found by using all of balance0 and balance1 // at current price to determine % boost used since boost will fill up fast otherwise uint256 hypotheticalLiquidity = LiquidityAmounts.getLiquidityForAmounts( boostedLiquidityCache.currentSqrtRatioX96, boostedLiquidityCache.lowerSqrtRatioX96, boostedLiquidityCache.upperSqrtRatioX96, poolBalanceCache.hypBalance0, poolBalanceCache.hypBalance1 ); hypotheticalLiquidity = FullMath.mulDiv( hypotheticalLiquidity, boostedLiquidityCache.veNftRatio, 1e18 ); veNftBoostAvailable = FullMath.mulDiv(hypotheticalLiquidity, veNftBoostAvailableRatio, 1e18); if ( boostedLiquidityCache.newBoostedLiquidity > veNftBoostAvailable && boostedLiquidityCache.veNftRatio < veNftUncapThreshold ) { boostedLiquidityCache.newBoostedLiquidity = veNftBoostAvailable; } veNftBoostCache.positionBoostUsedRatio = hypotheticalLiquidity == 0 ? 0 : FullMath.mulDiv(boostedLiquidityCache.newBoostedLiquidity, 1e18, hypotheticalLiquidity); } // update veNFTBoostUsedRatio and positionBoostUsedRatio states.boostInfos[period].veNftInfos[params.veNftTokenId].positionBoostUsedRatio[ _positionHash ] = veNftBoostCache.positionBoostUsedRatio; states.boostInfos[period].veNftInfos[params.veNftTokenId].veNftBoostUsedRatio = uint128( veNftBoostCache.veNftBoostUsedRatio + veNftBoostCache.positionBoostUsedRatio ); } boostedLiquidityDelta = int128(boostedLiquidityCache.newBoostedLiquidity - boostedPosition.boostAmount); } } UpdatePositionCache memory cache; cache.feeGrowthGlobal0X128 = states.feeGrowthGlobal0X128; // SLOAD for gas optimization cache.feeGrowthGlobal1X128 = states.feeGrowthGlobal1X128; // SLOAD for gas optimization // if we need to update the ticks, do it if (params.liquidityDelta != 0 || boostedLiquidityDelta != 0) { uint32 time = States._blockTimestamp(); ObservationCache memory observationCache; ( observationCache.tickCumulative, observationCache.secondsPerLiquidityCumulativeX128, observationCache.secondsPerBoostedLiquidityPeriodX128 ) = Oracle.observeSingle( states.observations, time, 0, states.slot0.tick, states.slot0.observationIndex, states.liquidity, states.boostedLiquidity, states.slot0.observationCardinality ); cache.flippedLower = Tick.update( states._ticks, Tick.UpdateTickParams( params.tickLower, params.tick, params.liquidityDelta, boostedLiquidityDelta, cache.feeGrowthGlobal0X128, cache.feeGrowthGlobal1X128, observationCache.secondsPerLiquidityCumulativeX128, observationCache.secondsPerBoostedLiquidityPeriodX128, observationCache.tickCumulative, time, false, states.maxLiquidityPerTick ) ); cache.flippedUpper = Tick.update( states._ticks, Tick.UpdateTickParams( params.tickUpper, params.tick, params.liquidityDelta, boostedLiquidityDelta, cache.feeGrowthGlobal0X128, cache.feeGrowthGlobal1X128, observationCache.secondsPerLiquidityCumulativeX128, observationCache.secondsPerBoostedLiquidityPeriodX128, observationCache.tickCumulative, time, true, states.maxLiquidityPerTick ) ); if (cache.flippedLower) { TickBitmap.flipTick(states.tickBitmap, params.tickLower, states.tickSpacing); } if (cache.flippedUpper) { TickBitmap.flipTick(states.tickBitmap, params.tickUpper, states.tickSpacing); } } (cache.feeGrowthInside0X128, cache.feeGrowthInside1X128) = Tick.getFeeGrowthInside( states._ticks, params.tickLower, params.tickUpper, params.tick, cache.feeGrowthGlobal0X128, cache.feeGrowthGlobal1X128 ); { (uint160 secondsPerLiquidityPeriodX128, uint160 secondsPerBoostedLiquidityPeriodX128) = Oracle .periodCumulativesInside(uint32(period), params.tickLower, params.tickUpper); if (!boostedPosition.initialized) { initializeSecondsStart( boostedPosition, position, PositionPeriodSecondsInRangeParams({ period: period, owner: params.owner, index: params.index, tickLower: params.tickLower, tickUpper: params.tickUpper }), secondsPerLiquidityPeriodX128, secondsPerBoostedLiquidityPeriodX128 ); } _updatePositionLiquidity( position, states, period, _positionHash, params.liquidityDelta, cache.feeGrowthInside0X128, cache.feeGrowthInside1X128 ); _updateBoostedPosition( boostedPosition, params.liquidityDelta, boostedLiquidityDelta, secondsPerLiquidityPeriodX128, secondsPerBoostedLiquidityPeriodX128 ); } // clear any tick data that is no longer needed if (params.liquidityDelta < 0) { if (cache.flippedLower) { Tick.clear(states._ticks, params.tickLower); } if (cache.flippedUpper) { Tick.clear(states._ticks, params.tickUpper); } } } /// @notice updates attached veNFT tokenId and veNFT amount /// @dev can only be called in _updatePostion since boostedSecondsDebt needs to be updated when this is called /// @param position the user's position /// @param boostedPosition the user's boosted position /// @param veNftTokenId the veNFT tokenId to switch to /// @param _positionHash the position's hash identifier function _switchAttached( PositionInfo storage position, BoostInfo storage boostedPosition, uint256 veNftTokenId, uint256 period, bytes32 _positionHash ) private { States.PoolStates storage states = States.getStorage(); address _votingEscrow = states.votingEscrow; require( veNftTokenId == 0 || msg.sender == states.nfpManager || IVotingEscrow(_votingEscrow).isApprovedOrOwner(msg.sender, veNftTokenId), 'TNA' // tokenId not authorized ); int128 veNftAmountDelta; uint256 oldAttached = position.attachedVeNftTokenId; // call detach and attach if needed if (veNftTokenId != oldAttached) { address _voter = states.voter; // detach, remove position from VeNFTAttachments, and update total veNFTAmount if (oldAttached != 0) { // call voter to notify detachment IVoter(_voter).detachTokenFromGauge(oldAttached, IVotingEscrow(_votingEscrow).ownerOf(oldAttached)); // update times attached and veNFTAmountDelta uint128 timesAttached = states.boostInfos[period].veNftInfos[oldAttached].timesAttached; // only modify veNFTAmountDelta if this is the last time // this veNFT has been used to attach to a position if (timesAttached == 1) { veNftAmountDelta -= boostedPosition.veNftAmount; } // update times this veNFT NFT has been attached to this pool states.boostInfos[period].veNftInfos[oldAttached].timesAttached = timesAttached - 1; // update veNFTBoostUsedRatio and positionBoostUsedRatio uint256 positionBoostUsedRatio = states .boostInfos[period] .veNftInfos[oldAttached] .positionBoostUsedRatio[_positionHash]; states.boostInfos[period].veNftInfos[oldAttached].veNftBoostUsedRatio -= uint128( positionBoostUsedRatio ); states.boostInfos[period].veNftInfos[oldAttached].positionBoostUsedRatio[_positionHash] = 0; } if (veNftTokenId != 0) { // call voter to notify attachment IVoter(_voter).attachTokenToGauge(veNftTokenId, IVotingEscrow(_votingEscrow).ownerOf(veNftTokenId)); } position.attachedVeNftTokenId = veNftTokenId; } if (veNftTokenId != 0) { // record new attachment amount int128 veNftAmountAfter = int128(IVotingEscrow(_votingEscrow).balanceOfNFT(veNftTokenId)); // can't overflow because bias is lower than locked, which is an int128 boostedPosition.veNftAmount = veNftAmountAfter; // update times attached and veNFTAmountDelta uint128 timesAttached = states.boostInfos[period].veNftInfos[veNftTokenId].timesAttached; // only add to veNFT total amount if it's newly attached to the pool if (timesAttached == 0) { veNftAmountDelta += veNftAmountAfter; } // update times attached states.boostInfos[period].veNftInfos[veNftTokenId].timesAttached = timesAttached + 1; } else { boostedPosition.veNftAmount = 0; } // update total veNFT amount int128 totalVeNftAmount = states.boostInfos[period].totalVeNftAmount; totalVeNftAmount += veNftAmountDelta; if (totalVeNftAmount < 0) { totalVeNftAmount = 0; } states.boostInfos[period].totalVeNftAmount = totalVeNftAmount; } /// @notice gets the checkpoint directly before the period /// @dev returns the 0th index if there's no checkpoints /// @param checkpoints the position's checkpoints in storage /// @param period the period of interest function getCheckpoint( PositionCheckpoint[] storage checkpoints, uint256 period ) internal view returns (uint256 checkpointIndex, uint256 checkpointPeriod) { { uint256 checkpointLength = checkpoints.length; // return 0 if length is 0 if (checkpointLength == 0) { return (0, 0); } checkpointPeriod = checkpoints[0].period; // return 0 if first checkpoint happened after period if (checkpointPeriod > period) { return (0, 0); } checkpointIndex = checkpointLength - 1; } checkpointPeriod = checkpoints[checkpointIndex].period; // Find relevant checkpoint if latest checkpoint isn't before period of interest if (checkpointPeriod > period) { uint256 lower = 0; uint256 upper = checkpointIndex; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow checkpointPeriod = checkpoints[center].period; if (checkpointPeriod == period) { checkpointIndex = center; return (checkpointIndex, checkpointPeriod); } else if (checkpointPeriod < period) { lower = center; } else { upper = center - 1; } } checkpointIndex = lower; checkpointPeriod = checkpoints[checkpointIndex].period; } return (checkpointIndex, checkpointPeriod); } struct PositionPeriodSecondsInRangeParams { uint256 period; address owner; uint256 index; int24 tickLower; int24 tickUpper; } // Get the period seconds in range of a specific position /// @return periodSecondsInsideX96 seconds the position was not in range for the period /// @return periodBoostedSecondsInsideX96 boosted seconds the period function positionPeriodSecondsInRange( PositionPeriodSecondsInRangeParams memory params ) public view returns (uint256 periodSecondsInsideX96, uint256 periodBoostedSecondsInsideX96) { States.PoolStates storage states = States.getStorage(); { uint256 currentPeriod = states.lastPeriod; require(params.period <= currentPeriod, 'FTR'); // Future period, or current period hasn't been updated } bytes32 _positionHash = positionHash(params.owner, params.index, params.tickLower, params.tickUpper); uint256 liquidity; uint256 boostedLiquidity; int160 secondsPerLiquidityPeriodStartX128; int160 secondsPerBoostedLiquidityPeriodStartX128; { PositionCheckpoint[] storage checkpoints = states.positionCheckpoints[_positionHash]; // get checkpoint at period, or last checkpoint before the period (uint256 checkpointIndex, uint256 checkpointPeriod) = getCheckpoint(checkpoints, params.period); // Return 0s if checkpointPeriod is 0 if (checkpointPeriod == 0) { return (0, 0); } liquidity = checkpoints[checkpointIndex].liquidity; // use period instead of checkpoint period for boosted liquidity because it needs to be renewed weekly boostedLiquidity = states.boostInfos[params.period].positions[_positionHash].boostAmount; secondsPerLiquidityPeriodStartX128 = states .boostInfos[params.period] .positions[_positionHash] .secondsPerLiquidityPeriodStartX128; secondsPerBoostedLiquidityPeriodStartX128 = states .boostInfos[params.period] .positions[_positionHash] .secondsPerBoostedLiquidityPeriodStartX128; } (uint160 secondsPerLiquidityInsideX128, uint160 secondsPerBoostedLiquidityInsideX128) = Oracle .periodCumulativesInside(uint32(params.period), params.tickLower, params.tickUpper); // underflow will be protected by sanity check secondsPerLiquidityInsideX128 = uint160( int160(secondsPerLiquidityInsideX128) - secondsPerLiquidityPeriodStartX128 ); secondsPerBoostedLiquidityInsideX128 = uint160( int160(secondsPerBoostedLiquidityInsideX128) - secondsPerBoostedLiquidityPeriodStartX128 ); BoostInfo storage boostPosition = states.boostInfos[params.period].positions[_positionHash]; int256 secondsDebtX96 = boostPosition.secondsDebtX96; int256 boostedSecondsDebtX96 = boostPosition.boostedSecondsDebtX96; // addDelta checks for under and overflows periodSecondsInsideX96 = FullMath.mulDiv(liquidity, secondsPerLiquidityInsideX128, FixedPoint32.Q32); // Need to check if secondsDebtX96>periodSecondsInsideX96, since rounding can cause underflows if (secondsDebtX96 < 0 || periodSecondsInsideX96 > uint256(secondsDebtX96)) { periodSecondsInsideX96 = LiquidityMath.addDelta256(periodSecondsInsideX96, -secondsDebtX96); } else { periodSecondsInsideX96 = 0; } // addDelta checks for under and overflows periodBoostedSecondsInsideX96 = FullMath.mulDiv( boostedLiquidity, secondsPerBoostedLiquidityInsideX128, FixedPoint32.Q32 ); // Need to check if secondsDebtX96>periodSecondsInsideX96, since rounding can cause underflows if (boostedSecondsDebtX96 < 0 || periodBoostedSecondsInsideX96 > uint256(boostedSecondsDebtX96)) { periodBoostedSecondsInsideX96 = LiquidityMath.addDelta256( periodBoostedSecondsInsideX96, -boostedSecondsDebtX96 ); } else { periodBoostedSecondsInsideX96 = 0; } // sanity if (periodSecondsInsideX96 > 1 weeks * FixedPoint96.Q96) { periodSecondsInsideX96 = 0; } if (periodBoostedSecondsInsideX96 > 1 weeks * FixedPoint96.Q96) { periodBoostedSecondsInsideX96 = 0; } // require(periodSecondsInsideX96 <= 1 weeks * FixedPoint96.Q96); // require(periodBoostedSecondsInsideX96 <= 1 weeks * FixedPoint96.Q96); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6 || ^0.8.13; pragma abicoder v2; interface IVoter { function _ve() external view returns (address); function governor() external view returns (address); function emergencyCouncil() external view returns (address); function attachTokenToGauge(uint256 _tokenId, address account) external; function detachTokenFromGauge(uint256 _tokenId, address account) external; function emitDeposit( uint256 _tokenId, address account, uint256 amount ) external; function emitWithdraw( uint256 _tokenId, address account, uint256 amount ) external; function isWhitelisted(address token) external view returns (bool); function notifyRewardAmount(uint256 amount) external; function distribute(address _gauge) external; function gauges(address pool) external view returns (address); function feeDistributors(address gauge) external view returns (address); function gaugefactory() external view returns (address); function feeDistributorFactory() external view returns (address); function minter() external view returns (address); function factory() external view returns (address); function length() external view returns (uint256); function pools(uint256) external view returns (address); function isAlive(address) external view returns (bool); function setXRatio(uint256 _xRatio) external; function setPoolXRatio( address[] calldata _gauges, uint256[] calldata _xRaRatios ) external; function resetGaugeXRatio(address[] calldata _gauges) external; function whitelist(address _token) external; function forbid(address _token, bool _status) external; function whitelistOperator() external view returns (address); function gaugeXRatio(address gauge) external view returns (uint256); function isGauge(address gauge) external view returns (bool); function killGauge(address _gauge) external; function reviveGauge(address _gauge) external; function stale(uint256 _tokenID) external view returns (bool); function poolForGauge(address gauge) external view returns (address pool); function recoverFees( address[] calldata fees, address[][] calldata tokens ) external; function designateStale(uint256 _tokenId, bool _status) external; function base() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity =0.7.6 || ^0.8.13; pragma abicoder v2; interface IVotingEscrow { struct Point { int128 bias; int128 slope; // # -dweight / dt uint256 ts; uint256 blk; // block } struct LockedBalance { int128 amount; uint256 end; } function emissionsToken() external view returns (address); function team() external returns (address); function epoch() external view returns (uint256); function pointHistory(uint256 loc) external view returns (Point memory); function userPointHistory( uint256 tokenId, uint256 loc ) external view returns (Point memory); function userPointEpoch(uint256 tokenId) external view returns (uint256); function ownerOf(uint256) external view returns (address); function isApprovedOrOwner(address, uint256) external view returns (bool); function transferFrom(address, address, uint256) external; function voting(uint256 tokenId) external; function abstain(uint256 tokenId) external; function attach(uint256 tokenId) external; function detach(uint256 tokenId) external; function checkpoint() external; function depositFor(uint256 tokenId, uint256 value) external; function createLockFor( uint256, uint256, address ) external returns (uint256); function balanceOfNFT(uint256) external view returns (uint256); function balanceOfNFTAt(uint256, uint256) external view returns (uint256); function totalSupply() external view returns (uint256); function locked__end(uint256) external view returns (uint256); function balanceOf(address) external view returns (uint256); function tokenOfOwnerByIndex( address, uint256 ) external view returns (uint256); function increaseUnlockTime(uint256 tokenID, uint256 duration) external; function locked( uint256 tokenID ) external view returns (uint256 amount, uint256 unlockTime); function increaseAmount(uint256 _tokenId, uint256 _value) external; function isDelegate( address _operator, uint256 _tokenId ) external view returns (bool); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.0; import './../../v2/libraries/FullMath.sol'; import './../../v2/libraries/FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Minimal ERC20 interface for RA /// @notice Contains a subset of the full ERC20 interface that is used in RA V2 interface IERC20Minimal { /// @notice Returns the balance of a token /// @param account The account for which to look up the number of tokens it has, i.e. its balance /// @return The number of tokens held by the account function balanceOf(address account) external view returns (uint256); /// @notice Transfers the amount of token from the `msg.sender` to the recipient /// @param recipient The account that will receive the amount transferred /// @param amount The number of tokens to send from the sender to the recipient /// @return Returns true for a successful transfer, false for an unsuccessful transfer function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Returns the current allowance given to a spender by an owner /// @param owner The account of the token owner /// @param spender The account of the token spender /// @return The current allowance granted by `owner` to `spender` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount` /// @param spender The account which will be allowed to spend a given amount of the owners tokens /// @param amount The amount of tokens allowed to be used by `spender` /// @return Returns true for a successful approval, false for unsuccessful function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` /// @param sender The account from which the transfer will be initiated /// @param recipient The recipient of the transfer /// @param amount The amount of the transfer /// @return Returns true for a successful transfer, false for unsuccessful function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. /// @param from The account from which the tokens were sent, i.e. the balance decreased /// @param to The account to which the tokens were sent, i.e. the balance increased /// @param value The amount of tokens that were transferred event Transfer(address indexed from, address indexed to, uint256 value); /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes. /// @param owner The account that approved spending of its tokens /// @param spender The account for which the spending allowance was modified /// @param value The new allowance from the owner to the spender event Approval(address indexed owner, address indexed spender, uint256 value); }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title BitMath /// @dev This library provides functionality for computing bit properties of an unsigned integer library BitMath { /// @notice Returns the index of the most significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// x >= 2**mostSignificantBit(x) and x < 2**(mostSignificantBit(x)+1) /// @param x the value for which to compute the most significant bit, must be greater than 0 /// @return r the index of the most significant bit function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } /// @notice Returns the index of the least significant bit of the number, /// where the least significant bit is at index 0 and the most significant bit is at index 255 /// @dev The function satisfies the property: /// (x & 2**leastSignificantBit(x)) != 0 and (x & (2**(leastSignificantBit(x)) - 1)) == 0) /// @param x the value for which to compute the least significant bit, must be greater than 0 /// @return r the index of the least significant bit function leastSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0); r = 255; if (x & type(uint128).max > 0) { r -= 128; } else { x >>= 128; } if (x & type(uint64).max > 0) { r -= 64; } else { x >>= 64; } if (x & type(uint32).max > 0) { r -= 32; } else { x >>= 32; } if (x & type(uint16).max > 0) { r -= 16; } else { x >>= 16; } if (x & type(uint8).max > 0) { r -= 8; } else { x >>= 8; } if (x & 0xf > 0) { r -= 4; } else { x >>= 4; } if (x & 0x3 > 0) { r -= 2; } else { x >>= 2; } if (x & 0x1 > 0) r -= 1; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint32 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint32 { uint8 internal constant RESOLUTION = 32; uint256 internal constant Q32 = 0x100000000; }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; }
// SPDX-License-Identifier: MIT pragma solidity >=0.4.0 <0.8.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; import './FullMath.sol'; import './SafeCast.sol'; import '@openzeppelin-3.4.2/contracts/math/Math.sol'; /// @title Math library for liquidity library LiquidityMath { /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta(uint128 x, int128 y) internal pure returns (uint128 z) { if (y < 0) { require((z = x - uint128(-y)) < x, 'LS'); } else { require((z = x + uint128(y)) >= x, 'LA'); } } /// @notice Add a signed liquidity delta to liquidity and revert if it overflows or underflows /// @param x The liquidity before change /// @param y The delta by which liquidity should be changed /// @return z The liquidity delta function addDelta256(uint256 x, int256 y) internal pure returns (uint256 z) { if (y < 0) { require((z = x - uint256(-y)) < x, 'LS'); } else { require((z = x + uint256(y)) >= x, 'LA'); } } function calculateBoostedLiquidity( uint128 liquidity, int128 veNftAmount, int128 totalVeNftAmount ) internal pure returns (uint256 veNftRatio, uint128 boostedLiquidity) { veNftRatio = FullMath.mulDiv( uint256(veNftAmount), 1.5e18, totalVeNftAmount != 0 ? uint256(totalVeNftAmount) : 1 ); // users acheive full boost if their veRA is >=10% of the total veRA attached to the pool // full boost is 1x original + 1.5x boost //uint256 boostRatio = Math.min(veNftRatio * 10, 1.5e18); // veNftAmount and totalVeNftAmount can't go below 0 uint256 boostRatio = 1.5e18; boostedLiquidity = SafeCast.toUint128(FullMath.mulDiv(liquidity, boostRatio, 1e18)); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.0; /// @title Optimized overflow and underflow safe math operations /// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost library LowGasSafeMath { /// @notice Returns x + y, reverts if sum overflows uint256 /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } /// @notice Returns x - y, reverts if underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } /// @notice Returns x * y, reverts if overflows /// @param x The multiplicand /// @param y The multiplier /// @return z The product of x and y function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(x == 0 || (z = x * y) / x == y); } /// @notice Returns x + y, reverts if overflows or underflows /// @param x The augend /// @param y The addend /// @return z The sum of x and y function add(int256 x, int256 y) internal pure returns (int256 z) { require((z = x + y) >= x == (y >= 0)); } /// @notice Returns x - y, reverts if overflows or underflows /// @param x The minuend /// @param y The subtrahend /// @return z The difference of x and y function sub(int256 x, int256 y) internal pure returns (int256 z) { require((z = x - y) <= x == (y >= 0)); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.0; import './Tick.sol'; import './States.sol'; /// @title Oracle /// @notice Provides price and liquidity data useful for a wide variety of system designs /// @dev Instances of stored oracle data, "observations", are collected in the oracle array /// Every pool is initialized with an oracle array length of 1. Anyone can pay the SSTOREs to increase the /// maximum length of the oracle array. New slots will be added when the array is fully populated. /// Observations are overwritten when the full length of the oracle array is populated. /// The most recent observation is available, independent of the length of the oracle array, by passing 0 to observe() library Oracle { /// @notice Transforms a previous observation into a new observation, given the passage of time and the current tick and liquidity values /// @dev blockTimestamp _must_ be chronologically equal to or greater than last.blockTimestamp, safe for 0 or 1 overflows /// @param last The specified observation to be transformed /// @param blockTimestamp The timestamp of the new observation /// @param tick The active tick at the time of the new observation /// @param liquidity The total in-range liquidity at the time of the new observation /// @return Observation The newly populated observation function transform( Observation memory last, uint32 blockTimestamp, int24 tick, uint128 liquidity, uint128 boostedLiquidity ) internal pure returns (Observation memory) { uint32 delta = blockTimestamp - last.blockTimestamp; return Observation({ blockTimestamp: blockTimestamp, tickCumulative: last.tickCumulative + int56(tick) * delta, secondsPerLiquidityCumulativeX128: last.secondsPerLiquidityCumulativeX128 + ((uint160(delta) << 128) / (liquidity > 0 ? liquidity : 1)), secondsPerBoostedLiquidityPeriodX128: last.secondsPerBoostedLiquidityPeriodX128 + ((uint160(delta) << 128) / (boostedLiquidity > 0 ? boostedLiquidity : 1)), initialized: true, boostedInRange: boostedLiquidity > 0 ? last.boostedInRange + delta : last.boostedInRange }); } /// @notice Initialize the oracle array by writing the first slot. Called once for the lifecycle of the observations array /// @param self The stored oracle array /// @param time The time of the oracle initialization, via block.timestamp truncated to uint32 /// @return cardinality The number of populated elements in the oracle array /// @return cardinalityNext The new length of the oracle array, independent of population function initialize( Observation[65535] storage self, uint32 time ) external returns (uint16 cardinality, uint16 cardinalityNext) { self[0] = Observation({ blockTimestamp: time, tickCumulative: 0, secondsPerLiquidityCumulativeX128: 0, secondsPerBoostedLiquidityPeriodX128: 0, initialized: true, boostedInRange: 0 }); return (1, 1); } /// @notice Writes an oracle observation to the array /// @dev Writable at most once per block. Index represents the most recently written element. cardinality and index must be tracked publicly. /// If the index is at the end of the allowable array length (according to cardinality), and the next cardinality /// is greater than the current one, cardinality may be increased. This restriction is created to preserve ordering. /// @param self The stored oracle array /// @param index The index of the observation that was most recently written to the observations array /// @param blockTimestamp The timestamp of the new observation /// @param tick The active tick at the time of the new observation /// @param liquidity The total in-range liquidity at the time of the new observation /// @param cardinality The number of populated elements in the oracle array /// @param cardinalityNext The new length of the oracle array, independent of population /// @return indexUpdated The new index of the most recently written element in the oracle array /// @return cardinalityUpdated The new cardinality of the oracle array function write( Observation[65535] storage self, uint16 index, uint32 blockTimestamp, int24 tick, uint128 liquidity, uint128 boostedLiquidity, uint16 cardinality, uint16 cardinalityNext ) external returns (uint16 indexUpdated, uint16 cardinalityUpdated) { Observation memory last = self[index]; // early return if we've already written an observation this block if (last.blockTimestamp == blockTimestamp) return (index, cardinality); // if the conditions are right, we can bump the cardinality if (cardinalityNext > cardinality && index == (cardinality - 1)) { cardinalityUpdated = cardinalityNext; } else { cardinalityUpdated = cardinality; } indexUpdated = (index + 1) % cardinalityUpdated; self[indexUpdated] = transform(last, blockTimestamp, tick, liquidity, boostedLiquidity); } /// @notice Prepares the oracle array to store up to `next` observations /// @param self The stored oracle array /// @param current The current next cardinality of the oracle array /// @param next The proposed next cardinality which will be populated in the oracle array /// @return next The next cardinality which will be populated in the oracle array function grow(Observation[65535] storage self, uint16 current, uint16 next) external returns (uint16) { require(current > 0, 'I'); // no-op if the passed next value isn't greater than the current next value if (next <= current) return current; // store in each slot to prevent fresh SSTOREs in swaps // this data will not be used because the initialized boolean is still false for (uint16 i = current; i < next; i++) self[i].blockTimestamp = 1; return next; } /// @notice comparator for 32-bit timestamps /// @dev safe for 0 or 1 overflows, a and b _must_ be chronologically before or equal to time /// @param time A timestamp truncated to 32 bits /// @param a A comparison timestamp from which to determine the relative position of `time` /// @param b From which to determine the relative position of `time` /// @return bool Whether `a` is chronologically <= `b` function lte(uint32 time, uint32 a, uint32 b) internal pure returns (bool) { // if there hasn't been overflow, no need to adjust if (a <= time && b <= time) return a <= b; uint256 aAdjusted = a > time ? a : a + 2 ** 32; uint256 bAdjusted = b > time ? b : b + 2 ** 32; return aAdjusted <= bAdjusted; } /// @notice Fetches the observations beforeOrAt and atOrAfter a target, i.e. where [beforeOrAt, atOrAfter] is satisfied. /// The result may be the same observation, or adjacent observations. /// @dev The answer must be contained in the array, used when the target is located within the stored observation /// boundaries: older than the most recent observation and younger, or the same age as, the oldest observation /// @param self The stored oracle array /// @param time The current block.timestamp /// @param target The timestamp at which the reserved observation should be for /// @param index The index of the observation that was most recently written to the observations array /// @param cardinality The number of populated elements in the oracle array /// @return beforeOrAt The observation recorded before, or at, the target /// @return atOrAfter The observation recorded at, or after, the target function binarySearch( Observation[65535] storage self, uint32 time, uint32 target, uint16 index, uint16 cardinality ) internal view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { uint256 l = (index + 1) % cardinality; // oldest observation uint256 r = l + cardinality - 1; // newest observation uint256 i; while (true) { i = (l + r) / 2; beforeOrAt = self[i % cardinality]; // we've landed on an uninitialized tick, keep searching higher (more recently) if (!beforeOrAt.initialized) { l = i + 1; continue; } atOrAfter = self[(i + 1) % cardinality]; bool targetAtOrAfter = lte(time, beforeOrAt.blockTimestamp, target); // check if we've found the answer! if (targetAtOrAfter && lte(time, target, atOrAfter.blockTimestamp)) break; if (!targetAtOrAfter) r = i - 1; else l = i + 1; } } /// @notice Fetches the observations beforeOrAt and atOrAfter a given target, i.e. where [beforeOrAt, atOrAfter] is satisfied /// @dev Assumes there is at least 1 initialized observation. /// Used by observeSingle() to compute the counterfactual accumulator values as of a given block timestamp. /// @param self The stored oracle array /// @param time The current block.timestamp /// @param target The timestamp at which the reserved observation should be for /// @param tick The active tick at the time of the returned or simulated observation /// @param index The index of the observation that was most recently written to the observations array /// @param liquidity The total pool liquidity at the time of the call /// @param cardinality The number of populated elements in the oracle array /// @return beforeOrAt The observation which occurred at, or before, the given timestamp /// @return atOrAfter The observation which occurred at, or after, the given timestamp function getSurroundingObservations( Observation[65535] storage self, uint32 time, uint32 target, int24 tick, uint16 index, uint128 liquidity, uint128 boostedLiquidity, uint16 cardinality ) internal view returns (Observation memory beforeOrAt, Observation memory atOrAfter) { // optimistically set before to the newest observation beforeOrAt = self[index]; // if the target is chronologically at or after the newest observation, we can early return if (lte(time, beforeOrAt.blockTimestamp, target)) { if (beforeOrAt.blockTimestamp == target) { // if newest observation equals target, we're in the same block, so we can ignore atOrAfter return (beforeOrAt, atOrAfter); } else { // otherwise, we need to transform return (beforeOrAt, transform(beforeOrAt, target, tick, liquidity, boostedLiquidity)); } } // now, set before to the oldest observation beforeOrAt = self[(index + 1) % cardinality]; if (!beforeOrAt.initialized) beforeOrAt = self[0]; // ensure that the target is chronologically at or after the oldest observation require(lte(time, beforeOrAt.blockTimestamp, target), 'OLD'); // if we've reached this point, we have to binary search return binarySearch(self, time, target, index, cardinality); } /// @dev Reverts if an observation at or before the desired observation timestamp does not exist. /// 0 may be passed as `secondsAgo' to return the current cumulative values. /// If called with a timestamp falling between two observations, returns the counterfactual accumulator values /// at exactly the timestamp between the two observations. /// @param self The stored oracle array /// @param time The current block timestamp /// @param secondsAgo The amount of time to look back, in seconds, at which point to return an observation /// @param tick The current tick /// @param index The index of the observation that was most recently written to the observations array /// @param liquidity The current in-range pool liquidity /// @param cardinality The number of populated elements in the oracle array /// @return tickCumulative The tick * time elapsed since the pool was first initialized, as of `secondsAgo` /// @return secondsPerLiquidityCumulativeX128 The time elapsed / max(1, liquidity) since the pool was first initialized, as of `secondsAgo` function observeSingle( Observation[65535] storage self, uint32 time, uint32 secondsAgo, int24 tick, uint16 index, uint128 liquidity, uint128 boostedLiquidity, uint16 cardinality ) public view returns ( int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, uint160 periodSecondsPerBoostedLiquidityX128 ) { if (secondsAgo == 0) { Observation memory last = self[index]; if (last.blockTimestamp != time) { last = transform(last, time, tick, liquidity, boostedLiquidity); } return ( last.tickCumulative, last.secondsPerLiquidityCumulativeX128, last.secondsPerBoostedLiquidityPeriodX128 ); } uint32 target = time - secondsAgo; (Observation memory beforeOrAt, Observation memory atOrAfter) = getSurroundingObservations( self, time, target, tick, index, liquidity, boostedLiquidity, cardinality ); if (target == beforeOrAt.blockTimestamp) { // we're at the left boundary return ( beforeOrAt.tickCumulative, beforeOrAt.secondsPerLiquidityCumulativeX128, beforeOrAt.secondsPerBoostedLiquidityPeriodX128 ); } else if (target == atOrAfter.blockTimestamp) { // we're at the right boundary return ( atOrAfter.tickCumulative, atOrAfter.secondsPerLiquidityCumulativeX128, atOrAfter.secondsPerBoostedLiquidityPeriodX128 ); } else { // we're in the middle uint32 observationTimeDelta = atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp; uint32 targetDelta = target - beforeOrAt.blockTimestamp; return ( beforeOrAt.tickCumulative + ((atOrAfter.tickCumulative - beforeOrAt.tickCumulative) / observationTimeDelta) * targetDelta, beforeOrAt.secondsPerLiquidityCumulativeX128 + uint160( (uint256( atOrAfter.secondsPerLiquidityCumulativeX128 - beforeOrAt.secondsPerLiquidityCumulativeX128 ) * targetDelta) / observationTimeDelta ), beforeOrAt.secondsPerBoostedLiquidityPeriodX128 + uint160( (uint256( atOrAfter.secondsPerBoostedLiquidityPeriodX128 - beforeOrAt.secondsPerBoostedLiquidityPeriodX128 ) * targetDelta) / observationTimeDelta ) ); } } /// @notice Returns the accumulator values as of each time seconds ago from the given time in the array of `secondsAgos` /// @dev Reverts if `secondsAgos` > oldest observation /// @param self The stored oracle array /// @param time The current block.timestamp /// @param secondsAgos Each amount of time to look back, in seconds, at which point to return an observation /// @param tick The current tick /// @param index The index of the observation that was most recently written to the observations array /// @param liquidity The current in-range pool liquidity /// @param cardinality The number of populated elements in the oracle array /// @return tickCumulatives The tick * time elapsed since the pool was first initialized, as of each `secondsAgo` /// @return secondsPerLiquidityCumulativeX128s The cumulative seconds / max(1, liquidity) since the pool was first initialized, as of each `secondsAgo` function observe( Observation[65535] storage self, uint32 time, uint32[] memory secondsAgos, int24 tick, uint16 index, uint128 liquidity, uint128 boostedLiquidity, uint16 cardinality ) external view returns ( int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s, uint160[] memory periodSecondsPerBoostedLiquidityX128s ) { require(cardinality > 0, 'I'); tickCumulatives = new int56[](secondsAgos.length); secondsPerLiquidityCumulativeX128s = new uint160[](secondsAgos.length); periodSecondsPerBoostedLiquidityX128s = new uint160[](secondsAgos.length); for (uint256 i = 0; i < secondsAgos.length; i++) { ( tickCumulatives[i], secondsPerLiquidityCumulativeX128s[i], periodSecondsPerBoostedLiquidityX128s[i] ) = observeSingle(self, time, secondsAgos[i], tick, index, liquidity, boostedLiquidity, cardinality); } } function newPeriod( Observation[65535] storage self, uint16 index, uint256 period ) external returns ( uint160 secondsPerLiquidityCumulativeX128, uint160 secondsPerBoostedLiquidityCumulativeX128, uint32 boostedInRange ) { Observation memory last = self[index]; States.PoolStates storage states = States.getStorage(); uint32 delta = uint32(period) * 1 weeks - last.blockTimestamp; secondsPerLiquidityCumulativeX128 = last.secondsPerLiquidityCumulativeX128 + ((uint160(delta) << 128) / (states.liquidity > 0 ? states.liquidity : 1)); secondsPerBoostedLiquidityCumulativeX128 = last.secondsPerBoostedLiquidityPeriodX128 + ((uint160(delta) << 128) / (states.boostedLiquidity > 0 ? states.boostedLiquidity : 1)); boostedInRange = states.boostedLiquidity > 0 ? last.boostedInRange + delta : last.boostedInRange; self[index] = Observation({ blockTimestamp: uint32(period) * 1 weeks, tickCumulative: last.tickCumulative + int56(states.slot0.tick) * delta, secondsPerLiquidityCumulativeX128: secondsPerLiquidityCumulativeX128, secondsPerBoostedLiquidityPeriodX128: secondsPerBoostedLiquidityCumulativeX128, initialized: last.initialized, boostedInRange: 0 }); } struct SnapShot { int56 tickCumulativeLower; int56 tickCumulativeUpper; uint160 secondsPerLiquidityOutsideLowerX128; uint160 secondsPerLiquidityOutsideUpperX128; uint160 secondsPerBoostedLiquidityOutsideLowerX128; uint160 secondsPerBoostedLiquidityOutsideUpperX128; uint32 secondsOutsideLower; uint32 secondsOutsideUpper; } struct SnapshotCumulativesInsideCache { uint32 time; int56 tickCumulative; uint160 secondsPerLiquidityCumulativeX128; uint160 secondsPerBoostedLiquidityCumulativeX128; } /// @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. Boosted data is only valid if it's within the same period /// @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 secondsPerBoostedLiquidityInsideX128 The snapshot of seconds per boosted 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, uint160 secondsPerBoostedLiquidityInsideX128, uint32 secondsInside ) { States.PoolStates storage states = States.getStorage(); TickInfo storage lower = states._ticks[tickLower]; TickInfo storage upper = states._ticks[tickUpper]; SnapShot memory snapshot; { uint256 period = States._blockTimestamp() / 1 weeks; bool initializedLower; ( snapshot.tickCumulativeLower, snapshot.secondsPerLiquidityOutsideLowerX128, snapshot.secondsPerBoostedLiquidityOutsideLowerX128, snapshot.secondsOutsideLower, initializedLower ) = ( lower.tickCumulativeOutside, lower.secondsPerLiquidityOutsideX128, uint160(lower.periodSecondsPerBoostedLiquidityOutsideX128[period]), lower.secondsOutside, lower.initialized ); require(initializedLower); bool initializedUpper; ( snapshot.tickCumulativeUpper, snapshot.secondsPerLiquidityOutsideUpperX128, snapshot.secondsPerBoostedLiquidityOutsideUpperX128, snapshot.secondsOutsideUpper, initializedUpper ) = ( upper.tickCumulativeOutside, upper.secondsPerLiquidityOutsideX128, uint160(upper.periodSecondsPerBoostedLiquidityOutsideX128[period]), upper.secondsOutside, upper.initialized ); require(initializedUpper); } Slot0 memory _slot0 = states.slot0; if (_slot0.tick < tickLower) { return ( snapshot.tickCumulativeLower - snapshot.tickCumulativeUpper, snapshot.secondsPerLiquidityOutsideLowerX128 - snapshot.secondsPerLiquidityOutsideUpperX128, snapshot.secondsPerBoostedLiquidityOutsideLowerX128 - snapshot.secondsPerBoostedLiquidityOutsideUpperX128, snapshot.secondsOutsideLower - snapshot.secondsOutsideUpper ); } else if (_slot0.tick < tickUpper) { SnapshotCumulativesInsideCache memory cache; cache.time = States._blockTimestamp(); ( cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128, cache.secondsPerBoostedLiquidityCumulativeX128 ) = observeSingle( states.observations, cache.time, 0, _slot0.tick, _slot0.observationIndex, states.liquidity, states.boostedLiquidity, _slot0.observationCardinality ); return ( cache.tickCumulative - snapshot.tickCumulativeLower - snapshot.tickCumulativeUpper, cache.secondsPerLiquidityCumulativeX128 - snapshot.secondsPerLiquidityOutsideLowerX128 - snapshot.secondsPerLiquidityOutsideUpperX128, cache.secondsPerBoostedLiquidityCumulativeX128 - snapshot.secondsPerBoostedLiquidityOutsideLowerX128 - snapshot.secondsPerBoostedLiquidityOutsideUpperX128, cache.time - snapshot.secondsOutsideLower - snapshot.secondsOutsideUpper ); } else { return ( snapshot.tickCumulativeUpper - snapshot.tickCumulativeLower, snapshot.secondsPerLiquidityOutsideUpperX128 - snapshot.secondsPerLiquidityOutsideLowerX128, snapshot.secondsPerBoostedLiquidityOutsideUpperX128 - snapshot.secondsPerBoostedLiquidityOutsideLowerX128, snapshot.secondsOutsideUpper - snapshot.secondsOutsideLower ); } } /// @notice Returns the seconds per liquidity and seconds inside a tick range for a period /// @dev This does not ensure the range is a valid range /// @param period The timestamp of the period /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsPerBoostedLiquidityInsideX128 The snapshot of seconds per boosted liquidity for the range function periodCumulativesInside( uint32 period, int24 tickLower, int24 tickUpper ) external view returns (uint160 secondsPerLiquidityInsideX128, uint160 secondsPerBoostedLiquidityInsideX128) { States.PoolStates storage states = States.getStorage(); TickInfo storage lower = states._ticks[tickLower]; TickInfo storage upper = states._ticks[tickUpper]; SnapShot memory snapshot; { int24 startTick = states.periods[period].startTick; uint256 previousPeriod = states.periods[period].previousPeriod; (snapshot.secondsPerLiquidityOutsideLowerX128, snapshot.secondsPerBoostedLiquidityOutsideLowerX128) = ( uint160(lower.periodSecondsPerLiquidityOutsideX128[period]), uint160(lower.periodSecondsPerBoostedLiquidityOutsideX128[period]) ); if (tickLower <= startTick && snapshot.secondsPerLiquidityOutsideLowerX128 == 0) { snapshot.secondsPerLiquidityOutsideLowerX128 = states .periods[previousPeriod] .endSecondsPerLiquidityPeriodX128; } // separate conditions because liquidity and boosted liquidity can be different if (tickLower <= startTick && snapshot.secondsPerBoostedLiquidityOutsideLowerX128 == 0) { snapshot.secondsPerBoostedLiquidityOutsideLowerX128 = states .periods[previousPeriod] .endSecondsPerBoostedLiquidityPeriodX128; } (snapshot.secondsPerLiquidityOutsideUpperX128, snapshot.secondsPerBoostedLiquidityOutsideUpperX128) = ( uint160(upper.periodSecondsPerLiquidityOutsideX128[period]), uint160(upper.periodSecondsPerBoostedLiquidityOutsideX128[period]) ); if (tickUpper <= startTick && snapshot.secondsPerLiquidityOutsideUpperX128 == 0) { snapshot.secondsPerLiquidityOutsideUpperX128 = states .periods[previousPeriod] .endSecondsPerLiquidityPeriodX128; } // separate conditions because liquidity and boosted liquidity can be different if (tickUpper <= startTick && snapshot.secondsPerBoostedLiquidityOutsideUpperX128 == 0) { snapshot.secondsPerBoostedLiquidityOutsideUpperX128 = states .periods[previousPeriod] .endSecondsPerBoostedLiquidityPeriodX128; } } int24 lastTick; uint256 currentPeriod = states.lastPeriod; { // if period is already finalized, use period's last tick, if not, use current tick if (currentPeriod > period) { lastTick = states.periods[period].lastTick; } else { lastTick = states.slot0.tick; } } if (lastTick < tickLower) { return ( snapshot.secondsPerLiquidityOutsideLowerX128 - snapshot.secondsPerLiquidityOutsideUpperX128, snapshot.secondsPerBoostedLiquidityOutsideLowerX128 - snapshot.secondsPerBoostedLiquidityOutsideUpperX128 ); } else if (lastTick < tickUpper) { SnapshotCumulativesInsideCache memory cache; // if period's on-going, observeSingle, if finalized, use endSecondsPerLiquidityPeriodX128 if (currentPeriod <= period) { cache.time = States._blockTimestamp(); // limit to the end of period if (cache.time > currentPeriod * 1 weeks + 1 weeks) { cache.time = uint32(currentPeriod * 1 weeks + 1 weeks); } Slot0 memory _slot0 = states.slot0; ( , cache.secondsPerLiquidityCumulativeX128, cache.secondsPerBoostedLiquidityCumulativeX128 ) = observeSingle( states.observations, cache.time, 0, _slot0.tick, _slot0.observationIndex, states.liquidity, states.boostedLiquidity, _slot0.observationCardinality ); } else { cache.secondsPerLiquidityCumulativeX128 = states.periods[period].endSecondsPerLiquidityPeriodX128; cache.secondsPerBoostedLiquidityCumulativeX128 = states .periods[period] .endSecondsPerBoostedLiquidityPeriodX128; } return ( cache.secondsPerLiquidityCumulativeX128 - snapshot.secondsPerLiquidityOutsideLowerX128 - snapshot.secondsPerLiquidityOutsideUpperX128, cache.secondsPerBoostedLiquidityCumulativeX128 - snapshot.secondsPerBoostedLiquidityOutsideLowerX128 - snapshot.secondsPerBoostedLiquidityOutsideUpperX128 ); } else { return ( snapshot.secondsPerLiquidityOutsideUpperX128 - snapshot.secondsPerLiquidityOutsideLowerX128, snapshot.secondsPerBoostedLiquidityOutsideUpperX128 - snapshot.secondsPerBoostedLiquidityOutsideLowerX128 ); } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint128, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint128(uint256 y) internal pure returns (uint128 z) { require((z = uint128(y)) == y); } /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2 ** 255); z = int256(y); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './LowGasSafeMath.sol'; import './SafeCast.sol'; import './FullMath.sol'; import './UnsafeMath.sol'; import './FixedPoint96.sol'; /// @title Functions based on Q64.96 sqrt price and liquidity /// @notice Contains the math that uses square root of price as a Q64.96 and liquidity to compute deltas library SqrtPriceMath { using LowGasSafeMath for uint256; using SafeCast for uint256; /// @notice Gets the next sqrt price given a delta of token0 /// @dev Always rounds up, because in the exact output case (increasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (decreasing price) we need to move the /// price less in order to not send too much output. /// The most precise formula for this is liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96), /// if this is impossible because of overflow, we calculate liquidity / (liquidity / sqrtPX96 +- amount). /// @param sqrtPX96 The starting price, i.e. before accounting for the token0 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token0 to add or remove from virtual reserves /// @param add Whether to add or remove the amount of token0 /// @return The price after adding or removing amount, depending on add function getNextSqrtPriceFromAmount0RoundingUp( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // we short circuit amount == 0 because the result is otherwise not guaranteed to equal the input price if (amount == 0) return sqrtPX96; uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; if (add) { uint256 product; if ((product = amount * sqrtPX96) / amount == sqrtPX96) { uint256 denominator = numerator1 + product; if (denominator >= numerator1) // always fits in 160 bits return uint160(FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator)); } return uint160(UnsafeMath.divRoundingUp(numerator1, (numerator1 / sqrtPX96).add(amount))); } else { uint256 product; // if the product overflows, we know the denominator underflows // in addition, we must check that the denominator does not underflow require((product = amount * sqrtPX96) / amount == sqrtPX96 && numerator1 > product); uint256 denominator = numerator1 - product; return FullMath.mulDivRoundingUp(numerator1, sqrtPX96, denominator).toUint160(); } } /// @notice Gets the next sqrt price given a delta of token1 /// @dev Always rounds down, because in the exact output case (decreasing price) we need to move the price at least /// far enough to get the desired output amount, and in the exact input case (increasing price) we need to move the /// price less in order to not send too much output. /// The formula we compute is within <1 wei of the lossless version: sqrtPX96 +- amount / liquidity /// @param sqrtPX96 The starting price, i.e., before accounting for the token1 delta /// @param liquidity The amount of usable liquidity /// @param amount How much of token1 to add, or remove, from virtual reserves /// @param add Whether to add, or remove, the amount of token1 /// @return The price after adding or removing `amount` function getNextSqrtPriceFromAmount1RoundingDown( uint160 sqrtPX96, uint128 liquidity, uint256 amount, bool add ) internal pure returns (uint160) { // if we're adding (subtracting), rounding down requires rounding the quotient down (up) // in both cases, avoid a mulDiv for most inputs if (add) { uint256 quotient = ( amount <= type(uint160).max ? (amount << FixedPoint96.RESOLUTION) / liquidity : FullMath.mulDiv(amount, FixedPoint96.Q96, liquidity) ); return uint256(sqrtPX96).add(quotient).toUint160(); } else { uint256 quotient = ( amount <= type(uint160).max ? UnsafeMath.divRoundingUp(amount << FixedPoint96.RESOLUTION, liquidity) : FullMath.mulDivRoundingUp(amount, FixedPoint96.Q96, liquidity) ); require(sqrtPX96 > quotient); // always fits 160 bits return uint160(sqrtPX96 - quotient); } } /// @notice Gets the next sqrt price given an input amount of token0 or token1 /// @dev Throws if price or liquidity are 0, or if the next price is out of bounds /// @param sqrtPX96 The starting price, i.e., before accounting for the input amount /// @param liquidity The amount of usable liquidity /// @param amountIn How much of token0, or token1, is being swapped in /// @param zeroForOne Whether the amount in is token0 or token1 /// @return sqrtQX96 The price after adding the input amount to token0 or token1 function getNextSqrtPriceFromInput( uint160 sqrtPX96, uint128 liquidity, uint256 amountIn, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we don't pass the target price return zeroForOne ? getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountIn, true) : getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountIn, true); } /// @notice Gets the next sqrt price given an output amount of token0 or token1 /// @dev Throws if price or liquidity are 0 or the next price is out of bounds /// @param sqrtPX96 The starting price before accounting for the output amount /// @param liquidity The amount of usable liquidity /// @param amountOut How much of token0, or token1, is being swapped out /// @param zeroForOne Whether the amount out is token0 or token1 /// @return sqrtQX96 The price after removing the output amount of token0 or token1 function getNextSqrtPriceFromOutput( uint160 sqrtPX96, uint128 liquidity, uint256 amountOut, bool zeroForOne ) internal pure returns (uint160 sqrtQX96) { require(sqrtPX96 > 0); require(liquidity > 0); // round to make sure that we pass the target price return zeroForOne ? getNextSqrtPriceFromAmount1RoundingDown(sqrtPX96, liquidity, amountOut, false) : getNextSqrtPriceFromAmount0RoundingUp(sqrtPX96, liquidity, amountOut, false); } /// @notice Gets the amount0 delta between two prices /// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper), /// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up or down /// @return amount0 Amount of token0 required to cover a position of size liquidity between the two passed prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 numerator1 = uint256(liquidity) << FixedPoint96.RESOLUTION; uint256 numerator2 = sqrtRatioBX96 - sqrtRatioAX96; require(sqrtRatioAX96 > 0); return roundUp ? UnsafeMath.divRoundingUp( FullMath.mulDivRoundingUp(numerator1, numerator2, sqrtRatioBX96), sqrtRatioAX96 ) : FullMath.mulDiv(numerator1, numerator2, sqrtRatioBX96) / sqrtRatioAX96; } /// @notice Gets the amount1 delta between two prices /// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The amount of usable liquidity /// @param roundUp Whether to round the amount up, or down /// @return amount1 Amount of token1 required to cover a position of size liquidity between the two passed prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return roundUp ? FullMath.mulDivRoundingUp(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96) : FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Helper that gets signed token0 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount0 delta /// @return amount0 Amount of token0 corresponding to the passed liquidityDelta between the two prices function getAmount0Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount0) { return liquidity < 0 ? -getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount0Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } /// @notice Helper that gets signed token1 delta /// @param sqrtRatioAX96 A sqrt price /// @param sqrtRatioBX96 Another sqrt price /// @param liquidity The change in liquidity for which to compute the amount1 delta /// @return amount1 Amount of token1 corresponding to the passed liquidityDelta between the two prices function getAmount1Delta( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, int128 liquidity ) internal pure returns (int256 amount1) { return liquidity < 0 ? -getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(-liquidity), false).toInt256() : getAmount1Delta(sqrtRatioAX96, sqrtRatioBX96, uint128(liquidity), true).toInt256(); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.9.0; import './../interfaces/IERC20Minimal.sol'; struct Slot0 { // the current price uint160 sqrtPriceX96; // the current tick int24 tick; // the most-recently updated index of the observations array uint16 observationIndex; // the current maximum number of observations that are being stored uint16 observationCardinality; // the next maximum number of observations to store, triggered in observations.write uint16 observationCardinalityNext; // the current protocol fee as a percentage of the swap fee taken on withdrawal // represented as an integer denominator (1/x)% uint8 feeProtocol; // whether the pool is locked bool unlocked; } struct Observation { // the block timestamp of the observation uint32 blockTimestamp; // the tick accumulator, i.e. tick * time elapsed since the pool was first initialized int56 tickCumulative; // the seconds per liquidity, i.e. seconds elapsed / max(1, liquidity) since the pool was first initialized uint160 secondsPerLiquidityCumulativeX128; // whether or not the observation is initialized bool initialized; // see secondsPerLiquidityCumulativeX128 but with boost, only valid if timestamp < new period // recorded at the end to not breakup struct slot uint160 secondsPerBoostedLiquidityPeriodX128; // the seconds boosted positions were in range in this period uint32 boostedInRange; } // info stored for each user's position struct PositionInfo { // the amount of liquidity owned by this position uint128 liquidity; // fee growth per unit of liquidity as of the last update to liquidity or fees owed uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; // the fees owed to the position owner in token0/token1 uint128 tokensOwed0; uint128 tokensOwed1; uint256 attachedVeNftTokenId; } struct PeriodBoostInfo { // the total amount of boost this period has uint128 totalBoostAmount; // the total amount of veNFT attached to this period int128 totalVeNftAmount; // individual positions' boost info for this period mapping(bytes32 => BoostInfo) positions; // how a veNFT has been attached to this pool mapping(uint256 => VeNftInfo) veNftInfos; } struct VeNftInfo { // how many times a veNFT has been attached to this pool uint128 timesAttached; // boost ratio used, out of 1e18 uint128 veNftBoostUsedRatio; // how much boost ratio is used by each position mapping(bytes32 => uint256) positionBoostUsedRatio; } struct BoostInfo { // the amount of boost this position has for this period uint128 boostAmount; // the amount of veNFT attached to this position for this period int128 veNftAmount; // used to account for changes in the boostAmount and veNFT locked during the period int256 boostedSecondsDebtX96; // used to account for changes in the deposit amount int256 secondsDebtX96; // used to check if starting seconds have already been written bool initialized; // used to account for changes in secondsPerLiquidity int160 secondsPerLiquidityPeriodStartX128; int160 secondsPerBoostedLiquidityPeriodStartX128; } // info stored for each initialized individual tick struct TickInfo { // the total position liquidity that references this tick uint128 liquidityGross; // amount of net liquidity added (subtracted) when tick is crossed from left to right (right to left), int128 liquidityNet; // the total position boosted liquidity that references this tick uint128 cleanUnusedSlot; // clean unused slot int128 cleanUnusedSlot2; // fee growth per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint256 feeGrowthOutside0X128; uint256 feeGrowthOutside1X128; // the cumulative tick value on the other side of the tick int56 tickCumulativeOutside; // the seconds per unit of liquidity on the _other_ side of this tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint160 secondsPerLiquidityOutsideX128; // the seconds spent on the other side of the tick (relative to the current tick) // only has relative meaning, not absolute — the value depends on when the tick is initialized uint32 secondsOutside; // true iff the tick is initialized, i.e. the value is exactly equivalent to the expression liquidityGross != 0 // these 8 bits are set to prevent fresh sstores when crossing newly initialized ticks bool initialized; // secondsPerLiquidityOutsideX128 separated into periods, placed here to preserve struct slots mapping(uint256 => uint256) periodSecondsPerLiquidityOutsideX128; // see secondsPerLiquidityOutsideX128, for boosted liquidity mapping(uint256 => uint256) periodSecondsPerBoostedLiquidityOutsideX128; // the total position boosted liquidity that references this tick mapping(uint256 => uint128) boostedLiquidityGross; // period amount of net boosted liquidity added (subtracted) when tick is crossed from left to right (right to left), mapping(uint256 => int128) boostedLiquidityNet; } // info stored for each period struct PeriodInfo { uint32 previousPeriod; int24 startTick; int24 lastTick; uint160 endSecondsPerLiquidityPeriodX128; uint160 endSecondsPerBoostedLiquidityPeriodX128; uint32 boostedInRange; } // accumulated protocol fees in token0/token1 units struct ProtocolFees { uint128 token0; uint128 token1; } // Position period and liquidity struct PositionCheckpoint { uint256 period; uint256 liquidity; } library States { bytes32 public constant STATES_SLOT = keccak256('states.storage'); struct PoolStates { address factory; address nfpManager; address votingEscrow; address voter; address token0; address token1; uint24 fee; int24 tickSpacing; uint128 maxLiquidityPerTick; Slot0 slot0; mapping(uint256 => PeriodInfo) periods; uint256 lastPeriod; uint256 feeGrowthGlobal0X128; uint256 feeGrowthGlobal1X128; ProtocolFees protocolFees; uint128 liquidity; uint128 boostedLiquidity; mapping(int24 => TickInfo) _ticks; mapping(int16 => uint256) tickBitmap; mapping(bytes32 => PositionInfo) positions; mapping(uint256 => PeriodBoostInfo) boostInfos; mapping(bytes32 => uint256) cleanUnusedSlot; Observation[65535] observations; mapping(bytes32 => PositionCheckpoint[]) positionCheckpoints; uint24 initialFee; bool initialized; } // Return state storage struct for reading and writing function getStorage() internal pure returns (PoolStates storage storageStruct) { bytes32 position = STATES_SLOT; assembly { storageStruct.slot := position } } /// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests. function _blockTimestamp() internal view returns (uint32) { return uint32(block.timestamp); // truncation is desired } /// @dev Get the pool's balance of token0 /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize /// check function balance0() internal view returns (uint256) { PoolStates storage states = getStorage(); (bool success, bytes memory data) = states.token0.staticcall( abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)) ); require(success && data.length >= 32); return abi.decode(data, (uint256)); } /// @dev Get the pool's balance of token1 /// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize /// check function balance1() internal view returns (uint256) { PoolStates storage states = getStorage(); (bool success, bytes memory data) = states.token1.staticcall( abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)) ); require(success && data.length >= 32); return abi.decode(data, (uint256)); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.0; pragma abicoder v2; import './LowGasSafeMath.sol'; import './SafeCast.sol'; import './TickMath.sol'; import './LiquidityMath.sol'; import './States.sol'; /// @title Tick /// @notice Contains functions for managing tick processes and relevant calculations library Tick { using LowGasSafeMath for int256; using SafeCast for int256; /// @notice Derives max liquidity per tick from given tick spacing /// @dev Executed within the pool constructor /// @param tickSpacing The amount of required tick separation, realized in multiples of `tickSpacing` /// e.g., a tickSpacing of 3 requires ticks to be initialized every 3rd tick i.e., ..., -6, -3, 0, 3, 6, ... /// @return The max liquidity per tick function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing) external pure returns (uint128) { int24 minTick = (TickMath.MIN_TICK / tickSpacing) * tickSpacing; int24 maxTick = (TickMath.MAX_TICK / tickSpacing) * tickSpacing; uint24 numTicks = uint24((maxTick - minTick) / tickSpacing) + 1; return type(uint128).max / numTicks; } /// @notice Retrieves fee growth data /// @param self The mapping containing all tick information for initialized ticks /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @param tickCurrent The current tick /// @param feeGrowthGlobal0X128 The all-time global fee growth, per unit of liquidity, in token0 /// @param feeGrowthGlobal1X128 The all-time global fee growth, per unit of liquidity, in token1 /// @return feeGrowthInside0X128 The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries /// @return feeGrowthInside1X128 The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries function getFeeGrowthInside( mapping(int24 => TickInfo) storage self, int24 tickLower, int24 tickUpper, int24 tickCurrent, uint256 feeGrowthGlobal0X128, uint256 feeGrowthGlobal1X128 ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { TickInfo storage lower = self[tickLower]; TickInfo storage upper = self[tickUpper]; // calculate fee growth below uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (tickCurrent >= tickLower) { feeGrowthBelow0X128 = lower.feeGrowthOutside0X128; feeGrowthBelow1X128 = lower.feeGrowthOutside1X128; } else { feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lower.feeGrowthOutside0X128; feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lower.feeGrowthOutside1X128; } // calculate fee growth above uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (tickCurrent < tickUpper) { feeGrowthAbove0X128 = upper.feeGrowthOutside0X128; feeGrowthAbove1X128 = upper.feeGrowthOutside1X128; } else { feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upper.feeGrowthOutside0X128; feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upper.feeGrowthOutside1X128; } feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } /// @notice Retrieves fee growth data /// @param self The mapping containing all tick information for initialized ticks /// @param tickLower The lower tick boundary of the position /// @param tickUpper The upper tick boundary of the position /// @param tickCurrent The current tick /// @param endSecondsPerBoostedLiquidityPeriodX128 The seconds in range, per unit of liquidity /// @param period The period's timestamp /// @return secondsInsidePerBoostedLiquidityX128 The seconds per unit of liquidity, inside the position's tick boundaries function getSecondsInsidePerBoostedLiquidity( mapping(int24 => TickInfo) storage self, int24 tickLower, int24 tickUpper, int24 tickCurrent, uint256 endSecondsPerBoostedLiquidityPeriodX128, uint256 period ) external view returns (uint256 secondsInsidePerBoostedLiquidityX128) { TickInfo storage lower = self[tickLower]; TickInfo storage upper = self[tickUpper]; // calculate secondInside growth below uint256 secondsInsidePerBoostedLiquidityBelowX128; if (tickCurrent >= tickLower) { secondsInsidePerBoostedLiquidityBelowX128 = lower.periodSecondsPerBoostedLiquidityOutsideX128[period]; } else { secondsInsidePerBoostedLiquidityBelowX128 = endSecondsPerBoostedLiquidityPeriodX128 - lower.periodSecondsPerBoostedLiquidityOutsideX128[period]; } // calculate secondsInside growth above uint256 secondsInsidePerBoostedLiquidityAboveX128; if (tickCurrent < tickUpper) { secondsInsidePerBoostedLiquidityAboveX128 = upper.periodSecondsPerBoostedLiquidityOutsideX128[period]; } else { secondsInsidePerBoostedLiquidityAboveX128 = endSecondsPerBoostedLiquidityPeriodX128 - upper.periodSecondsPerBoostedLiquidityOutsideX128[period]; } secondsInsidePerBoostedLiquidityX128 = endSecondsPerBoostedLiquidityPeriodX128 - secondsInsidePerBoostedLiquidityBelowX128 - secondsInsidePerBoostedLiquidityAboveX128; } struct UpdateTickParams { // the tick that will be updated int24 tick; // the current tick int24 tickCurrent; // a new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left) int128 liquidityDelta; // a new amount of boosted liquidity to be added (subtracted) when tick is crossed from left to right (right to left) int128 boostedLiquidityDelta; // the all-time global fee growth, per unit of liquidity, in token0 uint256 feeGrowthGlobal0X128; // the all-time global fee growth, per unit of liquidity, in token1 uint256 feeGrowthGlobal1X128; // The all-time seconds per max(1, liquidity) of the pool uint160 secondsPerLiquidityCumulativeX128; // The period seconds per max(1, boostedLiquidity) of the pool uint160 secondsPerBoostedLiquidityPeriodX128; // the tick * time elapsed since the pool was first initialized int56 tickCumulative; // the current block timestamp cast to a uint32 uint32 time; // true for updating a position's upper tick, or false for updating a position's lower tick bool upper; // the maximum liquidity allocation for a single tick uint128 maxLiquidity; } /// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa /// @param self The mapping containing all tick information for initialized ticks /// @param params the tick details and changes /// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa function update( mapping(int24 => TickInfo) storage self, UpdateTickParams memory params ) internal returns (bool flipped) { TickInfo storage info = self[params.tick]; uint128 liquidityGrossBefore = info.liquidityGross; uint128 liquidityGrossAfter = LiquidityMath.addDelta(liquidityGrossBefore, params.liquidityDelta); require(liquidityGrossAfter <= params.maxLiquidity, 'LO'); flipped = (liquidityGrossAfter == 0) != (liquidityGrossBefore == 0); if (liquidityGrossBefore == 0) { // by convention, we assume that all growth before a tick was initialized happened _below_ the tick if (params.tick <= params.tickCurrent) { info.feeGrowthOutside0X128 = params.feeGrowthGlobal0X128; info.feeGrowthOutside1X128 = params.feeGrowthGlobal1X128; info.secondsPerLiquidityOutsideX128 = params.secondsPerLiquidityCumulativeX128; info.tickCumulativeOutside = params.tickCumulative; info.secondsOutside = params.time; } info.initialized = true; } info.liquidityGross = liquidityGrossAfter; info.boostedLiquidityGross[params.time / 1 weeks] = LiquidityMath.addDelta( info.boostedLiquidityGross[params.time / 1 weeks], params.boostedLiquidityDelta ); // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed) info.liquidityNet = params.upper ? int256(info.liquidityNet).sub(params.liquidityDelta).toInt128() : int256(info.liquidityNet).add(params.liquidityDelta).toInt128(); // when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed) info.boostedLiquidityNet[params.time / 1 weeks] = params.upper ? int256(info.boostedLiquidityNet[params.time / 1 weeks]).sub(params.boostedLiquidityDelta).toInt128() : int256(info.boostedLiquidityNet[params.time / 1 weeks]).add(params.boostedLiquidityDelta).toInt128(); } /// @notice Clears tick data /// @param self The mapping containing all initialized tick information for initialized ticks /// @param tick The tick that will be cleared function clear(mapping(int24 => TickInfo) storage self, int24 tick) internal { delete self[tick]; } struct CrossParams { // The destination tick of the transition int24 tick; // The all-time global fee growth, per unit of liquidity, in token0 uint256 feeGrowthGlobal0X128; // The all-time global fee growth, per unit of liquidity, in token1 uint256 feeGrowthGlobal1X128; // The current seconds per liquidity uint160 secondsPerLiquidityCumulativeX128; // The current seconds per boosted liquidity uint160 secondsPerBoostedLiquidityCumulativeX128; // The previous period end's seconds per liquidity uint256 endSecondsPerLiquidityPeriodX128; // The previous period end's seconds per boosted liquidity uint256 endSecondsPerBoostedLiquidityPeriodX128; // The starting tick of the period int24 periodStartTick; // The tick * time elapsed since the pool was first initialized int56 tickCumulative; // The current block.timestamp uint32 time; } /// @notice Transitions to next tick as needed by price movement /// @param self The mapping containing all tick information for initialized ticks /// @param params Structured cross params /// @return liquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left) /// @return boostedLiquidityNet The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left) function cross( mapping(int24 => TickInfo) storage self, CrossParams calldata params ) external returns (int128 liquidityNet, int128 boostedLiquidityNet) { TickInfo storage info = self[params.tick]; uint256 period = params.time / 1 weeks; info.feeGrowthOutside0X128 = params.feeGrowthGlobal0X128 - info.feeGrowthOutside0X128; info.feeGrowthOutside1X128 = params.feeGrowthGlobal1X128 - info.feeGrowthOutside1X128; info.secondsPerLiquidityOutsideX128 = params.secondsPerLiquidityCumulativeX128 - info.secondsPerLiquidityOutsideX128; { uint256 periodSecondsPerLiquidityOutsideX128; uint256 periodSecondsPerLiquidityOutsideBeforeX128 = info.periodSecondsPerLiquidityOutsideX128[period]; if (params.tick <= params.periodStartTick && periodSecondsPerLiquidityOutsideBeforeX128 == 0) { periodSecondsPerLiquidityOutsideX128 = params.secondsPerLiquidityCumulativeX128 - periodSecondsPerLiquidityOutsideBeforeX128 - params.endSecondsPerLiquidityPeriodX128; } else { periodSecondsPerLiquidityOutsideX128 = params.secondsPerLiquidityCumulativeX128 - periodSecondsPerLiquidityOutsideBeforeX128; } info.periodSecondsPerLiquidityOutsideX128[period] = periodSecondsPerLiquidityOutsideX128; } { uint256 periodSecondsPerBoostedLiquidityOutsideX128; uint256 periodSecondsPerBoostedLiquidityOutsideBeforeX128 = info .periodSecondsPerBoostedLiquidityOutsideX128[period]; if (params.tick <= params.periodStartTick && periodSecondsPerBoostedLiquidityOutsideBeforeX128 == 0) { periodSecondsPerBoostedLiquidityOutsideX128 = params.secondsPerBoostedLiquidityCumulativeX128 - params.endSecondsPerBoostedLiquidityPeriodX128; } else { periodSecondsPerBoostedLiquidityOutsideX128 = params.secondsPerBoostedLiquidityCumulativeX128 - periodSecondsPerBoostedLiquidityOutsideBeforeX128; } info.periodSecondsPerBoostedLiquidityOutsideX128[period] = periodSecondsPerBoostedLiquidityOutsideX128; } info.tickCumulativeOutside = params.tickCumulative - info.tickCumulativeOutside; info.secondsOutside = params.time - info.secondsOutside; liquidityNet = info.liquidityNet; boostedLiquidityNet = info.boostedLiquidityNet[period]; } /// @dev Common checks for valid tick inputs. function checkTicks(int24 tickLower, int24 tickUpper) external pure { require(tickLower < tickUpper, 'TLU'); require(tickLower >= TickMath.MIN_TICK, 'TLM'); require(tickUpper <= TickMath.MAX_TICK, 'TUM'); } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <=0.7.6; import './BitMath.sol'; /// @title Packed tick initialized state library /// @notice Stores a packed mapping of tick index to its initialized state /// @dev The mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word. library TickBitmap { /// @notice Computes the position in the mapping where the initialized bit for a tick lives /// @param tick The tick for which to compute the position /// @return wordPos The key in the mapping containing the word in which the bit is stored /// @return bitPos The bit position in the word where the flag is stored function position(int24 tick) private pure returns (int16 wordPos, uint8 bitPos) { wordPos = int16(tick >> 8); bitPos = uint8(tick % 256); } /// @notice Flips the initialized state for a given tick from false to true, or vice versa /// @param self The mapping in which to flip the tick /// @param tick The tick to flip /// @param tickSpacing The spacing between usable ticks function flipTick(mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing) internal { require(tick % tickSpacing == 0); // ensure that the tick is spaced (int16 wordPos, uint8 bitPos) = position(tick / tickSpacing); uint256 mask = 1 << bitPos; self[wordPos] ^= mask; } /// @notice Returns the next initialized tick contained in the same word (or adjacent word) as the tick that is either /// to the left (less than or equal to) or right (greater than) of the given tick /// @param self The mapping in which to compute the next initialized tick /// @param tick The starting tick /// @param tickSpacing The spacing between usable ticks /// @param lte Whether to search for the next initialized tick to the left (less than or equal to the starting tick) /// @return next The next initialized or uninitialized tick up to 256 ticks away from the current tick /// @return initialized Whether the next tick is initialized, as the function only searches within up to 256 ticks function nextInitializedTickWithinOneWord( mapping(int16 => uint256) storage self, int24 tick, int24 tickSpacing, bool lte ) internal view returns (int24 next, bool initialized) { int24 compressed = tick / tickSpacing; if (tick < 0 && tick % tickSpacing != 0) compressed--; // round towards negative infinity if (lte) { (int16 wordPos, uint8 bitPos) = position(compressed); // all the 1s at or to the right of the current bitPos uint256 mask = (1 << bitPos) - 1 + (1 << bitPos); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the right of or at the current tick, return rightmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed - int24(bitPos - BitMath.mostSignificantBit(masked))) * tickSpacing : (compressed - int24(bitPos)) * tickSpacing; } else { // start from the word of the next tick, since the current tick state doesn't matter (int16 wordPos, uint8 bitPos) = position(compressed + 1); // all the 1s at or to the left of the bitPos uint256 mask = ~((1 << bitPos) - 1); uint256 masked = self[wordPos] & mask; // if there are no initialized ticks to the left of the current tick, return leftmost in the word initialized = masked != 0; // overflow/underflow is possible, but prevented externally by limiting both tickSpacing and tick next = initialized ? (compressed + 1 + int24(BitMath.leastSignificantBit(masked) - bitPos)) * tickSpacing : (compressed + 1 + int24(type(uint8).max - bitPos)) * tickSpacing; } } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.8.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; } }
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math functions that do not check inputs or outputs /// @notice Contains methods that perform common math functions but do not do any overflow or underflow checks library UnsafeMath { /// @notice Returns ceil(x / y) /// @dev division by 0 has unspecified behavior, and must be checked externally /// @param x The dividend /// @param y The divisor /// @return z The quotient, ceil(x / y) function divRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) { assembly { z := add(div(x, y), gt(mod(x, y), 0)) } } }
{ "optimizer": { "enabled": true, "runs": 800 }, "metadata": { "bytecodeHash": "none" }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": { "contracts/v2/libraries/Oracle.sol": { "Oracle": "0xe7f0bdbdaebbf97e70c1182bd861388597079178" } } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
[{"inputs":[{"components":[{"internalType":"uint256","name":"period","type":"uint256"},{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"}],"internalType":"struct Position.PositionPeriodSecondsInRangeParams","name":"params","type":"tuple"}],"name":"positionPeriodSecondsInRange","outputs":[{"internalType":"uint256","name":"periodSecondsInsideX96","type":"uint256"},{"internalType":"uint256","name":"periodBoostedSecondsInsideX96","type":"uint256"}],"stateMutability":"view","type":"function"}]
Contract Creation Code
613546610026600b82828239805160001a60731461001957fe5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600436106100565760003560e01c806355bec4041461005b57806368e5d907146100845780639c766c9d146100b3578063d2e6311b146100c6575b600080fd5b61006e61006936600461310c565b6100e7565b60405161007b91906134bb565b60405180910390f35b81801561009057600080fd5b506100a461009f366004613164565b610114565b60405161007b939291906134c4565b61006e6100c136600461310c565b610546565b6100d96100d43660046131f9565b610557565b60405161007b9291906134f1565b60008560010160006100fb8787878761089f565b8152602001908152602001600020905095945050505050565b6000806000806101226108d8565b9050846060015160020b856040015160020b1261015a5760405162461bcd60e51b8152600401610151906133f2565b60405180910390fd5b620d89e71960020b856040015160020b12156101885760405162461bcd60e51b815260040161015190613449565b6060850151620d89e860029190910b13156101b55760405162461bcd60e51b81526004016101519061342c565b6040805160e0808201835260078401546001600160a01b038082168452600160a01b8204600290810b810b810b602080870191825261ffff600160b81b86048116888a0152600160c81b860481166060808a0191909152600160d81b87049091166080808a019190915260ff600160e81b8804811660a0808c0191909152600160f01b90980416151560c0808b01919091528a519889018b528f5190961688528e830151928801929092528d890151840b988701989098528c880151830b978601979097528b870151600f0b96850196909652945190940b8282015288015192810192909252906000906102a8906108fc565b60808901519197509150600f0b1515806102c6575080600f0b600014155b1561053c57866040015160020b826020015160020b121561030f576103086102f18860400151611435565b6102fe8960600151611435565b8960800151611767565b945061053c565b866060015160020b826020015160020b121561051257600d83015460408301516001600160801b0380831692600160801b9004169073e7f0bdbdaebbf97e70c1182bd861388597079178906334ef26e690601388019061036d6117ae565b602089015160608a015160808b01516040517fffffffff0000000000000000000000000000000000000000000000000000000060e089901b1681526103bc96959493928b928b9260040161334e565b604080518083038186803b1580156103d357600080fd5b505af41580156103e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061040b91906132ad565b6007870180547fffffffffff0000ffffffffffffffffffffffffffffffffffffffffffffffffff16600160c81b61ffff93841602177fffffffffffffff0000ffffffffffffffffffffffffffffffffffffffffffffff16600160b81b9390921692909202179055835160608a0151610491919061048790611435565b8b60800151611767565b96506104af6104a38a60400151611435565b855160808c01516117b2565b95506104bf828a608001516117e1565b600d860180546001600160801b0319166001600160801b03929092169190911790556104eb81846117e1565b600d860180546001600160801b03928316600160801b0292169190911790555061053c9050565b6105396105228860400151611435565b61052f8960600151611435565b89608001516117b2565b93505b5050509193909250565b60008560006100fb8787878761089f565b60008060006105646108d8565b600981015485519192509081101561058e5760405162461bcd60e51b81526004016101519061340f565b5060006105ad856020015186604001518760600151886080015161089f565b90506000806000806000866202001101600087815260200190815260200160002090506000806105e1838d6000015161189d565b915091508060001415610603576000809a509a5050505050505050505061089a565b82828154811061060f57fe5b90600052602060002090600202016001015496508860110160008d600001518152602001908152602001600020600101600089815260200190815260200160002060000160009054906101000a90046001600160801b03166001600160801b031695508860110160008d600001518152602001908152602001600020600101600089815260200190815260200160002060030160019054906101000a900460130b94508860110160008d600001518152602001908152602001600020600101600089815260200190815260200160002060040160009054906101000a900460130b935050505060008073e7f0bdbdaebbf97e70c1182bd86138859707917863add5887e8c600001518d606001518e608001516040518463ffffffff1660e01b815260040161073f939291906134ff565b604080518083038186803b15801561075657600080fd5b505af415801561076a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061078e9190613274565b8c51600090815260118b01602090815260408083208c8452600190810190925290912060028101549181015493889003955091869003935090916107e1896001600160a01b0387166401000000006119af565b9c5060008212806107f15750818d115b1561080a576108038d83600003611a5e565b9c5061080f565b60009c505b61082888856001600160a01b03166401000000006119af565b9b5060008112806108385750808c115b156108515761084a8c82600003611a5e565b9b50610856565b60009b505b6e093a800000000000000000000000008d11156108725760009c505b6e093a800000000000000000000000008c111561088e5760009b505b50505050505050505050505b915091565b6000848484846040516020016108b894939291906132f7565b604051602081830303815290604052805190602001209050949350505050565b7f568f905fee3c29dbecf3583ddfaf086f7336b6bee88b499cc887c595fb7bf1da90565b60008060006109096108d8565b9050600062093a806109196117ae565b63ffffffff168161092657fe5b0463ffffffff169050600061094d866000015187602001518860400151896060015161089f565b600081815260108501602090815260408083208684526011880183528184208585526001019092528220815460808b01519299509394509261099a916001600160801b03909116906117e1565b90506001600160801b0381166109c0576109b8878360008787611ae7565b600060c08901525b6000198860c00151146109de576109de87838a60c001518787611ae7565b6109e6612f91565b82546000868152601188016020526040902054610a18918491600160801b91829004600f90810b92909104900b611fe2565b6001600160801b03166020830181905290825215610f1157610a38612fbf565b610a4061204c565b6040820152610a4d612186565b606082015260408a0151610a6090611435565b6001600160a01b0316604083015260608a0151610a7c90611435565b6001600160a01b0390811660608401526007880154166080830152815166853a0d2313c0001115610b9d576000610ac960028c606001518d604001510160020b81610ac357fe5b05611435565b90506000610ae38285606001516001600160801b0361221e565b90506000610afd8560400151846001600160801b03612287565b90508184604001511115610b1357818452610b1b565b604084015184525b8084606001511115610b335760208401819052610b3e565b606084015160208501525b50506000610b5f8285604001518660600151866000015187602001516122ca565b6001600160801b031690506000610b83828660000151670de0b6b3a76400006119af565b90508085602001511115610b9957602085018190525b5050505b6000610ba7612fe7565b88601101600089815260200190815260200160002060020160008d60c00151815260200190815260200160002060010160008881526020019081526020016000205481602001818152505088601101600089815260200190815260200160002060020160008d60c00151815260200190815260200160002060000160109054906101000a90046001600160801b03166001600160801b03168160000181815250508060200151816000015111610c5e576000610c67565b60208101518151035b808252600090670de0b6b3a764000011610c82576000610c8f565b8151670de0b6b3a7640000035b905066853a0d2313c000856000015110610cae5750670de0b6b3a76400005b60008086604001516001600160a01b031687608001516001600160a01b03161015610cf457610ced876040015188606001516001600160801b0361221e565b9150610d70565b86606001516001600160a01b031687608001516001600160a01b03161015610d5357610d30876080015188606001516001600160801b0361221e565b9150610d4c876040015188608001516001600160801b03612287565b9050610d70565b610d6d876040015188606001516001600160801b03612287565b90505b8186604001511115610d8457818652610d8c565b604086015186525b8086606001511115610da45760208601819052610daf565b606086015160208701525b50506000610dd4866080015187604001518860600151886000015189602001516122ca565b6001600160801b03169050610df6818760000151670de0b6b3a76400006119af565b9050610e0b8183670de0b6b3a76400006119af565b9350838660200151118015610e275750855166853a0d2313c000115b15610e3457602086018490525b8015610e5657610e518660200151670de0b6b3a7640000836119af565b610e59565b60005b836020018181525050505080602001518960110160008a815260200190815260200160002060020160008e60c00151815260200190815260200160002060010160008981526020019081526020016000208190555080602001518160000151018960110160008a815260200190815260200160002060020160008e60c00151815260200190815260200160002060000160106101000a8154816001600160801b0302191690836001600160801b031602179055505050505b82546020909101516001600160801b0390911690039550610f329050613001565b600a8501548152600b85015460208201526080880151600f0b151580610f5c575085600f0b600014155b1561128d576000610f6b6117ae565b9050610f7561303b565b6007870154600d88015460405163d6b4bf9760e01b815273e7f0bdbdaebbf97e70c1182bd8613885970791789263d6b4bf9792610ff79260138d01928892600092600160a01b830460020b9261ffff600160b81b82048116936001600160801b0380821694600160801b9092041692600160c81b90049091169060040161339f565b60606040518083038186803b15801561100f57600080fd5b505af4158015611023573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061104791906130bb565b836000018460200185604001836001600160a01b03166001600160a01b0316815250836001600160a01b03166001600160a01b03168152508360060b60060b81525050505061115487600e016040518061018001604052808d6040015160020b81526020018d60a0015160020b81526020018d60800151600f0b81526020018b600f0b8152602001866000015181526020018660200151815260200184602001516001600160a01b0316815260200184604001516001600160a01b03168152602001846000015160060b81526020018563ffffffff1681526020016000151581526020018a60060160009054906101000a90046001600160801b03166001600160801b031681525061238e565b83606001901515908115158152505061122b87600e016040518061018001604052808d6060015160020b81526020018d60a0015160020b81526020018d60800151600f0b81526020018b600f0b8152602001866000015181526020018660200151815260200184602001516001600160a01b0316815260200184604001516001600160a01b03168152602001846000015160060b81526020018563ffffffff1681526020016001151581526020018a60060160009054906101000a90046001600160801b03166001600160801b031681525061238e565b1515604084015260608301511561125e5760408a0151600588015461125e91600f8a0191600160b81b900460020b61275a565b82604001511561128a5760608a0151600588015461128a91600f8a0191600160b81b900460020b61275a565b50505b6112b285600e0189604001518a606001518b60a00151856000015186602001516127c0565b60a0830152608082015260408089015160608a015191516356eac43f60e11b8152600092839273e7f0bdbdaebbf97e70c1182bd8613885970791789263add5887e92611305928b929091906004016134ff565b604080518083038186803b15801561131c57600080fd5b505af4158015611330573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113549190613274565b6003860154919350915060ff166113b7576113b7848a6040518060a001604052808a81526020018e600001516001600160a01b031681526020018e6020015181526020018e6040015160020b81526020018e6060015160020b815250858561286c565b6113d2898888888e6080015188608001518960a0015161292b565b6113e3848b608001518a8585612ba9565b505060008860800151600f0b121561142b578060600151156114105761141085600e018960400151612cd1565b80604001511561142b5761142b85600e018960600151612cd1565b5050505050915091565b60008060008360020b1261144c578260020b611454565b8260020b6000035b9050620d89e8811115611492576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b6000600182166114a657600160801b6114b8565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff16905060028216156114ec576ffff97272373d413259a46990580e213a0260801c5b600482161561150b576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b600882161561152a576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615611549576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615611568576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615611587576fff2ea16466c96a3843ec78b326b528610260801c5b60808216156115a6576ffe5dee046a99a2a811c461f1969c30530260801c5b6101008216156115c6576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b6102008216156115e6576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615611606576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615611626576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615611646576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615611666576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615611686576f70d869a156d2a1b890bb3df62baf32f70260801c5b6180008216156116a6576f31be135f97d08fd981231505542fcfa60260801c5b620100008216156116c7576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b620200008216156116e7576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615611706576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615611723576b048a170391f7dc42444e8fa20260801c5b60008460020b131561173e57806000198161173a57fe5b0490505b640100000000810615611752576001611755565b60005b60ff16602082901c0192505050919050565b60008082600f0b1261178d576117886117838585856001612d04565b612dc1565b6117a4565b6117a06117838585856000036000612d04565b6000035b90505b9392505050565b4290565b60008082600f0b126117ce576117886117838585856001612dd7565b6117a06117838585856000036000612dd7565b60008082600f0b121561184657826001600160801b03168260000384039150816001600160801b031610611841576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b611897565b826001600160801b03168284019150816001600160801b03161015611897576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b92915050565b81546000908190806118b65760008092509250506119a8565b846000815481106118c357fe5b9060005260206000209060020201600001549150838211156118ec5760008092509250506119a8565b600181039250508382815481106118ff57fe5b9060005260206000209060020201600001549050828111156119a8576000825b818111156119825760006002838303048203905086818154811061193f57fe5b9060005260206000209060020201600001549350858414156119655793506119a8915050565b858410156119755780925061197c565b6001810391505b5061191f565b81935085848154811061199157fe5b906000526020600020906002020160000154925050505b9250929050565b60008080600019858709868602925082811090839003039050806119e557600084116119da57600080fd5b5082900490506117a7565b8084116119f157600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b600080821215611aa9578282600003840391508110611841576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b5080820182811015611897576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b6000611af16108d8565b60028101549091506001600160a01b0316841580611b1b575060018201546001600160a01b031633145b80611b9f575060405163430c208160e01b81526001600160a01b0382169063430c208190611b4f9033908990600401613335565b60206040518083038186803b158015611b6757600080fd5b505afa158015611b7b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b9f919061309b565b611bbb5760405162461bcd60e51b81526004016101519061349e565b6004870154600090868114611e565760038401546001600160a01b03168115611d6b57806001600160a01b031663411b1f7783866001600160a01b0316636352211e866040518263ffffffff1660e01b8152600401611c1a91906134bb565b60206040518083038186803b158015611c3257600080fd5b505afa158015611c46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c6a919061307f565b6040518363ffffffff1660e01b8152600401611c879291906134da565b600060405180830381600087803b158015611ca157600080fd5b505af1158015611cb5573d6000803e3d6000fd5b505050600088815260118701602090815260408083208684526002019091529020546001600160801b031690506001811415611cfc578954600160801b9004600f0b909303925b60008881526011870160209081526040808320868452600201825280832080546001600160801b0360001990960186166001600160801b0319909116178082558b8552600182018085529285208054600160801b80840489169190910388160291909616179055898352905290555b8715611e4d57806001600160a01b031663698473e389866001600160a01b0316636352211e8c6040518263ffffffff1660e01b8152600401611dad91906134bb565b60206040518083038186803b158015611dc557600080fd5b505afa158015611dd9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dfd919061307f565b6040518363ffffffff1660e01b8152600401611e1a9291906134da565b600060405180830381600087803b158015611e3457600080fd5b505af1158015611e48573d6000803e3d6000fd5b505050505b50600489018790555b8615611f6a576040516339f890b560e21b81526000906001600160a01b0385169063e7e242d490611e8b908b906004016134bb565b60206040518083038186803b158015611ea357600080fd5b505afa158015611eb7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611edb91906132df565b89546001600160801b03908116600160801b600f84900b831602178b55600089815260118801602090815260408083208d84526002019091529020549192501680611f2557928101925b600088815260118701602090815260408083208c8452600201909152902080546001600160801b0319166001929092016001600160801b031691909117905550611f78565b87546001600160801b031688555b6000868152601185016020526040812054600160801b9004600f90810b8401919082900b1215611fa6575060005b60009687526011909401602052505060409093208054600f9290920b6001600160801b03908116600160801b0292169190911790555050505050565b60008061201284600f0b6714d1120d7b16000085600f0b6000141561200857600161200d565b85600f0b5b6119af565b91506714d1120d7b16000061204161203c6001600160801b03881683670de0b6b3a76400006119af565b612e47565b915050935093915050565b6000806120576108d8565b6004810154604080513060248083019190915282518083039091018152604490910182526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166370a0823160e01b1781529151815194955060009485946001600160a01b03169382918083835b602083106120e55780518252601f1990920191602091820191016120c6565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114612145576040519150601f19603f3d011682016040523d82523d6000602084013e61214a565b606091505b509150915081801561215e57506020815110155b61216757600080fd5b80806020019051602081101561217c57600080fd5b5051935050505090565b6000806121916108d8565b6005810154604080513060248083019190915282518083039091018152604490910182526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166370a0823160e01b1781529151815194955060009485946001600160a01b0316938291808383602083106120e55780518252601f1990920191602091820191016120c6565b6000826001600160a01b0316846001600160a01b0316111561223e579192915b836001600160a01b0316612277606060ff16846001600160801b0316901b8686036001600160a01b0316866001600160a01b03166119af565b8161227e57fe5b04949350505050565b6000826001600160a01b0316846001600160a01b031611156122a7579192915b6117a4826001600160801b03168585036001600160a01b0316600160601b6119af565b6000836001600160a01b0316856001600160a01b031611156122ea579293925b846001600160a01b0316866001600160a01b0316116123155761230e858585612e62565b9050612385565b836001600160a01b0316866001600160a01b0316101561237757600061233c878686612e62565b9050600061234b878986612ec0565b9050806001600160801b0316826001600160801b03161061236c578061236e565b815b92505050612385565b612382858584612ec0565b90505b95945050505050565b8051600290810b900b60009081526020839052604080822080549184015190916001600160801b03169083906123c59083906117e1565b90508461016001516001600160801b0316816001600160801b031611156123fe5760405162461bcd60e51b815260040161015190613466565b6001600160801b03828116159082161581141594501561251a57846020015160020b856000015160020b136124ea576080850151600284015560a0850151600384015560c085015160048401805461010088015161012089015163ffffffff16600160d81b027fff00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffff60069290920b66ffffffffffffff1666ffffffffffffff196001600160a01b03909616670100000000000000027fffffffffff0000000000000000000000000000000000000000ffffffffffffff909416939093179490941691909117169190911790555b6004830180547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160f81b1790555b82546001600160801b0319166001600160801b0382811691909117845561012086015162093a8063ffffffff91821604166000908152600785016020526040902054606087015161256f9291909116906117e1565b83600701600062093a8088610120015163ffffffff168161258c57fe5b0463ffffffff16815260200190815260200160002060006101000a8154816001600160801b0302191690836001600160801b031602179055508461014001516125fe57604085015183546125f9916125f491600160801b9004600f90810b810b91900b612efd565b612f13565b612623565b60408501518354612623916125f491600160801b9004600f90810b810b91900b612f24565b8354600f9190910b6001600160801b03908116600160801b0291161783556101408501516126a45761269f6125f48660600151600f0b85600801600062093a808a610120015163ffffffff168161267657fe5b0463ffffffff9081168252602082019290925260400160002054600f90810b900b9190612efd16565b6126f8565b6126f86125f48660600151600f0b85600801600062093a808a610120015163ffffffff16816126cf57fe5b0463ffffffff9081168252602082019290925260400160002054600f90810b900b9190612f2416565b83600801600062093a8088610120015163ffffffff168161271557fe5b0463ffffffff16815260200190815260200160002060006101000a8154816001600160801b030219169083600f0b6001600160801b0316021790555050505092915050565b8060020b8260020b8161276957fe5b0760020b1561277757600080fd5b6000806127928360020b8560020b8161278c57fe5b05612f3a565b600191820b820b60009081526020979097526040909620805460ff9097169190911b90951890945550505050565b600285810b80820b60009081526020899052604080822088850b850b83529082209193849391929184918291908a900b1261280657505060028201546003830154612819565b8360020154880391508360030154870390505b6000808b60020b8b60020b121561283b5750506002830154600384015461284e565b84600201548a0391508460030154890390505b92909803979097039b96909503949094039850939650505050505050565b60038501805460ff1916600117905583546001600160801b0316156128ab5760008061289785610557565b600091820360028a01559003600188015550505b6003850180547fffffffffffffffffffffff0000000000000000000000000000000000000000ff166101006001600160a01b03601395860b81169190910291909117909155600490950180547fffffffffffffffffffffffff0000000000000000000000000000000000000000169190920b909416939093179092555050565b6040805160c08101825288546001600160801b03908116825260018a0154602083015260028a01549282019290925260038901548083166060830152600160801b90049091166080820152600488015460a08201526000600f85900b6129ba5781516001600160801b03166129b25760405162461bcd60e51b815260040161015190613482565b5080516129c9565b81516129c690866117e1565b90505b60006129ed8360200151860384600001516001600160801b0316600160801b6119af565b90506000612a138460400151860385600001516001600160801b0316600160801b6119af565b905086600f0b600014612a3a578a546001600160801b0319166001600160801b038416178b555b60018b0186905560028b018590556001600160801b038216151580612a6857506000816001600160801b0316115b15612aa65760038b0180546001600160801b031981166001600160801b039182168501821617808216600160801b9182900483168501909216021790555b6000888152620200118b016020526040902054801580612afb57506000898152620200118c016020526040902080548b91906000198401908110612ae657fe5b90600052602060002090600202016000015414155b15612b57576000898152620200118c016020908152604080832081518083019092528d82526001600160801b03881682840190815281546001818101845592865293909420915160029093029091019182559151910155612b9b565b6000898152620200118c016020526040902080546001600160801b03861691906000198401908110612b8557fe5b9060005260206000209060020201600101819055505b505050505050505050505050565b845482908290612bc2906001600160801b0316866117e1565b87546001600160801b0319166001600160801b039190911617875560038701546004880154610100909104601390810b938490039391810b92839003929060009085900b1215612c1157600093505b60008360130b1215612c2257600092505b6000612c5561178360008b600f0b13612c41578a600003600f0b612c46565b8a600f0b5b8760130b640100000000612f4c565b90506000612c7661178360008b600f0b13612c41578a600003600f0b612c46565b9050600089600f0b13612c8f57808b6001015403612c97565b808b60010154015b60018c01556000600f8b900b13612cb457818b6002015403612cbc565b818b60020154015b8b600201819055505050505050505050505050565b600290810b810b600090815260209290925260408220828155600181018390559081018290556003810182905560040155565b6000836001600160a01b0316856001600160a01b03161115612d24579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b038686038116908716612d6057600080fd5b83612d9057866001600160a01b0316612d838383896001600160a01b03166119af565b81612d8a57fe5b04612db6565b612db6612da78383896001600160a01b0316612f4c565b886001600160a01b0316612f86565b979650505050505050565b6000600160ff1b8210612dd357600080fd5b5090565b6000836001600160a01b0316856001600160a01b03161115612df7579293925b81612e2457612e1f836001600160801b03168686036001600160a01b0316600160601b6119af565b612385565b612385836001600160801b03168686036001600160a01b0316600160601b612f4c565b806001600160801b0381168114612e5d57600080fd5b919050565b6000826001600160a01b0316846001600160a01b03161115612e82579192915b6000612ea5856001600160a01b0316856001600160a01b0316600160601b6119af565b905061238561203c84838888036001600160a01b03166119af565b6000826001600160a01b0316846001600160a01b03161115612ee0579192915b6117a461203c83600160601b8787036001600160a01b03166119af565b8181018281121560008312151461189757600080fd5b80600f81900b8114612e5d57600080fd5b8082038281131560008312151461189757600080fd5b60020b600881901d9161010090910790565b6000612f598484846119af565b905060008280612f6557fe5b84860911156117a7576000198110612f7c57600080fd5b6001019392505050565b808204910615150190565b6040805160a08101825260008082526020820181905291810182905260608101829052608081019190915290565b6040518060800160405280600081526020016000815260200160008152602001600081525090565b604051806040016040528060008152602001600081525090565b6040518060c00160405280600081526020016000815260200160001515815260200160001515815260200160008152602001600081525090565b604080516060810182526000808252602082018190529181019190915290565b8035600281900b8114612e5d57600080fd5b805161ffff81168114612e5d57600080fd5b600060208284031215613090578081fd5b81516117a781613521565b6000602082840312156130ac578081fd5b815180151581146117a7578182fd5b6000806000606084860312156130cf578182fd5b83518060060b81146130df578283fd5b60208501519093506130f081613521565b604085015190925061310181613521565b809150509250925092565b600080600080600060a08688031215613123578081fd5b85359450602086013561313581613521565b93506040860135925061314a6060870161305b565b91506131586080870161305b565b90509295509295909350565b600060c08284031215613175578081fd5b60405160c0810181811067ffffffffffffffff8211171561319257fe5b60405282356131a081613521565b8152602083810135908201526131b86040840161305b565b60408201526131c96060840161305b565b6060820152608083013580600f0b81146131e1578283fd5b608082015260a0928301359281019290925250919050565b600060a0828403121561320a578081fd5b60405160a0810181811067ffffffffffffffff8211171561322757fe5b60405282358152602083013561323c81613521565b6020820152604083810135908201526132576060840161305b565b60608201526132686080840161305b565b60808201529392505050565b60008060408385031215613286578182fd5b825161329181613521565b60208401519092506132a281613521565b809150509250929050565b600080604083850312156132bf578182fd5b6132c88361306d565b91506132d66020840161306d565b90509250929050565b6000602082840312156132f0578081fd5b5051919050565b60609490941b6bffffffffffffffffffffffff191684526014840192909252600290810b60e890811b603485015291900b901b6037820152603a0190565b6001600160a01b03929092168252602082015260400190565b97885261ffff968716602089015263ffffffff95909516604088015260029390930b60608701526001600160801b0391821660808701521660a0850152821660c08401521660e08201526101000190565b97885263ffffffff968716602089015294909516604087015260029290920b606086015261ffff90811660808601526001600160801b0391821660a0860152921660c08401521660e08201526101000190565b602080825260039082015262544c5560e81b604082015260600190565b602080825260039082015262232a2960e91b604082015260600190565b60208082526003908201526254554d60e81b604082015260600190565b602080825260039082015262544c4d60e81b604082015260600190565b6020808252600290820152614c4f60f01b604082015260600190565b60208082526002908201526104e560f41b604082015260600190565b602080825260039082015262544e4160e81b604082015260600190565b90815260200190565b9283526020830191909152604082015260600190565b9182526001600160a01b0316602082015260400190565b918252602082015260400190565b63ffffffff939093168352600291820b6020840152900b604082015260600190565b6001600160a01b038116811461353657600080fd5b5056fea164736f6c6343000706000a
Deployed Bytecode
0x73c66a64f8c1d14fa2e888cf67cf187782b9dabe8030146080604052600436106100565760003560e01c806355bec4041461005b57806368e5d907146100845780639c766c9d146100b3578063d2e6311b146100c6575b600080fd5b61006e61006936600461310c565b6100e7565b60405161007b91906134bb565b60405180910390f35b81801561009057600080fd5b506100a461009f366004613164565b610114565b60405161007b939291906134c4565b61006e6100c136600461310c565b610546565b6100d96100d43660046131f9565b610557565b60405161007b9291906134f1565b60008560010160006100fb8787878761089f565b8152602001908152602001600020905095945050505050565b6000806000806101226108d8565b9050846060015160020b856040015160020b1261015a5760405162461bcd60e51b8152600401610151906133f2565b60405180910390fd5b620d89e71960020b856040015160020b12156101885760405162461bcd60e51b815260040161015190613449565b6060850151620d89e860029190910b13156101b55760405162461bcd60e51b81526004016101519061342c565b6040805160e0808201835260078401546001600160a01b038082168452600160a01b8204600290810b810b810b602080870191825261ffff600160b81b86048116888a0152600160c81b860481166060808a0191909152600160d81b87049091166080808a019190915260ff600160e81b8804811660a0808c0191909152600160f01b90980416151560c0808b01919091528a519889018b528f5190961688528e830151928801929092528d890151840b988701989098528c880151830b978601979097528b870151600f0b96850196909652945190940b8282015288015192810192909252906000906102a8906108fc565b60808901519197509150600f0b1515806102c6575080600f0b600014155b1561053c57866040015160020b826020015160020b121561030f576103086102f18860400151611435565b6102fe8960600151611435565b8960800151611767565b945061053c565b866060015160020b826020015160020b121561051257600d83015460408301516001600160801b0380831692600160801b9004169073e7f0bdbdaebbf97e70c1182bd861388597079178906334ef26e690601388019061036d6117ae565b602089015160608a015160808b01516040517fffffffff0000000000000000000000000000000000000000000000000000000060e089901b1681526103bc96959493928b928b9260040161334e565b604080518083038186803b1580156103d357600080fd5b505af41580156103e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061040b91906132ad565b6007870180547fffffffffff0000ffffffffffffffffffffffffffffffffffffffffffffffffff16600160c81b61ffff93841602177fffffffffffffff0000ffffffffffffffffffffffffffffffffffffffffffffff16600160b81b9390921692909202179055835160608a0151610491919061048790611435565b8b60800151611767565b96506104af6104a38a60400151611435565b855160808c01516117b2565b95506104bf828a608001516117e1565b600d860180546001600160801b0319166001600160801b03929092169190911790556104eb81846117e1565b600d860180546001600160801b03928316600160801b0292169190911790555061053c9050565b6105396105228860400151611435565b61052f8960600151611435565b89608001516117b2565b93505b5050509193909250565b60008560006100fb8787878761089f565b60008060006105646108d8565b600981015485519192509081101561058e5760405162461bcd60e51b81526004016101519061340f565b5060006105ad856020015186604001518760600151886080015161089f565b90506000806000806000866202001101600087815260200190815260200160002090506000806105e1838d6000015161189d565b915091508060001415610603576000809a509a5050505050505050505061089a565b82828154811061060f57fe5b90600052602060002090600202016001015496508860110160008d600001518152602001908152602001600020600101600089815260200190815260200160002060000160009054906101000a90046001600160801b03166001600160801b031695508860110160008d600001518152602001908152602001600020600101600089815260200190815260200160002060030160019054906101000a900460130b94508860110160008d600001518152602001908152602001600020600101600089815260200190815260200160002060040160009054906101000a900460130b935050505060008073e7f0bdbdaebbf97e70c1182bd86138859707917863add5887e8c600001518d606001518e608001516040518463ffffffff1660e01b815260040161073f939291906134ff565b604080518083038186803b15801561075657600080fd5b505af415801561076a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061078e9190613274565b8c51600090815260118b01602090815260408083208c8452600190810190925290912060028101549181015493889003955091869003935090916107e1896001600160a01b0387166401000000006119af565b9c5060008212806107f15750818d115b1561080a576108038d83600003611a5e565b9c5061080f565b60009c505b61082888856001600160a01b03166401000000006119af565b9b5060008112806108385750808c115b156108515761084a8c82600003611a5e565b9b50610856565b60009b505b6e093a800000000000000000000000008d11156108725760009c505b6e093a800000000000000000000000008c111561088e5760009b505b50505050505050505050505b915091565b6000848484846040516020016108b894939291906132f7565b604051602081830303815290604052805190602001209050949350505050565b7f568f905fee3c29dbecf3583ddfaf086f7336b6bee88b499cc887c595fb7bf1da90565b60008060006109096108d8565b9050600062093a806109196117ae565b63ffffffff168161092657fe5b0463ffffffff169050600061094d866000015187602001518860400151896060015161089f565b600081815260108501602090815260408083208684526011880183528184208585526001019092528220815460808b01519299509394509261099a916001600160801b03909116906117e1565b90506001600160801b0381166109c0576109b8878360008787611ae7565b600060c08901525b6000198860c00151146109de576109de87838a60c001518787611ae7565b6109e6612f91565b82546000868152601188016020526040902054610a18918491600160801b91829004600f90810b92909104900b611fe2565b6001600160801b03166020830181905290825215610f1157610a38612fbf565b610a4061204c565b6040820152610a4d612186565b606082015260408a0151610a6090611435565b6001600160a01b0316604083015260608a0151610a7c90611435565b6001600160a01b0390811660608401526007880154166080830152815166853a0d2313c0001115610b9d576000610ac960028c606001518d604001510160020b81610ac357fe5b05611435565b90506000610ae38285606001516001600160801b0361221e565b90506000610afd8560400151846001600160801b03612287565b90508184604001511115610b1357818452610b1b565b604084015184525b8084606001511115610b335760208401819052610b3e565b606084015160208501525b50506000610b5f8285604001518660600151866000015187602001516122ca565b6001600160801b031690506000610b83828660000151670de0b6b3a76400006119af565b90508085602001511115610b9957602085018190525b5050505b6000610ba7612fe7565b88601101600089815260200190815260200160002060020160008d60c00151815260200190815260200160002060010160008881526020019081526020016000205481602001818152505088601101600089815260200190815260200160002060020160008d60c00151815260200190815260200160002060000160109054906101000a90046001600160801b03166001600160801b03168160000181815250508060200151816000015111610c5e576000610c67565b60208101518151035b808252600090670de0b6b3a764000011610c82576000610c8f565b8151670de0b6b3a7640000035b905066853a0d2313c000856000015110610cae5750670de0b6b3a76400005b60008086604001516001600160a01b031687608001516001600160a01b03161015610cf457610ced876040015188606001516001600160801b0361221e565b9150610d70565b86606001516001600160a01b031687608001516001600160a01b03161015610d5357610d30876080015188606001516001600160801b0361221e565b9150610d4c876040015188608001516001600160801b03612287565b9050610d70565b610d6d876040015188606001516001600160801b03612287565b90505b8186604001511115610d8457818652610d8c565b604086015186525b8086606001511115610da45760208601819052610daf565b606086015160208701525b50506000610dd4866080015187604001518860600151886000015189602001516122ca565b6001600160801b03169050610df6818760000151670de0b6b3a76400006119af565b9050610e0b8183670de0b6b3a76400006119af565b9350838660200151118015610e275750855166853a0d2313c000115b15610e3457602086018490525b8015610e5657610e518660200151670de0b6b3a7640000836119af565b610e59565b60005b836020018181525050505080602001518960110160008a815260200190815260200160002060020160008e60c00151815260200190815260200160002060010160008981526020019081526020016000208190555080602001518160000151018960110160008a815260200190815260200160002060020160008e60c00151815260200190815260200160002060000160106101000a8154816001600160801b0302191690836001600160801b031602179055505050505b82546020909101516001600160801b0390911690039550610f329050613001565b600a8501548152600b85015460208201526080880151600f0b151580610f5c575085600f0b600014155b1561128d576000610f6b6117ae565b9050610f7561303b565b6007870154600d88015460405163d6b4bf9760e01b815273e7f0bdbdaebbf97e70c1182bd8613885970791789263d6b4bf9792610ff79260138d01928892600092600160a01b830460020b9261ffff600160b81b82048116936001600160801b0380821694600160801b9092041692600160c81b90049091169060040161339f565b60606040518083038186803b15801561100f57600080fd5b505af4158015611023573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061104791906130bb565b836000018460200185604001836001600160a01b03166001600160a01b0316815250836001600160a01b03166001600160a01b03168152508360060b60060b81525050505061115487600e016040518061018001604052808d6040015160020b81526020018d60a0015160020b81526020018d60800151600f0b81526020018b600f0b8152602001866000015181526020018660200151815260200184602001516001600160a01b0316815260200184604001516001600160a01b03168152602001846000015160060b81526020018563ffffffff1681526020016000151581526020018a60060160009054906101000a90046001600160801b03166001600160801b031681525061238e565b83606001901515908115158152505061122b87600e016040518061018001604052808d6060015160020b81526020018d60a0015160020b81526020018d60800151600f0b81526020018b600f0b8152602001866000015181526020018660200151815260200184602001516001600160a01b0316815260200184604001516001600160a01b03168152602001846000015160060b81526020018563ffffffff1681526020016001151581526020018a60060160009054906101000a90046001600160801b03166001600160801b031681525061238e565b1515604084015260608301511561125e5760408a0151600588015461125e91600f8a0191600160b81b900460020b61275a565b82604001511561128a5760608a0151600588015461128a91600f8a0191600160b81b900460020b61275a565b50505b6112b285600e0189604001518a606001518b60a00151856000015186602001516127c0565b60a0830152608082015260408089015160608a015191516356eac43f60e11b8152600092839273e7f0bdbdaebbf97e70c1182bd8613885970791789263add5887e92611305928b929091906004016134ff565b604080518083038186803b15801561131c57600080fd5b505af4158015611330573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113549190613274565b6003860154919350915060ff166113b7576113b7848a6040518060a001604052808a81526020018e600001516001600160a01b031681526020018e6020015181526020018e6040015160020b81526020018e6060015160020b815250858561286c565b6113d2898888888e6080015188608001518960a0015161292b565b6113e3848b608001518a8585612ba9565b505060008860800151600f0b121561142b578060600151156114105761141085600e018960400151612cd1565b80604001511561142b5761142b85600e018960600151612cd1565b5050505050915091565b60008060008360020b1261144c578260020b611454565b8260020b6000035b9050620d89e8811115611492576040805162461bcd60e51b81526020600482015260016024820152601560fa1b604482015290519081900360640190fd5b6000600182166114a657600160801b6114b8565b6ffffcb933bd6fad37aa2d162d1a5940015b70ffffffffffffffffffffffffffffffffff16905060028216156114ec576ffff97272373d413259a46990580e213a0260801c5b600482161561150b576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b600882161561152a576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615611549576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615611568576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615611587576fff2ea16466c96a3843ec78b326b528610260801c5b60808216156115a6576ffe5dee046a99a2a811c461f1969c30530260801c5b6101008216156115c6576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b6102008216156115e6576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615611606576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615611626576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615611646576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615611666576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615611686576f70d869a156d2a1b890bb3df62baf32f70260801c5b6180008216156116a6576f31be135f97d08fd981231505542fcfa60260801c5b620100008216156116c7576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b620200008216156116e7576e5d6af8dedb81196699c329225ee6040260801c5b62040000821615611706576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615611723576b048a170391f7dc42444e8fa20260801c5b60008460020b131561173e57806000198161173a57fe5b0490505b640100000000810615611752576001611755565b60005b60ff16602082901c0192505050919050565b60008082600f0b1261178d576117886117838585856001612d04565b612dc1565b6117a4565b6117a06117838585856000036000612d04565b6000035b90505b9392505050565b4290565b60008082600f0b126117ce576117886117838585856001612dd7565b6117a06117838585856000036000612dd7565b60008082600f0b121561184657826001600160801b03168260000384039150816001600160801b031610611841576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b611897565b826001600160801b03168284019150816001600160801b03161015611897576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b92915050565b81546000908190806118b65760008092509250506119a8565b846000815481106118c357fe5b9060005260206000209060020201600001549150838211156118ec5760008092509250506119a8565b600181039250508382815481106118ff57fe5b9060005260206000209060020201600001549050828111156119a8576000825b818111156119825760006002838303048203905086818154811061193f57fe5b9060005260206000209060020201600001549350858414156119655793506119a8915050565b858410156119755780925061197c565b6001810391505b5061191f565b81935085848154811061199157fe5b906000526020600020906002020160000154925050505b9250929050565b60008080600019858709868602925082811090839003039050806119e557600084116119da57600080fd5b5082900490506117a7565b8084116119f157600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b600080821215611aa9578282600003840391508110611841576040805162461bcd60e51b81526020600482015260026024820152614c5360f01b604482015290519081900360640190fd5b5080820182811015611897576040805162461bcd60e51b81526020600482015260026024820152614c4160f01b604482015290519081900360640190fd5b6000611af16108d8565b60028101549091506001600160a01b0316841580611b1b575060018201546001600160a01b031633145b80611b9f575060405163430c208160e01b81526001600160a01b0382169063430c208190611b4f9033908990600401613335565b60206040518083038186803b158015611b6757600080fd5b505afa158015611b7b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b9f919061309b565b611bbb5760405162461bcd60e51b81526004016101519061349e565b6004870154600090868114611e565760038401546001600160a01b03168115611d6b57806001600160a01b031663411b1f7783866001600160a01b0316636352211e866040518263ffffffff1660e01b8152600401611c1a91906134bb565b60206040518083038186803b158015611c3257600080fd5b505afa158015611c46573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c6a919061307f565b6040518363ffffffff1660e01b8152600401611c879291906134da565b600060405180830381600087803b158015611ca157600080fd5b505af1158015611cb5573d6000803e3d6000fd5b505050600088815260118701602090815260408083208684526002019091529020546001600160801b031690506001811415611cfc578954600160801b9004600f0b909303925b60008881526011870160209081526040808320868452600201825280832080546001600160801b0360001990960186166001600160801b0319909116178082558b8552600182018085529285208054600160801b80840489169190910388160291909616179055898352905290555b8715611e4d57806001600160a01b031663698473e389866001600160a01b0316636352211e8c6040518263ffffffff1660e01b8152600401611dad91906134bb565b60206040518083038186803b158015611dc557600080fd5b505afa158015611dd9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611dfd919061307f565b6040518363ffffffff1660e01b8152600401611e1a9291906134da565b600060405180830381600087803b158015611e3457600080fd5b505af1158015611e48573d6000803e3d6000fd5b505050505b50600489018790555b8615611f6a576040516339f890b560e21b81526000906001600160a01b0385169063e7e242d490611e8b908b906004016134bb565b60206040518083038186803b158015611ea357600080fd5b505afa158015611eb7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611edb91906132df565b89546001600160801b03908116600160801b600f84900b831602178b55600089815260118801602090815260408083208d84526002019091529020549192501680611f2557928101925b600088815260118701602090815260408083208c8452600201909152902080546001600160801b0319166001929092016001600160801b031691909117905550611f78565b87546001600160801b031688555b6000868152601185016020526040812054600160801b9004600f90810b8401919082900b1215611fa6575060005b60009687526011909401602052505060409093208054600f9290920b6001600160801b03908116600160801b0292169190911790555050505050565b60008061201284600f0b6714d1120d7b16000085600f0b6000141561200857600161200d565b85600f0b5b6119af565b91506714d1120d7b16000061204161203c6001600160801b03881683670de0b6b3a76400006119af565b612e47565b915050935093915050565b6000806120576108d8565b6004810154604080513060248083019190915282518083039091018152604490910182526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166370a0823160e01b1781529151815194955060009485946001600160a01b03169382918083835b602083106120e55780518252601f1990920191602091820191016120c6565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855afa9150503d8060008114612145576040519150601f19603f3d011682016040523d82523d6000602084013e61214a565b606091505b509150915081801561215e57506020815110155b61216757600080fd5b80806020019051602081101561217c57600080fd5b5051935050505090565b6000806121916108d8565b6005810154604080513060248083019190915282518083039091018152604490910182526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166370a0823160e01b1781529151815194955060009485946001600160a01b0316938291808383602083106120e55780518252601f1990920191602091820191016120c6565b6000826001600160a01b0316846001600160a01b0316111561223e579192915b836001600160a01b0316612277606060ff16846001600160801b0316901b8686036001600160a01b0316866001600160a01b03166119af565b8161227e57fe5b04949350505050565b6000826001600160a01b0316846001600160a01b031611156122a7579192915b6117a4826001600160801b03168585036001600160a01b0316600160601b6119af565b6000836001600160a01b0316856001600160a01b031611156122ea579293925b846001600160a01b0316866001600160a01b0316116123155761230e858585612e62565b9050612385565b836001600160a01b0316866001600160a01b0316101561237757600061233c878686612e62565b9050600061234b878986612ec0565b9050806001600160801b0316826001600160801b03161061236c578061236e565b815b92505050612385565b612382858584612ec0565b90505b95945050505050565b8051600290810b900b60009081526020839052604080822080549184015190916001600160801b03169083906123c59083906117e1565b90508461016001516001600160801b0316816001600160801b031611156123fe5760405162461bcd60e51b815260040161015190613466565b6001600160801b03828116159082161581141594501561251a57846020015160020b856000015160020b136124ea576080850151600284015560a0850151600384015560c085015160048401805461010088015161012089015163ffffffff16600160d81b027fff00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffff60069290920b66ffffffffffffff1666ffffffffffffff196001600160a01b03909616670100000000000000027fffffffffff0000000000000000000000000000000000000000ffffffffffffff909416939093179490941691909117169190911790555b6004830180547effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16600160f81b1790555b82546001600160801b0319166001600160801b0382811691909117845561012086015162093a8063ffffffff91821604166000908152600785016020526040902054606087015161256f9291909116906117e1565b83600701600062093a8088610120015163ffffffff168161258c57fe5b0463ffffffff16815260200190815260200160002060006101000a8154816001600160801b0302191690836001600160801b031602179055508461014001516125fe57604085015183546125f9916125f491600160801b9004600f90810b810b91900b612efd565b612f13565b612623565b60408501518354612623916125f491600160801b9004600f90810b810b91900b612f24565b8354600f9190910b6001600160801b03908116600160801b0291161783556101408501516126a45761269f6125f48660600151600f0b85600801600062093a808a610120015163ffffffff168161267657fe5b0463ffffffff9081168252602082019290925260400160002054600f90810b900b9190612efd16565b6126f8565b6126f86125f48660600151600f0b85600801600062093a808a610120015163ffffffff16816126cf57fe5b0463ffffffff9081168252602082019290925260400160002054600f90810b900b9190612f2416565b83600801600062093a8088610120015163ffffffff168161271557fe5b0463ffffffff16815260200190815260200160002060006101000a8154816001600160801b030219169083600f0b6001600160801b0316021790555050505092915050565b8060020b8260020b8161276957fe5b0760020b1561277757600080fd5b6000806127928360020b8560020b8161278c57fe5b05612f3a565b600191820b820b60009081526020979097526040909620805460ff9097169190911b90951890945550505050565b600285810b80820b60009081526020899052604080822088850b850b83529082209193849391929184918291908a900b1261280657505060028201546003830154612819565b8360020154880391508360030154870390505b6000808b60020b8b60020b121561283b5750506002830154600384015461284e565b84600201548a0391508460030154890390505b92909803979097039b96909503949094039850939650505050505050565b60038501805460ff1916600117905583546001600160801b0316156128ab5760008061289785610557565b600091820360028a01559003600188015550505b6003850180547fffffffffffffffffffffff0000000000000000000000000000000000000000ff166101006001600160a01b03601395860b81169190910291909117909155600490950180547fffffffffffffffffffffffff0000000000000000000000000000000000000000169190920b909416939093179092555050565b6040805160c08101825288546001600160801b03908116825260018a0154602083015260028a01549282019290925260038901548083166060830152600160801b90049091166080820152600488015460a08201526000600f85900b6129ba5781516001600160801b03166129b25760405162461bcd60e51b815260040161015190613482565b5080516129c9565b81516129c690866117e1565b90505b60006129ed8360200151860384600001516001600160801b0316600160801b6119af565b90506000612a138460400151860385600001516001600160801b0316600160801b6119af565b905086600f0b600014612a3a578a546001600160801b0319166001600160801b038416178b555b60018b0186905560028b018590556001600160801b038216151580612a6857506000816001600160801b0316115b15612aa65760038b0180546001600160801b031981166001600160801b039182168501821617808216600160801b9182900483168501909216021790555b6000888152620200118b016020526040902054801580612afb57506000898152620200118c016020526040902080548b91906000198401908110612ae657fe5b90600052602060002090600202016000015414155b15612b57576000898152620200118c016020908152604080832081518083019092528d82526001600160801b03881682840190815281546001818101845592865293909420915160029093029091019182559151910155612b9b565b6000898152620200118c016020526040902080546001600160801b03861691906000198401908110612b8557fe5b9060005260206000209060020201600101819055505b505050505050505050505050565b845482908290612bc2906001600160801b0316866117e1565b87546001600160801b0319166001600160801b039190911617875560038701546004880154610100909104601390810b938490039391810b92839003929060009085900b1215612c1157600093505b60008360130b1215612c2257600092505b6000612c5561178360008b600f0b13612c41578a600003600f0b612c46565b8a600f0b5b8760130b640100000000612f4c565b90506000612c7661178360008b600f0b13612c41578a600003600f0b612c46565b9050600089600f0b13612c8f57808b6001015403612c97565b808b60010154015b60018c01556000600f8b900b13612cb457818b6002015403612cbc565b818b60020154015b8b600201819055505050505050505050505050565b600290810b810b600090815260209290925260408220828155600181018390559081018290556003810182905560040155565b6000836001600160a01b0316856001600160a01b03161115612d24579293925b7bffffffffffffffffffffffffffffffff000000000000000000000000606084901b166001600160a01b038686038116908716612d6057600080fd5b83612d9057866001600160a01b0316612d838383896001600160a01b03166119af565b81612d8a57fe5b04612db6565b612db6612da78383896001600160a01b0316612f4c565b886001600160a01b0316612f86565b979650505050505050565b6000600160ff1b8210612dd357600080fd5b5090565b6000836001600160a01b0316856001600160a01b03161115612df7579293925b81612e2457612e1f836001600160801b03168686036001600160a01b0316600160601b6119af565b612385565b612385836001600160801b03168686036001600160a01b0316600160601b612f4c565b806001600160801b0381168114612e5d57600080fd5b919050565b6000826001600160a01b0316846001600160a01b03161115612e82579192915b6000612ea5856001600160a01b0316856001600160a01b0316600160601b6119af565b905061238561203c84838888036001600160a01b03166119af565b6000826001600160a01b0316846001600160a01b03161115612ee0579192915b6117a461203c83600160601b8787036001600160a01b03166119af565b8181018281121560008312151461189757600080fd5b80600f81900b8114612e5d57600080fd5b8082038281131560008312151461189757600080fd5b60020b600881901d9161010090910790565b6000612f598484846119af565b905060008280612f6557fe5b84860911156117a7576000198110612f7c57600080fd5b6001019392505050565b808204910615150190565b6040805160a08101825260008082526020820181905291810182905260608101829052608081019190915290565b6040518060800160405280600081526020016000815260200160008152602001600081525090565b604051806040016040528060008152602001600081525090565b6040518060c00160405280600081526020016000815260200160001515815260200160001515815260200160008152602001600081525090565b604080516060810182526000808252602082018190529181019190915290565b8035600281900b8114612e5d57600080fd5b805161ffff81168114612e5d57600080fd5b600060208284031215613090578081fd5b81516117a781613521565b6000602082840312156130ac578081fd5b815180151581146117a7578182fd5b6000806000606084860312156130cf578182fd5b83518060060b81146130df578283fd5b60208501519093506130f081613521565b604085015190925061310181613521565b809150509250925092565b600080600080600060a08688031215613123578081fd5b85359450602086013561313581613521565b93506040860135925061314a6060870161305b565b91506131586080870161305b565b90509295509295909350565b600060c08284031215613175578081fd5b60405160c0810181811067ffffffffffffffff8211171561319257fe5b60405282356131a081613521565b8152602083810135908201526131b86040840161305b565b60408201526131c96060840161305b565b6060820152608083013580600f0b81146131e1578283fd5b608082015260a0928301359281019290925250919050565b600060a0828403121561320a578081fd5b60405160a0810181811067ffffffffffffffff8211171561322757fe5b60405282358152602083013561323c81613521565b6020820152604083810135908201526132576060840161305b565b60608201526132686080840161305b565b60808201529392505050565b60008060408385031215613286578182fd5b825161329181613521565b60208401519092506132a281613521565b809150509250929050565b600080604083850312156132bf578182fd5b6132c88361306d565b91506132d66020840161306d565b90509250929050565b6000602082840312156132f0578081fd5b5051919050565b60609490941b6bffffffffffffffffffffffff191684526014840192909252600290810b60e890811b603485015291900b901b6037820152603a0190565b6001600160a01b03929092168252602082015260400190565b97885261ffff968716602089015263ffffffff95909516604088015260029390930b60608701526001600160801b0391821660808701521660a0850152821660c08401521660e08201526101000190565b97885263ffffffff968716602089015294909516604087015260029290920b606086015261ffff90811660808601526001600160801b0391821660a0860152921660c08401521660e08201526101000190565b602080825260039082015262544c5560e81b604082015260600190565b602080825260039082015262232a2960e91b604082015260600190565b60208082526003908201526254554d60e81b604082015260600190565b602080825260039082015262544c4d60e81b604082015260600190565b6020808252600290820152614c4f60f01b604082015260600190565b60208082526002908201526104e560f41b604082015260600190565b602080825260039082015262544e4160e81b604082015260600190565b90815260200190565b9283526020830191909152604082015260600190565b9182526001600160a01b0316602082015260400190565b918252602082015260400190565b63ffffffff939093168352600291820b6020840152900b604082015260600190565b6001600160a01b038116811461353657600080fd5b5056fea164736f6c6343000706000a
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
[ 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.