Transactions
Token Transfers
Tokens
Internal Transactions
Coin Balance History
Logs
Code
Read Contract
Write Contract
Warning! Contract bytecode has been changed and doesn't match the verified one. Therefore, interaction with this smart contract may be risky.
This contract has been partially verified via Sourcify.
View contract in Sourcify repository
- Contract name:
- V4Pool
- Optimization enabled
- true
- Compiler version
- v0.8.20+commit.a1b79de6
- Optimization runs
- 0
- EVM Version
- paris
- Verified at
- 2026-06-27T20:41:30.095103Z
contracts/V4Pool.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
pragma abicoder v1;
import './base/V4PoolBase.sol';
import './base/ReentrancyGuard.sol';
import './base/Positions.sol';
import './base/SwapCalculation.sol';
import './base/ReservesManager.sol';
import './base/TickStructure.sol';
import './libraries/FullMath.sol';
import './libraries/SafeCast.sol';
import './libraries/TickMath.sol';
import './libraries/LiquidityMath.sol';
import './interfaces/IV4Factory.sol';
/// @title V4 concentrated liquidity pool
/// @notice This contract is responsible for liquidity positions, swaps and flashloans
/// @dev Version: V4 Dex 1.0
contract V4Pool is V4PoolBase, TickStructure, ReentrancyGuard, Positions, SwapCalculation, ReservesManager {
using SafeCast for uint256;
using SafeCast for uint128;
/// @inheritdoc IV4PoolActions
function initialize(uint160 initialPrice) external override {
int24 tick = TickMath.getTickAtSqrtRatio(initialPrice); // getTickAtSqrtRatio checks validity of initialPrice inside
if (globalState.price != 0) revert alreadyInitialized(); // after initialization, the price can never become zero
globalState.price = initialPrice;
globalState.tick = tick;
emit Initialize(initialPrice, tick);
_callBeforeInitialize(initialPrice);
(uint16 _communityFee, int24 _tickSpacing, uint16 _fee) = _getDefaultConfiguration();
_setFee(_fee);
_setTickSpacing(_tickSpacing);
if (_communityFee != 0 && communityVault == address(0)) revert invalidNewCommunityFee(); // the pool should not accumulate a community fee without a vault
_setCommunityFee(_communityFee);
_callAfterInitialize(initialPrice, tick);
}
/// @inheritdoc IV4PoolActions
function mint(
address leftoversRecipient,
address recipient,
int24 bottomTick,
int24 topTick,
uint128 liquidityDesired,
bytes calldata data
) external override onlyValidTicks(bottomTick, topTick) returns (uint256 amount0, uint256 amount1, uint128 liquidityActual) {
if (liquidityDesired == 0) revert zeroLiquidityDesired();
_callBeforeModifyPosition(recipient, bottomTick, topTick, liquidityDesired.toInt128(), data);
_lock();
{
// scope to prevent stack too deep
int24 currentTick = globalState.tick;
uint160 currentPrice = globalState.price;
if (currentPrice == 0) revert notInitialized();
unchecked {
int24 _tickSpacing = tickSpacing;
if (bottomTick % _tickSpacing | topTick % _tickSpacing != 0) revert tickIsNotSpaced();
}
(amount0, amount1, ) = LiquidityMath.getAmountsForLiquidity(bottomTick, topTick, liquidityDesired.toInt128(), currentTick, currentPrice);
}
(uint256 receivedAmount0, uint256 receivedAmount1) = _updateReserves();
_mintCallback(amount0, amount1, data); // IV4MintCallback.v4MintCallback to msg.sender
receivedAmount0 = amount0 == 0 ? 0 : _balanceToken0() - receivedAmount0;
receivedAmount1 = amount1 == 0 ? 0 : _balanceToken1() - receivedAmount1;
if (receivedAmount0 < amount0) {
liquidityActual = uint128(FullMath.mulDiv(uint256(liquidityDesired), receivedAmount0, amount0));
} else {
liquidityActual = liquidityDesired;
}
if (receivedAmount1 < amount1) {
uint128 liquidityForRA1 = uint128(FullMath.mulDiv(uint256(liquidityDesired), receivedAmount1, amount1));
if (liquidityForRA1 < liquidityActual) liquidityActual = liquidityForRA1;
}
if (liquidityActual == 0) revert zeroLiquidityActual();
// scope to prevent "stack too deep"
{
Position storage _position = getOrCreatePosition(recipient, bottomTick, topTick);
(amount0, amount1) = _updatePositionTicksAndFees(_position, bottomTick, topTick, liquidityActual.toInt128());
}
unchecked {
// revert on any underpayment first, then return leftovers
if (receivedAmount0 < amount0 || receivedAmount1 < amount1) revert insufficientInputAmount();
if (receivedAmount0 > amount0) _transfer(token0, leftoversRecipient, receivedAmount0 - amount0);
if (receivedAmount1 > amount1) _transfer(token1, leftoversRecipient, receivedAmount1 - amount1);
}
_changeReserves(int256(amount0), int256(amount1), 0, 0, 0, 0);
emit Mint(msg.sender, recipient, bottomTick, topTick, liquidityActual, amount0, amount1);
_unlock();
_callAfterModifyPosition(recipient, bottomTick, topTick, liquidityActual.toInt128(), amount0, amount1, data);
}
/// @inheritdoc IV4PoolActions
function burn(
int24 bottomTick,
int24 topTick,
uint128 amount,
bytes calldata data
) external override onlyValidTicks(bottomTick, topTick) returns (uint256 amount0, uint256 amount1) {
if (amount > uint128(type(int128).max)) revert arithmeticError();
int128 liquidityDelta = -int128(amount);
uint24 pluginFee = _callBeforeModifyPosition(msg.sender, bottomTick, topTick, liquidityDelta, data);
_lock();
_updateReserves();
{
Position storage position = getOrCreatePosition(msg.sender, bottomTick, topTick);
(amount0, amount1) = _updatePositionTicksAndFees(position, bottomTick, topTick, liquidityDelta);
if (pluginFee > 0) {
uint256 deltaPluginFeePending0;
uint256 deltaPluginFeePending1;
if (amount0 > 0) {
deltaPluginFeePending0 = FullMath.mulDiv(amount0, pluginFee, Constants.FEE_DENOMINATOR);
amount0 -= deltaPluginFeePending0;
}
if (amount1 > 0) {
deltaPluginFeePending1 = FullMath.mulDiv(amount1, pluginFee, Constants.FEE_DENOMINATOR);
amount1 -= deltaPluginFeePending1;
}
_changeReserves(0, 0, 0, 0, deltaPluginFeePending0, deltaPluginFeePending1);
}
if (amount0 | amount1 != 0) {
// since we do not support tokens whose total supply can exceed uint128, these casts are safe
// and, theoretically, unchecked cast prevents a complete blocking of burn
(position.fees0, position.fees1) = (position.fees0 + uint128(amount0), position.fees1 + uint128(amount1));
}
}
if (amount | amount0 | amount1 != 0) {
emit BurnFee(msg.sender, pluginFee);
emit Burn(msg.sender, bottomTick, topTick, amount, amount0, amount1);
}
_unlock();
_callAfterModifyPosition(msg.sender, bottomTick, topTick, liquidityDelta, amount0, amount1, data);
}
// hook helpers are implemented in Hooks base
/// @inheritdoc IV4PoolActions
function collect(
address recipient,
int24 bottomTick,
int24 topTick,
uint128 amount0Requested,
uint128 amount1Requested
) external override returns (uint128 amount0, uint128 amount1) {
_lock();
// we don't check tick range validity, because if ticks are incorrect, the position will be empty
Position storage position = getOrCreatePosition(msg.sender, bottomTick, topTick);
(uint128 positionFees0, uint128 positionFees1) = (position.fees0, position.fees1);
if (amount0Requested > positionFees0) amount0Requested = positionFees0;
if (amount1Requested > positionFees1) amount1Requested = positionFees1;
if (amount0Requested | amount1Requested != 0) {
// use one if since fees0 and fees1 are tightly packed
(amount0, amount1) = (amount0Requested, amount1Requested);
unchecked {
// single SSTORE
(position.fees0, position.fees1) = (positionFees0 - amount0, positionFees1 - amount1);
if (amount0 > 0) _transfer(token0, recipient, amount0);
if (amount1 > 0) _transfer(token1, recipient, amount1);
_changeReserves(-int256(uint256(amount0)), -int256(uint256(amount1)), 0, 0, 0, 0);
}
emit Collect(msg.sender, recipient, bottomTick, topTick, amount0, amount1);
}
_unlock();
}
/// @inheritdoc IV4PoolActions
function swap(
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bytes calldata data
) external override returns (int256 amount0, int256 amount1) {
(uint24 overrideFee, uint24 pluginFee) = _callBeforeSwap(recipient, zeroToOne, amountRequired, limitSqrtPrice, false, data);
_lock();
{
// scope to prevent "stack too deep"
FeesAmount memory fees;
(amount0, amount1, , , , fees) = _calculateSwap(overrideFee, pluginFee, zeroToOne, amountRequired, limitSqrtPrice);
(uint256 balance0Before, uint256 balance1Before) = _updateReserves();
if (zeroToOne) {
unchecked {
if (amount1 < 0) _transfer(token1, recipient, uint256(-amount1)); // amount1 cannot be > 0
}
_swapCallback(amount0, amount1, data); // callback to get tokens from the msg.sender
if (balance0Before + uint256(amount0) > _balanceToken0()) revert insufficientInputAmount();
_changeReserves(amount0, amount1, fees.communityFeeAmount, 0, fees.pluginFeeAmount, 0); // reflect reserve change and pay communityFee
} else {
unchecked {
if (amount0 < 0) _transfer(token0, recipient, uint256(-amount0)); // amount0 cannot be > 0
}
_swapCallback(amount0, amount1, data); // callback to get tokens from the msg.sender
if (balance1Before + uint256(amount1) > _balanceToken1()) revert insufficientInputAmount();
_changeReserves(amount0, amount1, 0, fees.communityFeeAmount, 0, fees.pluginFeeAmount); // reflect reserve change and pay communityFee
}
_emitSwapEvent(recipient, amount0, amount1, globalState.price, liquidity, globalState.tick, overrideFee, pluginFee);
}
_unlock();
_callAfterSwap(recipient, zeroToOne, amountRequired, limitSqrtPrice, amount0, amount1, data);
}
/// @inheritdoc IV4PoolActions
function swapWithPaymentInAdvance(
address leftoversRecipient,
address recipient,
bool zeroToOne,
int256 amountToSell,
uint160 limitSqrtPrice,
bytes calldata data
) external override returns (int256 amount0, int256 amount1) {
if (amountToSell < 0) revert invalidAmountRequired(); // we support only exactInput here
_lock();
// firstly we are getting tokens from the original caller of the transaction
// since the pool can get less/more tokens then expected, _amountToSell_ can be changed
{
// scope to prevent "stack too deep"
int256 amountReceived;
if (zeroToOne) {
uint256 balanceBefore = _balanceToken0();
_swapCallback(amountToSell, 0, data); // callback to get tokens from the msg.sender
uint256 balanceAfter = _balanceToken0();
amountReceived = (balanceAfter - balanceBefore).toInt256();
_changeReserves(amountReceived, 0, 0, 0, 0, 0);
} else {
uint256 balanceBefore = _balanceToken1();
_swapCallback(0, amountToSell, data); // callback to get tokens from the msg.sender
uint256 balanceAfter = _balanceToken1();
amountReceived = (balanceAfter - balanceBefore).toInt256();
_changeReserves(0, amountReceived, 0, 0, 0, 0);
}
if (amountReceived != amountToSell) amountToSell = amountReceived;
}
if (amountToSell == 0) revert insufficientInputAmount();
_unlock();
(uint24 overrideFee, uint24 pluginFee) = _callBeforeSwap(recipient, zeroToOne, amountToSell, limitSqrtPrice, true, data);
_lock();
_updateReserves();
FeesAmount memory fees;
(amount0, amount1, , , , fees) = _calculateSwap(overrideFee, pluginFee, zeroToOne, amountToSell, limitSqrtPrice);
unchecked {
// transfer to the recipient
if (zeroToOne) {
if (amount1 < 0) _transfer(token1, recipient, uint256(-amount1)); // amount1 cannot be > 0
uint256 leftover = uint256(amountToSell - amount0); // return the leftovers
if (leftover != 0) _transfer(token0, leftoversRecipient, leftover);
_changeReserves(-leftover.toInt256(), amount1, fees.communityFeeAmount, 0, fees.pluginFeeAmount, 0); // reflect reserve change and pay communityFee
} else {
if (amount0 < 0) _transfer(token0, recipient, uint256(-amount0)); // amount0 cannot be > 0
uint256 leftover = uint256(amountToSell - amount1); // return the leftovers
if (leftover != 0) _transfer(token1, leftoversRecipient, leftover);
_changeReserves(amount0, -leftover.toInt256(), 0, fees.communityFeeAmount, 0, fees.pluginFeeAmount); // reflect reserve change and pay communityFee
}
}
_emitSwapEvent(recipient, amount0, amount1, globalState.price, liquidity, globalState.tick, overrideFee, pluginFee);
_unlock();
_callAfterSwap(recipient, zeroToOne, amountToSell, limitSqrtPrice, amount0, amount1, data);
}
/// @dev internal function to reduce bytecode size
function _emitSwapEvent(
address recipient,
int256 amount0,
int256 amount1,
uint160 newPrice,
uint128 newLiquidity,
int24 newTick,
uint24 overrideFee,
uint24 pluginFee
) private {
emit SwapFee(msg.sender, overrideFee, pluginFee);
emit Swap(msg.sender, recipient, amount0, amount1, newPrice, newLiquidity, newTick);
}
// before/after swap logic moved to Hooks base
/// @inheritdoc IV4PoolActions
function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external override {
_callBeforeFlash(recipient, amount0, amount1, data);
_lock();
uint256 paid0;
uint256 paid1;
{
(uint256 balance0Before, uint256 balance1Before) = _updateReserves();
uint256 fee0;
if (amount0 > 0) {
fee0 = FullMath.mulDivRoundingUp(amount0, Constants.FLASH_FEE, Constants.FEE_DENOMINATOR);
_transfer(token0, recipient, amount0);
}
uint256 fee1;
if (amount1 > 0) {
fee1 = FullMath.mulDivRoundingUp(amount1, Constants.FLASH_FEE, Constants.FEE_DENOMINATOR);
_transfer(token1, recipient, amount1);
}
_flashCallback(fee0, fee1, data); // IV4FlashCallback.v4FlashCallback to msg.sender
paid0 = _balanceToken0();
if (balance0Before + fee0 > paid0) revert flashInsufficientPaid0();
paid1 = _balanceToken1();
if (balance1Before + fee1 > paid1) revert flashInsufficientPaid1();
unchecked {
paid0 -= balance0Before;
paid1 -= balance1Before;
}
uint256 _communityFee = globalState.communityFee;
if (_communityFee > 0) {
uint256 communityFee0;
if (paid0 > 0) communityFee0 = FullMath.mulDiv(paid0, _communityFee, Constants.COMMUNITY_FEE_DENOMINATOR);
uint256 communityFee1;
if (paid1 > 0) communityFee1 = FullMath.mulDiv(paid1, _communityFee, Constants.COMMUNITY_FEE_DENOMINATOR);
_changeReserves(int256(communityFee0), int256(communityFee1), communityFee0, communityFee1, 0, 0);
}
emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);
}
_unlock();
_callAfterFlash(recipient, amount0, amount1, paid0, paid1, data);
}
/// @dev using function to save bytecode
function _checkIfAdministrator() private view {
if (!IV4Factory(factory).hasRoleOrOwner(Constants.POOLS_ADMINISTRATOR_ROLE, msg.sender)) revert notAllowed();
}
// permissioned actions use reentrancy lock to prevent call from callback (to keep the correct order of events, etc.)
/// @inheritdoc IV4PoolPermissionedActions
function setCommunityFee(uint16 newCommunityFee) external override onlyUnlocked {
_checkIfAdministrator();
if (
newCommunityFee > Constants.MAX_COMMUNITY_FEE ||
newCommunityFee == globalState.communityFee ||
(newCommunityFee != 0 && communityVault == address(0))
) revert invalidNewCommunityFee();
_setCommunityFee(newCommunityFee);
}
/// @inheritdoc IV4PoolPermissionedActions
function setTickSpacing(int24 newTickSpacing) external override onlyUnlocked {
_checkIfAdministrator();
if (newTickSpacing <= 0 || newTickSpacing > Constants.MAX_TICK_SPACING || tickSpacing == newTickSpacing) revert invalidNewTickSpacing();
_setTickSpacing(newTickSpacing);
}
/// @inheritdoc IV4PoolPermissionedActions
/// @dev Flushes any pending plugin fees to the current plugin before updating the plugin address.
function setPlugin(address newPluginAddress) external override onlyUnlocked {
_checkIfAdministrator();
address currentPlugin = plugin;
// If there are pending plugin fees, flush them to the old plugin
if (pluginFeePending0 | pluginFeePending1 != 0) {
if (currentPlugin == address(0)) revert pluginFeesPendingToCollect();
_flushPluginFees(currentPlugin);
}
_setPluginConfig(0);
_setPlugin(newPluginAddress);
}
/// @inheritdoc IV4PoolPermissionedActions
function setPluginConfig(uint8 newConfig) external override onlyUnlocked {
address _plugin = plugin;
if (_plugin == address(0)) revert pluginIsNotConnected(); // it is not allowed to set plugin config without plugin
if (msg.sender != _plugin) _checkIfAdministrator();
_setPluginConfig(newConfig);
}
/// @inheritdoc IV4PoolPermissionedActions
function setCommunityVault(address newCommunityVault) external override onlyUnlocked {
if (msg.sender != factory) _checkIfAdministrator();
if (newCommunityVault == address(0)) {
if (communityFeePending0 | communityFeePending1 != 0) revert communityFeesPendingToCollect();
if (globalState.communityFee != 0) _setCommunityFee(0);
}
_setCommunityFeeVault(newCommunityVault);
}
/// @inheritdoc IV4PoolPermissionedActions
function setFee(uint16 newFee) external override {
_checkIfAdministrator();
if (!globalState.unlocked) revert locked(); // cheaper to check lock here
if (_hasPluginFlag(Plugins.DYNAMIC_FEE)) revert dynamicFeeActive();
if (newFee >= 1e6) revert incorrectPluginFee();
_setFee(newFee);
}
/// @dev using function to save bytecode
function _checkIfPlugin() private view {
if (msg.sender != plugin) revert notAllowed();
}
/// @inheritdoc IV4PoolPermissionedActions
function sync() external override {
_checkIfPlugin();
_lock();
_updateReserves();
_unlock();
}
/// @inheritdoc IV4PoolPermissionedActions
function skim() external override {
_checkIfPlugin();
_lock();
_skimReserves(msg.sender);
_unlock();
}
}
/V4PoolDeployer.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
pragma abicoder v1;
import './interfaces/IV4PoolDeployer.sol';
import './V4Pool.sol';
/// @title V4 pool deployer
/// @notice Is used by V4Factory to deploy pools
/// @dev Version: V4 Dex 1.0
contract V4PoolDeployer is IV4PoolDeployer {
/// @dev two storage slots for dense cache packing
bytes32 private cache0;
bytes32 private cache1;
address private immutable factory;
constructor(address _factory) {
assembly {
if iszero(_factory) {
revert(0, 0)
}
}
factory = _factory;
}
/// @inheritdoc IV4PoolDeployer
function getDeployParameters() external view override returns (address _plugin, address _factory, address _token0, address _token1) {
bytes32 _cache0 = cache0;
bytes32 _cache1 = cache1;
assembly {
_plugin := shr(96, _cache0)
_token0 := or(shl(64, and(_cache0, 0xFFFFFFFFFFFFFFFFFFFFFFFF)), shr(160, _cache1))
_token1 := and(_cache1, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
_factory = factory;
}
/// @inheritdoc IV4PoolDeployer
function deploy(address plugin, address token0, address token1, address deployer) external override returns (address pool) {
address _factory = factory;
bytes memory _encodedParams;
assembly {
if iszero(eq(caller(), _factory)) {
revert(0, 0)
}
token0 := and(token0, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) // clean higher bits, just in case
// cache0 = [plugin, token0[0, 96]], cache1 = [token0[0, 64], 0-s x32 , token1]
sstore(cache0.slot, or(shr(64, token0), shl(96, plugin)))
sstore(cache1.slot, or(shl(160, token0), and(token1, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)))
let ptr := mload(0x40)
_encodedParams := ptr
switch deployer
case 0 {
mstore(ptr, 0x40)
mstore(add(ptr, 0x20), token0)
mstore(add(ptr, 0x40), token1)
}
default {
mstore(ptr, 0x60)
mstore(add(ptr, 0x20), deployer)
mstore(add(ptr, 0x40), token0)
mstore(add(ptr, 0x60), token1)
}
}
pool = address(new V4Pool{salt: keccak256(_encodedParams)}());
assembly {
sstore(cache0.slot, 0)
sstore(cache1.slot, 0)
}
}
}
/TokenDeltaMath.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './SafeCast.sol';
import './FullMath.sol';
import './Constants.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 TokenDeltaMath {
using SafeCast for uint256;
/// @notice Gets the token0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper)
/// @param priceLower A Q64.96 sqrt price
/// @param priceUpper Another Q64.96 sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up or down
/// @return token0Delta Amount of token0 required to cover a position of size liquidity between the two passed prices
function getToken0Delta(uint160 priceLower, uint160 priceUpper, uint128 liquidity, bool roundUp) internal pure returns (uint256 token0Delta) {
unchecked {
uint256 priceDelta = priceUpper - priceLower;
require(priceDelta < priceUpper); // forbids underflow and 0 priceLower
uint256 liquidityShifted = uint256(liquidity) << Constants.RESOLUTION;
token0Delta = roundUp
? FullMath.unsafeDivRoundingUp(FullMath.mulDivRoundingUp(priceDelta, liquidityShifted, priceUpper), priceLower) // denominator always > 0
: FullMath.mulDiv(priceDelta, liquidityShifted, priceUpper) / priceLower;
}
}
/// @notice Gets the token1 delta between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// @param priceLower A Q64.96 sqrt price
/// @param priceUpper Another Q64.96 sqrt price
/// @param liquidity The amount of usable liquidity
/// @param roundUp Whether to round the amount up, or down
/// @return token1Delta Amount of token1 required to cover a position of size liquidity between the two passed prices
function getToken1Delta(uint160 priceLower, uint160 priceUpper, uint128 liquidity, bool roundUp) internal pure returns (uint256 token1Delta) {
unchecked {
require(priceUpper >= priceLower);
uint256 priceDelta = priceUpper - priceLower;
token1Delta = roundUp ? FullMath.mulDivRoundingUp(priceDelta, liquidity, Constants.Q96) : FullMath.mulDiv(priceDelta, liquidity, Constants.Q96);
}
}
/// @notice Helper that gets signed token0 delta
/// @param priceLower A Q64.96 sqrt price
/// @param priceUpper Another Q64.96 sqrt price
/// @param liquidity The change in liquidity for which to compute the token0 delta
/// @return token0Delta Amount of token0 corresponding to the passed liquidityDelta between the two prices
function getToken0Delta(uint160 priceLower, uint160 priceUpper, int128 liquidity) internal pure returns (int256 token0Delta) {
unchecked {
token0Delta = liquidity >= 0
? getToken0Delta(priceLower, priceUpper, uint128(liquidity), true).toInt256()
: -getToken0Delta(priceLower, priceUpper, uint128(-liquidity), false).toInt256();
}
}
/// @notice Helper that gets signed token1 delta
/// @param priceLower A Q64.96 sqrt price
/// @param priceUpper Another Q64.96 sqrt price
/// @param liquidity The change in liquidity for which to compute the token1 delta
/// @return token1Delta Amount of token1 corresponding to the passed liquidityDelta between the two prices
function getToken1Delta(uint160 priceLower, uint160 priceUpper, int128 liquidity) internal pure returns (int256 token1Delta) {
unchecked {
token1Delta = liquidity >= 0
? getToken1Delta(priceLower, priceUpper, uint128(liquidity), true).toInt256()
: -getToken1Delta(priceLower, priceUpper, uint128(-liquidity), false).toInt256();
}
}
}
/TickTree.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './TickMath.sol';
/// @title Packed tick initialized state library
/// @notice Stores a packed mapping of tick index to its initialized state and search tree
/// @dev The leafs mapping uses int16 for keys since ticks are represented as int24 and there are 256 (2^8) values per word.
library TickTree {
int16 internal constant SECOND_LAYER_OFFSET = 3466; // ceil(-MIN_TICK / 256)
/// @notice Toggles the initialized state for a given tick from false to true, or vice versa
/// @param leafs The mapping of words with ticks
/// @param secondLayer The mapping of words with leafs
/// @param treeRoot The word with info about active subtrees
/// @param tick The tick to toggle
function toggleTick(
mapping(int16 => uint256) storage leafs,
mapping(int16 => uint256) storage secondLayer,
uint32 treeRoot,
int24 tick
) internal returns (uint32 newTreeRoot) {
newTreeRoot = treeRoot;
(bool toggledNode, int16 nodeIndex) = _toggleBitInNode(leafs, tick); // toggle in leaf
if (toggledNode) {
unchecked {
(toggledNode, nodeIndex) = _toggleBitInNode(secondLayer, nodeIndex + SECOND_LAYER_OFFSET);
}
if (toggledNode) {
assembly {
newTreeRoot := xor(newTreeRoot, shl(nodeIndex, 1))
}
}
}
}
/// @notice Toggles a bit in a tree layer by its index
/// @param treeLevel The level of tree
/// @param bitIndex The end-to-end index of a bit in a layer of tree
/// @return toggledNode Toggled whole node or not
/// @return nodeIndex Number of corresponding node
function _toggleBitInNode(mapping(int16 => uint256) storage treeLevel, int24 bitIndex) private returns (bool toggledNode, int16 nodeIndex) {
assembly {
nodeIndex := sar(8, bitIndex)
}
uint256 node = treeLevel[nodeIndex];
assembly {
toggledNode := iszero(node)
node := xor(node, shl(and(bitIndex, 0xFF), 1))
toggledNode := xor(toggledNode, iszero(node))
}
treeLevel[nodeIndex] = node;
}
/// @notice Returns the next initialized tick in tree to the right (gte) of the given tick or `MAX_TICK`
/// @param leafs The words with ticks
/// @param secondLayer The words with info about active leafs
/// @param treeRoot The word with info about active subtrees
/// @param tick The starting tick
/// @return nextTick The next initialized tick or `MAX_TICK`
function getNextTick(
mapping(int16 => uint256) storage leafs,
mapping(int16 => uint256) storage secondLayer,
uint32 treeRoot,
int24 tick
) internal view returns (int24 nextTick) {
unchecked {
tick++; // start searching from the next tick
int16 nodeIndex;
assembly {
// index in treeRoot
nodeIndex := shr(8, add(sar(8, tick), SECOND_LAYER_OFFSET))
}
bool initialized;
// if subtree has active ticks
if (treeRoot & (1 << uint16(nodeIndex)) != 0) {
// try to find initialized tick in the corresponding leaf of the tree
(nodeIndex, nextTick, initialized) = _nextActiveBitInSameNode(leafs, tick);
if (initialized) return nextTick;
// try to find next initialized leaf in the tree
(nodeIndex, nextTick, initialized) = _nextActiveBitInSameNode(secondLayer, nodeIndex + SECOND_LAYER_OFFSET + 1);
}
if (!initialized) {
// try to find which subtree has an active leaf
// nodeIndex is now the index of the second level node
(nextTick, initialized) = _nextActiveBitInWord(treeRoot, ++nodeIndex);
if (!initialized) return TickMath.MAX_TICK;
nextTick = _firstActiveBitInNode(secondLayer, nextTick); // we found a second level node that has a leaf with an active tick
}
nextTick = _firstActiveBitInNode(leafs, nextTick - SECOND_LAYER_OFFSET);
}
}
/// @notice Returns the index of the next active bit in the same tree node
/// @param treeLevel The level of search tree
/// @param bitIndex The starting bit index
/// @return nodeIndex The index of corresponding node
/// @return nextBitIndex The index of next active bit or last bit in node
/// @return initialized Is nextBitIndex initialized or not
function _nextActiveBitInSameNode(
mapping(int16 => uint256) storage treeLevel,
int24 bitIndex
) internal view returns (int16 nodeIndex, int24 nextBitIndex, bool initialized) {
assembly {
nodeIndex := sar(8, bitIndex)
}
(nextBitIndex, initialized) = _nextActiveBitInWord(treeLevel[nodeIndex], bitIndex);
}
/// @notice Returns first active bit in given node
/// @param treeLevel The level of search tree
/// @param nodeIndex The index of corresponding node in the level of tree
/// @return bitIndex Number of next active bit or last bit in node
function _firstActiveBitInNode(mapping(int16 => uint256) storage treeLevel, int24 nodeIndex) internal view returns (int24 bitIndex) {
assembly {
bitIndex := shl(8, nodeIndex)
}
(bitIndex, ) = _nextActiveBitInWord(treeLevel[int16(nodeIndex)], bitIndex);
}
/// @notice Returns the next initialized bit contained in the word that is to the right or at (gte) of the given bit
/// @param word The word in which to compute the next initialized bit
/// @param bitIndex The end-to-end index of a bit in a layer of tree
/// @return nextBitIndex The next initialized or uninitialized bit up to 256 bits away from the current bit
/// @return initialized Whether the next bit is initialized, as the function only searches within up to 256 bits
function _nextActiveBitInWord(uint256 word, int24 bitIndex) internal pure returns (int24 nextBitIndex, bool initialized) {
uint256 bitIndexInWord;
assembly {
bitIndexInWord := and(bitIndex, 0xFF)
}
unchecked {
uint256 _row = word >> bitIndexInWord; // all the 1s at or to the left of the bitIndexInWord
if (_row == 0) {
nextBitIndex = bitIndex | 255;
} else {
nextBitIndex = bitIndex + int24(uint24(getSingleSignificantBit((0 - _row) & _row))); // least significant bit
initialized = true;
}
}
}
/// @notice get position of single 1-bit
/// @dev it is assumed that word contains exactly one 1-bit, otherwise the result will be incorrect
/// @param word The word containing only one 1-bit
function getSingleSignificantBit(uint256 word) internal pure returns (uint8 singleBitPos) {
assembly {
singleBitPos := iszero(and(word, 0x5555555555555555555555555555555555555555555555555555555555555555))
singleBitPos := or(singleBitPos, shl(7, iszero(and(word, 0x00000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))))
singleBitPos := or(singleBitPos, shl(6, iszero(and(word, 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF))))
singleBitPos := or(singleBitPos, shl(5, iszero(and(word, 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF))))
singleBitPos := or(singleBitPos, shl(4, iszero(and(word, 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF))))
singleBitPos := or(singleBitPos, shl(3, iszero(and(word, 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF))))
singleBitPos := or(singleBitPos, shl(2, iszero(and(word, 0x0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F))))
singleBitPos := or(singleBitPos, shl(1, iszero(and(word, 0x3333333333333333333333333333333333333333333333333333333333333333))))
}
}
}
/TickMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IV4PoolErrors.sol';
/// @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
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
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 price 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 price) {
unchecked {
// get abs value
int24 absTickMask = tick >> (24 - 1);
uint256 absTick = uint24((tick + absTickMask) ^ absTickMask);
if (absTick > uint24(MAX_TICK)) revert IV4PoolErrors.tickOutOfRange();
uint256 ratio = 0x100000000000000000000000000000000;
if (absTick & 0x1 != 0) ratio = 0xfffcb933bd6fad37aa2d162d1a594001;
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) {
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
}
if (tick > 0) {
assembly {
ratio := div(not(0), 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
price = uint160((ratio + 0xFFFFFFFF) >> 32);
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case price < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param price 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 price) internal pure returns (int24 tick) {
unchecked {
// second inequality must be >= because the price can never reach the price at the max tick
if (price < MIN_SQRT_RATIO || price >= MAX_SQRT_RATIO) revert IV4PoolErrors.priceOutOfRange();
uint256 ratio = uint256(price) << 32;
uint256 r = ratio;
uint256 msb;
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) <= price
? tickHi
: tickLow;
}
}
}
/TickManagement.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../interfaces/pool/IV4PoolErrors.sol';
import './TickMath.sol';
import './LiquidityMath.sol';
import './Constants.sol';
/// @title Library for managing and interacting with ticks
/// @notice Contains functions for managing tick processes and relevant calculations
/// @dev Ticks are organized as a doubly linked list
library TickManagement {
// info stored for each initialized individual tick
struct Tick {
uint256 liquidityTotal; // the total position liquidity that references this tick
int128 liquidityDelta; // amount of net liquidity added (subtracted) when tick is crossed left-right (right-left),
int24 prevTick;
int24 nextTick;
// 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 outerFeeGrowth0Token;
uint256 outerFeeGrowth1Token;
}
function checkTickRangeValidity(int24 bottomTick, int24 topTick) internal pure {
if (topTick > TickMath.MAX_TICK) revert IV4PoolErrors.topTickAboveMAX();
if (topTick <= bottomTick) revert IV4PoolErrors.topTickLowerOrEqBottomTick();
if (bottomTick < TickMath.MIN_TICK) revert IV4PoolErrors.bottomTickLowerThanMIN();
}
/// @notice Retrieves fee growth data
/// @dev F-02: Tick boundary convention - Position is active when bottomTick <= currentTick < topTick
/// @dev This is consistent with Uniswap V3 and ensures unambiguous fee attribution at boundaries
/// @param self The mapping containing all tick information for initialized ticks
/// @param bottomTick The lower tick boundary of the position
/// @param topTick The upper tick boundary of the position
/// @param currentTick The current tick
/// @param totalFeeGrowth0Token The all-time global fee growth, per unit of liquidity, in token0
/// @param totalFeeGrowth1Token The all-time global fee growth, per unit of liquidity, in token1
/// @return innerFeeGrowth0Token The all-time fee growth in token0, per unit of liquidity, inside the position's tick boundaries
/// @return innerFeeGrowth1Token The all-time fee growth in token1, per unit of liquidity, inside the position's tick boundaries
function getInnerFeeGrowth(
mapping(int24 => Tick) storage self,
int24 bottomTick,
int24 topTick,
int24 currentTick,
uint256 totalFeeGrowth0Token,
uint256 totalFeeGrowth1Token
) internal view returns (uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token) {
Tick storage lower = self[bottomTick];
Tick storage upper = self[topTick];
uint256 feeGrowthBelow0Token;
uint256 feeGrowthBelow1Token;
if (currentTick >= bottomTick) {
feeGrowthBelow0Token = lower.outerFeeGrowth0Token;
feeGrowthBelow1Token = lower.outerFeeGrowth1Token;
} else {
unchecked {
feeGrowthBelow0Token = totalFeeGrowth0Token - lower.outerFeeGrowth0Token;
feeGrowthBelow1Token = totalFeeGrowth1Token - lower.outerFeeGrowth1Token;
}
}
uint256 feeGrowthAbove0Token;
uint256 feeGrowthAbove1Token;
if (currentTick < topTick) {
feeGrowthAbove0Token = upper.outerFeeGrowth0Token;
feeGrowthAbove1Token = upper.outerFeeGrowth1Token;
} else {
unchecked {
feeGrowthAbove0Token = totalFeeGrowth0Token - upper.outerFeeGrowth0Token;
feeGrowthAbove1Token = totalFeeGrowth1Token - upper.outerFeeGrowth1Token;
}
}
unchecked {
innerFeeGrowth0Token = totalFeeGrowth0Token - feeGrowthBelow0Token - feeGrowthAbove0Token;
innerFeeGrowth1Token = totalFeeGrowth1Token - feeGrowthBelow1Token - feeGrowthAbove1Token;
}
}
/// @notice Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa
/// @dev F-02: Consistent tick initialization - ticks at or below current price get current global fee growth
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The tick that will be updated
/// @param currentTick The current tick
/// @param liquidityDelta A new amount of liquidity to be added (subtracted) when tick is crossed from left to right (right to left)
/// @param totalFeeGrowth0Token The all-time global fee growth, per unit of liquidity, in token0
/// @param totalFeeGrowth1Token The all-time global fee growth, per unit of liquidity, in token1
/// @param upper True for updating a position's upper tick, or false for updating a position's lower tick
/// @return flipped Whether the tick was flipped from initialized to uninitialized, or vice versa
function update(
mapping(int24 => Tick) storage self,
int24 tick,
int24 currentTick,
int128 liquidityDelta,
uint256 totalFeeGrowth0Token,
uint256 totalFeeGrowth1Token,
bool upper
) internal returns (bool flipped) {
Tick storage data = self[tick];
uint256 liquidityTotalBefore = data.liquidityTotal;
uint256 liquidityTotalAfter = LiquidityMath.addDelta(uint128(liquidityTotalBefore), liquidityDelta);
if (liquidityTotalAfter > Constants.MAX_LIQUIDITY_PER_TICK) revert IV4PoolErrors.liquidityOverflow();
int128 liquidityDeltaBefore = data.liquidityDelta;
// when the lower (upper) tick is crossed left to right (right to left), liquidity must be added (removed)
data.liquidityDelta = upper ? int128(int256(liquidityDeltaBefore) - liquidityDelta) : int128(int256(liquidityDeltaBefore) + liquidityDelta);
data.liquidityTotal = liquidityTotalAfter;
flipped = (liquidityTotalAfter == 0);
if (liquidityTotalBefore == 0) {
flipped = !flipped;
// F-02: By convention, all growth before a tick was initialized happened _below_ the tick
if (tick <= currentTick) (data.outerFeeGrowth0Token, data.outerFeeGrowth1Token) = (totalFeeGrowth0Token, totalFeeGrowth1Token);
}
}
/// @notice Transitions to next tick as needed by price movement
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The destination tick of the transition
/// @param feeGrowth0 The all-time global fee growth, per unit of liquidity, in token0
/// @param feeGrowth1 The all-time global fee growth, per unit of liquidity, in token1
/// @return liquidityDelta The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)
/// @return prevTick The previous active tick before _tick_
/// @return nextTick The next active tick after _tick_
function cross(
mapping(int24 => Tick) storage self,
int24 tick,
uint256 feeGrowth0,
uint256 feeGrowth1
) internal returns (int128 liquidityDelta, int24 prevTick, int24 nextTick) {
Tick storage data = self[tick];
unchecked {
(data.outerFeeGrowth1Token, data.outerFeeGrowth0Token) = (feeGrowth1 - data.outerFeeGrowth1Token, feeGrowth0 - data.outerFeeGrowth0Token);
}
return (data.liquidityDelta, data.prevTick, data.nextTick);
}
/// @notice Used for initial setup of ticks list
/// @param self The mapping containing all tick information for initialized ticks
function initTickState(mapping(int24 => Tick) storage self) internal {
(self[TickMath.MIN_TICK].prevTick, self[TickMath.MIN_TICK].nextTick) = (TickMath.MIN_TICK, TickMath.MAX_TICK);
(self[TickMath.MAX_TICK].prevTick, self[TickMath.MAX_TICK].nextTick) = (TickMath.MIN_TICK, TickMath.MAX_TICK);
}
/// @notice Removes tick from the linked list
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The tick that will be removed
/// @return prevTick The previous active tick before _tick_
/// @return nextTick The next active tick after _tick_
function removeTick(mapping(int24 => Tick) storage self, int24 tick) internal returns (int24 prevTick, int24 nextTick) {
(prevTick, nextTick) = (self[tick].prevTick, self[tick].nextTick);
delete self[tick];
if (tick == TickMath.MIN_TICK || tick == TickMath.MAX_TICK) {
// MIN_TICK and MAX_TICK cannot be removed from tick list
(self[tick].prevTick, self[tick].nextTick) = (prevTick, nextTick);
} else {
if (prevTick == nextTick) revert IV4PoolErrors.tickIsNotInitialized();
self[prevTick].nextTick = nextTick;
self[nextTick].prevTick = prevTick;
}
return (prevTick, nextTick);
}
/// @notice Adds tick to the linked list
/// @param self The mapping containing all tick information for initialized ticks
/// @param tick The tick that will be inserted
/// @param prevTick The previous active tick before _tick_
/// @param nextTick The next active tick after _tick_
function insertTick(mapping(int24 => Tick) storage self, int24 tick, int24 prevTick, int24 nextTick) internal {
if (tick == TickMath.MIN_TICK || tick == TickMath.MAX_TICK) return;
if (!(prevTick < tick && nextTick > tick)) revert IV4PoolErrors.tickInvalidLinks();
(self[tick].prevTick, self[tick].nextTick) = (prevTick, nextTick);
self[prevTick].nextTick = tick;
self[nextTick].prevTick = tick;
}
}
/SafeTransfer.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IV4PoolErrors.sol';
/// @title SafeTransfer
/// @notice Safe ERC20 transfer library that gracefully handles missing return values.
/// @dev Credit to Solmate under MIT license: https://github.com/transmissions11/solmate/blob/ed67feda67b24fdeff8ad1032360f0ee6047ba0a/src/utils/SafeTransferLib.sol
/// @dev Please note that this library does not check if the token has a code! That responsibility is delegated to the caller.
library SafeTransfer {
/// @notice Transfers tokens to a recipient
/// @dev Calls transfer on token contract, errors with transferFailed() if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param amount The amount of the token to transfer
function safeTransfer(address token, address to, uint256 amount) internal {
bool success;
assembly {
let freeMemoryPointer := mload(0x40) // we will need to restore 0x40 slot
mstore(0x00, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // "transfer(address,uint256)" selector
mstore(0x04, and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // append cleaned "to" address
mstore(0x24, amount)
// now we use 0x00 - 0x44 bytes (68), freeMemoryPointer is dirty
success := call(gas(), token, 0, 0, 0x44, 0, 0x20)
success := and(
// set success to true if call isn't reverted and returned exactly 1 (can't just be non-zero data) or nothing
or(and(eq(mload(0), 1), eq(returndatasize(), 32)), iszero(returndatasize())),
success
)
mstore(0x40, freeMemoryPointer) // restore the freeMemoryPointer
}
if (!success) revert IV4PoolErrors.transferFailed();
}
}
/SafeCast.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
library SafeCast {
/// @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 uint256 to a uint128, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint128
function toUint128(uint256 y) internal pure returns (uint128 z) {
require((z = uint128(y)) == y);
}
/// @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 uint128 to a int128, revert on overflow
/// @param y The uint128 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(uint128 y) internal pure returns (int128 z) {
require((z = int128(y)) >= 0);
}
/// @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((z = int256(y)) >= 0);
}
}
/PriceMovementMath.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../interfaces/pool/IV4PoolErrors.sol';
import './FullMath.sol';
import './LowGasSafeMath.sol';
import './TokenDeltaMath.sol';
import './Constants.sol';
/// @title Computes the result of price movement
/// @notice Contains methods for computing the result of price movement within a single tick price range.
library PriceMovementMath {
using LowGasSafeMath for uint256;
using SafeCast for uint256;
/// @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 price The starting Q64.96 sqrt price, i.e., before accounting for the input amount
/// @param liquidity The amount of usable liquidity
/// @param input How much of token0, or token1, is being swapped in
/// @param zeroToOne Whether the amount in is token0 or token1
/// @return resultPrice The Q64.96 sqrt price after adding the input amount to token0 or token1
function getNewPriceAfterInput(uint160 price, uint128 liquidity, uint256 input, bool zeroToOne) internal pure returns (uint160 resultPrice) {
return getNewPrice(price, liquidity, input, zeroToOne, 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 price The starting Q64.96 sqrt price before accounting for the output amount
/// @param liquidity The amount of usable liquidity
/// @param output How much of token0, or token1, is being swapped out
/// @param zeroToOne Whether the amount out is token0 or token1
/// @return resultPrice The Q64.96 sqrt price after removing the output amount of token0 or token1
function getNewPriceAfterOutput(uint160 price, uint128 liquidity, uint256 output, bool zeroToOne) internal pure returns (uint160 resultPrice) {
return getNewPrice(price, liquidity, output, zeroToOne, false);
}
function getNewPrice(uint160 price, uint128 liquidity, uint256 amount, bool zeroToOne, bool fromInput) internal pure returns (uint160 resultPrice) {
unchecked {
require(price != 0);
require(liquidity != 0);
if (amount == 0) return price;
if (zeroToOne == fromInput) {
// rounding up or down
uint256 liquidityShifted = uint256(liquidity) << Constants.RESOLUTION;
if (fromInput) {
uint256 product;
if ((product = amount * price) / amount == price) {
uint256 denominator = liquidityShifted + product;
if (denominator >= liquidityShifted) return uint160(FullMath.mulDivRoundingUp(liquidityShifted, price, denominator)); // always fits in 160 bits
}
return uint160(FullMath.unsafeDivRoundingUp(liquidityShifted, (liquidityShifted / price).add(amount))); // denominator always > 0
} else {
uint256 product;
require((product = amount * price) / amount == price); // if the product overflows, we know the denominator underflows
require(liquidityShifted > product); // in addition, we must check that the denominator does not underflow
return FullMath.mulDivRoundingUp(liquidityShifted, price, liquidityShifted - product).toUint160();
}
} else {
// if we're adding (subtracting), rounding down requires rounding the quotient down (up)
// in both cases, avoid a mulDiv for most inputs
if (fromInput) {
return
uint256(price)
.add(amount <= type(uint160).max ? (amount << Constants.RESOLUTION) / liquidity : FullMath.mulDiv(amount, Constants.Q96, liquidity))
.toUint160();
} else {
uint256 quotient = amount <= type(uint160).max
? FullMath.unsafeDivRoundingUp(amount << Constants.RESOLUTION, liquidity) // denominator always > 0
: FullMath.mulDivRoundingUp(amount, Constants.Q96, liquidity);
require(price > quotient);
return uint160(price - quotient); // always fits 160 bits
}
}
}
}
function getInputTokenDelta01(uint160 to, uint160 from, uint128 liquidity) internal pure returns (uint256) {
return TokenDeltaMath.getToken0Delta(to, from, liquidity, true);
}
function getInputTokenDelta10(uint160 to, uint160 from, uint128 liquidity) internal pure returns (uint256) {
return TokenDeltaMath.getToken1Delta(from, to, liquidity, true);
}
function getOutputTokenDelta01(uint160 to, uint160 from, uint128 liquidity) internal pure returns (uint256) {
return TokenDeltaMath.getToken1Delta(to, from, liquidity, false);
}
function getOutputTokenDelta10(uint160 to, uint160 from, uint128 liquidity) internal pure returns (uint256) {
return TokenDeltaMath.getToken0Delta(from, to, liquidity, false);
}
/// @notice Computes the result of swapping some amount in, or amount out, given the parameters of the swap
/// @dev The fee, plus the amount in, will never exceed the amount remaining if the swap's `amountSpecified` is positive
/// @param zeroToOne The direction of price movement
/// @param currentPrice The current Q64.96 sqrt price of the pool
/// @param targetPrice The Q64.96 sqrt price that cannot be exceeded, from which the direction of the swap is inferred
/// @param liquidity The usable liquidity
/// @param amountAvailable How much input or output amount is remaining to be swapped in/out
/// @param fee The fee taken from the input amount, expressed in hundredths of a bip
/// @return resultPrice The Q64.96 sqrt price after swapping the amount in/out, not to exceed the price target
/// @return input The amount to be swapped in, of either token0 or token1, based on the direction of the swap
/// @return output The amount to be received, of either token0 or token1, based on the direction of the swap
/// @return feeAmount The amount of input that will be taken as a fee
function movePriceTowardsTarget(
bool zeroToOne,
uint160 currentPrice,
uint160 targetPrice,
uint128 liquidity,
int256 amountAvailable,
uint24 fee
) internal pure returns (uint160 resultPrice, uint256 input, uint256 output, uint256 feeAmount) {
unchecked {
function(uint160, uint160, uint128) pure returns (uint256) getInputTokenAmount = zeroToOne ? getInputTokenDelta01 : getInputTokenDelta10;
if (amountAvailable >= 0) {
// exactIn or not
uint256 amountAvailableAfterFee = FullMath.mulDiv(uint256(amountAvailable), Constants.FEE_DENOMINATOR - fee, Constants.FEE_DENOMINATOR);
input = getInputTokenAmount(targetPrice, currentPrice, liquidity);
if (amountAvailableAfterFee >= input) {
resultPrice = targetPrice;
feeAmount = FullMath.mulDivRoundingUp(input, fee, Constants.FEE_DENOMINATOR - fee);
} else {
resultPrice = getNewPriceAfterInput(currentPrice, liquidity, amountAvailableAfterFee, zeroToOne);
assert(targetPrice != resultPrice); // should always be true
input = getInputTokenAmount(resultPrice, currentPrice, liquidity);
// we didn't reach the target, so take the remainder of the maximum input as fee
feeAmount = uint256(amountAvailable) - input; // input <= amountAvailable due to used formulas. This invariant is checked by fuzzy tests
}
output = (zeroToOne ? getOutputTokenDelta01 : getOutputTokenDelta10)(resultPrice, currentPrice, liquidity);
} else {
function(uint160, uint160, uint128) pure returns (uint256) getOutputTokenAmount = zeroToOne ? getOutputTokenDelta01 : getOutputTokenDelta10;
output = getOutputTokenAmount(targetPrice, currentPrice, liquidity);
amountAvailable = -amountAvailable;
if (amountAvailable < 0) revert IV4PoolErrors.invalidAmountRequired(); // in case of type(int256).min
if (uint256(amountAvailable) >= output) resultPrice = targetPrice;
else {
resultPrice = getNewPriceAfterOutput(currentPrice, liquidity, uint256(amountAvailable), zeroToOne);
// should be always true if the price is in the allowed range
if (targetPrice != resultPrice) output = getOutputTokenAmount(resultPrice, currentPrice, liquidity);
// cap the output amount to not exceed the remaining output amount
if (output > uint256(amountAvailable)) output = uint256(amountAvailable);
}
input = getInputTokenAmount(resultPrice, currentPrice, liquidity);
feeAmount = FullMath.mulDivRoundingUp(input, fee, Constants.FEE_DENOMINATOR - fee);
}
}
}
}
/PoolHelpers.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IV4PoolErrors.sol';
import './Constants.sol';
/// @title Pool helpers
/// @notice Small helper utilities to keep core contracts readable
library PoolHelpers {
/// @notice Validates that a plugin fee is below the denominator
function validatePluginFee(uint24 pluginFee) internal pure {
if (pluginFee >= Constants.FEE_DENOMINATOR) revert IV4PoolErrors.incorrectPluginFee();
}
/// @notice Adds two fee parts and reverts if the sum exceeds or equals denominator
/// @return sum The resulting fee value
function addFeesOrRevert(uint24 a, uint24 b) internal pure returns (uint24 sum) {
unchecked {
sum = a + b;
}
if (sum >= Constants.FEE_DENOMINATOR) revert IV4PoolErrors.incorrectPluginFee();
}
}
/Plugins.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IV4PoolErrors.sol';
/// @title Contains logic and constants for interacting with the plugin through hooks
/// @dev Allows pool to check which hooks are enabled, as well as control the return selector
library Plugins {
function hasFlag(uint8 pluginConfig, uint256 flag) internal pure returns (bool res) {
assembly {
res := gt(and(pluginConfig, flag), 0)
}
}
function shouldReturn(bytes4 selector, bytes4 expectedSelector) internal pure {
if (selector != expectedSelector) revert IV4PoolErrors.invalidHookResponse(expectedSelector);
}
uint256 internal constant BEFORE_SWAP_FLAG = 1;
uint256 internal constant AFTER_SWAP_FLAG = 1 << 1;
uint256 internal constant BEFORE_POSITION_MODIFY_FLAG = 1 << 2;
uint256 internal constant AFTER_POSITION_MODIFY_FLAG = 1 << 3;
uint256 internal constant BEFORE_FLASH_FLAG = 1 << 4;
uint256 internal constant AFTER_FLASH_FLAG = 1 << 5;
uint256 internal constant AFTER_INIT_FLAG = 1 << 6;
uint256 internal constant DYNAMIC_FEE = 1 << 7;
}
/LowGasSafeMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.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
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
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) {
unchecked {
require((z = x - y) <= x == (y >= 0));
}
}
/// @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 add128(uint128 x, uint128 y) internal pure returns (uint128 z) {
unchecked {
require((z = x + y) >= x);
}
}
}
/LiquidityMath.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4 <0.9.0;
import '../interfaces/pool/IV4PoolErrors.sol';
import './TickMath.sol';
import './TokenDeltaMath.sol';
/// @title Math library for liquidity
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries
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) {
unchecked {
if (y < 0) {
if ((z = x - uint128(-y)) >= x) revert IV4PoolErrors.liquiditySub();
} else {
if ((z = x + uint128(y)) < x) revert IV4PoolErrors.liquidityAdd();
}
}
}
function getAmountsForLiquidity(
int24 bottomTick,
int24 topTick,
int128 liquidityDelta,
int24 currentTick,
uint160 currentPrice
) internal pure returns (uint256 amount0, uint256 amount1, int128 globalLiquidityDelta) {
uint160 priceAtBottomTick = TickMath.getSqrtRatioAtTick(bottomTick);
uint160 priceAtTopTick = TickMath.getSqrtRatioAtTick(topTick);
int256 amount0Int;
int256 amount1Int;
if (currentTick < bottomTick) {
// If current tick is less than the provided bottom one then only the token0 has to be provided
amount0Int = TokenDeltaMath.getToken0Delta(priceAtBottomTick, priceAtTopTick, liquidityDelta);
} else if (currentTick < topTick) {
amount0Int = TokenDeltaMath.getToken0Delta(currentPrice, priceAtTopTick, liquidityDelta);
amount1Int = TokenDeltaMath.getToken1Delta(priceAtBottomTick, currentPrice, liquidityDelta);
globalLiquidityDelta = liquidityDelta;
} else {
// If current tick is greater than the provided top one then only the token1 has to be provided
amount1Int = TokenDeltaMath.getToken1Delta(priceAtBottomTick, priceAtTopTick, liquidityDelta);
}
unchecked {
(amount0, amount1) = liquidityDelta < 0 ? (uint256(-amount0Int), uint256(-amount1Int)) : (uint256(amount0Int), uint256(amount1Int));
}
}
}
/FullMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^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) {
unchecked {
// 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 = a * b; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
assembly {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
// Subtract 256 bit remainder from 512 bit number
assembly {
let remainder := mulmod(a, b, denominator)
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 = (0 - 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 preconditions 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) {
unchecked {
if (a == 0 || ((result = a * b) / a == b)) {
require(denominator > 0);
assembly {
result := add(div(result, denominator), gt(mod(result, denominator), 0))
}
} else {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
}
/// @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 unsafeDivRoundingUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
/Constants.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0 <0.9.0;
/// @title Contains common constants for V4 contracts
/// @dev Constants moved to the library, not the base contract, to further emphasize their constant nature
library Constants {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 1 << 96;
uint256 internal constant Q128 = 1 << 128;
uint24 internal constant FEE_DENOMINATOR = 1e6;
uint16 internal constant FLASH_FEE = 0.01e4; // fee for flash loan in hundredths of a bip (0.01%)
uint16 internal constant INIT_DEFAULT_FEE = 0.05e4; // init default fee value in hundredths of a bip (0.05%)
uint16 internal constant MAX_DEFAULT_FEE = 5e4; // max default fee value in hundredths of a bip (5%)
int24 internal constant INIT_DEFAULT_TICK_SPACING = 5;
int24 internal constant MAX_TICK_SPACING = 500;
int24 internal constant MIN_TICK_SPACING = 1;
// the frequency with which the accumulated community fees are sent to the vault
uint32 internal constant FEE_TRANSFER_FREQUENCY = 8 hours;
// max(uint128) / (MAX_TICK - MIN_TICK)
uint128 internal constant MAX_LIQUIDITY_PER_TICK = 191757638537527648490752896198553;
uint16 internal constant MAX_COMMUNITY_FEE = 1e3; // 100%
uint256 internal constant COMMUNITY_FEE_DENOMINATOR = 1e3;
// role that can change settings in pools
bytes32 internal constant POOLS_ADMINISTRATOR_ROLE = keccak256('POOLS_ADMINISTRATOR');
}
/IV4VaultFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the V4 Vault Factory
/// @notice This contract can be used for automatic vaults creation
/// @dev Version: V4 Dex
interface IV4VaultFactory {
/// @notice Emitted when a vault is created for a pool
/// @param communityFeeVault The address of the community fee vault
/// @param pool The address of the V4 Dex pool
/// @param creator The address of the creator
/// @param deployer The address of the deployer
/// @param token0 The address of the first token
/// @param token1 The address of the second token
event VaultCreated(
address indexed communityFeeVault,
address indexed pool,
address indexed creator,
address deployer,
address token0,
address token1
);
/// @notice Emitted when the default v4 fee manager is changed
/// @param v4FeeManager The new default v4 fee manager
event DefaultV4FeeManager(address v4FeeManager);
/// @notice Thrown when a vault is already created for a pool
error vaultAlreadyExists();
/// @notice Thrown when an address input/configuration is invalid
error InvalidAddress();
/// @notice Thrown when caller lacks required administrator/factory permission
error OnlyAdministrator();
/// @notice returns address of the community fee vault for the pool
/// @param pool the address of V4 Dex pool
/// @return communityFeeVault the address of community fee vault
function getVaultForPool(address pool) external view returns (address communityFeeVault);
/// @notice creates the community fee vault for the pool if needed
/// @param pool the address of V4 Dex pool
/// @return communityFeeVault the address of community fee vault
function createVaultForPool(
address pool,
address creator,
address deployer,
address token0,
address token1
) external returns (address communityFeeVault);
/// @notice Sets default v4 fee manager applied to newly created community vaults
/// @param newV4FeeManager The default manager address (zero address clears explicit default)
function setDefaultV4FeeManager(address newV4FeeManager) external;
}
/IV4PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @dev Important security note: when using this data by external contracts, it is necessary to take into account the possibility
/// of manipulation (including read-only reentrancy).
/// This interface is based on the UniswapV3 interface, credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolState {
/// @notice Safely get most important state values of V4 Dex AMM
/// @dev Several values exposed as a single method to save gas when accessed externally.
/// **Important security note: this method checks reentrancy lock and should be preferred in most cases**.
/// @return sqrtPrice The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current global tick of the pool. May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return activeLiquidity The currently in-range liquidity available to the pool
/// @return nextTick The next initialized tick after current global tick
/// @return previousTick The previous initialized tick before (or at) current global tick
function safelyGetStateOfAMM()
external
view
returns (uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick);
/// @notice Allows to easily get current reentrancy lock status
/// @dev can be used to prevent read-only reentrancy.
/// This method just returns `globalState.unlocked` value
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function isUnlocked() external view returns (bool unlocked);
// ! IMPORTANT security note: the pool state can be manipulated.
// ! The following methods do not check reentrancy lock themselves.
/// @notice The globalState structure in the pool stores many values but requires only one slot
/// and is exposed as a single method to save gas when accessed externally.
/// @dev **important security note: caller should check `unlocked` flag to prevent read-only reentrancy**
/// @return price The current price of the pool as a sqrt(dToken1/dToken0) Q64.96 value
/// @return tick The current tick of the pool, i.e. according to the last tick transition that was run
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @return lastFee The current (last known) pool fee value in hundredths of a bip, i.e. 1e-6 (so '100' is '0.01%'). May be obsolete if using dynamic fee plugin
/// @return pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @return communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%)
/// @return unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
function globalState() external view returns (uint160 price, int24 tick, uint16 lastFee, uint8 pluginConfig, uint16 communityFee, bool unlocked);
/// @notice Look up information about a specific tick in the pool
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param tick The tick to look up
/// @return liquidityTotal The total amount of position liquidity that uses the pool either as tick lower or tick upper
/// @return liquidityDelta How much liquidity changes when the pool price crosses the tick
/// @return prevTick The previous tick in tick list
/// @return nextTick The next tick in tick list
/// @return outerFeeGrowth0Token The fee growth on the other side of the tick from the current tick in token0
/// @return outerFeeGrowth1Token The fee growth on the other side of the tick from the current tick in token1
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(
int24 tick
)
external
view
returns (
uint256 liquidityTotal,
int128 liquidityDelta,
int24 prevTick,
int24 nextTick,
uint256 outerFeeGrowth0Token,
uint256 outerFeeGrowth1Token
);
/// @notice The timestamp of the last sending of community fees to the vault
/// @return The timestamp truncated to 32 bits
function lastCommunityFeeTimestamp() external view returns (uint32);
/// @notice The timestamp of the last sending of plugin fees to the plugin
/// @return The timestamp truncated to 32 bits
function lastPluginFeeTimestamp() external view returns (uint32);
/// @notice The amounts of token0 and token1 that will be sent to the vault
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after lastCommunityFeeTimestamp
/// @return communityFeePending0 The amount of token0 that will be sent to the vault
/// @return communityFeePending1 The amount of token1 that will be sent to the vault
function getCommunityFeePending() external view returns (uint128 communityFeePending0, uint128 communityFeePending1);
/// @notice The amounts of token0 and token1 that will be sent to the plugin
/// @dev Will be sent FEE_TRANSFER_FREQUENCY after lastPluginFeeTimestamp
/// @return pluginFeePending0 The amount of token0 that will be sent to the plugin
/// @return pluginFeePending1 The amount of token1 that will be sent to the plugin
function getPluginFeePending() external view returns (uint128 pluginFeePending0, uint128 pluginFeePending1);
/// @notice Returns the address of currently used plugin
/// @dev The plugin is subject to change
/// @return pluginAddress The address of currently used plugin
function plugin() external view returns (address pluginAddress);
/// @notice The contract to which community fees are transferred
/// @return communityVaultAddress The communityVault address
function communityVault() external view returns (address communityVaultAddress);
/// @notice Returns 256 packed tick initialized boolean values. See TickTree for more information
/// @param wordPosition Index of 256-bits word with ticks
/// @return The 256-bits word with packed ticks info
function tickTable(int16 wordPosition) external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
/// @return The fee growth accumulator for token0
function totalFeeGrowth0Token() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
/// @return The fee growth accumulator for token1
function totalFeeGrowth1Token() external view returns (uint256);
/// @notice The current pool fee value
/// @dev In case dynamic fee is enabled in the pool, this method will call the plugin to get the current fee.
/// If the plugin implements complex fee logic, this method may return an incorrect value or revert.
/// In this case, see the plugin implementation and related documentation.
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return currentFee The current pool fee value in hundredths of a bip, i.e. 1e-6
function fee() external view returns (uint16 currentFee);
/// @notice The tracked token0 and token1 reserves of pool
/// @dev If at any time the real balance is larger, the excess will be transferred to liquidity providers as additional fee.
/// If the balance exceeds uint128, the excess will be sent to the communityVault.
/// @return reserve0 The last known reserve of token0
/// @return reserve1 The last known reserve of token1
function getReserves() external view returns (uint128 reserve0, uint128 reserve1);
/// @notice Returns the information about a position by the position's key
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @param key The position's key is a packed concatenation of the owner address, bottomTick and topTick indexes
/// @return liquidity The amount of liquidity in the position
/// @return innerFeeGrowth0Token Fee growth of token0 inside the tick range as of the last mint/burn/poke
/// @return innerFeeGrowth1Token Fee growth of token1 inside the tick range as of the last mint/burn/poke
/// @return fees0 The computed amount of token0 owed to the position as of the last mint/burn/poke
/// @return fees1 The computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(
bytes32 key
) external view returns (uint256 liquidity, uint256 innerFeeGrowth0Token, uint256 innerFeeGrowth1Token, uint128 fees0, uint128 fees1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks.
/// Returned value cannot exceed type(uint128).max
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The current in range liquidity
function liquidity() external view returns (uint128);
/// @notice The current tick spacing
/// @dev Ticks can only be initialized by new mints at multiples of this value
/// e.g.: a tickSpacing of 60 means ticks can be initialized every 60th tick, i.e., ..., -120, -60, 0, 60, 120, ...
/// However, tickspacing can be changed after the ticks have been initialized.
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The current tick spacing
function tickSpacing() external view returns (int24);
/// @notice The previous initialized tick before (or at) current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The previous initialized tick
function prevTickGlobal() external view returns (int24);
/// @notice The next initialized tick after current global tick
/// @dev **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The next initialized tick
function nextTickGlobal() external view returns (int24);
/// @notice The root of tick search tree
/// @dev Each bit corresponds to one node in the second layer of tick tree: '1' if node has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The root of tick search tree as bitmap
function tickTreeRoot() external view returns (uint32);
/// @notice The second layer of tick search tree
/// @dev Each bit in node corresponds to one node in the leafs layer (`tickTable`) of tick tree: '1' if leaf has at least one active bit.
/// **important security note: caller should check reentrancy lock to prevent read-only reentrancy**
/// @return The node of tick search tree second layer
function tickTreeSecondLayer(int16) external view returns (uint256);
}
/IV4PoolPermissionedActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by permissioned addresses
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolPermissionedActions {
/// @notice Set the community's % share of the fees. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newCommunityFee The new community fee percent in thousandths (1e-3)
function setCommunityFee(uint16 newCommunityFee) external;
/// @notice Set the new tick spacing values. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newTickSpacing The new tick spacing value
function setTickSpacing(int24 newTickSpacing) external;
/// @notice Set the new plugin address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newPluginAddress The new plugin address
function setPlugin(address newPluginAddress) external;
/// @notice Set new plugin config. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @param newConfig In the new configuration of the plugin,
/// each bit of which is responsible for a particular hook.
function setPluginConfig(uint8 newConfig) external;
/// @notice Set new community fee vault address. Only factory owner or POOLS_ADMINISTRATOR_ROLE role
/// @dev Community fee vault receives collected community fees.
/// **accumulated but not yet sent to the vault community fees once will be sent to the `newCommunityVault` address**
/// @param newCommunityVault The address of new community fee vault
function setCommunityVault(address newCommunityVault) external;
/// @notice Set new pool fee. Can be called by owner if dynamic fee is disabled.
/// Called by the plugin if dynamic fee is enabled
/// @param newFee The new fee value
function setFee(uint16 newFee) external;
/// @notice Forces balances to match reserves. Excessive tokens will be distributed between active LPs
/// @dev Only plugin can call this function
function sync() external;
/// @notice Forces balances to match reserves. Excessive tokens will be sent to msg.sender
/// @dev Only plugin can call this function
function skim() external;
}
/IV4PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolImmutables {
/// @notice The V4 factory contract, which must adhere to the IV4Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
/IV4PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swaps cannot be emitted by the pool before Initialize
/// @param price The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 price, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed bottomTick,
int24 indexed topTick,
uint128 liquidityAmount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @param owner The owner of the position for which fees are collected
/// @param recipient The address that received fees
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(address indexed owner, address recipient, int24 indexed bottomTick, int24 indexed topTick, uint128 amount0, uint128 amount1);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param liquidityAmount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(address indexed owner, int24 indexed bottomTick, int24 indexed topTick, uint128 liquidityAmount, uint256 amount0, uint256 amount1);
/// @notice Emitted when a plugin fee is applied during a burn
/// @param owner The owner of the position
/// @param pluginFee The fee to be sent to the plugin
event BurnFee(address indexed owner, uint24 pluginFee);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param price The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 price, uint128 liquidity, int24 tick);
/// @notice Emitted by the pool after any swaps
/// @param sender The address that initiated the swap
/// @param overrideFee The fee to be applied to the trade
/// @param pluginFee The fee to be sent to the plugin
event SwapFee(address indexed sender, uint24 overrideFee, uint24 pluginFee);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1);
/// @notice Emitted when the pool has higher balances than expected.
/// Any excess of tokens will be distributed between liquidity providers as fee.
/// @dev Fees after flash also will trigger this event due to mechanics of flash.
/// @param amount0 The excess of token0
/// @param amount1 The excess of token1
event ExcessTokens(uint256 amount0, uint256 amount1);
/// @notice Emitted when the community fee is changed by the pool
/// @param communityFeeNew The updated value of the community fee in thousandths (1e-3)
event CommunityFee(uint16 communityFeeNew);
/// @notice Emitted when the tick spacing changes
/// @param newTickSpacing The updated value of the new tick spacing
event TickSpacing(int24 newTickSpacing);
/// @notice Emitted when the plugin address changes
/// @param newPluginAddress New plugin address
event Plugin(address newPluginAddress);
/// @notice Emitted when the plugin config changes
/// @param newPluginConfig New plugin config
event PluginConfig(uint8 newPluginConfig);
/// @notice Emitted when the fee changes inside the pool
/// @param fee The current fee in hundredths of a bip, i.e. 1e-6
event Fee(uint16 fee);
/// @notice Emitted when the community vault address changes
/// @param newCommunityVault New community vault
event CommunityVault(address newCommunityVault);
/// @notice Emitted when the plugin does skim the excess of tokens
/// @param to THe receiver of tokens (plugin)
/// @param amount0 The amount of token0
/// @param amount1 The amount of token1
event Skim(address indexed to, uint256 amount0, uint256 amount1);
/// @notice Emitted when fees are transferred to a recipient (community vault or plugin)
/// @param recipient The address receiving fees (community vault or plugin)
/// @param amount0 The amount of token0 fees transferred
/// @param amount1 The amount of token1 fees transferred
event FeeTransferred(address indexed recipient, uint256 amount0, uint256 amount1);
}
/IV4PoolErrors.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
/// @title Errors emitted by a pool
/// @notice Contains custom errors emitted by the pool
/// @dev Custom errors are separated from the common pool interface for compatibility with older versions of Solidity
interface IV4PoolErrors {
// #### pool errors ####
/// @notice Emitted by the reentrancy guard
error locked();
/// @notice Emitted if arithmetic error occurred
error arithmeticError();
/// @notice Emitted if an attempt is made to initialize the pool twice
error alreadyInitialized();
/// @notice Emitted if an attempt is made to mint or swap in uninitialized pool
error notInitialized();
/// @notice Emitted if 0 is passed as amountRequired to swap function
error zeroAmountRequired();
/// @notice Emitted if invalid amount is passed as amountRequired to swap function
error invalidAmountRequired();
/// @notice Emitted if plugin fee param greater than fee/override fee
error incorrectPluginFee();
/// @notice Emitted if the pool received fewer tokens than it should have
error insufficientInputAmount();
/// @notice Emitted if there was an attempt to mint zero liquidity
error zeroLiquidityDesired();
/// @notice Emitted if actual amount of liquidity is zero (due to insufficient amount of tokens received)
error zeroLiquidityActual();
/// @notice Emitted if the pool received fewer tokens0 after flash than it should have
error flashInsufficientPaid0();
/// @notice Emitted if the pool received fewer tokens1 after flash than it should have
error flashInsufficientPaid1();
/// @notice Emitted if limitSqrtPrice param is incorrect
error invalidLimitSqrtPrice();
/// @notice Tick must be divisible by tickspacing
error tickIsNotSpaced();
/// @notice Emitted if a method is called that is accessible only to the factory owner or dedicated role
error notAllowed();
/// @notice Emitted if new tick spacing exceeds max allowed value
error invalidNewTickSpacing();
/// @notice Emitted if new community fee exceeds max allowed value
error invalidNewCommunityFee();
/// @notice Emitted if an attempt is made to manually change the fee value, but dynamic fee is enabled
error dynamicFeeActive();
/// @notice Emitted if an attempt is made by plugin to change the fee value, but dynamic fee is disabled
error dynamicFeeDisabled();
/// @notice Emitted if an attempt is made to change the plugin configuration, but the plugin is not connected
error pluginIsNotConnected();
/// @notice Emitted if an attempt is made to set plugin to zero while there are pending plugin fees
error pluginFeesPendingToCollect();
/// @notice Emitted if an attempt is made to set community vault to zero while there are pending community fees
error communityFeesPendingToCollect();
/// @notice Emitted if a plugin returns invalid selector after hook call
/// @param expectedSelector The expected selector
error invalidHookResponse(bytes4 expectedSelector);
// #### LiquidityMath errors ####
/// @notice Emitted if liquidity underflows
error liquiditySub();
/// @notice Emitted if liquidity overflows
error liquidityAdd();
// #### TickManagement errors ####
/// @notice Emitted if the topTick param not greater then the bottomTick param
error topTickLowerOrEqBottomTick();
/// @notice Emitted if the bottomTick param is lower than min allowed value
error bottomTickLowerThanMIN();
/// @notice Emitted if the topTick param is greater than max allowed value
error topTickAboveMAX();
/// @notice Emitted if the liquidity value associated with the tick exceeds MAX_LIQUIDITY_PER_TICK
error liquidityOverflow();
/// @notice Emitted if an attempt is made to interact with an uninitialized tick
error tickIsNotInitialized();
/// @notice Emitted if there is an attempt to insert a new tick into the list of ticks with incorrect indexes of the previous and next ticks
error tickInvalidLinks();
// #### SafeTransfer errors ####
/// @notice Emitted if token transfer failed internally
error transferFailed();
// #### TickMath errors ####
/// @notice Emitted if tick is greater than the maximum or less than the minimum allowed value
error tickOutOfRange();
/// @notice Emitted if price is greater than the maximum or less than the minimum allowed value
error priceOutOfRange();
}
/IV4PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @dev Initialization should be done in one transaction with pool creation to avoid front-running
/// @param initialPrice The initial sqrt price of the pool as a Q64.96
function initialize(uint160 initialPrice) external;
/// @notice Adds liquidity for the given recipient/bottomTick/topTick position
/// @dev The caller of this method receives a callback in the form of IV4MintCallback#v4MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on bottomTick, topTick, the amount of liquidity, and the current price.
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address for which the liquidity will be created
/// @param bottomTick The lower tick of the position in which to add liquidity
/// @param topTick The upper tick of the position in which to add liquidity
/// @param liquidityDesired The desired amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return liquidityActual The actual minted amount of liquidity
function mint(
address leftoversRecipient,
address recipient,
int24 bottomTick,
int24 topTick,
uint128 liquidityDesired,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1, uint128 liquidityActual);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param bottomTick The lower tick of the position for which to collect fees
/// @param topTick The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 bottomTick,
int24 topTick,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param bottomTick The lower tick of the position for which to burn liquidity
/// @param topTick The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @param data Any data that should be passed through to the plugin
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(int24 bottomTick, int24 topTick, uint128 amount, bytes calldata data) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IV4SwapCallback#v4SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Swap token0 for token1, or token1 for token0 with prepayment
/// @dev The caller of this method receives a callback in the form of IV4SwapCallback#v4SwapCallback
/// caller must send tokens in callback before swap calculation
/// the actually sent amount of tokens is used for further calculations
/// @param leftoversRecipient The address which will receive potential surplus of paid tokens
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountToSell The amount of the swap, only positive (exact input) amount allowed
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback. If using the Router it should contain SwapRouter#SwapCallbackData
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swapWithPaymentInAdvance(
address leftoversRecipient,
address recipient,
bool zeroToOne,
int256 amountToSell,
uint160 limitSqrtPrice,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IV4FlashCallback#v4FlashCallback
/// @dev All excess tokens paid in the callback are distributed to currently in-range liquidity providers as an additional fee.
/// If there are no in-range liquidity providers, the fee will be transferred to the first active provider in the future
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external;
}
/IV4PluginFactory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title An interface for a contract that is capable of deploying V4 plugins
/// @dev Such a factory can be used for automatic plugin creation for new pools.
/// Also a factory be used as an entry point for custom (additional) pools creation
interface IV4PluginFactory {
/// @notice Deploys new plugin contract for pool
/// @param pool The address of the new pool
/// @param creator The address that initiated the pool creation
/// @param deployer The plugin factory address (0 if not used)
/// @param token0 First token of the pool
/// @param token1 Second token of the pool
/// @return New plugin address
function beforeCreatePoolHook(
address pool,
address creator,
address deployer,
address token0,
address token1,
bytes calldata data
) external returns (address);
/// @notice Called after the pool is created
/// @param plugin The plugin address
/// @param pool The address of the new pool
/// @param deployer The plugin factory address (0 if not used)
function afterCreatePoolHook(address plugin, address pool, address deployer) external;
}
/IV4Plugin.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The V4 plugin interface
/// @dev The plugin will be called by the pool using hook methods depending on the current pool settings
interface IV4Plugin {
/// @notice Returns plugin config
/// @return config Each bit of the config is responsible for enabling/disabling the hooks.
/// The last bit indicates whether the plugin contains dynamic fees logic
function defaultPluginConfig() external view returns (uint8);
/// @notice Handle plugin fee transfer on plugin contract
/// @param pluginFee0 Fee0 amount transferred to plugin
/// @param pluginFee1 Fee1 amount transferred to plugin
/// @return bytes4 The function selector
function handlePluginFee(uint256 pluginFee0, uint256 pluginFee1) external returns (bytes4);
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, uint160 sqrtPriceX96, int24 tick) external returns (bytes4);
/// @notice The hook called before a position is modified
/// @param sender The initial msg.sender for the modify position call
/// @param recipient Address to which the liquidity will be assigned in case of a mint or
/// to which tokens will be sent in case of a burn
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param desiredLiquidityDelta The desired amount of liquidity to mint/burn
/// @param data Data that passed through the callback
/// @return selector The function selector for the hook
function beforeModifyPosition(
address sender,
address recipient,
int24 bottomTick,
int24 topTick,
int128 desiredLiquidityDelta,
bytes calldata data
) external returns (bytes4 selector, uint24 pluginFee);
/// @notice The hook called after a position is modified
/// @param sender The initial msg.sender for the modify position call
/// @param recipient Address to which the liquidity will be assigned in case of a mint or
/// to which tokens will be sent in case of a burn
/// @param bottomTick The lower tick of the position
/// @param topTick The upper tick of the position
/// @param desiredLiquidityDelta The desired amount of liquidity to mint/burn
/// @param amount0 The amount of token0 sent to the recipient or was paid to mint
/// @param amount1 The amount of token0 sent to the recipient or was paid to mint
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function afterModifyPosition(
address sender,
address recipient,
int24 bottomTick,
int24 topTick,
int128 desiredLiquidityDelta,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external returns (bytes4);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param withPaymentInAdvance The flag indicating whether the `swapWithPaymentInAdvance` method was called
/// @param data Data that passed through the callback
/// @return selector The function selector for the hook
function beforeSwap(
address sender,
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
bool withPaymentInAdvance,
bytes calldata data
) external returns (bytes4 selector, uint24 feeOverride, uint24 pluginFee);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param recipient The address to receive the output of the swap
/// @param zeroToOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountRequired The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param limitSqrtPrice The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @param amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function afterSwap(
address sender,
address recipient,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice,
int256 amount0,
int256 amount1,
bytes calldata data
) external returns (bytes4);
/// @notice The hook called before flash
/// @param sender The initial msg.sender for the flash call
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 being requested for flash
/// @param amount1 The amount of token1 being requested for flash
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function beforeFlash(address sender, address recipient, uint256 amount0, uint256 amount1, bytes calldata data) external returns (bytes4);
/// @notice The hook called after flash
/// @param sender The initial msg.sender for the flash call
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 being requested for flash
/// @param amount1 The amount of token1 being requested for flash
/// @param paid0 The amount of token0 being paid for flash
/// @param paid1 The amount of token1 being paid for flash
/// @param data Data that passed through the callback
/// @return bytes4 The function selector for the hook
function afterFlash(
address sender,
address recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1,
bytes calldata data
) external returns (bytes4);
}
/IV4DynamicFeePlugin.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the V4 plugin with dynamic fee logic
/// @dev A plugin with a dynamic fee must implement this interface so that the current base fee can be known through the pool
/// and amount-aware public fee quotes can be read directly from the plugin.
/// If the dynamic fee logic does not allow the fee to be calculated without additional data, the method should revert with the appropriate message
interface IV4DynamicFeePlugin {
/// @notice Returns fee from plugin
/// @return fee The pool fee value in hundredths of a bip, i.e. 1e-6
function getCurrentFee() external view returns (uint16 fee);
/// @notice Returns directional fee from plugin for a concrete swap amount
/// @return fee The pool fee value in hundredths of a bip, i.e. 1e-6
function getCurrentFeeDirectional(bool zeroToOne, int256 amountSpecified) external view returns (uint24 fee);
}
/IV4PoolDeployer.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title An interface for a contract that is capable of deploying V4 Pools
/// @notice A contract that constructs a pool must implement this to pass arguments to the pool
/// @dev This is used to avoid having constructor arguments in the pool contract, which results in the init code hash
/// of the pool being constant allowing the CREATE2 address of the pool to be cheaply computed on-chain.
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4PoolDeployer {
/// @notice Get the parameters to be used in constructing the pool, set transiently during pool creation.
/// @dev Called by the pool constructor to fetch the parameters of the pool
/// @return plugin The pool associated plugin (if any)
/// @return factory The V4 Factory address
/// @return token0 The first token of the pool by address sort order
/// @return token1 The second token of the pool by address sort order
function getDeployParameters() external view returns (address plugin, address factory, address token0, address token1);
/// @dev Deploys a pool with the given parameters by transiently setting the parameters in cache.
/// @param plugin The pool associated plugin (if any)
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @return pool The deployed pool's address
function deploy(address plugin, address token0, address token1, address deployer) external returns (address pool);
}
/IV4Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.4;
import './pool/IV4PoolImmutables.sol';
import './pool/IV4PoolState.sol';
import './pool/IV4PoolActions.sol';
import './pool/IV4PoolPermissionedActions.sol';
import './pool/IV4PoolEvents.sol';
import './pool/IV4PoolErrors.sol';
/// @title The interface for a V4 Pool
/// @dev The pool interface is broken up into many smaller pieces.
/// This interface includes custom error definitions and cannot be used in older versions of Solidity.
/// For older versions of Solidity use #IV4PoolLegacy
/// Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4Pool is IV4PoolImmutables, IV4PoolState, IV4PoolActions, IV4PoolPermissionedActions, IV4PoolEvents, IV4PoolErrors {
// used only for combining interfaces
}
/IV4Factory.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import './plugin/IV4PluginFactory.sol';
import './vault/IV4VaultFactory.sol';
/// @title The interface for the V4 Factory
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4Factory {
/// @notice Emitted when a process of ownership renounce is started
/// @param timestamp The timestamp of event
/// @param finishTimestamp The timestamp when ownership renounce will be possible to finish
event RenounceOwnershipStart(uint256 timestamp, uint256 finishTimestamp);
/// @notice Emitted when a process of ownership renounce cancelled
/// @param timestamp The timestamp of event
event RenounceOwnershipStop(uint256 timestamp);
/// @notice Emitted when a process of ownership renounce finished
/// @param timestamp The timestamp of ownership renouncement
event RenounceOwnershipFinish(uint256 timestamp);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event Pool(address indexed token0, address indexed token1, address pool);
/// @notice Emitted when a pool is created
/// @param deployer The corresponding custom deployer contract
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param pool The address of the created pool
event CustomPool(address indexed deployer, address indexed token0, address indexed token1, address pool);
/// @notice Emitted when the default community fee is changed
/// @param newDefaultCommunityFee The new default community fee value
event DefaultCommunityFee(uint16 newDefaultCommunityFee);
/// @notice Emitted when the default tickspacing is changed
/// @param newDefaultTickspacing The new default tickspacing value
event DefaultTickspacing(int24 newDefaultTickspacing);
/// @notice Emitted when the default fee is changed
/// @param newDefaultFee The new default fee value
event DefaultFee(uint16 newDefaultFee);
/// @notice Emitted when the defaultPluginFactory address is changed
/// @param defaultPluginFactoryAddress The new defaultPluginFactory address
event DefaultPluginFactory(address defaultPluginFactoryAddress);
/// @notice Emitted when the vaultFactory address is changed
/// @param newVaultFactory The new vaultFactory address
event VaultFactory(address newVaultFactory);
/// @notice role that can change communityFee and tickspacing in pools
/// @return The hash corresponding to this role
function POOLS_ADMINISTRATOR_ROLE() external view returns (bytes32);
/// @notice role that can call `createCustomPool` function
/// @return The hash corresponding to this role
function CUSTOM_POOL_DEPLOYER() external view returns (bytes32);
/// @notice Returns `true` if `account` has been granted `role` or `account` is owner.
/// @param role The hash corresponding to the role
/// @param account The address for which the role is checked
/// @return bool Whether the address has this role or the owner role or not
function hasRoleOrOwner(bytes32 role, address account) external view returns (bool);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via transferOwnership(address newOwner)
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the current poolDeployerAddress
/// @return The address of the poolDeployer
function poolDeployer() external view returns (address);
/// @notice Returns the default community fee
/// @return Fee which will be set at the creation of the pool
function defaultCommunityFee() external view returns (uint16);
/// @notice Returns the default fee
/// @return Fee which will be set at the creation of the pool
function defaultFee() external view returns (uint16);
/// @notice Returns the default tickspacing
/// @return Tickspacing which will be set at the creation of the pool
function defaultTickspacing() external view returns (int24);
/// @notice Return the current pluginFactory address
/// @dev This contract is used to automatically set a plugin address in new liquidity pools
/// @return V4 plugin factory
function defaultPluginFactory() external view returns (IV4PluginFactory);
/// @notice Return the current vaultFactory address
/// @dev This contract is used to automatically set a vault address in new liquidity pools
/// @return V4 vault factory
function vaultFactory() external view returns (IV4VaultFactory);
/// @notice Returns the default communityFee, tickspacing, fee and communityFeeVault for pool
/// @return communityFee which will be set at the creation of the pool
/// @return tickSpacing which will be set at the creation of the pool
/// @return fee which will be set at the creation of the pool
function defaultConfigurationForPool() external view returns (uint16 communityFee, int24 tickSpacing, uint16 fee);
/// @notice Deterministically computes the pool address given the token0 and token1
/// @dev The method does not check if such a pool has been created
/// @param token0 first token
/// @param token1 second token
/// @return pool The contract address of the V4 pool
function computePoolAddress(address token0, address token1) external view returns (address pool);
/// @notice Deterministically computes the custom pool address given the customDeployer, token0 and token1
/// @dev The method does not check if such a pool has been created
/// @param customDeployer the address of the custom plugin factory used to namespace pools
/// @param token0 first token
/// @param token1 second token
/// @return customPool The contract address of the V4 pool
function computeCustomPoolAddress(address customDeployer, address token0, address token1) external view returns (address customPool);
/// @notice Returns the pool address for a given pair of tokens, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return pool The pool address
function poolByPair(address tokenA, address tokenB) external view returns (address pool);
/// @notice Returns the custom pool address for a customDeployer and a given pair of tokens, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param customDeployer The custom plugin factory address used to namespace custom pools
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @return customPool The pool address
function customPoolByPair(address customDeployer, address tokenA, address tokenB) external view returns (address customPool);
/// @notice returns keccak256 of V4Pool init bytecode.
/// @dev the hash value changes with any change in the pool bytecode
/// @return Keccak256 hash of V4Pool contract init bytecode
function POOL_INIT_CODE_HASH() external view returns (bytes32);
/// @return timestamp The timestamp of the beginning of the renounceOwnership process
function renounceOwnershipStartTimestamp() external view returns (uint256 timestamp);
/// @notice Creates a pool for the given two tokens
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param data Data for plugin creation
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the pool already exists or the token arguments are invalid.
/// @return pool The address of the newly created pool
function createPool(address tokenA, address tokenB, bytes calldata data) external returns (address pool);
/// @notice Creates a custom pool for the given two tokens using `deployer` contract
/// @dev `msg.sender` is expected to be the plugin entry point (e.g. V4CustomPoolEntryPoint) that implements
/// IV4PluginFactory hooks. The `deployer` argument is forwarded to that entry point and used as the namespace
/// for deterministic pool address calculation and as the ultimate plugin factory address.
/// @param deployer The address of the custom plugin factory; used for namespacing and forwarded to hooks by the caller
/// @param creator The initiator of custom pool creation
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param data The additional data bytes
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0.
/// The call will revert if the pool already exists or the token arguments are invalid.
/// @return customPool The address of the newly created custom pool
function createCustomPool(
address deployer,
address creator,
address tokenA,
address tokenB,
bytes calldata data
) external returns (address customPool);
/// @dev updates default community fee for new pools
/// @param newDefaultCommunityFee The new community fee, _must_ be <= MAX_COMMUNITY_FEE
function setDefaultCommunityFee(uint16 newDefaultCommunityFee) external;
/// @dev updates default fee for new pools
/// @param newDefaultFee The new fee, _must_ be <= MAX_DEFAULT_FEE
function setDefaultFee(uint16 newDefaultFee) external;
/// @dev updates default tickspacing for new pools
/// @param newDefaultTickspacing The new tickspacing, _must_ be <= MAX_TICK_SPACING and >= MIN_TICK_SPACING
function setDefaultTickspacing(int24 newDefaultTickspacing) external;
/// @dev updates pluginFactory address
/// @param newDefaultPluginFactory address of new plugin factory
function setDefaultPluginFactory(address newDefaultPluginFactory) external;
/// @dev updates vaultFactory address
/// @param newVaultFactory address of new vault factory
function setVaultFactory(address newVaultFactory) external;
/// @notice Starts process of renounceOwnership. After that, a certain period
/// of time must pass before the ownership renounce can be completed.
function startRenounceOwnership() external;
/// @notice Stops process of renounceOwnership and removes timer.
function stopRenounceOwnership() external;
}
/IERC20Minimal.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Minimal ERC20 interface for V4
/// @notice Contains a subset of the full ERC20 interface that is used in V4
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
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);
}
/IV4SwapCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IV4PoolActions#swap
/// @notice Any contract that calls IV4PoolActions#swap must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IV4Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method _must_ be checked to be a V4Pool deployed by the canonical V4Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IV4PoolActions#swap call
function v4SwapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata data) external;
}
/IV4MintCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IV4PoolActions#mint
/// @notice Any contract that calls IV4PoolActions#mint must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IV4Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method _must_ be checked to be a V4Pool deployed by the canonical V4Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IV4PoolActions#mint call
function v4MintCallback(uint256 amount0Owed, uint256 amount1Owed, bytes calldata data) external;
}
/IV4FlashCallback.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IV4PoolActions#flash
/// @notice Any contract that calls IV4PoolActions#flash must implement this interface
/// @dev Credit to Uniswap Labs under GPL-2.0-or-later license:
/// https://github.com/Uniswap/v3-core/tree/main/contracts/interfaces
interface IV4FlashCallback {
/// @notice Called to `msg.sender` after transferring to the recipient from IV4Pool#flash.
/// @dev In the implementation you must repay the pool the tokens sent by flash plus the computed fee amounts.
/// The caller of this method _must_ be checked to be a V4Pool deployed by the canonical V4Factory.
/// @param fee0 The fee amount in token0 due to the pool by the end of the flash
/// @param fee1 The fee amount in token1 due to the pool by the end of the flash
/// @param data Any data passed through by the caller via the IV4PoolActions#flash call
function v4FlashCallback(uint256 fee0, uint256 fee1, bytes calldata data) external;
}
/V4PoolBase.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../interfaces/callback/IV4SwapCallback.sol';
import '../interfaces/callback/IV4MintCallback.sol';
import '../interfaces/callback/IV4FlashCallback.sol';
import '../interfaces/plugin/IV4DynamicFeePlugin.sol';
import '../interfaces/IV4Pool.sol';
import '../interfaces/IV4Factory.sol';
import '../interfaces/IV4PoolDeployer.sol';
import '../interfaces/IERC20Minimal.sol';
import '../libraries/TickManagement.sol';
import '../libraries/SafeTransfer.sol';
import '../libraries/Plugins.sol';
import '../interfaces/plugin/IV4Plugin.sol';
import '../libraries/PoolHelpers.sol';
import './common/Timestamp.sol';
/// @title V4 pool base abstract contract
/// @notice Contains state variables, immutables and common internal functions
/// @dev Decoupling into a separate abstract contract simplifies testing
abstract contract V4PoolBase is IV4Pool, Timestamp {
using TickManagement for mapping(int24 => TickManagement.Tick);
using Plugins for bytes4;
using Plugins for uint8;
/// @notice The struct with important state values of pool
/// @dev fits into one storage slot
/// @param price The square root of the current price in Q64.96 format
/// @param tick The current tick (price(tick) <= current price). May not always be equal to SqrtTickMath.getTickAtSqrtRatio(price) if the price is on a tick boundary
/// @param lastFee The current (last known) fee in hundredths of a bip, i.e. 1e-6 (so 100 is 0.01%). May be obsolete if using dynamic fee plugin
/// @param pluginConfig The current plugin config as bitmap. Each bit is responsible for enabling/disabling the hooks, the last bit turns on/off dynamic fees logic
/// @param communityFee The community fee represented as a percent of all collected fee in thousandths, i.e. 1e-3 (so 100 is 10%)
/// @param unlocked Reentrancy lock flag, true if the pool currently is unlocked, otherwise - false
struct GlobalState {
uint160 price;
int24 tick;
uint16 lastFee;
uint8 pluginConfig;
uint16 communityFee;
bool unlocked;
}
/// @inheritdoc IV4PoolImmutables
uint128 public constant override maxLiquidityPerTick = Constants.MAX_LIQUIDITY_PER_TICK;
/// @inheritdoc IV4PoolImmutables
address public immutable override factory;
/// @inheritdoc IV4PoolImmutables
address public immutable override token0;
/// @inheritdoc IV4PoolImmutables
address public immutable override token1;
// ! IMPORTANT security note: the pool state can be manipulated
// ! external contracts using this data must prevent read-only reentrancy
/// @inheritdoc IV4PoolState
uint256 public override totalFeeGrowth0Token;
/// @inheritdoc IV4PoolState
uint256 public override totalFeeGrowth1Token;
/// @inheritdoc IV4PoolState
GlobalState public override globalState;
/// @inheritdoc IV4PoolState
mapping(int24 => TickManagement.Tick) public override ticks;
/// @dev The amounts of token0 and token1 that will be sent to the vault
uint104 internal communityFeePending0;
uint104 internal communityFeePending1;
/// @inheritdoc IV4PoolState
uint32 public override lastCommunityFeeTimestamp;
uint104 internal pluginFeePending0;
uint104 internal pluginFeePending1;
/// @inheritdoc IV4PoolState
uint32 public override lastPluginFeeTimestamp;
/// @inheritdoc IV4PoolState
address public override plugin;
/// @inheritdoc IV4PoolState
address public override communityVault;
/// @inheritdoc IV4PoolState
mapping(int16 => uint256) public override tickTable;
/// @inheritdoc IV4PoolState
int24 public override nextTickGlobal;
/// @inheritdoc IV4PoolState
int24 public override prevTickGlobal;
/// @inheritdoc IV4PoolState
uint128 public override liquidity;
/// @inheritdoc IV4PoolState
int24 public override tickSpacing;
/// @notice Check that the lower and upper ticks do not violate the boundaries of allowed ticks and are specified in the correct order
modifier onlyValidTicks(int24 bottomTick, int24 topTick) {
TickManagement.checkTickRangeValidity(bottomTick, topTick);
_;
}
constructor() {
address _plugin;
(_plugin, factory, token0, token1) = _getDeployParameters();
(prevTickGlobal, nextTickGlobal) = (TickMath.MIN_TICK, TickMath.MAX_TICK);
globalState.unlocked = true;
if (_plugin != address(0)) {
_setPlugin(_plugin);
}
}
/// @inheritdoc IV4PoolState
/// @dev safe from read-only reentrancy getter function
function safelyGetStateOfAMM()
external
view
override
returns (uint160 sqrtPrice, int24 tick, uint16 lastFee, uint8 pluginConfig, uint128 activeLiquidity, int24 nextTick, int24 previousTick)
{
sqrtPrice = globalState.price;
tick = globalState.tick;
lastFee = globalState.lastFee;
pluginConfig = globalState.pluginConfig;
bool unlocked = globalState.unlocked;
if (!unlocked) revert IV4PoolErrors.locked();
activeLiquidity = liquidity;
nextTick = nextTickGlobal;
previousTick = prevTickGlobal;
}
/// @inheritdoc IV4PoolState
function isUnlocked() external view override returns (bool unlocked) {
return globalState.unlocked;
}
/// @inheritdoc IV4PoolState
function getCommunityFeePending() external view override returns (uint128, uint128) {
return (communityFeePending0, communityFeePending1);
}
function getPluginFeePending() external view override returns (uint128, uint128) {
return (pluginFeePending0, pluginFeePending1);
}
/// @dev Checks whether a specific plugin flag is enabled in the current config
function _hasPluginFlag(uint256 flag) internal view returns (bool) {
return Plugins.hasFlag(globalState.pluginConfig, flag);
}
/// @dev Checks whether msg.sender is the connected plugin
function _isPlugin() internal view returns (bool) {
return msg.sender == plugin;
}
/// @inheritdoc IV4PoolState
function fee() external view override returns (uint16 currentFee) {
currentFee = globalState.lastFee;
if (_hasPluginFlag(Plugins.DYNAMIC_FEE)) return IV4DynamicFeePlugin(plugin).getCurrentFee();
}
/// @dev Gets the parameter values for creating the pool. They are not passed in the constructor to make it easier to use create2 opcode
/// Can be overridden in tests
function _getDeployParameters() internal virtual returns (address, address, address, address) {
return IV4PoolDeployer(msg.sender).getDeployParameters();
}
/// @dev Gets the default settings for pool initialization. Can be overridden in tests
function _getDefaultConfiguration() internal virtual returns (uint16, int24, uint16) {
return IV4Factory(factory).defaultConfigurationForPool();
}
// The main external calls that are used by the pool. Can be overridden in tests
function _balanceToken0() internal view virtual returns (uint256) {
return IERC20Minimal(token0).balanceOf(address(this));
}
function _balanceToken1() internal view virtual returns (uint256) {
return IERC20Minimal(token1).balanceOf(address(this));
}
function _transfer(address token, address to, uint256 amount) internal virtual {
SafeTransfer.safeTransfer(token, to, amount);
}
// These 'callback' functions are wrappers over the callbacks that the pool calls on the msg.sender
// These methods can be overridden in tests
/// @dev Using function to save bytecode
function _swapCallback(int256 amount0, int256 amount1, bytes calldata data) internal virtual {
IV4SwapCallback(msg.sender).v4SwapCallback(amount0, amount1, data);
}
function _mintCallback(uint256 amount0, uint256 amount1, bytes calldata data) internal virtual {
IV4MintCallback(msg.sender).v4MintCallback(amount0, amount1, data);
}
function _flashCallback(uint256 fee0, uint256 fee1, bytes calldata data) internal virtual {
IV4FlashCallback(msg.sender).v4FlashCallback(fee0, fee1, data);
}
// This virtual function is implemented in TickStructure and used in Positions
/// @dev Add or remove a pair of ticks to the corresponding data structure
function _addOrRemoveTicks(int24 bottomTick, int24 topTick, bool toggleBottom, bool toggleTop, int24 currentTick, bool remove) internal virtual;
function _setCommunityFee(uint16 _communityFee) internal {
globalState.communityFee = _communityFee;
emit CommunityFee(_communityFee);
}
function _setCommunityFeeVault(address _communityFeeVault) internal {
communityVault = _communityFeeVault;
emit CommunityVault(_communityFeeVault);
}
function _setFee(uint16 _fee) internal {
globalState.lastFee = _fee;
emit Fee(_fee);
}
function _setTickSpacing(int24 _tickSpacing) internal {
tickSpacing = _tickSpacing;
emit TickSpacing(_tickSpacing);
}
function _setPlugin(address _plugin) internal {
plugin = _plugin;
emit Plugin(_plugin);
}
function _setPluginConfig(uint8 _pluginConfig) internal {
globalState.pluginConfig = _pluginConfig;
emit PluginConfig(_pluginConfig);
}
function _callBeforeInitialize(uint160 initialPrice) internal {
if (plugin == address(0)) return;
IV4Plugin(plugin).beforeInitialize(msg.sender, initialPrice).shouldReturn(IV4Plugin.beforeInitialize.selector);
}
function _callAfterInitialize(uint160 initialPrice, int24 tick) internal {
if (_hasPluginFlag(Plugins.AFTER_INIT_FLAG)) {
IV4Plugin(plugin).afterInitialize(msg.sender, initialPrice, tick).shouldReturn(IV4Plugin.afterInitialize.selector);
}
}
function _callBeforeModifyPosition(
address owner,
int24 bottomTick,
int24 topTick,
int128 liquidityDelta,
bytes calldata data
) internal returns (uint24 pluginFee) {
if (_hasPluginFlag(Plugins.BEFORE_POSITION_MODIFY_FLAG)) {
if (_isPlugin()) return 0;
bytes4 selector;
(selector, pluginFee) = IV4Plugin(plugin).beforeModifyPosition(msg.sender, owner, bottomTick, topTick, liquidityDelta, data);
PoolHelpers.validatePluginFee(pluginFee);
selector.shouldReturn(IV4Plugin.beforeModifyPosition.selector);
}
}
function _callAfterModifyPosition(
address owner,
int24 bTick,
int24 tTick,
int128 deltaL,
uint256 amount0,
uint256 amount1,
bytes calldata data
) internal {
if (_isPlugin()) return;
if (_hasPluginFlag(Plugins.AFTER_POSITION_MODIFY_FLAG)) {
IV4Plugin(plugin).afterModifyPosition(msg.sender, owner, bTick, tTick, deltaL, amount0, amount1, data).shouldReturn(
IV4Plugin.afterModifyPosition.selector
);
}
}
function _callBeforeSwap(
address recipient,
bool zto,
int256 amount,
uint160 limitPrice,
bool payInAdvance,
bytes calldata data
) internal returns (uint24 overrideFee, uint24 pluginFee) {
uint8 pluginConfig = globalState.pluginConfig;
if (pluginConfig.hasFlag(Plugins.BEFORE_SWAP_FLAG)) {
if (_isPlugin()) return (0, 0);
bytes4 selector;
(selector, overrideFee, pluginFee) = IV4Plugin(plugin).beforeSwap(msg.sender, recipient, zto, amount, limitPrice, payInAdvance, data);
if (!pluginConfig.hasFlag(Plugins.DYNAMIC_FEE) && (overrideFee > 0 || pluginFee > 0)) revert IV4PoolErrors.dynamicFeeDisabled();
// we will check that fee is less than denominator inside the swap calculation
selector.shouldReturn(IV4Plugin.beforeSwap.selector);
}
}
function _callAfterSwap(
address recipient,
bool zto,
int256 amount,
uint160 limitPrice,
int256 amount0,
int256 amount1,
bytes calldata data
) internal {
if (_hasPluginFlag(Plugins.AFTER_SWAP_FLAG)) {
if (_isPlugin()) return;
IV4Plugin(plugin).afterSwap(msg.sender, recipient, zto, amount, limitPrice, amount0, amount1, data).shouldReturn(IV4Plugin.afterSwap.selector);
}
}
function _callBeforeFlash(address recipient, uint256 amount0, uint256 amount1, bytes calldata data) internal {
if (_hasPluginFlag(Plugins.BEFORE_FLASH_FLAG)) {
IV4Plugin(plugin).beforeFlash(msg.sender, recipient, amount0, amount1, data).shouldReturn(IV4Plugin.beforeFlash.selector);
}
}
function _callAfterFlash(address recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1, bytes calldata data) internal {
if (_hasPluginFlag(Plugins.AFTER_FLASH_FLAG)) {
IV4Plugin(plugin).afterFlash(msg.sender, recipient, amount0, amount1, paid0, paid1, data).shouldReturn(IV4Plugin.afterFlash.selector);
}
}
}
/TickStructure.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../libraries/TickManagement.sol';
import '../libraries/TickTree.sol';
import './V4PoolBase.sol';
/// @title V4 tick structure abstract contract
/// @notice Encapsulates the logic of interaction with the data structure with ticks
/// @dev Ticks are stored as a doubly linked list. A three-level bitmap tree is used to search through the list
abstract contract TickStructure is V4PoolBase {
using TickManagement for mapping(int24 => TickManagement.Tick);
using TickTree for mapping(int16 => uint256);
/// @inheritdoc IV4PoolState
uint32 public override tickTreeRoot; // The root bitmap of search tree
/// @inheritdoc IV4PoolState
mapping(int16 => uint256) public override tickTreeSecondLayer; // The second layer of search tree
// the leaves of the tree are stored in `tickTable`
constructor() {
ticks.initTickState();
}
/// @notice Used to add or remove a tick from a doubly linked list and search tree
/// @param tick The tick being removed or added now
/// @param currentTick The current global tick in the pool
/// @param oldTickTreeRoot The current tick tree root
/// @param prevInitializedTick Previous active tick before `currentTick`
/// @param nextInitializedTick Next active tick after `currentTick`
/// @param remove Remove or add the tick
/// @return New previous active tick before `currentTick` if changed
/// @return New next active tick after `currentTick` if changed
/// @return New tick tree root if changed
function _addOrRemoveTick(
int24 tick,
int24 currentTick,
uint32 oldTickTreeRoot,
int24 prevInitializedTick,
int24 nextInitializedTick,
bool remove
) internal returns (int24, int24, uint32) {
if (remove) {
(int24 prevTick, int24 nextTick) = ticks.removeTick(tick);
if (prevInitializedTick == tick) prevInitializedTick = prevTick;
else if (nextInitializedTick == tick) nextInitializedTick = nextTick;
} else {
int24 prevTick;
int24 nextTick;
if (prevInitializedTick < tick && nextInitializedTick > tick) {
(prevTick, nextTick) = (prevInitializedTick, nextInitializedTick); // we know next and prev ticks
if (tick > currentTick) nextInitializedTick = tick;
else prevInitializedTick = tick;
} else {
nextTick = tickTable.getNextTick(tickTreeSecondLayer, oldTickTreeRoot, tick);
prevTick = ticks[nextTick].prevTick;
}
ticks.insertTick(tick, prevTick, nextTick);
}
uint32 newTickTreeRoot = tickTable.toggleTick(tickTreeSecondLayer, oldTickTreeRoot, tick);
return (prevInitializedTick, nextInitializedTick, newTickTreeRoot);
}
/// @notice Used to add or remove a pair of ticks from a doubly linked list and search tree
/// @param bottomTick The bottom tick being removed or added now
/// @param topTick The top tick being removed or added now
/// @param toggleBottom Should bottom tick be changed or not
/// @param toggleTop Should top tick be changed or not
/// @param currentTick The current global tick in the pool
/// @param remove Remove or add the ticks
function _addOrRemoveTicks(int24 bottomTick, int24 topTick, bool toggleBottom, bool toggleTop, int24 currentTick, bool remove) internal override {
(int24 prevInitializedTick, int24 nextInitializedTick, uint32 oldTickTreeRoot) = (prevTickGlobal, nextTickGlobal, tickTreeRoot);
(int24 newPrevTick, int24 newNextTick, uint32 newTreeRoot) = (prevInitializedTick, nextInitializedTick, oldTickTreeRoot);
if (toggleBottom) {
(newPrevTick, newNextTick, newTreeRoot) = _addOrRemoveTick(bottomTick, currentTick, newTreeRoot, newPrevTick, newNextTick, remove);
}
if (toggleTop) {
(newPrevTick, newNextTick, newTreeRoot) = _addOrRemoveTick(topTick, currentTick, newTreeRoot, newPrevTick, newNextTick, remove);
}
if (prevInitializedTick != newPrevTick || nextInitializedTick != newNextTick || newTreeRoot != oldTickTreeRoot) {
(prevTickGlobal, nextTickGlobal, tickTreeRoot) = (newPrevTick, newNextTick, newTreeRoot);
}
}
}
/SwapCalculation.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../libraries/PriceMovementMath.sol';
import '../libraries/LowGasSafeMath.sol';
import '../libraries/SafeCast.sol';
import './V4PoolBase.sol';
/// @title V4 swap calculation abstract contract
/// @notice Contains _calculateSwap encapsulating internal logic of swaps
abstract contract SwapCalculation is V4PoolBase {
using TickManagement for mapping(int24 => TickManagement.Tick);
using SafeCast for uint256;
using LowGasSafeMath for uint256;
using LowGasSafeMath for int256;
struct SwapCalculationCache {
uint256 communityFee; // The community fee of the selling token, uint256 to minimize casts
bool crossedAnyTick; // If we have already crossed at least one active tick
int256 amountRequiredInitial; // The initial value of the exact input\output amount
int256 amountCalculated; // The additive amount of total output\input calculated through the swap
uint256 totalFeeGrowthInput; // The initial totalFeeGrowth + the fee growth during a swap
uint256 totalFeeGrowthOutput; // The initial totalFeeGrowth for output token, should not change during swap
bool exactInput; // Whether the exact input or output is specified
uint24 fee; // The current fee value in hundredths of a bip, i.e. 1e-6
int24 prevInitializedTick; // The previous initialized tick in linked list
int24 nextInitializedTick; // The next initialized tick in linked list
uint24 pluginFee;
}
struct PriceMovementCache {
uint256 stepSqrtPrice; // The Q64.96 sqrt of the price at the start of the step, uint256 to minimize casts
uint256 nextTickPrice; // The Q64.96 sqrt of the price calculated from the _nextTick_, uint256 to minimize casts
uint256 input; // The additive amount of tokens that have been provided
uint256 output; // The additive amount of token that have been withdrawn
uint256 feeAmount; // The total amount of fee earned within a current step
}
struct FeesAmount {
uint256 communityFeeAmount;
uint256 pluginFeeAmount;
}
function _calculateSwap(
uint24 overrideFee,
uint24 pluginFee,
bool zeroToOne,
int256 amountRequired,
uint160 limitSqrtPrice
) internal returns (int256 amount0, int256 amount1, uint160 currentPrice, int24 currentTick, uint128 currentLiquidity, FeesAmount memory fees) {
if (amountRequired == 0) revert zeroAmountRequired();
if (amountRequired == type(int256).min) revert invalidAmountRequired(); // to avoid problems when changing sign
SwapCalculationCache memory cache;
(cache.amountRequiredInitial, cache.exactInput, cache.pluginFee) = (amountRequired, amountRequired > 0, pluginFee);
// load from one storage slot
(currentLiquidity, cache.prevInitializedTick, cache.nextInitializedTick) = (liquidity, prevTickGlobal, nextTickGlobal);
// load from one storage slot too
(currentPrice, currentTick, cache.fee, cache.communityFee) = (globalState.price, globalState.tick, globalState.lastFee, globalState.communityFee);
if (currentPrice == 0) revert notInitialized();
if (overrideFee != 0) {
cache.fee = overrideFee + pluginFee;
if (cache.fee >= 1e6) revert incorrectPluginFee();
} else {
if (pluginFee != 0) {
cache.fee += pluginFee;
if (cache.fee >= 1e6) revert incorrectPluginFee();
}
}
if (zeroToOne) {
if (limitSqrtPrice >= currentPrice || limitSqrtPrice <= TickMath.MIN_SQRT_RATIO) revert invalidLimitSqrtPrice();
cache.totalFeeGrowthInput = totalFeeGrowth0Token;
} else {
if (limitSqrtPrice <= currentPrice || limitSqrtPrice >= TickMath.MAX_SQRT_RATIO) revert invalidLimitSqrtPrice();
cache.totalFeeGrowthInput = totalFeeGrowth1Token;
}
PriceMovementCache memory step;
unchecked {
// swap until there is remaining input or output tokens or we reach the price limit
do {
int24 nextTick = zeroToOne ? cache.prevInitializedTick : cache.nextInitializedTick;
step.stepSqrtPrice = currentPrice;
step.nextTickPrice = TickMath.getSqrtRatioAtTick(nextTick);
(currentPrice, step.input, step.output, step.feeAmount) = PriceMovementMath.movePriceTowardsTarget(
zeroToOne, // if zeroToOne then the price is moving down
currentPrice,
(zeroToOne == (step.nextTickPrice < limitSqrtPrice)) // move the price to the nearest of the next tick and the limit price
? limitSqrtPrice
: uint160(step.nextTickPrice), // cast is safe
currentLiquidity,
amountRequired,
cache.fee
);
if (cache.exactInput) {
amountRequired -= (step.input + step.feeAmount).toInt256(); // decrease remaining input amount
cache.amountCalculated = cache.amountCalculated.sub(step.output.toInt256()); // decrease calculated output amount
} else {
amountRequired += step.output.toInt256(); // increase remaining output amount (since its negative)
cache.amountCalculated = cache.amountCalculated.add((step.input + step.feeAmount).toInt256()); // increase calculated input amount
}
if (cache.communityFee > 0) {
uint256 delta = (step.feeAmount.mul(cache.communityFee)) / Constants.COMMUNITY_FEE_DENOMINATOR;
step.feeAmount -= delta;
fees.communityFeeAmount += delta;
}
if (cache.pluginFee > 0 && cache.fee > 0) {
uint256 delta = FullMath.mulDiv(step.feeAmount, cache.pluginFee, cache.fee);
step.feeAmount -= delta;
fees.pluginFeeAmount += delta;
}
if (currentLiquidity > 0) cache.totalFeeGrowthInput += FullMath.mulDiv(step.feeAmount, Constants.Q128, currentLiquidity);
// min or max tick can not be crossed due to limitSqrtPrice check
if (currentPrice == step.nextTickPrice) {
// crossing tick
if (!cache.crossedAnyTick) {
cache.crossedAnyTick = true;
cache.totalFeeGrowthOutput = zeroToOne ? totalFeeGrowth1Token : totalFeeGrowth0Token;
}
int128 liquidityDelta;
if (zeroToOne) {
// F-02: When crossing down, new currentTick = crossedTick - 1 to maintain bottomTick <= currentTick < topTick
(liquidityDelta, cache.prevInitializedTick, ) = ticks.cross(nextTick, cache.totalFeeGrowthInput, cache.totalFeeGrowthOutput);
liquidityDelta = -liquidityDelta;
(currentTick, cache.nextInitializedTick) = (nextTick - 1, nextTick);
} else {
// F-02: When crossing up, new currentTick = crossedTick to maintain bottomTick <= currentTick < topTick
(liquidityDelta, , cache.nextInitializedTick) = ticks.cross(nextTick, cache.totalFeeGrowthOutput, cache.totalFeeGrowthInput);
(currentTick, cache.prevInitializedTick) = (nextTick, nextTick);
}
currentLiquidity = LiquidityMath.addDelta(currentLiquidity, liquidityDelta);
} else if (currentPrice != step.stepSqrtPrice) {
currentTick = TickMath.getTickAtSqrtRatio(currentPrice); // the price has changed but hasn't reached the target
break; // since the price hasn't reached the target, amountRequired should be 0
}
} while (amountRequired != 0 && currentPrice != limitSqrtPrice); // check stop condition
int256 amountSpent = cache.amountRequiredInitial - amountRequired; // spent amount could be less than initially specified (e.g. reached limit)
(amount0, amount1) = zeroToOne == cache.exactInput ? (amountSpent, cache.amountCalculated) : (cache.amountCalculated, amountSpent);
}
(globalState.price, globalState.tick) = (currentPrice, currentTick);
if (cache.crossedAnyTick) {
(liquidity, prevTickGlobal, nextTickGlobal) = (currentLiquidity, cache.prevInitializedTick, cache.nextInitializedTick);
}
if (zeroToOne) {
totalFeeGrowth0Token = cache.totalFeeGrowthInput;
} else {
totalFeeGrowth1Token = cache.totalFeeGrowthInput;
}
}
}
/ReservesManager.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../libraries/SafeCast.sol';
import '../libraries/Plugins.sol';
import './V4PoolBase.sol';
import '../interfaces/plugin/IV4Plugin.sol';
import '../interfaces/pool/IV4PoolErrors.sol';
/// @title V4 reserves management abstract contract
/// @notice Encapsulates logic for tracking and changing pool reserves
/// @dev The reserve mechanism allows the pool to keep track of unexpected increases in balances
abstract contract ReservesManager is V4PoolBase {
using Plugins for bytes4;
using SafeCast for uint256;
/// @dev The tracked token0 and token1 reserves of pool
uint128 internal reserve0;
uint128 internal reserve1;
/// @inheritdoc IV4PoolState
function getReserves() external view returns (uint128, uint128) {
return (reserve0, reserve1);
}
/// @dev updates reserves data and distributes excess in the form of fee to liquidity providers.
/// If any of the balances is greater than uint128, the excess is sent to the communityVault
function _updateReserves() internal returns (uint256 balance0, uint256 balance1) {
(balance0, balance1) = (_balanceToken0(), _balanceToken1());
// we do not support tokens with totalSupply > type(uint128).max, so any excess will be sent to communityVault
// this situation can only occur if the tokens are sent directly to the pool from outside
// **such excessive tokens will be burned if there is no communityVault connected**
if (balance0 > type(uint128).max || balance1 > type(uint128).max) {
unchecked {
address _communityVault = communityVault;
if (balance0 > type(uint128).max) {
_transfer(token0, _communityVault, balance0 - type(uint128).max);
balance0 = type(uint128).max;
}
if (balance1 > type(uint128).max) {
_transfer(token1, _communityVault, balance1 - type(uint128).max);
balance1 = type(uint128).max;
}
}
}
uint128 _liquidity = liquidity;
if (_liquidity == 0) return (balance0, balance1);
(uint128 _reserve0, uint128 _reserve1) = (reserve0, reserve1);
(bool hasExcessToken0, bool hasExcessToken1) = (balance0 > _reserve0, balance1 > _reserve1);
if (hasExcessToken0 || hasExcessToken1) {
unchecked {
if (hasExcessToken0) totalFeeGrowth0Token += FullMath.mulDiv(balance0 - _reserve0, Constants.Q128, _liquidity);
if (hasExcessToken1) totalFeeGrowth1Token += FullMath.mulDiv(balance1 - _reserve1, Constants.Q128, _liquidity);
emit ExcessTokens(hasExcessToken0 ? balance0 - _reserve0 : 0, hasExcessToken1 ? balance1 - _reserve1 : 0);
(reserve0, reserve1) = (uint128(balance0), uint128(balance1));
}
}
}
/// @notice Forces reserves to match balances. Excess of tokens will be sent to `receiver`
function _skimReserves(address receiver) internal {
(uint256 balance0, uint256 balance1) = (_balanceToken0(), _balanceToken1());
(uint128 _reserve0, uint128 _reserve1) = (reserve0, reserve1);
if (balance0 > _reserve0 || balance1 > _reserve1) {
if (balance0 > _reserve0) _transfer(token0, receiver, balance0 - _reserve0);
if (balance1 > _reserve1) _transfer(token1, receiver, balance1 - _reserve1);
emit Skim(receiver, balance0 - _reserve0, balance1 - _reserve1);
}
}
/// @notice Accrues fees and transfers them to `recipient`
/// @dev If we transfer fees, writes zeros to the storage slot specified by the slot argument
/// If we do not transfer fees, returns actual pendingFees
function _accrueAndTransferFees(
uint256 fee0,
uint256 fee1,
uint256 lastTimestamp,
bytes32 receiverSlot,
bytes32 feePendingSlot
) internal returns (uint104, uint104, uint256, uint256) {
if (fee0 | fee1 != 0) {
uint256 feePending0;
uint256 feePending1;
assembly {
// Load the storage slot specified by the slot argument
let sl := sload(feePendingSlot)
// Extract the uint104 value
feePending0 := and(sl, 0xFFFFFFFFFFFFFFFFFFFFFFFFFF)
// Shift right by 104 bits and extract the uint104 value
feePending1 := and(shr(104, sl), 0xFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
feePending0 += fee0;
feePending1 += fee1;
if (
_blockTimestamp() - lastTimestamp >= Constants.FEE_TRANSFER_FREQUENCY || feePending0 > type(uint104).max || feePending1 > type(uint104).max
) {
// use sload from slot (like pointer dereference) to avoid gas
address recipient;
assembly {
recipient := sload(receiverSlot)
}
(uint256 feeSent0, uint256 feeSent1) = _transferFees(feePending0, feePending1, recipient);
// use sload from slot (like pointer dereference) to avoid gas
// override feePendingSlot with zeros is OK
// caller will update relevant timestamp
assembly {
sstore(feePendingSlot, 0)
}
// sent fees return 0 pending and sent fees
return (0, 0, feeSent0, feeSent1);
} else {
// didn't send fees return pending fees and 0 sent
return (uint104(feePending0), uint104(feePending1), 0, 0);
}
} else {
if (_blockTimestamp() - lastTimestamp >= Constants.FEE_TRANSFER_FREQUENCY) {
uint256 feePending0;
uint256 feePending1;
assembly {
// Load the storage slot specified by the slot argument
let sl := sload(feePendingSlot)
// Extract the uint104 value
feePending0 := and(sl, 0xFFFFFFFFFFFFFFFFFFFFFFFFFF)
// Shift right by 104 bits and extract the uint104 value
feePending1 := and(shr(104, sl), 0xFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
if (feePending0 | feePending1 != 0) {
address recipient;
// use sload from slot (like pointer dereference) to avoid gas
assembly {
recipient := sload(receiverSlot)
}
(uint256 feeSent0, uint256 feeSent1) = _transferFees(feePending0, feePending1, recipient);
// use sload from slot (like pointer dereference) to avoid gas
assembly {
sstore(feePendingSlot, 0)
}
// sent fees return 0 pending and sent fees
return (0, 0, feeSent0, feeSent1);
}
}
// didn't either sent fees or increased pending
return (0, 0, 0, 0);
}
}
function _transferFees(uint256 feePending0, uint256 feePending1, address feesRecipient) private returns (uint256, uint256) {
if (feePending0 > 0) _transfer(token0, feesRecipient, feePending0);
if (feePending1 > 0) _transfer(token1, feesRecipient, feePending1);
if (feePending0 | feePending1 != 0) emit FeeTransferred(feesRecipient, feePending0, feePending1);
return (feePending0, feePending1);
}
function _processFees(
uint256 fee0,
uint256 fee1,
uint256 lastTimestamp,
bytes32 feePendingSlot,
bytes32 feeRecipientSlot,
uint32 ts,
bool isPlugin
) private returns (uint256 sent0, uint256 sent1) {
uint104 feePending0;
uint104 feePending1;
(feePending0, feePending1, sent0, sent1) = _accrueAndTransferFees(fee0, fee1, lastTimestamp, feeRecipientSlot, feePendingSlot);
if (sent0 | sent1 != 0) {
if (isPlugin) {
lastPluginFeeTimestamp = ts;
IV4Plugin(plugin).handlePluginFee(sent0, sent1).shouldReturn(IV4Plugin.handlePluginFee.selector);
} else {
lastCommunityFeeTimestamp = ts;
}
} else if (feePending0 | feePending1 != 0) {
if (isPlugin) (pluginFeePending0, pluginFeePending1) = (feePending0, feePending1);
else (communityFeePending0, communityFeePending1) = (feePending0, feePending1);
}
}
/// @notice Flushes pending plugin fees to the specified recipient plugin
/// @dev Must be called before changing the plugin address to ensure fees go to the correct plugin
/// @param pluginAddress The plugin address to send fees to and notify
function _flushPluginFees(address pluginAddress) internal {
uint256 feePending0 = pluginFeePending0;
uint256 feePending1 = pluginFeePending1;
if (feePending0 | feePending1 == 0) return; // no pending fees to flush
// Reset pending fees and timestamp atomically via assembly
// This zeros pending fees and sets timestamp in one sstore
uint32 ts = _blockTimestamp();
assembly {
sstore(pluginFeePending0.slot, shl(208, ts))
}
// Transfer fees to the plugin
(uint256 feeSent0, uint256 feeSent1) = _transferFees(feePending0, feePending1, pluginAddress);
// Update reserves to reflect the transfer
unchecked {
(reserve0, reserve1) = (uint128(reserve0 - feeSent0), uint128(reserve1 - feeSent1));
}
// Notify the plugin about the transferred fees
IV4Plugin(pluginAddress).handlePluginFee(feeSent0, feeSent1).shouldReturn(IV4Plugin.handlePluginFee.selector);
}
/// @notice Applies deltas to reserves and pays communityFees
/// @dev Community fee is sent to the vault at a specified frequency or when variables communityFeePending{0,1} overflow
/// @param deltaR0 Amount of token0 to add/subtract to/from reserve0, must not exceed uint128
/// @param deltaR1 Amount of token1 to add/subtract to/from reserve1, must not exceed uint128
/// @param communityFee0 Amount of token0 to pay as communityFee, must not exceed uint128
/// @param communityFee1 Amount of token1 to pay as communityFee, must not exceed uint128
function _changeReserves(
int256 deltaR0,
int256 deltaR1,
uint256 communityFee0,
uint256 communityFee1,
uint256 pluginFee0,
uint256 pluginFee1
) internal {
if (communityFee0 > 0 || communityFee1 > 0 || pluginFee0 > 0 || pluginFee1 > 0) {
bytes32 feePendingSlot;
bytes32 feeRecipientSlot;
uint256 feeSent0;
uint256 feeSent1;
uint32 ts = _blockTimestamp();
// Process community fees with its own timestamp
assembly {
feePendingSlot := communityFeePending0.slot
feeRecipientSlot := communityVault.slot
}
(feeSent0, feeSent1) = _processFees(communityFee0, communityFee1, lastCommunityFeeTimestamp, feePendingSlot, feeRecipientSlot, ts, false);
if (feeSent0 | feeSent1 != 0) (deltaR0, deltaR1) = (deltaR0 - feeSent0.toInt256(), deltaR1 - feeSent1.toInt256());
// Process plugin fees with its own timestamp
assembly {
feePendingSlot := pluginFeePending0.slot
feeRecipientSlot := plugin.slot
}
(feeSent0, feeSent1) = _processFees(pluginFee0, pluginFee1, lastPluginFeeTimestamp, feePendingSlot, feeRecipientSlot, ts, true);
if (feeSent0 | feeSent1 != 0) (deltaR0, deltaR1) = (deltaR0 - feeSent0.toInt256(), deltaR1 - feeSent1.toInt256());
}
if (deltaR0 | deltaR1 == 0) return;
(uint256 _reserve0, uint256 _reserve1) = (reserve0, reserve1);
if (deltaR0 != 0) _reserve0 = (uint256(int256(_reserve0) + deltaR0)).toUint128();
if (deltaR1 != 0) _reserve1 = (uint256(int256(_reserve1) + deltaR1)).toUint128();
(reserve0, reserve1) = (uint128(_reserve0), uint128(_reserve1));
}
}
/ReentrancyGuard.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import './V4PoolBase.sol';
/// @title V4 reentrancy protection
/// @notice Provides a modifier that protects against reentrancy
abstract contract ReentrancyGuard is V4PoolBase {
/// @notice checks that reentrancy lock is unlocked
modifier onlyUnlocked() {
_checkUnlocked();
_;
}
/// @dev using private function to save bytecode
function _checkUnlocked() internal view {
if (!globalState.unlocked) revert IV4PoolErrors.locked();
}
/// @dev using private function to save bytecode
function _lock() internal {
if (!globalState.unlocked) revert IV4PoolErrors.locked();
globalState.unlocked = false;
}
/// @dev using private function to save bytecode
function _unlock() internal {
globalState.unlocked = true;
}
}
/Positions.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.8.20;
import '../libraries/LiquidityMath.sol';
import '../libraries/TickManagement.sol';
import './V4PoolBase.sol';
/// @title V4 positions abstract contract
/// @notice Contains the logic of recalculation and change of liquidity positions
/// @dev Relies on method _addOrRemoveTicks, which is implemented in TickStructure
abstract contract Positions is V4PoolBase {
using TickManagement for mapping(int24 => TickManagement.Tick);
struct Position {
uint256 liquidity; // The amount of liquidity concentrated in the range
uint256 innerFeeGrowth0Token; // The last updated fee growth per unit of liquidity
uint256 innerFeeGrowth1Token;
uint128 fees0; // The amount of token0 owed to a LP
uint128 fees1; // The amount of token1 owed to a LP
}
/// @inheritdoc IV4PoolState
mapping(bytes32 => Position) public override positions;
/// @notice This function fetches certain position object
/// @param owner The address owing the position
/// @param bottomTick The position's bottom tick
/// @param topTick The position's top tick
/// @return position The Position object
function getOrCreatePosition(address owner, int24 bottomTick, int24 topTick) internal view returns (Position storage) {
bytes32 key;
assembly {
key := or(shl(24, or(shl(24, owner), and(bottomTick, 0xFFFFFF))), and(topTick, 0xFFFFFF))
}
return positions[key];
}
/// @dev Updates position's ticks and its fees
/// @return amount0 The abs amount of token0 that corresponds to liquidityDelta
/// @return amount1 The abs amount of token1 that corresponds to liquidityDelta
function _updatePositionTicksAndFees(
Position storage position,
int24 bottomTick,
int24 topTick,
int128 liquidityDelta
) internal returns (uint256 amount0, uint256 amount1) {
(uint160 currentPrice, int24 currentTick) = (globalState.price, globalState.tick);
bool toggledBottom;
bool toggledTop;
{
// scope to prevent "stack too deep"
(uint256 _totalFeeGrowth0, uint256 _totalFeeGrowth1) = (totalFeeGrowth0Token, totalFeeGrowth1Token);
if (liquidityDelta != 0) {
toggledBottom = ticks.update(bottomTick, currentTick, liquidityDelta, _totalFeeGrowth0, _totalFeeGrowth1, false); // isTopTick: false
toggledTop = ticks.update(topTick, currentTick, liquidityDelta, _totalFeeGrowth0, _totalFeeGrowth1, true); // isTopTick: true
}
(uint256 feeGrowth0, uint256 feeGrowth1) = ticks.getInnerFeeGrowth(bottomTick, topTick, currentTick, _totalFeeGrowth0, _totalFeeGrowth1);
_recalculatePosition(position, liquidityDelta, feeGrowth0, feeGrowth1);
}
if (liquidityDelta != 0) {
// if liquidityDelta is negative and the tick was toggled, it means that it should not be initialized anymore, so we delete it
if (toggledBottom || toggledTop) {
_addOrRemoveTicks(bottomTick, topTick, toggledBottom, toggledTop, currentTick, liquidityDelta < 0);
}
int128 globalLiquidityDelta;
(amount0, amount1, globalLiquidityDelta) = LiquidityMath.getAmountsForLiquidity(bottomTick, topTick, liquidityDelta, currentTick, currentPrice);
if (globalLiquidityDelta != 0) liquidity = LiquidityMath.addDelta(liquidity, liquidityDelta); // update global liquidity
}
}
/// @notice Increases amounts of tokens owed to owner of the position
/// @param position The position object to operate with
/// @param liquidityDelta The amount on which to increase\decrease the liquidity
/// @param innerFeeGrowth0Token Total fee token0 fee growth per liquidity between position's lower and upper ticks
/// @param innerFeeGrowth1Token Total fee token1 fee growth per liquidity between position's lower and upper ticks
function _recalculatePosition(
Position storage position,
int128 liquidityDelta,
uint256 innerFeeGrowth0Token,
uint256 innerFeeGrowth1Token
) internal {
uint128 liquidityBefore = uint128(position.liquidity);
if (liquidityDelta == 0) {
if (liquidityBefore == 0) return; // Do not recalculate the empty ranges
} else {
// change position liquidity
position.liquidity = LiquidityMath.addDelta(liquidityBefore, liquidityDelta);
}
unchecked {
// update the position
(uint256 lastInnerFeeGrowth0Token, uint256 lastInnerFeeGrowth1Token) = (position.innerFeeGrowth0Token, position.innerFeeGrowth1Token);
uint128 fees0;
if (lastInnerFeeGrowth0Token != innerFeeGrowth0Token) {
position.innerFeeGrowth0Token = innerFeeGrowth0Token;
fees0 = uint128(FullMath.mulDiv(innerFeeGrowth0Token - lastInnerFeeGrowth0Token, liquidityBefore, Constants.Q128));
}
uint128 fees1;
if (lastInnerFeeGrowth1Token != innerFeeGrowth1Token) {
position.innerFeeGrowth1Token = innerFeeGrowth1Token;
fees1 = uint128(FullMath.mulDiv(innerFeeGrowth1Token - lastInnerFeeGrowth1Token, liquidityBefore, Constants.Q128));
}
// To avoid overflow owner has to collect fee before it
if (fees0 | fees1 != 0) {
position.fees0 += fees0;
position.fees1 += fees1;
}
}
}
}
/Timestamp.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0 <0.9.0;
/// @title Abstract contract with modified blockTimestamp functionality
/// @notice Allows the pool and other contracts to get a timestamp truncated to 32 bits
/// @dev Can be overridden in tests to make testing easier
abstract contract Timestamp {
/// @dev This function is created for testing by overriding it.
/// @return A timestamp converted to uint32
function _blockTimestamp() internal view virtual returns (uint32) {
return uint32(block.timestamp); // truncation is desired
}
}
Compiler Settings
{"remappings":[],"optimizer":{"runs":0,"enabled":true},"metadata":{"bytecodeHash":"none"},"libraries":{},"evmVersion":"paris","compilationTarget":{"contracts/V4Pool.sol":"V4Pool"}}
Contract ABI
[{"type":"error","name":"alreadyInitialized","inputs":[]},{"type":"error","name":"arithmeticError","inputs":[]},{"type":"error","name":"bottomTickLowerThanMIN","inputs":[]},{"type":"error","name":"communityFeesPendingToCollect","inputs":[]},{"type":"error","name":"dynamicFeeActive","inputs":[]},{"type":"error","name":"dynamicFeeDisabled","inputs":[]},{"type":"error","name":"flashInsufficientPaid0","inputs":[]},{"type":"error","name":"flashInsufficientPaid1","inputs":[]},{"type":"error","name":"incorrectPluginFee","inputs":[]},{"type":"error","name":"insufficientInputAmount","inputs":[]},{"type":"error","name":"invalidAmountRequired","inputs":[]},{"type":"error","name":"invalidHookResponse","inputs":[{"type":"bytes4","name":"expectedSelector","internalType":"bytes4"}]},{"type":"error","name":"invalidLimitSqrtPrice","inputs":[]},{"type":"error","name":"invalidNewCommunityFee","inputs":[]},{"type":"error","name":"invalidNewTickSpacing","inputs":[]},{"type":"error","name":"liquidityAdd","inputs":[]},{"type":"error","name":"liquidityOverflow","inputs":[]},{"type":"error","name":"liquiditySub","inputs":[]},{"type":"error","name":"locked","inputs":[]},{"type":"error","name":"notAllowed","inputs":[]},{"type":"error","name":"notInitialized","inputs":[]},{"type":"error","name":"pluginFeesPendingToCollect","inputs":[]},{"type":"error","name":"pluginIsNotConnected","inputs":[]},{"type":"error","name":"priceOutOfRange","inputs":[]},{"type":"error","name":"tickInvalidLinks","inputs":[]},{"type":"error","name":"tickIsNotInitialized","inputs":[]},{"type":"error","name":"tickIsNotSpaced","inputs":[]},{"type":"error","name":"tickOutOfRange","inputs":[]},{"type":"error","name":"topTickAboveMAX","inputs":[]},{"type":"error","name":"topTickLowerOrEqBottomTick","inputs":[]},{"type":"error","name":"transferFailed","inputs":[]},{"type":"error","name":"zeroAmountRequired","inputs":[]},{"type":"error","name":"zeroLiquidityActual","inputs":[]},{"type":"error","name":"zeroLiquidityDesired","inputs":[]},{"type":"event","name":"Burn","inputs":[{"type":"address","name":"owner","internalType":"address","indexed":true},{"type":"int24","name":"bottomTick","internalType":"int24","indexed":true},{"type":"int24","name":"topTick","internalType":"int24","indexed":true},{"type":"uint128","name":"liquidityAmount","internalType":"uint128","indexed":false},{"type":"uint256","name":"amount0","internalType":"uint256","indexed":false},{"type":"uint256","name":"amount1","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"BurnFee","inputs":[{"type":"address","name":"owner","internalType":"address","indexed":true},{"type":"uint24","name":"pluginFee","internalType":"uint24","indexed":false}],"anonymous":false},{"type":"event","name":"Collect","inputs":[{"type":"address","name":"owner","internalType":"address","indexed":true},{"type":"address","name":"recipient","internalType":"address","indexed":false},{"type":"int24","name":"bottomTick","internalType":"int24","indexed":true},{"type":"int24","name":"topTick","internalType":"int24","indexed":true},{"type":"uint128","name":"amount0","internalType":"uint128","indexed":false},{"type":"uint128","name":"amount1","internalType":"uint128","indexed":false}],"anonymous":false},{"type":"event","name":"CommunityFee","inputs":[{"type":"uint16","name":"communityFeeNew","internalType":"uint16","indexed":false}],"anonymous":false},{"type":"event","name":"CommunityVault","inputs":[{"type":"address","name":"newCommunityVault","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"ExcessTokens","inputs":[{"type":"uint256","name":"amount0","internalType":"uint256","indexed":false},{"type":"uint256","name":"amount1","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Fee","inputs":[{"type":"uint16","name":"fee","internalType":"uint16","indexed":false}],"anonymous":false},{"type":"event","name":"FeeTransferred","inputs":[{"type":"address","name":"recipient","internalType":"address","indexed":true},{"type":"uint256","name":"amount0","internalType":"uint256","indexed":false},{"type":"uint256","name":"amount1","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Flash","inputs":[{"type":"address","name":"sender","internalType":"address","indexed":true},{"type":"address","name":"recipient","internalType":"address","indexed":true},{"type":"uint256","name":"amount0","internalType":"uint256","indexed":false},{"type":"uint256","name":"amount1","internalType":"uint256","indexed":false},{"type":"uint256","name":"paid0","internalType":"uint256","indexed":false},{"type":"uint256","name":"paid1","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Initialize","inputs":[{"type":"uint160","name":"price","internalType":"uint160","indexed":false},{"type":"int24","name":"tick","internalType":"int24","indexed":false}],"anonymous":false},{"type":"event","name":"Mint","inputs":[{"type":"address","name":"sender","internalType":"address","indexed":false},{"type":"address","name":"owner","internalType":"address","indexed":true},{"type":"int24","name":"bottomTick","internalType":"int24","indexed":true},{"type":"int24","name":"topTick","internalType":"int24","indexed":true},{"type":"uint128","name":"liquidityAmount","internalType":"uint128","indexed":false},{"type":"uint256","name":"amount0","internalType":"uint256","indexed":false},{"type":"uint256","name":"amount1","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Plugin","inputs":[{"type":"address","name":"newPluginAddress","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"PluginConfig","inputs":[{"type":"uint8","name":"newPluginConfig","internalType":"uint8","indexed":false}],"anonymous":false},{"type":"event","name":"Skim","inputs":[{"type":"address","name":"to","internalType":"address","indexed":true},{"type":"uint256","name":"amount0","internalType":"uint256","indexed":false},{"type":"uint256","name":"amount1","internalType":"uint256","indexed":false}],"anonymous":false},{"type":"event","name":"Swap","inputs":[{"type":"address","name":"sender","internalType":"address","indexed":true},{"type":"address","name":"recipient","internalType":"address","indexed":true},{"type":"int256","name":"amount0","internalType":"int256","indexed":false},{"type":"int256","name":"amount1","internalType":"int256","indexed":false},{"type":"uint160","name":"price","internalType":"uint160","indexed":false},{"type":"uint128","name":"liquidity","internalType":"uint128","indexed":false},{"type":"int24","name":"tick","internalType":"int24","indexed":false}],"anonymous":false},{"type":"event","name":"SwapFee","inputs":[{"type":"address","name":"sender","internalType":"address","indexed":true},{"type":"uint24","name":"overrideFee","internalType":"uint24","indexed":false},{"type":"uint24","name":"pluginFee","internalType":"uint24","indexed":false}],"anonymous":false},{"type":"event","name":"TickSpacing","inputs":[{"type":"int24","name":"newTickSpacing","internalType":"int24","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"amount0","internalType":"uint256"},{"type":"uint256","name":"amount1","internalType":"uint256"}],"name":"burn","inputs":[{"type":"int24","name":"bottomTick","internalType":"int24"},{"type":"int24","name":"topTick","internalType":"int24"},{"type":"uint128","name":"amount","internalType":"uint128"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint128","name":"amount0","internalType":"uint128"},{"type":"uint128","name":"amount1","internalType":"uint128"}],"name":"collect","inputs":[{"type":"address","name":"recipient","internalType":"address"},{"type":"int24","name":"bottomTick","internalType":"int24"},{"type":"int24","name":"topTick","internalType":"int24"},{"type":"uint128","name":"amount0Requested","internalType":"uint128"},{"type":"uint128","name":"amount1Requested","internalType":"uint128"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"communityVault","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"factory","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint16","name":"currentFee","internalType":"uint16"}],"name":"fee","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"flash","inputs":[{"type":"address","name":"recipient","internalType":"address"},{"type":"uint256","name":"amount0","internalType":"uint256"},{"type":"uint256","name":"amount1","internalType":"uint256"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint128","name":"","internalType":"uint128"},{"type":"uint128","name":"","internalType":"uint128"}],"name":"getCommunityFeePending","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint128","name":"","internalType":"uint128"},{"type":"uint128","name":"","internalType":"uint128"}],"name":"getPluginFeePending","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint128","name":"","internalType":"uint128"},{"type":"uint128","name":"","internalType":"uint128"}],"name":"getReserves","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint160","name":"price","internalType":"uint160"},{"type":"int24","name":"tick","internalType":"int24"},{"type":"uint16","name":"lastFee","internalType":"uint16"},{"type":"uint8","name":"pluginConfig","internalType":"uint8"},{"type":"uint16","name":"communityFee","internalType":"uint16"},{"type":"bool","name":"unlocked","internalType":"bool"}],"name":"globalState","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialize","inputs":[{"type":"uint160","name":"initialPrice","internalType":"uint160"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"unlocked","internalType":"bool"}],"name":"isUnlocked","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint32","name":"","internalType":"uint32"}],"name":"lastCommunityFeeTimestamp","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint32","name":"","internalType":"uint32"}],"name":"lastPluginFeeTimestamp","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint128","name":"","internalType":"uint128"}],"name":"liquidity","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint128","name":"","internalType":"uint128"}],"name":"maxLiquidityPerTick","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"uint256","name":"amount0","internalType":"uint256"},{"type":"uint256","name":"amount1","internalType":"uint256"},{"type":"uint128","name":"liquidityActual","internalType":"uint128"}],"name":"mint","inputs":[{"type":"address","name":"leftoversRecipient","internalType":"address"},{"type":"address","name":"recipient","internalType":"address"},{"type":"int24","name":"bottomTick","internalType":"int24"},{"type":"int24","name":"topTick","internalType":"int24"},{"type":"uint128","name":"liquidityDesired","internalType":"uint128"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"int24","name":"","internalType":"int24"}],"name":"nextTickGlobal","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"plugin","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"liquidity","internalType":"uint256"},{"type":"uint256","name":"innerFeeGrowth0Token","internalType":"uint256"},{"type":"uint256","name":"innerFeeGrowth1Token","internalType":"uint256"},{"type":"uint128","name":"fees0","internalType":"uint128"},{"type":"uint128","name":"fees1","internalType":"uint128"}],"name":"positions","inputs":[{"type":"bytes32","name":"","internalType":"bytes32"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"int24","name":"","internalType":"int24"}],"name":"prevTickGlobal","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint160","name":"sqrtPrice","internalType":"uint160"},{"type":"int24","name":"tick","internalType":"int24"},{"type":"uint16","name":"lastFee","internalType":"uint16"},{"type":"uint8","name":"pluginConfig","internalType":"uint8"},{"type":"uint128","name":"activeLiquidity","internalType":"uint128"},{"type":"int24","name":"nextTick","internalType":"int24"},{"type":"int24","name":"previousTick","internalType":"int24"}],"name":"safelyGetStateOfAMM","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setCommunityFee","inputs":[{"type":"uint16","name":"newCommunityFee","internalType":"uint16"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setCommunityVault","inputs":[{"type":"address","name":"newCommunityVault","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setFee","inputs":[{"type":"uint16","name":"newFee","internalType":"uint16"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setPlugin","inputs":[{"type":"address","name":"newPluginAddress","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setPluginConfig","inputs":[{"type":"uint8","name":"newConfig","internalType":"uint8"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setTickSpacing","inputs":[{"type":"int24","name":"newTickSpacing","internalType":"int24"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"skim","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"int256","name":"amount0","internalType":"int256"},{"type":"int256","name":"amount1","internalType":"int256"}],"name":"swap","inputs":[{"type":"address","name":"recipient","internalType":"address"},{"type":"bool","name":"zeroToOne","internalType":"bool"},{"type":"int256","name":"amountRequired","internalType":"int256"},{"type":"uint160","name":"limitSqrtPrice","internalType":"uint160"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[{"type":"int256","name":"amount0","internalType":"int256"},{"type":"int256","name":"amount1","internalType":"int256"}],"name":"swapWithPaymentInAdvance","inputs":[{"type":"address","name":"leftoversRecipient","internalType":"address"},{"type":"address","name":"recipient","internalType":"address"},{"type":"bool","name":"zeroToOne","internalType":"bool"},{"type":"int256","name":"amountToSell","internalType":"int256"},{"type":"uint160","name":"limitSqrtPrice","internalType":"uint160"},{"type":"bytes","name":"data","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"sync","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"int24","name":"","internalType":"int24"}],"name":"tickSpacing","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"tickTable","inputs":[{"type":"int16","name":"","internalType":"int16"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint32","name":"","internalType":"uint32"}],"name":"tickTreeRoot","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"tickTreeSecondLayer","inputs":[{"type":"int16","name":"","internalType":"int16"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"liquidityTotal","internalType":"uint256"},{"type":"int128","name":"liquidityDelta","internalType":"int128"},{"type":"int24","name":"prevTick","internalType":"int24"},{"type":"int24","name":"nextTick","internalType":"int24"},{"type":"uint256","name":"outerFeeGrowth0Token","internalType":"uint256"},{"type":"uint256","name":"outerFeeGrowth1Token","internalType":"uint256"}],"name":"ticks","inputs":[{"type":"int24","name":"","internalType":"int24"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"token0","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"token1","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalFeeGrowth0Token","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"totalFeeGrowth1Token","inputs":[]}]
Contract Creation Code
0x60e06040523480156200001157600080fd5b5060006200001e620000b0565b6001600160a01b0390811660c05290811660a052166080529050620d89e719620000488162000273565b6009805462ffffff93841663010000000265ffffffffffff1990911693909216929092171790556002805460ff60e01b1916600160e01b1790556001600160a01b038116156200009d576200009d8162000129565b50620000aa60036200017d565b6200031e565b600080600080336001600160a01b03166304889e266040518163ffffffff1660e01b8152600401608060405180830381865afa158015620000f5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906200011b9190620002c1565b935093509350935090919293565b600680546001600160a01b0319166001600160a01b0383169081179091556040519081527f27a3944eff2135a57675f17e72501038982b73620d01f794c72e93d61a3932a29060200160405180910390a150565b620d89e7196200018d8162000273565b620d89e7196000818152602085905260409020600101805465ffffffffffff60801b1916600160981b62ffffff9485160262ffffff60801b191617600160801b949093169390930291909117909155620001e78162000273565b826000620001f9620d89e71962000273565b60020b60020b81526020019081526020016000206001016010846000620d89e719620002259062000273565b60020b81526020810191909152604001600020600101805462ffffff948516600160981b0262ffffff60981b1990911617905581549383166101009190910a90810292021990921617905550565b60008160020b627fffff1981036200029b57634e487b7160e01b600052601160045260246000fd5b60000392915050565b80516001600160a01b0381168114620002bc57600080fd5b919050565b60008060008060808587031215620002d857600080fd5b620002e385620002a4565b9350620002f360208601620002a4565b92506200030360408601620002a4565b91506200031360608601620002a4565b905092959194509250565b60805160a05160c05161593f620003ef6000396000818161094001528181610be3015281816110c90152818161132b015281816116780152818161174501528181611aa7015281816127f201528181612c1501528181612ea001526148ee01526000818161025f01528181610c7401528181611085015281816112e8015281816116b00152818161170d01528181611a72015281816127a301528181612a0101528181612e5201526148bd0152600081816108b201528181611c7501528181612fb10152613bed015261593f6000f3fe608060405234801561001057600080fd5b50600436106101e35760003560e01c8063050a4d21146101e85780630902f1ac146102135780630dfe16811461025a578063128acb081461029d5780631a6865021461034a5780631dd19cb414610380578063240a875a1461038a5780633b3bc70e146103ab578063490e6cbc1461043d5780634f1eb3d8146104c7578063514ea4bf1461051857806353e97868146105a2578063578b9a36146105b55780636378ae44146105e557806370cf754a146106005780637bd78025146106155780638380edb7146106315780638e0055531461065257806397ce1c51146106735780639e4e0227146106d4578063a1eded8714610771578063a5e5eeae1461078d578063aafe29c0146107a4578063bca57f8114610876578063c00a461114610896578063c45a0155146108ad578063c677e3e0146108d4578063cc1f97cf14610901578063d0c93a7c14610927578063d21220a71461093b578063d5c35a7e14610962578063d8544cf31461096f578063d861903714610995578063ddca3f43146109c2578063e76c01e4146109e1578063ecdecf4214610a76578063ef01df4f14610a7f578063f085a61014610a92578063f30dba9314610ab2578063f637731d14610b4c578063fff6cae914610b72575b600080fd5b6009546101fc906301000000900460020b81565b6040805160029290920b8252519081900360200190f35b600c546001600160801b0380821691600160801b9004165b60405180836001600160801b03168152602001826001600160801b031681526020019250505060405180910390f35b6102817f000000000000000000000000000000000000000000000000000000000000000081565b604080516001600160a01b039092168252519081900360200190f35b610331600480360360a08110156102b357600080fd5b6001600160a01b0382358116926020810135151592604082013592606083013516919081019060a081016080820135600160201b8111156102f357600080fd5b82018360208201111561030557600080fd5b803590602001918460018302840111600160201b8311171561032657600080fd5b509092509050610b7a565b6040805192835260208301919091528051918290030190f35b60095461036490600160301b90046001600160801b031681565b604080516001600160801b039092168252519081900360200190f35b610388610d69565b005b610388600480360360208110156103a057600080fd5b503561ffff16610d8c565b610331600480360360808110156103c157600080fd5b8135600290810b92602081013590910b916001600160801b036040830135169190810190608081016060820135600160201b8111156103ff57600080fd5b82018360208201111561041157600080fd5b803590602001918460018302840111600160201b8311171561043257600080fd5b509092509050610e0b565b6103886004803603608081101561045357600080fd5b6001600160a01b038235169160208101359160408201359190810190608081016060820135600160201b81111561048957600080fd5b82018360208201111561049b57600080fd5b803590602001918460018302840111600160201b831117156104bc57600080fd5b50909250905061103f565b61022b600480360360a08110156104dd57600080fd5b506001600160a01b03813516906020810135600290810b91604081013590910b906001600160801b036060820135811691608001351661123c565b61056b6004803603602081101561052e57600080fd5b50600b60205235600090815260409020805460018201546002830154600390930154919290916001600160801b0380821691600160801b90041685565b604080519586526020860194909452848401929092526001600160801b039081166060850152166080830152519081900360a00190f35b600754610281906001600160a01b031681565b6009546105cc90600160c81b900463ffffffff1681565b6040805163ffffffff9092168252519081900360200190f35b6105ee60005481565b60408051918252519081900360200190f35b6103646d09745258e83de0d0f4e400fce79981565b6004546001600160681b0380821691600160681b90041661022b565b600254600160e01b900460ff16604080519115158252519081900360200190f35b6103886004803603602081101561066857600080fd5b503561ffff166113f8565b61067b611482565b604080516001600160a01b039098168852600296870b602089015261ffff9095168786015260ff90931660608701526001600160801b039091166080860152830b60a085015290910b60c0830152519081900360e00190f35b610331600480360360c08110156106ea57600080fd5b6001600160a01b0382358116926020810135821692604082013515159260608301359260808101359091169181019060c0810160a0820135600160201b81111561073357600080fd5b82018360208201111561074557600080fd5b803590602001918460018302840111600160201b8311171561076657600080fd5b509092509050611515565b6005546001600160681b0380821691600160681b90041661022b565b6004546105cc90600160d01b900463ffffffff1681565b61084f600480360360c08110156107ba57600080fd5b6001600160a01b0382358116926020810135909116916040820135600290810b92606081013590910b916001600160801b03608083013516919081019060c0810160a0820135600160201b81111561081157600080fd5b82018360208201111561082357600080fd5b803590602001918460018302840111600160201b8311171561084457600080fd5b5090925090506117f5565b6040805193845260208401929092526001600160801b031682820152519081900360600190f35b6103886004803603602081101561088c57600080fd5b503560ff16611b8c565b6005546105cc90600160d01b900463ffffffff1681565b6102817f000000000000000000000000000000000000000000000000000000000000000081565b6105ee600480360360208110156108ea57600080fd5b5060086020523560010b6000908152604090205481565b6103886004803603602081101561091757600080fd5b50356001600160a01b0316611be3565b6009546101fc90600160b01b900460020b81565b6102817f000000000000000000000000000000000000000000000000000000000000000081565b6009546101fc9060020b81565b6103886004803603602081101561098557600080fd5b50356001600160a01b0316611c62565b6105ee600480360360208110156109ab57600080fd5b50600a6020523560010b6000908152604090205481565b6109ca611d0c565b6040805161ffff9092168252519081900360200190f35b60028054610a2c916001600160a01b03821691600160a01b810490910b9061ffff600160b81b820481169160ff600160c81b8204811692600160d01b83041691600160e01b90041686565b604080516001600160a01b03909716875260029590950b602087015261ffff9384168686015260ff90921660608601529091166080840152151560a0830152519081900360c00190f35b6105ee60015481565b600654610281906001600160a01b031681565b61038860048036036020811015610aa857600080fd5b503560020b611da8565b610b1060048036036020811015610ac857600080fd5b50600360208190529035600290810b600090815260409020805460018201548284015492909401549093600f81900b93600160801b8204810b93600160981b909204900b9186565b60408051968752600f9590950b6020870152600293840b868601529190920b6060850152608084019190915260a0830152519081900360c00190f35b61038860048036036020811015610b6257600080fd5b50356001600160a01b0316611e11565b610388611f33565b600080600080610b908a8a8a8a60008b8b611f55565b91509150610b9c612089565b610ba4615437565b610bb183838c8c8c6120c2565b94995092975092935060009250829150610bcb905061274b565b915091508b15610c66576000861215610c0c57610c0c7f00000000000000000000000000000000000000000000000000000000000000008e88600003612976565b610c1887878b8b612986565b610c206129e7565b610c2a888461546f565b1115610c4957604051633ed6d50560e21b815260040160405180910390fd5b610c6187878560000151600087602001516000612a77565b610cf2565b6000871215610c9d57610c9d7f00000000000000000000000000000000000000000000000000000000000000008e89600003612976565b610ca987878b8b612986565b610cb1612bfb565b610cbb878361546f565b1115610cda57604051633ed6d50560e21b815260040160405180910390fd5b610cf287876000866000015160008860200151612a77565b610d418d8888600260000160009054906101000a90046001600160a01b0316600960069054906101000a90046001600160801b0316600260000160149054906101000a900460020b8b8b612c4a565b505050610d4c612cfd565b610d5c8a8a8a8a88888c8c612d12565b5050965096945050505050565b610d71612dc7565b610d79612089565b610d8233612df2565b610d8a612cfd565b565b610d94612f41565b610d9c612f6b565b6103e861ffff82161180610dbf575060025461ffff828116600160d01b90920416145b80610de1575061ffff811615801590610de157506007546001600160a01b0316155b15610dff5760405163a709b9af60e01b815260040160405180910390fd5b610e0881613031565b50565b6000808686610e1a8282613088565b60016001607f1b036001600160801b0388161115610e4b57604051638995290f60e01b815260040160405180910390fd5b6000610e5688615482565b90506000610e68338c8c858c8c61310a565b9050610e72612089565b610e7a61274b565b50506000610e89338d8d6131e3565b9050610e97818d8d8661320f565b909750955062ffffff821615610f0d576000808815610ed257610ec38962ffffff8616620f4240613331565b9150610ecf828a6154a5565b98505b8715610efa57610eeb8862ffffff8616620f4240613331565b9050610ef781896154a5565b97505b610f0a6000806000808686612a77565b50505b86861715610f72576003810154610f2e9088906001600160801b03166154b8565b6003820154610f4e908890600160801b90046001600160801b03166154b8565b6001600160801b039182169116600160801b026001600160801b0319161760038201555b506001600160801b0389168617851715611019576040805162ffffff83168152905133917f1a25098b7a731ae33ed362388b593b876963dfde0efb4db9c0befeed637ff26b919081900360200190a2604080516001600160801b038b16815260208101889052808201879052905160028c810b92908e900b9133917f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c919081900360600190a45b611021612cfd565b611031338c8c858a8a8e8e6133ca565b505050509550959350505050565b61104c858585858561342c565b611054612089565b60008060008061106261274b565b9092509050600088156110ab5761107e896064620f424061347c565b90506110ab7f00000000000000000000000000000000000000000000000000000000000000008b8b612976565b600088156110ef576110c2896064620f424061347c565b90506110ef7f00000000000000000000000000000000000000000000000000000000000000008c8b612976565b6110fb82828a8a6134fc565b6111036129e7565b955085611110838661546f565b111561112f576040516336de50ff60e11b815260040160405180910390fd5b611137612bfb565b945084611144828561546f565b11156111635760405163c998149f60e01b815260040160405180910390fd5b60025495849003959483900394600160d01b900461ffff1680156111c357600087156111995761119688836103e8613331565b90505b600087156111b1576111ae88846103e8613331565b90505b6111c082828484600080612a77565b50505b604080518c8152602081018c90528082018990526060810188905290516001600160a01b038e169133917fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6339181900360800190a35050505050611224612cfd565b61123387878785858989613525565b50505050505050565b600080611247612089565b60006112543388886131e3565b60038101549091506001600160801b0380821691600160801b9004811690871682101561127f578196505b806001600160801b0316866001600160801b0316111561129d578095505b6001600160801b0387871716156113e3576001600160801b0387830381168783038216600160801b026001600160801b031916176003850155879550869450851615611317576113177f00000000000000000000000000000000000000000000000000000000000000008b876001600160801b0316612976565b6001600160801b0384161561135a5761135a7f00000000000000000000000000000000000000000000000000000000000000008b866001600160801b0316612976565b611382856001600160801b0316600003856001600160801b0316600003600080600080612a77565b604080516001600160a01b038c1681526001600160801b038088166020830152861681830152905160028a810b92908c900b9133917f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c0919081900360600190a45b6113eb612cfd565b5050509550959350505050565b611400612f6b565b600254600160e01b900460ff1661142a57604051636798480960e11b815260040160405180910390fd5b6114346080613579565b15611452576040516369cdc70760e11b815260040160405180910390fd5b620f42408161ffff1610611479576040516315b2afa960e01b815260040160405180910390fd5b610e0881613594565b600280546001600160a01b03811691600160a01b8204900b9061ffff600160b81b8204169060ff600160c81b820481169160009182918291600160e01b90910416806114e157604051636798480960e11b815260040160405180910390fd5b505060095495969495939492936001600160801b03600160301b82041693600282810b9450630100000090920490910b9150565b600080600086121561153a576040516334cb3a0160e11b815260040160405180910390fd5b611542612089565b6000871561159b5760006115546129e7565b90506115638860008888612986565b600061156d6129e7565b905061158161157c83836154a5565b6135e4565b9250611594836000806000806000612a77565b50506115e3565b60006115a5612bfb565b90506115b46000898888612986565b60006115be612bfb565b90506115cd61157c83836154a5565b92506115e0600084600080600080612a77565b50505b8681146115ee578096505b508560000361161057604051633ed6d50560e21b815260040160405180910390fd5b611618612cfd565b60008061162b8a8a8a8a60018b8b611f55565b91509150611637612089565b61163f61274b565b5050611649615437565b61165683838c8c8c6120c2565b949950929750929350508b1591506116ff90505760008412156116a1576116a17f00000000000000000000000000000000000000000000000000000000000000008c86600003612976565b8489038986146116d6576116d67f00000000000000000000000000000000000000000000000000000000000000008e83612976565b6116f96116e2826135e4565b600003868460000151600086602001516000612a77565b50611790565b6000851215611736576117367f00000000000000000000000000000000000000000000000000000000000000008c87600003612976565b83890389851461176b5761176b7f00000000000000000000000000000000000000000000000000000000000000008e83612976565b61178e86611778836135e4565b6000036000856000015160008760200151612a77565b505b600280546009546117ce928e92899289926001600160a01b03831692600160301b9092046001600160801b031691600160a01b9004900b8989612c4a565b6117d6612cfd565b6117e68b8b8b8b89898d8d612d12565b50505097509795505050505050565b600080600087876118068282613088565b876001600160801b03166000036118305760405163e6ace6df60e01b815260040160405180910390fd5b61184f8b8b8b6118488c6001600160801b03166135f8565b8b8b61310a565b50611858612089565b60028054600160a01b810490910b906001600160a01b031660008190036118925760405163812eb65560e01b815260040160405180910390fd5b600954600160b01b9004600290810b9081908d900b816118b4576118b46154df565b078160020b8e60020b816118ca576118ca6154df565b071760020b156118ed57604051635f6e14f360e01b815260040160405180910390fd5b5061190c8c8c6119058d6001600160801b03166135f8565b858561360b565b5090975095506000915081905061192161274b565b9150915061193187878b8b6136ba565b861561194f57816119406129e7565b61194a91906154a5565b611952565b60005b915085156119725780611963612bfb565b61196d91906154a5565b611975565b60005b90508682101561199a576119938a6001600160801b03168389613331565b945061199e565b8994505b858110156119de5760006119bc8b6001600160801b03168389613331565b9050856001600160801b0316816001600160801b031610156119dc578095505b505b846001600160801b0316600003611a0857604051632fae8a9b60e21b815260040160405180910390fd5b6000611a158e8e8e6131e3565b9050611a34818e8e611a2f8a6001600160801b03166135f8565b61320f565b90985096505086821080611a4757508581105b15611a6557604051633ed6d50560e21b815260040160405180910390fd5b86821115611a9a57611a9a7f00000000000000000000000000000000000000000000000000000000000000008f898503612976565b85811115611acf57611acf7f00000000000000000000000000000000000000000000000000000000000000008f888403612976565b611adf8787600080600080612a77565b8a60020b8c60020b8e6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde33898c8c60405180856001600160a01b03168152602001846001600160801b0316815260200183815260200182815260200194505050505060405180910390a4611b5a612cfd565b611b7b8d8d8d611b72896001600160801b03166135f8565b8b8b8f8f6133ca565b505050509750975097945050505050565b611b94612f41565b6006546001600160a01b031680611bbe57604051639e727ce360e01b815260040160405180910390fd5b336001600160a01b03821614611bd657611bd6612f6b565b611bdf826136e3565b5050565b611beb612f41565b611bf3612f6b565b6006546005546001600160a01b03909116906001600160681b03808216600160681b909204161715611c4f576001600160a01b038116611c4657604051638ec9444160e01b815260040160405180910390fd5b611c4f81613731565b611c5960006136e3565b611bdf826137dd565b611c6a612f41565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614611ca257611ca2612f6b565b6001600160a01b038116611d03576004546001600160681b03808216600160681b909204161715611ce65760405163b8856c0b60e01b815260040160405180910390fd5b600254600160d01b900461ffff1615611d0357611d036000613031565b610e0881613828565b600254600160b81b900461ffff16611d246080613579565b15611da557600660009054906101000a90046001600160a01b03166001600160a01b031663f70d93626040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d7c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611da09190615507565b905090565b90565b611db0612f41565b611db8612f6b565b60008160020b131580611dd057506101f4600282900b135b80611dea5750600954600282810b600160b01b909204900b145b15611e0857604051632bf827d160e21b815260040160405180910390fd5b610e0881613873565b6000611e1c826138c3565b6002549091506001600160a01b031615611e4957604051631499a6b760e21b815260040160405180910390fd5b600280546001600160a01b0384166001600160b81b03199091168117600160a01b62ffffff851602178255604080519182529183900b602082015281517f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c95929181900390910190a1611eba82613b95565b6000806000611ec7613be6565b925092509250611ed681613594565b611edf82613873565b61ffff831615801590611efb57506007546001600160a01b0316155b15611f195760405163a709b9af60e01b815260040160405180910390fd5b611f2283613031565b611f2c8585613c78565b5050505050565b611f3b612dc7565b611f43612089565b611f4b61274b565b5050610d8a612cfd565b6002546000908190600160c81b900460ff16611f7381600116151590565b1561207b57611f80613ccf565b15611f9257600080925092505061207d565b60065460405163029c1cb760e01b81526000916001600160a01b03169063029c1cb790611fd19033908f908f908f908f908f908f908f9060040161554b565b6060604051808303816000875af1158015611ff0573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061201491906155d0565b9095509350905060808216158015612040575060008462ffffff161180612040575060008362ffffff16115b1561205e57604051633a4528ef60e01b815260040160405180910390fd5b6120796001600160e01b0319821663029c1cb760e01b613ce0565b505b505b97509795505050505050565b600254600160e01b900460ff166120b357604051636798480960e11b815260040160405180910390fd5b6002805460ff60e01b19169055565b60008060008060006120d2615437565b876000036120f3576040516301e76e6160e61b815260040160405180910390fd5b600160ff1b8803612117576040516334cb3a0160e11b815260040160405180910390fd5b6040805161016081018252600060208201819052606082018190526080820181905260a0820181905262ffffff8d16610140830152808b1360c08301529181018a9052600954600281810b61012084015263010000008204810b610100840152805461ffff600160d01b820481168552600160b81b82041660e08501526001600160a01b0381169850600160a01b9004900b9550600160301b90046001600160801b03169350908590036121de5760405163812eb65560e01b815260040160405180910390fd5b62ffffff8c1615612226576121f38b8d615613565b62ffffff1660e08201819052620f424011612221576040516315b2afa960e01b815260040160405180910390fd5b612278565b62ffffff8b1615612278578a8160e0018181516122439190615613565b62ffffff90811690915260e0830151620f42409116109050612278576040516315b2afa960e01b815260040160405180910390fd5b89156122d857846001600160a01b0316886001600160a01b03161015806122ad57506401000276a36001600160a01b03891611155b156122cb57604051631662672360e01b815260040160405180910390fd5b600054608082015261233d565b846001600160a01b0316886001600160a01b0316111580612316575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b03891610155b1561233457604051631662672360e01b815260040160405180910390fd5b60015460808201525b61236f6040518060a0016040528060008152602001600081526020016000815260200160008152602001600081525090565b60008b61238157826101200151612388565b8261010001515b6001600160a01b0388168352905061239f81613d1d565b6001600160a01b03908116602084018190526123dc918e918a918e1611821515146123ce5784602001516123d0565b8c5b888f8860e00151613ff8565b60808601526060850152604084015260c0840151909750156124345761240b82608001518360400151016135e4565b8b039a5061242a61241f83606001516135e4565b6060850151906141c6565b606084015261246c565b61244182606001516135e4565b8b019a5061246661245b83608001518460400151016135e4565b6060850151906141dc565b60608401525b8251156124ae57825160808301516000916103e89161248a916141f2565b81612497576124976154df565b608085018051929091049182900390528551018552505b600083610140015162ffffff161180156124d1575060008360e0015162ffffff16115b156125125760006124fa836080015185610140015162ffffff168660e0015162ffffff16613331565b60808401805182900390526020860180519091019052505b6001600160801b038516156125495761253d8260800151600160801b876001600160801b0316613331565b60808401805190910190525b8160200151876001600160a01b03160361261357826020015161258457600160208401528b61257a5760005461257e565b6001545b60a08401525b60008c156125cb57608084015160a08501516125a59160039185919061421c565b50600290810b61010087015283900b610120860152600019830197506000039050612601565b60a084015160808501516125e49160039185919061421c565b600290810b61012088015284900b61010087015250919650869190505b61260b8682614269565b955050612635565b81516001600160a01b038816146126355761262d876138c3565b95505061265c565b5089158015906126575750886001600160a01b0316866001600160a01b031614155b61236f575b60008a83604001510390508260c0015115158c15151461268157826060015181612688565b8083606001515b600280546001600160b81b031916600160a01b62ffffff8b16026001600160a01b031916176001600160a01b038b161790556020850151919a509850159050612720576101008201516101208301516009805462ffffff92831665ffffffffffff19909116176301000000929093169190910291909117600160301b600160b01b031916600160301b6001600160801b038716021790555b8a1561273357608082015160005561273c565b60808201516001555b50509550955095509550955095565b6000806127566129e7565b61275e612bfb565b90925090506001600160801b0382118061277e57506001600160801b0381115b1561282f576007546001600160a01b03166001600160801b038311156127de576127d37f0000000000000000000000000000000000000000000000000000000000000000826002600160801b03198601612976565b6001600160801b0392505b6001600160801b0382111561282d576128227f0000000000000000000000000000000000000000000000000000000000000000826002600160801b03198501612976565b6001600160801b0391505b505b600954600160301b90046001600160801b0316600081900361285057509091565b600c546001600160801b0380821691600160801b90041681851181851181806128765750805b1561296d5781156128ae576128a4846001600160801b03168803600160801b876001600160801b0316613331565b6000805490910190555b80156128e1576128d7836001600160801b03168703600160801b876001600160801b0316613331565b6001805490910190555b7fef10ebb00f0dbc72ad4602e94abbbda6f3d40632714f70e9c8fa30d5d44289c98261290e57600061291b565b846001600160801b031688035b82612927576000612934565b846001600160801b031688035b60405161294292919061562f565b60405180910390a16001600160801b03808816908716600160801b026001600160801b03191617600c555b50505050509091565b6129818383836142e3565b505050565b604051636a5ac18f60e01b81523390636a5ac18f906129af90879087908790879060040161563d565b600060405180830381600087803b1580156129c957600080fd5b505af11580156129dd573d6000803e3d6000fd5b5050505050505050565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a0823190612a3690309060040161565d565b602060405180830381865afa158015612a53573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611da09190615671565b6000841180612a865750600083115b80612a915750600082115b80612a9c5750600081115b15612b6f576004805460079060009081904290612acd908a908a90600160d01b900463ffffffff168888868861434d565b909350915082821715612b0657612ae3836135e4565b612aed908c61568a565b612af6836135e4565b612b00908c61568a565b909b5099505b6005805490955060069450612b309088908890600160d01b900463ffffffff16888886600161434d565b909350915082821715612b6957612b46836135e4565b612b50908c61568a565b612b59836135e4565b612b63908c61568a565b909b5099505b50505050505b85851715612bf357600c546001600160801b0380821691600160801b9004168715612bb257612ba6612ba189846156aa565b61448b565b6001600160801b031691505b8615612bd157612bc5612ba188836156aa565b6001600160801b031690505b6001600160801b039182169116600160801b026001600160801b03191617600c555b505050505050565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a0823190612a3690309060040161565d565b6040805162ffffff808516825283166020820152815133927f9443903d84c9719611bd4bba871daaf18a3950d00d5d78b1a2fa701f76df54ff928290030190a260408051888152602081018890526001600160a01b03878116828401526001600160801b0387166060830152600286900b60808301529151918a169133917fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67919081900360a00190a35050505050505050565b6002805460ff60e01b1916600160e01b179055565b612d1c6002613579565b156129dd57612d29613ccf565b6129dd57600654604051639cb5a96360e01b8082526129dd9290916001600160a01b0390911690639cb5a96390612d749033908e908e908e908e908e908e908e908e906004016156d2565b6020604051808303816000875af1158015612d93573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612db79190615735565b6001600160e01b03191690613ce0565b6006546001600160a01b03163314610d8a57604051634994c26960e11b815260040160405180910390fd5b600080612dfd6129e7565b612e05612bfb565b600c5491935091506001600160801b0380821691600160801b90041681841180612e375750806001600160801b031683115b15611f2c57816001600160801b0316841115612e8a57612e8a7f000000000000000000000000000000000000000000000000000000000000000086612e856001600160801b038616886154a5565b612976565b806001600160801b0316831115612ed357612ed37f000000000000000000000000000000000000000000000000000000000000000086612e856001600160801b038516876154a5565b6001600160a01b0385167fb94331e4420f16b156f53c397a8adcd09481283ee7830f7b688b22858e9db80b612f116001600160801b038516876154a5565b612f246001600160801b038516876154a5565b604051612f3292919061562f565b60405180910390a25050505050565b600254600160e01b900460ff16610d8a57604051636798480960e11b815260040160405180910390fd5b6040805163e8ae2b6960e01b81527fb73ce166ead2f8e9add217713a7989e4edfba9625f71dfd2516204bb67ad3442600482015233602482015290516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169163e8ae2b699160448083019260209291908290030181865afa158015612ffc573d6000803e3d6000fd5b505050506040513d602081101561301257600080fd5b5051610d8a57604051634994c26960e11b815260040160405180910390fd5b6002805461ffff60d01b1916600160d01b61ffff8416908102919091179091556040519081527f3647dccc990d4941b0b05b32527ef493a98d6187b20639ca2f9743f3b55ca5e1906020015b60405180910390a150565b613095620d89e719615750565b60020b8160020b13156130bb57604051631445443d60e01b815260040160405180910390fd5b8160020b8160020b136130e15760405163d9a841a760e01b815260040160405180910390fd5b620d89e719600283900b1215611bdf57604051631d1ac7f160e21b815260040160405180910390fd5b60006131166004613579565b156131d957613123613ccf565b15613130575060006131d9565b600654604051632f1208d960e11b81526000916001600160a01b031690635e2411b29061316d9033908c908c908c908c908c908c90600401615769565b60408051808303816000875af115801561318b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131af91906157b2565b925090506131bc826144a1565b6131d76001600160e01b03198216632f1208d960e11b613ce0565b505b9695505050505050565b62ffffff818116908316601885811b91909117901b176000908152600b602052604090205b9392505050565b6002805460008054600154919384936001600160a01b03811693600160a01b90910490910b918491829190600f89900b1561326b5761325560038c878c868660006144c9565b935061326860038b878c868660016144c9565b92505b60008061327d60038e8e8a88886145ba565b9150915061328d8e8c8484614661565b5050505086600f0b6000146133245781806132a55750805b156132be576132be898984848760008d600f0b12614756565b60006132cd8a8a8a878961360b565b91985096509050600f81900b15613322576009546132fb90600160301b90046001600160801b031689614269565b600960066101000a8154816001600160801b0302191690836001600160801b031602179055505b505b5050505094509492505050565b6000838302816000198587098281108382030391505080841161335357600080fd5b8060000361336657508290049050613208565b8385870960008581038616958690049560026003880281188089028203028089028203028089028203028089028203028089028203028089029091030291819003819004600101858411909403939093029190930391909104170290509392505050565b6133d2613ccf565b6129dd576133e06008613579565b156129dd57600654604051630d68520160e41b8082526129dd9290916001600160a01b039091169063d685201090612d749033908e908e908e908e908e908e908e908e906004016157e5565b6134366010613579565b15611f2c576006546040516346f0547760e11b808252611f2c9290916001600160a01b0390911690638de0a8ee90612d749033908b908b908b908b908b90600401615839565b600083158061349d5750508282028284828161349a5761349a6154df565b04145b156134be57600082116134af57600080fd5b81810490829006151501613208565b6134c9848484613331565b9050600082806134db576134db6154df565b84860911156132085760001981106134f257600080fd5b6001019392505050565b60405163b81ddfc960e01b8152339063b81ddfc9906129af90879087908790879060040161563d565b61352f6020613579565b156112335760065460405163343d37ff60e01b8082526112339290916001600160a01b039091169063343d37ff90612d749033908d908d908d908d908d908d908d90600401615880565b600254600090600160c81b9004821660ff1615155b92915050565b6002805461ffff60b81b1916600160b81b61ffff8416908102919091179091556040519081527f598b9f043c813aa6be3426ca60d1c65d17256312890be5118dab55b0775ebe2a9060200161307d565b8060008112156135f357600080fd5b919050565b806000600f82900b12156135f357600080fd5b60008060008061361a89613d1d565b9050600061362789613d1d565b90506000808b60020b8960020b121561364c5761364584848c61483f565b915061368a565b8a60020b8960020b121561367c5761366588848c61483f565b915061367284898c61487f565b905089945061368a565b61368784848c61487f565b90505b60008a600f0b1261369c5781816136a5565b81600003816000035b909d909c50949a509398505050505050505050565b60405163277dcadd60e01b8152339063277dcadd906129af90879087908790879060040161563d565b6002805460ff60c81b1916600160c81b60ff8416908102919091179091556040519081527f3a6271b36c1b44bd6a0a0d56230602dc6919b7c17af57254306fadf5fee69dc39060200161307d565b6005546001600160681b0380821691600160681b90041680821760000361375757505050565b4260d081901b60055560008061376e8585886148af565b600c80546001600160801b038082168590038116600160801b9283900482168590039091169091026001600160801b03191617905560405163aa6b14bb60e01b808252929450909250612bf391906001600160a01b0389169063aa6b14bb90612d74908790879060040161562f565b600680546001600160a01b0319166001600160a01b0383161790556040517f27a3944eff2135a57675f17e72501038982b73620d01f794c72e93d61a3932a29061307d90839061565d565b600780546001600160a01b0319166001600160a01b0383161790556040517fb0b573c1f636e1f8bd9b415ba6c04d6dd49100bc25493fc6305b65ec0e581df39061307d90839061565d565b6009805462ffffff60b01b1916600160b01b62ffffff841602179055604051600282900b81527f01413b1d5d4c359e9a0daa7909ecda165f6e8c51fe2ff529d74b22a5a7c026459060200161307d565b60006401000276a36001600160a01b03831610806138fe575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b03831610155b1561391c576040516355cf1e2360e01b815260040160405180910390fd5b600160201b600160c01b03602083901b166001600160801b03811160071b81811c6001600160401b03811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106139ae57607f810383901c91506139b8565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c6001603f1b161760c19b909b1c6001603e1b169a909a1760c29990991c6001603d1b169890981760c39790971c6001603c1b169690961760c49590951c6001603b1b169490941760c59390931c6001603a1b169290921760c69190911c600160391b161760c79190911c600160381b161760c89190911c600160371b161760c99190911c600160361b161760ca9190911c600160351b161760cb9190911c600160341b161760cc9190911c600160331b161760cd9190911c600160321b1617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b14613b8657886001600160a01b0316613b6b82613d1d565b6001600160a01b03161115613b805781613b88565b80613b88565b815b9998505050505050505050565b6006546001600160a01b0316613ba85750565b6006546040516318dbf60160e21b8082523360048301526001600160a01b038481166024840152610e0893919291169063636fd80490604401612d74565b60008060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166325b355d66040518163ffffffff1660e01b8152600401606060405180830381865afa158015613c49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c6d91906158c4565b925092509250909192565b613c826040613579565b15611bdf5760065460405163416eb29160e11b8082523360048301526001600160a01b038581166024840152600285900b6044840152611bdf9391929116906382dd652290606401612d74565b6006546001600160a01b0316331490565b6001600160e01b031982811690821614611bdf5760405163d3f5153b60e01b81526001600160e01b03198216600482015260240160405180910390fd5b6000600282900b60171d62ffffff818401821816620d89e8811115613d5557604051633c10250f60e01b815260040160405180910390fd5b600160801b6001821615613d7657506ffffcb933bd6fad37aa2d162d1a5940015b6002821615613d95576ffff97272373d413259a46990580e213a0260801c5b6004821615613db4576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615613dd3576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615613df2576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615613e11576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615613e30576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615613e4f576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615613e6f576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615613e8f576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615613eaf576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615613ecf576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615613eef576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615613f0f576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615613f2f576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615613f4f576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615613f70576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615613f90576e5d6af8dedb81196699c329225ee6040260801c5b620400008210613fd65762040000821615613fb9576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615613fd6576b048a170391f7dc42444e8fa20260801c5b60008560020b1315613fe757600019045b63ffffffff0160201c949350505050565b6000806000806154518a61400e57614969614012565b6149785b9050600087126140e657600061403b8888620f42400362ffffff16620f424062ffffff16613331565b905061404c8a8c8b8563ffffffff16565b945084811061407957899550614072858862ffffff1689620f42400362ffffff1661347c565b92506140bf565b6140858b8a838f614987565b9550856001600160a01b03168a6001600160a01b0316036140a8576140a8615906565b6140b7868c8b8563ffffffff16565b945084880392505b6140de868c8b8f6140d2576149a06140d6565b6149af5b63ffffffff16565b9350506141b8565b6154518b6140f6576149a06140fa565b6149af5b905061410b8a8c8b8463ffffffff16565b93508760000397506000881215614135576040516334cb3a0160e11b815260040160405180910390fd5b83881061414457899550614189565b6141508b8a8a8f6149be565b9550856001600160a01b03168a6001600160a01b03161461417d5761417a868c8b8463ffffffff16565b93505b87841115614189578793505b614198868c8b8563ffffffff16565b94506141b4858862ffffff1689620f42400362ffffff1661347c565b9250505b509650965096509692505050565b8082038281131560008312151461358e57600080fd5b8181018281121560008312151461358e57600080fd5b600082158061421357505081810281838281614210576142106154df565b04145b61358e57600080fd5b600283810b60009081526020869052604090206003810180548284018054870390558403905560010154600f81900b91600160801b8204810b91600160981b9004900b9450945094915050565b60008082600f0b12156142ab57508082016001600160801b03808416908216106142a6576040516302603ee960e31b815260040160405180910390fd5b61358e565b826001600160801b03168284019150816001600160801b0316101561358e57604051634cba017960e11b815260040160405180910390fd5b600060405163a9059cbb60e01b6000526001600160a01b03841660045282602452602060006044600080895af19150813d1560203d14600160005114161716915080604052508061434757604051637232c81f60e11b815260040160405180910390fd5b50505050565b6000806000806143608b8b8b8a8c6149ce565b90965094509092509050838317156143f75784156143d4576005805463ffffffff60d01b1916600160d01b63ffffffff89160217905560065460405163aa6b14bb60e01b8082526143cf9290916001600160a01b039091169063aa6b14bb90612d74908990899060040161562f565b612079565b6004805463ffffffff60d01b1916600160d01b63ffffffff891602179055612079565b6001600160681b03828217161561207957841561444957600580546001600160d01b031916600160681b6001600160681b03848116919091026001600160681b03191691909117908416179055612079565b600480546001600160d01b031916600160681b6001600160681b03938416026001600160681b0319161792909116919091179055909890975095505050505050565b806001600160801b03811681146135f357600080fd5b620f424062ffffff821610610e08576040516315b2afa960e01b815260040160405180910390fd5b600286900b60009081526020889052604081208054826144e98289614269565b6001600160801b031690506d09745258e83de0d0f4e400fce799811115614523576040516312dc1b2560e11b815260040160405180910390fd5b6001830154600f0b856145475788600f0b81600f0b61454291906156aa565b614559565b88600f0b81600f0b614559919061568a565b6001850180546001600160801b0319166001600160801b03929092169190911790558184558115945060008390036145ab57841594508960020b8b60020b136145ab5760038401879055600284018890555b50505050979650505050505050565b600285810b60008181526020899052604080822088850b83529082209193849391929184918291908a900b126145fb5750506002820154600383015461460e565b8360020154880391508360030154870390505b6000808b60020b8b60020b121561463057505060028301546003840154614643565b84600201548a0391508460030154890390505b92909803979097039b96909503949094039850939650505050505050565b8354600f84900b60000361468b57806001600160801b03166000036146865750614347565b6146a1565b6146958185614269565b6001600160801b031685555b6001850154600286015460008583146146d857600188018690556146d58387036001600160801b038616600160801b613331565b90505b600085831461470557600289018690556147028387036001600160801b038716600160801b613331565b90505b6001600160801b03828217161561474b57600389018054600160801b6001600160801b03808316860181166001600160801b031990931683178290048116850116021790555b505050505050505050565b60095463010000008104600290810b919081900b90600160c81b900463ffffffff1682828289156147975761478f8c898386868c614ada565b919450925090505b88156147b3576147ab8b898386868c614ada565b919450925090505b8260020b8660020b1415806147ce57508160020b8560020b14155b806147e557508363ffffffff168163ffffffff1614155b15614831576009805462ffffff80861663010000000265ffffffffffff1963ffffffff8616600160c81b021665ffffffffffff63ffffffff60c81b011990931692909217908516171790555b505050505050505050505050565b60008082600f0b12156148675761485f61157c8585856000036000614bcf565b600003614877565b61487761157c8585856001614bcf565b949350505050565b60008082600f0b121561489f5761485f61157c8585856000036000614c6a565b61487761157c8585856001614c6a565b60008084156148e3576148e37f00000000000000000000000000000000000000000000000000000000000000008487612976565b8315614914576149147f00000000000000000000000000000000000000000000000000000000000000008486612976565b8484171561496057826001600160a01b03167f1656ab6fb55adcbed3f1f85c025a5c427075a045777606fbe152783e3e7ca398868660405161495792919061562f565b60405180910390a25b50929391925050565b60006148778385846001614c6a565b60006148778484846001614bcf565b6000614997858585856001614cd1565b95945050505050565b60006148778385846000614bcf565b60006148778484846000614c6a565b6000614997858585856000614cd1565b600080808088881715614a7c5784546001600160681b038082169160681c166149f78b8361546f565b9150614a038a8261546f565b9050617080614a188a63ffffffff42166154a5565b101580614a2b57506001600160681b0382115b80614a3c57506001600160681b0381115b15614a6b578754600080614a518585856148af565b6000808d559a508a99509097509550614ace945050505050565b909450925060009150819050614ace565b617080614a8f8863ffffffff42166154a5565b10614ac15784546001600160681b038082169160681c1680821715614abe578754600080614a518585856148af565b50505b5060009250829150819050805b95509550955095915050565b60008060008315614b2457600080614af360038c614eef565b915091508a60020b8860020b03614b0c57819750614b1d565b8a60020b8760020b03614b1d578096505b5050614bad565b6000808a60020b8860020b128015614b4157508a60020b8760020b135b15614b6a57508690508560028a810b908c900b1315614b62578a9650614b9d565b8a9750614b9d565b614b786008600a8b8e615045565b600281810b600090815260036020526040902060010154600160801b9004900b925090505b614baa60038c84846150fa565b50505b6000614bbd6008600a8a8d6151f0565b969a9599509597509395505050505050565b60006001600160a01b0385850381169085168110614bec57600080fd5b600160601b600160e01b03606085901b1683614c3357866001600160a01b0316614c208383896001600160a01b0316613331565b81614c2d57614c2d6154df565b04614c5f565b614c5f614c4a8383896001600160a01b031661347c565b886001600160a01b0316808204910615150190565b979650505050505050565b6000846001600160a01b0316846001600160a01b03161015614c8b57600080fd5b6001600160a01b038585031682614cb957614cb481856001600160801b0316600160601b613331565b6131d9565b6131d981856001600160801b0316600160601b61347c565b6000856001600160a01b0316600003614ce957600080fd5b846001600160801b0316600003614cff57600080fd5b83600003614d0e575084614997565b81151583151503614e0a57600160601b600160e01b03606086901b168215614db8576001600160a01b03871685810290868281614d4d57614d4d6154df565b0403614d7d57818101828110614d7b57614d71838a6001600160a01b03168361347c565b9350505050614997565b505b614daf82614da4888b6001600160a01b03168681614d9d57614d9d6154df565b0490615237565b808204910615150190565b92505050614997565b6001600160a01b03871685810290868281614dd557614dd56154df565b0414614de057600080fd5b808211614dec57600080fd5b614daf614e05838a6001600160a01b031684860361347c565b615247565b8115614e7757614e70614e056001600160a01b03861115614e4257614e3d86600160601b896001600160801b0316613331565b614e60565b6001600160801b038716606087901b81614e5e57614e5e6154df565b045b6001600160a01b03891690615237565b9050614997565b60006001600160a01b03851115614ea557614ea085600160601b886001600160801b031661347c565b614ec2565b614ec2606086901b6001600160801b038816808204910615150190565b905080876001600160a01b031611614ed957600080fd5b6001600160a01b03871603905095945050505050565b600281810b60008181526020859052604081206001810180548383556001600160b01b03198116909155818501839055600390910191909155600160801b8104830b92600160981b909104900b90620d89e7191480614f5f5750614f56620d89e719615750565b60020b8360020b145b15614fb857600283900b6000908152602085905260409020600101805462ffffff808516600160801b0262ffffff60801b19918516600160981b029190911665ffffffffffff60801b199092169190911717905561503e565b8060020b8260020b03614fde57604051630d6e094960e01b815260040160405180910390fd5b600282810b6000908152602086905260408082206001908101805462ffffff808816600160981b0262ffffff60981b19909216919091179091559385900b83529120018054918416600160801b0262ffffff60801b199092169190911790555b9250929050565b600190810190600090600883811d610d8a01901c90829061ffff83161b851663ffffffff16156150a857615079878561525d565b9094509092509050801561508e575050614877565b61509f86610d8b840160010b61525d565b90945090925090505b806150eb576150c68563ffffffff168360010193508360010b61528e565b9093509050806150de5750620d89e891506148779050565b6150e886846153d7565b92505b614c5f87610d891985016153d7565b600283900b620d89e71914806151215750615118620d89e719615750565b60020b8360020b145b614347578260020b8260020b12801561513f57508260020b8160020b135b61515c5760405163e45ac17d60e01b815260040160405180910390fd5b600283810b600090815260209590955260408086206001908101805465ffffffffffff60801b1916600160981b62ffffff878116820262ffffff60801b1990811693909317600160801b8a831681029190911790945597860b8a52848a208401805462ffffff60981b191698909916908102979097179097559390920b865290942090930180549092169202919091179055565b816000806151fe8785615403565b91509150811561522d5761521986610d8a830160010b615403565b9092509050811561522d576001811b831892505b5050949350505050565b8082018281101561358e57600080fd5b806001600160a01b03811681146135f357600080fd5b600881901d600181900b6000908152602084905260408120548190615282908561528e565b93969095509293505050565b60008060ff831684811c8083036152aa578460ff1793506153ce565b7f555555555555555555555555555555555555555555555555555555555555555560008290038216908116156001600160801b0382161560071b176001600160401b03600160801b03600160c01b0382161560061b177bffffffff00000000ffffffff00000000ffffffff00000000ffffffff82161560051b177dffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff82161560041b177eff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff82161560031b177f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f82161560021b177f33333333333333333333333333333333333333333333333333333333333333339091161560011b1760ff1685019350600192505b50509250929050565b600181900b600090815260208390526040902054600882901b906153fb908261528e565b509392505050565b600881901d600181810b60009081526020949094526040909320805460ff9093169390931b80831890935591811490151891565b604051806040016040528060008152602001600081525090565b610d8a61591c565b634e487b7160e01b600052601160045260246000fd5b8082018082111561358e5761358e615459565b6000600f82900b6001607f1b810161549c5761549c615459565b60000392915050565b8181038181111561358e5761358e615459565b6001600160801b038181168382160190808211156154d8576154d8615459565b5092915050565b634e487b7160e01b600052601260045260246000fd5b805161ffff811681146135f357600080fd5b60006020828403121561551957600080fd5b613208826154f5565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6001600160a01b03898116825288811660208301528715156040830152606082018790528516608082015283151560a082015260e060c082018190526000906155979083018486615522565b9a9950505050505050505050565b80516001600160e01b0319811681146135f357600080fd5b805162ffffff811681146135f357600080fd5b6000806000606084860312156155e557600080fd5b6155ee846155a5565b92506155fc602085016155bd565b915061560a604085016155bd565b90509250925092565b62ffffff8181168382160190808211156154d8576154d8615459565b918252602082015260400190565b8481528360208201526060604082015260006131d9606083018486615522565b6001600160a01b0391909116815260200190565b60006020828403121561568357600080fd5b5051919050565b81810360008312801583831316838312821617156154d8576154d8615459565b80820182811260008312801582168215821617156156ca576156ca615459565b505092915050565b6001600160a01b038a8116825289811660208301528815156040830152606082018890528616608082015260a0810185905260c0810184905261010060e082018190526000906157258382018587615522565b9c9b505050505050505050505050565b60006020828403121561574757600080fd5b613208826155a5565b60008160020b627fffff19810361549c5761549c615459565b6001600160a01b03888116825287166020820152600286810b604083015285900b6060820152600f84900b608082015260c060a08201819052600090613b889083018486615522565b600080604083850312156157c557600080fd5b6157ce836155a5565b91506157dc602084016155bd565b90509250929050565b600061010060018060a01b03808d168452808c166020850152508960020b60408401528860020b606084015287600f0b60808401528660a08401528560c08401528060e08401526157258184018587615522565b6001600160a01b03878116825286166020820152604081018590526060810184905260a0608082018190526000906158749083018486615522565b98975050505050505050565b600060018060a01b03808b168352808a166020840152508760408301528660608301528560808301528460a083015260e060c083015261559760e083018486615522565b6000806000606084860312156158d957600080fd5b6158e2846154f5565b925060208401518060020b81146158f857600080fd5b915061560a604085016154f5565b634e487b7160e01b600052600160045260246000fd5b634e487b7160e01b600052605160045260246000fdfea164736f6c6343000814000a
Deployed ByteCode
0x608060405234801561001057600080fd5b50600436106101e35760003560e01c8063050a4d21146101e85780630902f1ac146102135780630dfe16811461025a578063128acb081461029d5780631a6865021461034a5780631dd19cb414610380578063240a875a1461038a5780633b3bc70e146103ab578063490e6cbc1461043d5780634f1eb3d8146104c7578063514ea4bf1461051857806353e97868146105a2578063578b9a36146105b55780636378ae44146105e557806370cf754a146106005780637bd78025146106155780638380edb7146106315780638e0055531461065257806397ce1c51146106735780639e4e0227146106d4578063a1eded8714610771578063a5e5eeae1461078d578063aafe29c0146107a4578063bca57f8114610876578063c00a461114610896578063c45a0155146108ad578063c677e3e0146108d4578063cc1f97cf14610901578063d0c93a7c14610927578063d21220a71461093b578063d5c35a7e14610962578063d8544cf31461096f578063d861903714610995578063ddca3f43146109c2578063e76c01e4146109e1578063ecdecf4214610a76578063ef01df4f14610a7f578063f085a61014610a92578063f30dba9314610ab2578063f637731d14610b4c578063fff6cae914610b72575b600080fd5b6009546101fc906301000000900460020b81565b6040805160029290920b8252519081900360200190f35b600c546001600160801b0380821691600160801b9004165b60405180836001600160801b03168152602001826001600160801b031681526020019250505060405180910390f35b6102817f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f0781565b604080516001600160a01b039092168252519081900360200190f35b610331600480360360a08110156102b357600080fd5b6001600160a01b0382358116926020810135151592604082013592606083013516919081019060a081016080820135600160201b8111156102f357600080fd5b82018360208201111561030557600080fd5b803590602001918460018302840111600160201b8311171561032657600080fd5b509092509050610b7a565b6040805192835260208301919091528051918290030190f35b60095461036490600160301b90046001600160801b031681565b604080516001600160801b039092168252519081900360200190f35b610388610d69565b005b610388600480360360208110156103a057600080fd5b503561ffff16610d8c565b610331600480360360808110156103c157600080fd5b8135600290810b92602081013590910b916001600160801b036040830135169190810190608081016060820135600160201b8111156103ff57600080fd5b82018360208201111561041157600080fd5b803590602001918460018302840111600160201b8311171561043257600080fd5b509092509050610e0b565b6103886004803603608081101561045357600080fd5b6001600160a01b038235169160208101359160408201359190810190608081016060820135600160201b81111561048957600080fd5b82018360208201111561049b57600080fd5b803590602001918460018302840111600160201b831117156104bc57600080fd5b50909250905061103f565b61022b600480360360a08110156104dd57600080fd5b506001600160a01b03813516906020810135600290810b91604081013590910b906001600160801b036060820135811691608001351661123c565b61056b6004803603602081101561052e57600080fd5b50600b60205235600090815260409020805460018201546002830154600390930154919290916001600160801b0380821691600160801b90041685565b604080519586526020860194909452848401929092526001600160801b039081166060850152166080830152519081900360a00190f35b600754610281906001600160a01b031681565b6009546105cc90600160c81b900463ffffffff1681565b6040805163ffffffff9092168252519081900360200190f35b6105ee60005481565b60408051918252519081900360200190f35b6103646d09745258e83de0d0f4e400fce79981565b6004546001600160681b0380821691600160681b90041661022b565b600254600160e01b900460ff16604080519115158252519081900360200190f35b6103886004803603602081101561066857600080fd5b503561ffff166113f8565b61067b611482565b604080516001600160a01b039098168852600296870b602089015261ffff9095168786015260ff90931660608701526001600160801b039091166080860152830b60a085015290910b60c0830152519081900360e00190f35b610331600480360360c08110156106ea57600080fd5b6001600160a01b0382358116926020810135821692604082013515159260608301359260808101359091169181019060c0810160a0820135600160201b81111561073357600080fd5b82018360208201111561074557600080fd5b803590602001918460018302840111600160201b8311171561076657600080fd5b509092509050611515565b6005546001600160681b0380821691600160681b90041661022b565b6004546105cc90600160d01b900463ffffffff1681565b61084f600480360360c08110156107ba57600080fd5b6001600160a01b0382358116926020810135909116916040820135600290810b92606081013590910b916001600160801b03608083013516919081019060c0810160a0820135600160201b81111561081157600080fd5b82018360208201111561082357600080fd5b803590602001918460018302840111600160201b8311171561084457600080fd5b5090925090506117f5565b6040805193845260208401929092526001600160801b031682820152519081900360600190f35b6103886004803603602081101561088c57600080fd5b503560ff16611b8c565b6005546105cc90600160d01b900463ffffffff1681565b6102817f000000000000000000000000ef72cbccf4a807dfa1fbecd61ddb488ff8a05fa381565b6105ee600480360360208110156108ea57600080fd5b5060086020523560010b6000908152604090205481565b6103886004803603602081101561091757600080fd5b50356001600160a01b0316611be3565b6009546101fc90600160b01b900460020b81565b6102817f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b1181565b6009546101fc9060020b81565b6103886004803603602081101561098557600080fd5b50356001600160a01b0316611c62565b6105ee600480360360208110156109ab57600080fd5b50600a6020523560010b6000908152604090205481565b6109ca611d0c565b6040805161ffff9092168252519081900360200190f35b60028054610a2c916001600160a01b03821691600160a01b810490910b9061ffff600160b81b820481169160ff600160c81b8204811692600160d01b83041691600160e01b90041686565b604080516001600160a01b03909716875260029590950b602087015261ffff9384168686015260ff90921660608601529091166080840152151560a0830152519081900360c00190f35b6105ee60015481565b600654610281906001600160a01b031681565b61038860048036036020811015610aa857600080fd5b503560020b611da8565b610b1060048036036020811015610ac857600080fd5b50600360208190529035600290810b600090815260409020805460018201548284015492909401549093600f81900b93600160801b8204810b93600160981b909204900b9186565b60408051968752600f9590950b6020870152600293840b868601529190920b6060850152608084019190915260a0830152519081900360c00190f35b61038860048036036020811015610b6257600080fd5b50356001600160a01b0316611e11565b610388611f33565b600080600080610b908a8a8a8a60008b8b611f55565b91509150610b9c612089565b610ba4615437565b610bb183838c8c8c6120c2565b94995092975092935060009250829150610bcb905061274b565b915091508b15610c66576000861215610c0c57610c0c7f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b118e88600003612976565b610c1887878b8b612986565b610c206129e7565b610c2a888461546f565b1115610c4957604051633ed6d50560e21b815260040160405180910390fd5b610c6187878560000151600087602001516000612a77565b610cf2565b6000871215610c9d57610c9d7f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f078e89600003612976565b610ca987878b8b612986565b610cb1612bfb565b610cbb878361546f565b1115610cda57604051633ed6d50560e21b815260040160405180910390fd5b610cf287876000866000015160008860200151612a77565b610d418d8888600260000160009054906101000a90046001600160a01b0316600960069054906101000a90046001600160801b0316600260000160149054906101000a900460020b8b8b612c4a565b505050610d4c612cfd565b610d5c8a8a8a8a88888c8c612d12565b5050965096945050505050565b610d71612dc7565b610d79612089565b610d8233612df2565b610d8a612cfd565b565b610d94612f41565b610d9c612f6b565b6103e861ffff82161180610dbf575060025461ffff828116600160d01b90920416145b80610de1575061ffff811615801590610de157506007546001600160a01b0316155b15610dff5760405163a709b9af60e01b815260040160405180910390fd5b610e0881613031565b50565b6000808686610e1a8282613088565b60016001607f1b036001600160801b0388161115610e4b57604051638995290f60e01b815260040160405180910390fd5b6000610e5688615482565b90506000610e68338c8c858c8c61310a565b9050610e72612089565b610e7a61274b565b50506000610e89338d8d6131e3565b9050610e97818d8d8661320f565b909750955062ffffff821615610f0d576000808815610ed257610ec38962ffffff8616620f4240613331565b9150610ecf828a6154a5565b98505b8715610efa57610eeb8862ffffff8616620f4240613331565b9050610ef781896154a5565b97505b610f0a6000806000808686612a77565b50505b86861715610f72576003810154610f2e9088906001600160801b03166154b8565b6003820154610f4e908890600160801b90046001600160801b03166154b8565b6001600160801b039182169116600160801b026001600160801b0319161760038201555b506001600160801b0389168617851715611019576040805162ffffff83168152905133917f1a25098b7a731ae33ed362388b593b876963dfde0efb4db9c0befeed637ff26b919081900360200190a2604080516001600160801b038b16815260208101889052808201879052905160028c810b92908e900b9133917f0c396cd989a39f4459b5fa1aed6a9a8dcdbc45908acfd67e028cd568da98982c919081900360600190a45b611021612cfd565b611031338c8c858a8a8e8e6133ca565b505050509550959350505050565b61104c858585858561342c565b611054612089565b60008060008061106261274b565b9092509050600088156110ab5761107e896064620f424061347c565b90506110ab7f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f078b8b612976565b600088156110ef576110c2896064620f424061347c565b90506110ef7f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b118c8b612976565b6110fb82828a8a6134fc565b6111036129e7565b955085611110838661546f565b111561112f576040516336de50ff60e11b815260040160405180910390fd5b611137612bfb565b945084611144828561546f565b11156111635760405163c998149f60e01b815260040160405180910390fd5b60025495849003959483900394600160d01b900461ffff1680156111c357600087156111995761119688836103e8613331565b90505b600087156111b1576111ae88846103e8613331565b90505b6111c082828484600080612a77565b50505b604080518c8152602081018c90528082018990526060810188905290516001600160a01b038e169133917fbdbdb71d7860376ba52b25a5028beea23581364a40522f6bcfb86bb1f2dca6339181900360800190a35050505050611224612cfd565b61123387878785858989613525565b50505050505050565b600080611247612089565b60006112543388886131e3565b60038101549091506001600160801b0380821691600160801b9004811690871682101561127f578196505b806001600160801b0316866001600160801b0316111561129d578095505b6001600160801b0387871716156113e3576001600160801b0387830381168783038216600160801b026001600160801b031916176003850155879550869450851615611317576113177f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f078b876001600160801b0316612976565b6001600160801b0384161561135a5761135a7f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b118b866001600160801b0316612976565b611382856001600160801b0316600003856001600160801b0316600003600080600080612a77565b604080516001600160a01b038c1681526001600160801b038088166020830152861681830152905160028a810b92908c900b9133917f70935338e69775456a85ddef226c395fb668b63fa0115f5f20610b388e6ca9c0919081900360600190a45b6113eb612cfd565b5050509550959350505050565b611400612f6b565b600254600160e01b900460ff1661142a57604051636798480960e11b815260040160405180910390fd5b6114346080613579565b15611452576040516369cdc70760e11b815260040160405180910390fd5b620f42408161ffff1610611479576040516315b2afa960e01b815260040160405180910390fd5b610e0881613594565b600280546001600160a01b03811691600160a01b8204900b9061ffff600160b81b8204169060ff600160c81b820481169160009182918291600160e01b90910416806114e157604051636798480960e11b815260040160405180910390fd5b505060095495969495939492936001600160801b03600160301b82041693600282810b9450630100000090920490910b9150565b600080600086121561153a576040516334cb3a0160e11b815260040160405180910390fd5b611542612089565b6000871561159b5760006115546129e7565b90506115638860008888612986565b600061156d6129e7565b905061158161157c83836154a5565b6135e4565b9250611594836000806000806000612a77565b50506115e3565b60006115a5612bfb565b90506115b46000898888612986565b60006115be612bfb565b90506115cd61157c83836154a5565b92506115e0600084600080600080612a77565b50505b8681146115ee578096505b508560000361161057604051633ed6d50560e21b815260040160405180910390fd5b611618612cfd565b60008061162b8a8a8a8a60018b8b611f55565b91509150611637612089565b61163f61274b565b5050611649615437565b61165683838c8c8c6120c2565b949950929750929350508b1591506116ff90505760008412156116a1576116a17f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b118c86600003612976565b8489038986146116d6576116d67f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f078e83612976565b6116f96116e2826135e4565b600003868460000151600086602001516000612a77565b50611790565b6000851215611736576117367f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f078c87600003612976565b83890389851461176b5761176b7f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b118e83612976565b61178e86611778836135e4565b6000036000856000015160008760200151612a77565b505b600280546009546117ce928e92899289926001600160a01b03831692600160301b9092046001600160801b031691600160a01b9004900b8989612c4a565b6117d6612cfd565b6117e68b8b8b8b89898d8d612d12565b50505097509795505050505050565b600080600087876118068282613088565b876001600160801b03166000036118305760405163e6ace6df60e01b815260040160405180910390fd5b61184f8b8b8b6118488c6001600160801b03166135f8565b8b8b61310a565b50611858612089565b60028054600160a01b810490910b906001600160a01b031660008190036118925760405163812eb65560e01b815260040160405180910390fd5b600954600160b01b9004600290810b9081908d900b816118b4576118b46154df565b078160020b8e60020b816118ca576118ca6154df565b071760020b156118ed57604051635f6e14f360e01b815260040160405180910390fd5b5061190c8c8c6119058d6001600160801b03166135f8565b858561360b565b5090975095506000915081905061192161274b565b9150915061193187878b8b6136ba565b861561194f57816119406129e7565b61194a91906154a5565b611952565b60005b915085156119725780611963612bfb565b61196d91906154a5565b611975565b60005b90508682101561199a576119938a6001600160801b03168389613331565b945061199e565b8994505b858110156119de5760006119bc8b6001600160801b03168389613331565b9050856001600160801b0316816001600160801b031610156119dc578095505b505b846001600160801b0316600003611a0857604051632fae8a9b60e21b815260040160405180910390fd5b6000611a158e8e8e6131e3565b9050611a34818e8e611a2f8a6001600160801b03166135f8565b61320f565b90985096505086821080611a4757508581105b15611a6557604051633ed6d50560e21b815260040160405180910390fd5b86821115611a9a57611a9a7f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f078f898503612976565b85811115611acf57611acf7f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b118f888403612976565b611adf8787600080600080612a77565b8a60020b8c60020b8e6001600160a01b03167f7a53080ba414158be7ec69b987b5fb7d07dee101fe85488f0853ae16239d0bde33898c8c60405180856001600160a01b03168152602001846001600160801b0316815260200183815260200182815260200194505050505060405180910390a4611b5a612cfd565b611b7b8d8d8d611b72896001600160801b03166135f8565b8b8b8f8f6133ca565b505050509750975097945050505050565b611b94612f41565b6006546001600160a01b031680611bbe57604051639e727ce360e01b815260040160405180910390fd5b336001600160a01b03821614611bd657611bd6612f6b565b611bdf826136e3565b5050565b611beb612f41565b611bf3612f6b565b6006546005546001600160a01b03909116906001600160681b03808216600160681b909204161715611c4f576001600160a01b038116611c4657604051638ec9444160e01b815260040160405180910390fd5b611c4f81613731565b611c5960006136e3565b611bdf826137dd565b611c6a612f41565b336001600160a01b037f000000000000000000000000ef72cbccf4a807dfa1fbecd61ddb488ff8a05fa31614611ca257611ca2612f6b565b6001600160a01b038116611d03576004546001600160681b03808216600160681b909204161715611ce65760405163b8856c0b60e01b815260040160405180910390fd5b600254600160d01b900461ffff1615611d0357611d036000613031565b610e0881613828565b600254600160b81b900461ffff16611d246080613579565b15611da557600660009054906101000a90046001600160a01b03166001600160a01b031663f70d93626040518163ffffffff1660e01b8152600401602060405180830381865afa158015611d7c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611da09190615507565b905090565b90565b611db0612f41565b611db8612f6b565b60008160020b131580611dd057506101f4600282900b135b80611dea5750600954600282810b600160b01b909204900b145b15611e0857604051632bf827d160e21b815260040160405180910390fd5b610e0881613873565b6000611e1c826138c3565b6002549091506001600160a01b031615611e4957604051631499a6b760e21b815260040160405180910390fd5b600280546001600160a01b0384166001600160b81b03199091168117600160a01b62ffffff851602178255604080519182529183900b602082015281517f98636036cb66a9c19a37435efc1e90142190214e8abeb821bdba3f2990dd4c95929181900390910190a1611eba82613b95565b6000806000611ec7613be6565b925092509250611ed681613594565b611edf82613873565b61ffff831615801590611efb57506007546001600160a01b0316155b15611f195760405163a709b9af60e01b815260040160405180910390fd5b611f2283613031565b611f2c8585613c78565b5050505050565b611f3b612dc7565b611f43612089565b611f4b61274b565b5050610d8a612cfd565b6002546000908190600160c81b900460ff16611f7381600116151590565b1561207b57611f80613ccf565b15611f9257600080925092505061207d565b60065460405163029c1cb760e01b81526000916001600160a01b03169063029c1cb790611fd19033908f908f908f908f908f908f908f9060040161554b565b6060604051808303816000875af1158015611ff0573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061201491906155d0565b9095509350905060808216158015612040575060008462ffffff161180612040575060008362ffffff16115b1561205e57604051633a4528ef60e01b815260040160405180910390fd5b6120796001600160e01b0319821663029c1cb760e01b613ce0565b505b505b97509795505050505050565b600254600160e01b900460ff166120b357604051636798480960e11b815260040160405180910390fd5b6002805460ff60e01b19169055565b60008060008060006120d2615437565b876000036120f3576040516301e76e6160e61b815260040160405180910390fd5b600160ff1b8803612117576040516334cb3a0160e11b815260040160405180910390fd5b6040805161016081018252600060208201819052606082018190526080820181905260a0820181905262ffffff8d16610140830152808b1360c08301529181018a9052600954600281810b61012084015263010000008204810b610100840152805461ffff600160d01b820481168552600160b81b82041660e08501526001600160a01b0381169850600160a01b9004900b9550600160301b90046001600160801b03169350908590036121de5760405163812eb65560e01b815260040160405180910390fd5b62ffffff8c1615612226576121f38b8d615613565b62ffffff1660e08201819052620f424011612221576040516315b2afa960e01b815260040160405180910390fd5b612278565b62ffffff8b1615612278578a8160e0018181516122439190615613565b62ffffff90811690915260e0830151620f42409116109050612278576040516315b2afa960e01b815260040160405180910390fd5b89156122d857846001600160a01b0316886001600160a01b03161015806122ad57506401000276a36001600160a01b03891611155b156122cb57604051631662672360e01b815260040160405180910390fd5b600054608082015261233d565b846001600160a01b0316886001600160a01b0316111580612316575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b03891610155b1561233457604051631662672360e01b815260040160405180910390fd5b60015460808201525b61236f6040518060a0016040528060008152602001600081526020016000815260200160008152602001600081525090565b60008b61238157826101200151612388565b8261010001515b6001600160a01b0388168352905061239f81613d1d565b6001600160a01b03908116602084018190526123dc918e918a918e1611821515146123ce5784602001516123d0565b8c5b888f8860e00151613ff8565b60808601526060850152604084015260c0840151909750156124345761240b82608001518360400151016135e4565b8b039a5061242a61241f83606001516135e4565b6060850151906141c6565b606084015261246c565b61244182606001516135e4565b8b019a5061246661245b83608001518460400151016135e4565b6060850151906141dc565b60608401525b8251156124ae57825160808301516000916103e89161248a916141f2565b81612497576124976154df565b608085018051929091049182900390528551018552505b600083610140015162ffffff161180156124d1575060008360e0015162ffffff16115b156125125760006124fa836080015185610140015162ffffff168660e0015162ffffff16613331565b60808401805182900390526020860180519091019052505b6001600160801b038516156125495761253d8260800151600160801b876001600160801b0316613331565b60808401805190910190525b8160200151876001600160a01b03160361261357826020015161258457600160208401528b61257a5760005461257e565b6001545b60a08401525b60008c156125cb57608084015160a08501516125a59160039185919061421c565b50600290810b61010087015283900b610120860152600019830197506000039050612601565b60a084015160808501516125e49160039185919061421c565b600290810b61012088015284900b61010087015250919650869190505b61260b8682614269565b955050612635565b81516001600160a01b038816146126355761262d876138c3565b95505061265c565b5089158015906126575750886001600160a01b0316866001600160a01b031614155b61236f575b60008a83604001510390508260c0015115158c15151461268157826060015181612688565b8083606001515b600280546001600160b81b031916600160a01b62ffffff8b16026001600160a01b031916176001600160a01b038b161790556020850151919a509850159050612720576101008201516101208301516009805462ffffff92831665ffffffffffff19909116176301000000929093169190910291909117600160301b600160b01b031916600160301b6001600160801b038716021790555b8a1561273357608082015160005561273c565b60808201516001555b50509550955095509550955095565b6000806127566129e7565b61275e612bfb565b90925090506001600160801b0382118061277e57506001600160801b0381115b1561282f576007546001600160a01b03166001600160801b038311156127de576127d37f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f07826002600160801b03198601612976565b6001600160801b0392505b6001600160801b0382111561282d576128227f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b11826002600160801b03198501612976565b6001600160801b0391505b505b600954600160301b90046001600160801b0316600081900361285057509091565b600c546001600160801b0380821691600160801b90041681851181851181806128765750805b1561296d5781156128ae576128a4846001600160801b03168803600160801b876001600160801b0316613331565b6000805490910190555b80156128e1576128d7836001600160801b03168703600160801b876001600160801b0316613331565b6001805490910190555b7fef10ebb00f0dbc72ad4602e94abbbda6f3d40632714f70e9c8fa30d5d44289c98261290e57600061291b565b846001600160801b031688035b82612927576000612934565b846001600160801b031688035b60405161294292919061562f565b60405180910390a16001600160801b03808816908716600160801b026001600160801b03191617600c555b50505050509091565b6129818383836142e3565b505050565b604051636a5ac18f60e01b81523390636a5ac18f906129af90879087908790879060040161563d565b600060405180830381600087803b1580156129c957600080fd5b505af11580156129dd573d6000803e3d6000fd5b5050505050505050565b6040516370a0823160e01b81526000906001600160a01b037f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f0716906370a0823190612a3690309060040161565d565b602060405180830381865afa158015612a53573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611da09190615671565b6000841180612a865750600083115b80612a915750600082115b80612a9c5750600081115b15612b6f576004805460079060009081904290612acd908a908a90600160d01b900463ffffffff168888868861434d565b909350915082821715612b0657612ae3836135e4565b612aed908c61568a565b612af6836135e4565b612b00908c61568a565b909b5099505b6005805490955060069450612b309088908890600160d01b900463ffffffff16888886600161434d565b909350915082821715612b6957612b46836135e4565b612b50908c61568a565b612b59836135e4565b612b63908c61568a565b909b5099505b50505050505b85851715612bf357600c546001600160801b0380821691600160801b9004168715612bb257612ba6612ba189846156aa565b61448b565b6001600160801b031691505b8615612bd157612bc5612ba188836156aa565b6001600160801b031690505b6001600160801b039182169116600160801b026001600160801b03191617600c555b505050505050565b6040516370a0823160e01b81526000906001600160a01b037f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b1116906370a0823190612a3690309060040161565d565b6040805162ffffff808516825283166020820152815133927f9443903d84c9719611bd4bba871daaf18a3950d00d5d78b1a2fa701f76df54ff928290030190a260408051888152602081018890526001600160a01b03878116828401526001600160801b0387166060830152600286900b60808301529151918a169133917fc42079f94a6350d7e6235f29174924f928cc2ac818eb64fed8004e115fbcca67919081900360a00190a35050505050505050565b6002805460ff60e01b1916600160e01b179055565b612d1c6002613579565b156129dd57612d29613ccf565b6129dd57600654604051639cb5a96360e01b8082526129dd9290916001600160a01b0390911690639cb5a96390612d749033908e908e908e908e908e908e908e908e906004016156d2565b6020604051808303816000875af1158015612d93573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612db79190615735565b6001600160e01b03191690613ce0565b6006546001600160a01b03163314610d8a57604051634994c26960e11b815260040160405180910390fd5b600080612dfd6129e7565b612e05612bfb565b600c5491935091506001600160801b0380821691600160801b90041681841180612e375750806001600160801b031683115b15611f2c57816001600160801b0316841115612e8a57612e8a7f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f0786612e856001600160801b038616886154a5565b612976565b806001600160801b0316831115612ed357612ed37f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b1186612e856001600160801b038516876154a5565b6001600160a01b0385167fb94331e4420f16b156f53c397a8adcd09481283ee7830f7b688b22858e9db80b612f116001600160801b038516876154a5565b612f246001600160801b038516876154a5565b604051612f3292919061562f565b60405180910390a25050505050565b600254600160e01b900460ff16610d8a57604051636798480960e11b815260040160405180910390fd5b6040805163e8ae2b6960e01b81527fb73ce166ead2f8e9add217713a7989e4edfba9625f71dfd2516204bb67ad3442600482015233602482015290516001600160a01b037f000000000000000000000000ef72cbccf4a807dfa1fbecd61ddb488ff8a05fa3169163e8ae2b699160448083019260209291908290030181865afa158015612ffc573d6000803e3d6000fd5b505050506040513d602081101561301257600080fd5b5051610d8a57604051634994c26960e11b815260040160405180910390fd5b6002805461ffff60d01b1916600160d01b61ffff8416908102919091179091556040519081527f3647dccc990d4941b0b05b32527ef493a98d6187b20639ca2f9743f3b55ca5e1906020015b60405180910390a150565b613095620d89e719615750565b60020b8160020b13156130bb57604051631445443d60e01b815260040160405180910390fd5b8160020b8160020b136130e15760405163d9a841a760e01b815260040160405180910390fd5b620d89e719600283900b1215611bdf57604051631d1ac7f160e21b815260040160405180910390fd5b60006131166004613579565b156131d957613123613ccf565b15613130575060006131d9565b600654604051632f1208d960e11b81526000916001600160a01b031690635e2411b29061316d9033908c908c908c908c908c908c90600401615769565b60408051808303816000875af115801561318b573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131af91906157b2565b925090506131bc826144a1565b6131d76001600160e01b03198216632f1208d960e11b613ce0565b505b9695505050505050565b62ffffff818116908316601885811b91909117901b176000908152600b602052604090205b9392505050565b6002805460008054600154919384936001600160a01b03811693600160a01b90910490910b918491829190600f89900b1561326b5761325560038c878c868660006144c9565b935061326860038b878c868660016144c9565b92505b60008061327d60038e8e8a88886145ba565b9150915061328d8e8c8484614661565b5050505086600f0b6000146133245781806132a55750805b156132be576132be898984848760008d600f0b12614756565b60006132cd8a8a8a878961360b565b91985096509050600f81900b15613322576009546132fb90600160301b90046001600160801b031689614269565b600960066101000a8154816001600160801b0302191690836001600160801b031602179055505b505b5050505094509492505050565b6000838302816000198587098281108382030391505080841161335357600080fd5b8060000361336657508290049050613208565b8385870960008581038616958690049560026003880281188089028203028089028203028089028203028089028203028089028203028089029091030291819003819004600101858411909403939093029190930391909104170290509392505050565b6133d2613ccf565b6129dd576133e06008613579565b156129dd57600654604051630d68520160e41b8082526129dd9290916001600160a01b039091169063d685201090612d749033908e908e908e908e908e908e908e908e906004016157e5565b6134366010613579565b15611f2c576006546040516346f0547760e11b808252611f2c9290916001600160a01b0390911690638de0a8ee90612d749033908b908b908b908b908b90600401615839565b600083158061349d5750508282028284828161349a5761349a6154df565b04145b156134be57600082116134af57600080fd5b81810490829006151501613208565b6134c9848484613331565b9050600082806134db576134db6154df565b84860911156132085760001981106134f257600080fd5b6001019392505050565b60405163b81ddfc960e01b8152339063b81ddfc9906129af90879087908790879060040161563d565b61352f6020613579565b156112335760065460405163343d37ff60e01b8082526112339290916001600160a01b039091169063343d37ff90612d749033908d908d908d908d908d908d908d90600401615880565b600254600090600160c81b9004821660ff1615155b92915050565b6002805461ffff60b81b1916600160b81b61ffff8416908102919091179091556040519081527f598b9f043c813aa6be3426ca60d1c65d17256312890be5118dab55b0775ebe2a9060200161307d565b8060008112156135f357600080fd5b919050565b806000600f82900b12156135f357600080fd5b60008060008061361a89613d1d565b9050600061362789613d1d565b90506000808b60020b8960020b121561364c5761364584848c61483f565b915061368a565b8a60020b8960020b121561367c5761366588848c61483f565b915061367284898c61487f565b905089945061368a565b61368784848c61487f565b90505b60008a600f0b1261369c5781816136a5565b81600003816000035b909d909c50949a509398505050505050505050565b60405163277dcadd60e01b8152339063277dcadd906129af90879087908790879060040161563d565b6002805460ff60c81b1916600160c81b60ff8416908102919091179091556040519081527f3a6271b36c1b44bd6a0a0d56230602dc6919b7c17af57254306fadf5fee69dc39060200161307d565b6005546001600160681b0380821691600160681b90041680821760000361375757505050565b4260d081901b60055560008061376e8585886148af565b600c80546001600160801b038082168590038116600160801b9283900482168590039091169091026001600160801b03191617905560405163aa6b14bb60e01b808252929450909250612bf391906001600160a01b0389169063aa6b14bb90612d74908790879060040161562f565b600680546001600160a01b0319166001600160a01b0383161790556040517f27a3944eff2135a57675f17e72501038982b73620d01f794c72e93d61a3932a29061307d90839061565d565b600780546001600160a01b0319166001600160a01b0383161790556040517fb0b573c1f636e1f8bd9b415ba6c04d6dd49100bc25493fc6305b65ec0e581df39061307d90839061565d565b6009805462ffffff60b01b1916600160b01b62ffffff841602179055604051600282900b81527f01413b1d5d4c359e9a0daa7909ecda165f6e8c51fe2ff529d74b22a5a7c026459060200161307d565b60006401000276a36001600160a01b03831610806138fe575073fffd8963efd1fc6a506488495d951d5263988d266001600160a01b03831610155b1561391c576040516355cf1e2360e01b815260040160405180910390fd5b600160201b600160c01b03602083901b166001600160801b03811160071b81811c6001600160401b03811160061b90811c63ffffffff811160051b90811c61ffff811160041b90811c60ff8111600390811b91821c600f811160021b90811c918211600190811b92831c979088119617909417909217179091171717608081106139ae57607f810383901c91506139b8565b80607f0383901b91505b908002607f81811c60ff83811c9190911c800280831c81831c1c800280841c81841c1c800280851c81851c1c800280861c81861c1c800280871c81871c1c800280881c81881c1c800280891c81891c1c8002808a1c818a1c1c8002808b1c818b1c1c8002808c1c818c1c1c8002808d1c818d1c1c8002808e1c9c81901c9c909c1c80029c8d901c9e9d607f198f0160401b60c09190911c6001603f1b161760c19b909b1c6001603e1b169a909a1760c29990991c6001603d1b169890981760c39790971c6001603c1b169690961760c49590951c6001603b1b169490941760c59390931c6001603a1b169290921760c69190911c600160391b161760c79190911c600160381b161760c89190911c600160371b161760c99190911c600160361b161760ca9190911c600160351b161760cb9190911c600160341b161760cc9190911c600160331b161760cd9190911c600160321b1617693627a301d71055774c8581026f028f6481ab7f045a5af012a19d003aa9198101608090811d906fdb2df09e81959a81455e260799a0632f8301901d600281810b9083900b14613b8657886001600160a01b0316613b6b82613d1d565b6001600160a01b03161115613b805781613b88565b80613b88565b815b9998505050505050505050565b6006546001600160a01b0316613ba85750565b6006546040516318dbf60160e21b8082523360048301526001600160a01b038481166024840152610e0893919291169063636fd80490604401612d74565b60008060007f000000000000000000000000ef72cbccf4a807dfa1fbecd61ddb488ff8a05fa36001600160a01b03166325b355d66040518163ffffffff1660e01b8152600401606060405180830381865afa158015613c49573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613c6d91906158c4565b925092509250909192565b613c826040613579565b15611bdf5760065460405163416eb29160e11b8082523360048301526001600160a01b038581166024840152600285900b6044840152611bdf9391929116906382dd652290606401612d74565b6006546001600160a01b0316331490565b6001600160e01b031982811690821614611bdf5760405163d3f5153b60e01b81526001600160e01b03198216600482015260240160405180910390fd5b6000600282900b60171d62ffffff818401821816620d89e8811115613d5557604051633c10250f60e01b815260040160405180910390fd5b600160801b6001821615613d7657506ffffcb933bd6fad37aa2d162d1a5940015b6002821615613d95576ffff97272373d413259a46990580e213a0260801c5b6004821615613db4576ffff2e50f5f656932ef12357cf3c7fdcc0260801c5b6008821615613dd3576fffe5caca7e10e4e61c3624eaa0941cd00260801c5b6010821615613df2576fffcb9843d60f6159c9db58835c9266440260801c5b6020821615613e11576fff973b41fa98c081472e6896dfb254c00260801c5b6040821615613e30576fff2ea16466c96a3843ec78b326b528610260801c5b6080821615613e4f576ffe5dee046a99a2a811c461f1969c30530260801c5b610100821615613e6f576ffcbe86c7900a88aedcffc83b479aa3a40260801c5b610200821615613e8f576ff987a7253ac413176f2b074cf7815e540260801c5b610400821615613eaf576ff3392b0822b70005940c7a398e4b70f30260801c5b610800821615613ecf576fe7159475a2c29b7443b29c7fa6e889d90260801c5b611000821615613eef576fd097f3bdfd2022b8845ad8f792aa58250260801c5b612000821615613f0f576fa9f746462d870fdf8a65dc1f90e061e50260801c5b614000821615613f2f576f70d869a156d2a1b890bb3df62baf32f70260801c5b618000821615613f4f576f31be135f97d08fd981231505542fcfa60260801c5b62010000821615613f70576f09aa508b5b7a84e1c677de54f3e99bc90260801c5b62020000821615613f90576e5d6af8dedb81196699c329225ee6040260801c5b620400008210613fd65762040000821615613fb9576d2216e584f5fa1ea926041bedfe980260801c5b62080000821615613fd6576b048a170391f7dc42444e8fa20260801c5b60008560020b1315613fe757600019045b63ffffffff0160201c949350505050565b6000806000806154518a61400e57614969614012565b6149785b9050600087126140e657600061403b8888620f42400362ffffff16620f424062ffffff16613331565b905061404c8a8c8b8563ffffffff16565b945084811061407957899550614072858862ffffff1689620f42400362ffffff1661347c565b92506140bf565b6140858b8a838f614987565b9550856001600160a01b03168a6001600160a01b0316036140a8576140a8615906565b6140b7868c8b8563ffffffff16565b945084880392505b6140de868c8b8f6140d2576149a06140d6565b6149af5b63ffffffff16565b9350506141b8565b6154518b6140f6576149a06140fa565b6149af5b905061410b8a8c8b8463ffffffff16565b93508760000397506000881215614135576040516334cb3a0160e11b815260040160405180910390fd5b83881061414457899550614189565b6141508b8a8a8f6149be565b9550856001600160a01b03168a6001600160a01b03161461417d5761417a868c8b8463ffffffff16565b93505b87841115614189578793505b614198868c8b8563ffffffff16565b94506141b4858862ffffff1689620f42400362ffffff1661347c565b9250505b509650965096509692505050565b8082038281131560008312151461358e57600080fd5b8181018281121560008312151461358e57600080fd5b600082158061421357505081810281838281614210576142106154df565b04145b61358e57600080fd5b600283810b60009081526020869052604090206003810180548284018054870390558403905560010154600f81900b91600160801b8204810b91600160981b9004900b9450945094915050565b60008082600f0b12156142ab57508082016001600160801b03808416908216106142a6576040516302603ee960e31b815260040160405180910390fd5b61358e565b826001600160801b03168284019150816001600160801b0316101561358e57604051634cba017960e11b815260040160405180910390fd5b600060405163a9059cbb60e01b6000526001600160a01b03841660045282602452602060006044600080895af19150813d1560203d14600160005114161716915080604052508061434757604051637232c81f60e11b815260040160405180910390fd5b50505050565b6000806000806143608b8b8b8a8c6149ce565b90965094509092509050838317156143f75784156143d4576005805463ffffffff60d01b1916600160d01b63ffffffff89160217905560065460405163aa6b14bb60e01b8082526143cf9290916001600160a01b039091169063aa6b14bb90612d74908990899060040161562f565b612079565b6004805463ffffffff60d01b1916600160d01b63ffffffff891602179055612079565b6001600160681b03828217161561207957841561444957600580546001600160d01b031916600160681b6001600160681b03848116919091026001600160681b03191691909117908416179055612079565b600480546001600160d01b031916600160681b6001600160681b03938416026001600160681b0319161792909116919091179055909890975095505050505050565b806001600160801b03811681146135f357600080fd5b620f424062ffffff821610610e08576040516315b2afa960e01b815260040160405180910390fd5b600286900b60009081526020889052604081208054826144e98289614269565b6001600160801b031690506d09745258e83de0d0f4e400fce799811115614523576040516312dc1b2560e11b815260040160405180910390fd5b6001830154600f0b856145475788600f0b81600f0b61454291906156aa565b614559565b88600f0b81600f0b614559919061568a565b6001850180546001600160801b0319166001600160801b03929092169190911790558184558115945060008390036145ab57841594508960020b8b60020b136145ab5760038401879055600284018890555b50505050979650505050505050565b600285810b60008181526020899052604080822088850b83529082209193849391929184918291908a900b126145fb5750506002820154600383015461460e565b8360020154880391508360030154870390505b6000808b60020b8b60020b121561463057505060028301546003840154614643565b84600201548a0391508460030154890390505b92909803979097039b96909503949094039850939650505050505050565b8354600f84900b60000361468b57806001600160801b03166000036146865750614347565b6146a1565b6146958185614269565b6001600160801b031685555b6001850154600286015460008583146146d857600188018690556146d58387036001600160801b038616600160801b613331565b90505b600085831461470557600289018690556147028387036001600160801b038716600160801b613331565b90505b6001600160801b03828217161561474b57600389018054600160801b6001600160801b03808316860181166001600160801b031990931683178290048116850116021790555b505050505050505050565b60095463010000008104600290810b919081900b90600160c81b900463ffffffff1682828289156147975761478f8c898386868c614ada565b919450925090505b88156147b3576147ab8b898386868c614ada565b919450925090505b8260020b8660020b1415806147ce57508160020b8560020b14155b806147e557508363ffffffff168163ffffffff1614155b15614831576009805462ffffff80861663010000000265ffffffffffff1963ffffffff8616600160c81b021665ffffffffffff63ffffffff60c81b011990931692909217908516171790555b505050505050505050505050565b60008082600f0b12156148675761485f61157c8585856000036000614bcf565b600003614877565b61487761157c8585856001614bcf565b949350505050565b60008082600f0b121561489f5761485f61157c8585856000036000614c6a565b61487761157c8585856001614c6a565b60008084156148e3576148e37f00000000000000000000000015d38573d2feeb82e7ad5187ab8c1d52810b1f078487612976565b8315614914576149147f000000000000000000000000f6f8db0aba00007681f8faf16a0fda1c9b030b118486612976565b8484171561496057826001600160a01b03167f1656ab6fb55adcbed3f1f85c025a5c427075a045777606fbe152783e3e7ca398868660405161495792919061562f565b60405180910390a25b50929391925050565b60006148778385846001614c6a565b60006148778484846001614bcf565b6000614997858585856001614cd1565b95945050505050565b60006148778385846000614bcf565b60006148778484846000614c6a565b6000614997858585856000614cd1565b600080808088881715614a7c5784546001600160681b038082169160681c166149f78b8361546f565b9150614a038a8261546f565b9050617080614a188a63ffffffff42166154a5565b101580614a2b57506001600160681b0382115b80614a3c57506001600160681b0381115b15614a6b578754600080614a518585856148af565b6000808d559a508a99509097509550614ace945050505050565b909450925060009150819050614ace565b617080614a8f8863ffffffff42166154a5565b10614ac15784546001600160681b038082169160681c1680821715614abe578754600080614a518585856148af565b50505b5060009250829150819050805b95509550955095915050565b60008060008315614b2457600080614af360038c614eef565b915091508a60020b8860020b03614b0c57819750614b1d565b8a60020b8760020b03614b1d578096505b5050614bad565b6000808a60020b8860020b128015614b4157508a60020b8760020b135b15614b6a57508690508560028a810b908c900b1315614b62578a9650614b9d565b8a9750614b9d565b614b786008600a8b8e615045565b600281810b600090815260036020526040902060010154600160801b9004900b925090505b614baa60038c84846150fa565b50505b6000614bbd6008600a8a8d6151f0565b969a9599509597509395505050505050565b60006001600160a01b0385850381169085168110614bec57600080fd5b600160601b600160e01b03606085901b1683614c3357866001600160a01b0316614c208383896001600160a01b0316613331565b81614c2d57614c2d6154df565b04614c5f565b614c5f614c4a8383896001600160a01b031661347c565b886001600160a01b0316808204910615150190565b979650505050505050565b6000846001600160a01b0316846001600160a01b03161015614c8b57600080fd5b6001600160a01b038585031682614cb957614cb481856001600160801b0316600160601b613331565b6131d9565b6131d981856001600160801b0316600160601b61347c565b6000856001600160a01b0316600003614ce957600080fd5b846001600160801b0316600003614cff57600080fd5b83600003614d0e575084614997565b81151583151503614e0a57600160601b600160e01b03606086901b168215614db8576001600160a01b03871685810290868281614d4d57614d4d6154df565b0403614d7d57818101828110614d7b57614d71838a6001600160a01b03168361347c565b9350505050614997565b505b614daf82614da4888b6001600160a01b03168681614d9d57614d9d6154df565b0490615237565b808204910615150190565b92505050614997565b6001600160a01b03871685810290868281614dd557614dd56154df565b0414614de057600080fd5b808211614dec57600080fd5b614daf614e05838a6001600160a01b031684860361347c565b615247565b8115614e7757614e70614e056001600160a01b03861115614e4257614e3d86600160601b896001600160801b0316613331565b614e60565b6001600160801b038716606087901b81614e5e57614e5e6154df565b045b6001600160a01b03891690615237565b9050614997565b60006001600160a01b03851115614ea557614ea085600160601b886001600160801b031661347c565b614ec2565b614ec2606086901b6001600160801b038816808204910615150190565b905080876001600160a01b031611614ed957600080fd5b6001600160a01b03871603905095945050505050565b600281810b60008181526020859052604081206001810180548383556001600160b01b03198116909155818501839055600390910191909155600160801b8104830b92600160981b909104900b90620d89e7191480614f5f5750614f56620d89e719615750565b60020b8360020b145b15614fb857600283900b6000908152602085905260409020600101805462ffffff808516600160801b0262ffffff60801b19918516600160981b029190911665ffffffffffff60801b199092169190911717905561503e565b8060020b8260020b03614fde57604051630d6e094960e01b815260040160405180910390fd5b600282810b6000908152602086905260408082206001908101805462ffffff808816600160981b0262ffffff60981b19909216919091179091559385900b83529120018054918416600160801b0262ffffff60801b199092169190911790555b9250929050565b600190810190600090600883811d610d8a01901c90829061ffff83161b851663ffffffff16156150a857615079878561525d565b9094509092509050801561508e575050614877565b61509f86610d8b840160010b61525d565b90945090925090505b806150eb576150c68563ffffffff168360010193508360010b61528e565b9093509050806150de5750620d89e891506148779050565b6150e886846153d7565b92505b614c5f87610d891985016153d7565b600283900b620d89e71914806151215750615118620d89e719615750565b60020b8360020b145b614347578260020b8260020b12801561513f57508260020b8160020b135b61515c5760405163e45ac17d60e01b815260040160405180910390fd5b600283810b600090815260209590955260408086206001908101805465ffffffffffff60801b1916600160981b62ffffff878116820262ffffff60801b1990811693909317600160801b8a831681029190911790945597860b8a52848a208401805462ffffff60981b191698909916908102979097179097559390920b865290942090930180549092169202919091179055565b816000806151fe8785615403565b91509150811561522d5761521986610d8a830160010b615403565b9092509050811561522d576001811b831892505b5050949350505050565b8082018281101561358e57600080fd5b806001600160a01b03811681146135f357600080fd5b600881901d600181900b6000908152602084905260408120548190615282908561528e565b93969095509293505050565b60008060ff831684811c8083036152aa578460ff1793506153ce565b7f555555555555555555555555555555555555555555555555555555555555555560008290038216908116156001600160801b0382161560071b176001600160401b03600160801b03600160c01b0382161560061b177bffffffff00000000ffffffff00000000ffffffff00000000ffffffff82161560051b177dffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff0000ffff82161560041b177eff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff82161560031b177f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f82161560021b177f33333333333333333333333333333333333333333333333333333333333333339091161560011b1760ff1685019350600192505b50509250929050565b600181900b600090815260208390526040902054600882901b906153fb908261528e565b509392505050565b600881901d600181810b60009081526020949094526040909320805460ff9093169390931b80831890935591811490151891565b604051806040016040528060008152602001600081525090565b610d8a61591c565b634e487b7160e01b600052601160045260246000fd5b8082018082111561358e5761358e615459565b6000600f82900b6001607f1b810161549c5761549c615459565b60000392915050565b8181038181111561358e5761358e615459565b6001600160801b038181168382160190808211156154d8576154d8615459565b5092915050565b634e487b7160e01b600052601260045260246000fd5b805161ffff811681146135f357600080fd5b60006020828403121561551957600080fd5b613208826154f5565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6001600160a01b03898116825288811660208301528715156040830152606082018790528516608082015283151560a082015260e060c082018190526000906155979083018486615522565b9a9950505050505050505050565b80516001600160e01b0319811681146135f357600080fd5b805162ffffff811681146135f357600080fd5b6000806000606084860312156155e557600080fd5b6155ee846155a5565b92506155fc602085016155bd565b915061560a604085016155bd565b90509250925092565b62ffffff8181168382160190808211156154d8576154d8615459565b918252602082015260400190565b8481528360208201526060604082015260006131d9606083018486615522565b6001600160a01b0391909116815260200190565b60006020828403121561568357600080fd5b5051919050565b81810360008312801583831316838312821617156154d8576154d8615459565b80820182811260008312801582168215821617156156ca576156ca615459565b505092915050565b6001600160a01b038a8116825289811660208301528815156040830152606082018890528616608082015260a0810185905260c0810184905261010060e082018190526000906157258382018587615522565b9c9b505050505050505050505050565b60006020828403121561574757600080fd5b613208826155a5565b60008160020b627fffff19810361549c5761549c615459565b6001600160a01b03888116825287166020820152600286810b604083015285900b6060820152600f84900b608082015260c060a08201819052600090613b889083018486615522565b600080604083850312156157c557600080fd5b6157ce836155a5565b91506157dc602084016155bd565b90509250929050565b600061010060018060a01b03808d168452808c166020850152508960020b60408401528860020b606084015287600f0b60808401528660a08401528560c08401528060e08401526157258184018587615522565b6001600160a01b03878116825286166020820152604081018590526060810184905260a0608082018190526000906158749083018486615522565b98975050505050505050565b600060018060a01b03808b168352808a166020840152508760408301528660608301528560808301528460a083015260e060c083015261559760e083018486615522565b6000806000606084860312156158d957600080fd5b6158e2846154f5565b925060208401518060020b81146158f857600080fd5b915061560a604085016154f5565b634e487b7160e01b600052600160045260246000fd5b634e487b7160e01b600052605160045260246000fdfea164736f6c6343000814000a