Contract Name:
AntiSnipAttackPositionManager
Contract Source Code:
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
pragma abicoder v2;
import {AntiSnipAttack} from '../periphery/libraries/AntiSnipAttack.sol';
import {SafeCast} from '../libraries/SafeCast.sol';
import './BasePositionManager.sol';
contract AntiSnipAttackPositionManager is BasePositionManager {
using SafeCast for uint256;
mapping(uint256 => AntiSnipAttack.Data) public antiSnipAttackData;
constructor(
address _factory,
address _WETH,
address _descriptor
) BasePositionManager(_factory, _WETH, _descriptor) {}
function mint(MintParams calldata params)
public
payable
override
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(tokenId, liquidity, amount0, amount1) = super.mint(params);
antiSnipAttackData[tokenId] = AntiSnipAttack.initialize(block.timestamp.toUint32());
}
function addLiquidity(IncreaseLiquidityParams calldata params)
external
payable
override
onlyNotExpired(params.deadline)
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
)
{
Position storage pos = _positions[params.tokenId];
PoolInfo memory poolInfo = _poolInfoById[pos.poolId];
IPool pool;
uint256 feeGrowthInsideLast;
(liquidity, amount0, amount1, feeGrowthInsideLast, pool) = _addLiquidity(
AddLiquidityParams({
token0: poolInfo.token0,
token1: poolInfo.token1,
fee: poolInfo.fee,
recipient: address(this),
tickLower: pos.tickLower,
tickUpper: pos.tickUpper,
ticksPrevious: params.ticksPrevious,
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min
})
);
uint128 tmpLiquidity = pos.liquidity;
if (feeGrowthInsideLast != pos.feeGrowthInsideLast) {
uint256 feeGrowthInsideDiff;
unchecked {
feeGrowthInsideDiff = feeGrowthInsideLast - pos.feeGrowthInsideLast;
}
// zero fees burnable when adding liquidity
(additionalRTokenOwed, ) = AntiSnipAttack.update(
antiSnipAttackData[params.tokenId],
tmpLiquidity,
liquidity,
block.timestamp.toUint32(),
true,
FullMath.mulDivFloor(tmpLiquidity, feeGrowthInsideDiff, C.TWO_POW_96),
IFactory(factory).vestingPeriod()
);
pos.rTokenOwed += additionalRTokenOwed;
pos.feeGrowthInsideLast = feeGrowthInsideLast;
}
pos.liquidity += liquidity;
emit AddLiquidity(params.tokenId, liquidity, amount0, amount1, additionalRTokenOwed);
}
function removeLiquidity(RemoveLiquidityParams calldata params)
external
override
isAuthorizedForToken(params.tokenId)
onlyNotExpired(params.deadline)
returns (
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
)
{
Position storage pos = _positions[params.tokenId];
uint128 tmpLiquidity = pos.liquidity;
require(tmpLiquidity >= params.liquidity, 'Insufficient liquidity');
PoolInfo memory poolInfo = _poolInfoById[pos.poolId];
IPool pool = _getPool(poolInfo.token0, poolInfo.token1, poolInfo.fee);
uint256 feeGrowthInsideLast;
(amount0, amount1, feeGrowthInsideLast) = pool.burn(
pos.tickLower,
pos.tickUpper,
params.liquidity
);
require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Low return amounts');
// call update() function regardless of fee growth difference
// to calculate burnable fees
uint256 feesBurnable;
uint256 feeGrowthInsideDiff;
unchecked {
feeGrowthInsideDiff = feeGrowthInsideLast - pos.feeGrowthInsideLast;
}
(additionalRTokenOwed, feesBurnable) = AntiSnipAttack.update(
antiSnipAttackData[params.tokenId],
tmpLiquidity,
params.liquidity,
block.timestamp.toUint32(),
false,
FullMath.mulDivFloor(tmpLiquidity, feeGrowthInsideDiff, C.TWO_POW_96),
IFactory(factory).vestingPeriod()
);
pos.rTokenOwed += additionalRTokenOwed;
pos.feeGrowthInsideLast = feeGrowthInsideLast;
if (feesBurnable > 0) pool.burnRTokens(feesBurnable, true);
pos.liquidity = tmpLiquidity - params.liquidity;
emit RemoveLiquidity(params.tokenId, params.liquidity, amount0, amount1, additionalRTokenOwed);
}
function syncFeeGrowth(uint256 tokenId)
external
override
isAuthorizedForToken(tokenId)
returns(uint256 additionalRTokenOwed)
{
Position storage pos = _positions[tokenId];
PoolInfo memory poolInfo = _poolInfoById[pos.poolId];
IPool pool = _getPool(poolInfo.token0, poolInfo.token1, poolInfo.fee);
uint256 feeGrowthInsideLast = pool.tweakPosZeroLiq(
pos.tickLower,
pos.tickUpper
);
uint256 feeGrowthInsideDiff;
unchecked {
feeGrowthInsideDiff = feeGrowthInsideLast - pos.feeGrowthInsideLast;
}
uint128 tmpLiquidity = pos.liquidity;
(additionalRTokenOwed, ) = AntiSnipAttack.update(
antiSnipAttackData[tokenId],
tmpLiquidity,
0,
block.timestamp.toUint32(),
false,
FullMath.mulDivFloor(tmpLiquidity, feeGrowthInsideDiff, C.TWO_POW_96),
IFactory(factory).vestingPeriod()
);
pos.rTokenOwed += additionalRTokenOwed;
pos.feeGrowthInsideLast = feeGrowthInsideLast;
emit SyncFeeGrowth(tokenId, additionalRTokenOwed);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import {Math} from '@openzeppelin/contracts/utils/math/Math.sol';
import {MathConstants as C} from '../../libraries/MathConstants.sol';
import {SafeCast} from '../../libraries/SafeCast.sol';
/// @title AntiSnipAttack
/// @notice Contains the snipping attack mechanism implementation
/// to be inherited by NFT position manager
library AntiSnipAttack {
using SafeCast for uint256;
using SafeCast for int256;
using SafeCast for int128;
struct Data {
// timestamp of last action performed
uint32 lastActionTime;
// average start time of lock schedule
uint32 lockTime;
// average unlock time of locked fees
uint32 unlockTime;
// locked rToken qty since last update
uint256 feesLocked;
}
/// @notice Initializes values for a new position
/// @return data Initialized snip attack data structure
function initialize(uint32 currentTime) internal pure returns (Data memory data) {
data.lastActionTime = currentTime;
data.lockTime = currentTime;
data.unlockTime = currentTime;
data.feesLocked = 0;
}
/// @notice Credits accumulated fees to a user's existing position
/// @dev The posiition should already have been initialized
/// @param self The individual position to update
/// @param liquidityDelta The change in pool liquidity as a result of the position update
/// this value should not be zero when called
/// @param isAddLiquidity true = add liquidity, false = remove liquidity
/// @param feesSinceLastAction rTokens collected by position since last action performed
/// in fee growth inside the tick range
/// @param vestingPeriod The maximum time duration for which LP fees
/// are proportionally burnt upon LP removals
/// @return feesClaimable The claimable rToken amount to be sent to the user
/// @return feesBurnable The rToken amount to be burnt
function update(
Data storage self,
uint128 currentLiquidity,
uint128 liquidityDelta,
uint32 currentTime,
bool isAddLiquidity,
uint256 feesSinceLastAction,
uint256 vestingPeriod
) internal returns (uint256 feesClaimable, uint256 feesBurnable) {
Data memory _self = self;
if (vestingPeriod == 0) {
// no locked fees, return
if (_self.feesLocked == 0) return (feesSinceLastAction, 0);
// unlock any locked fees
self.feesLocked = 0;
return (_self.feesLocked + feesSinceLastAction, 0);
}
// scoping of fee proportions to avoid stack too deep
{
// claimable proportion (in basis pts) of collected fees between last action and now
// lockTime is used instead of lastActionTime because we prefer to use the entire
// duration of the position as the measure, not just the duration after last action performed
uint256 feesClaimableSinceLastActionFeeUnits = Math.min(
C.FEE_UNITS,
(uint256(currentTime - _self.lockTime) * C.FEE_UNITS) / vestingPeriod
);
// claimable proportion (in basis pts) of locked fees
// lastActionTime is used instead of lockTime since the vested fees
// from lockTime to lastActionTime have already been claimed
uint256 feesClaimableVestedFeeUnits = _self.unlockTime <= _self.lastActionTime
? C.FEE_UNITS
: Math.min(
C.FEE_UNITS,
(uint256(currentTime - _self.lastActionTime) * C.FEE_UNITS) /
(_self.unlockTime - _self.lastActionTime)
);
uint256 feesLockedBeforeUpdate = _self.feesLocked;
(_self.feesLocked, feesClaimable) = calcFeeProportions(
_self.feesLocked,
feesSinceLastAction,
feesClaimableVestedFeeUnits,
feesClaimableSinceLastActionFeeUnits
);
// update unlock time
// the new lock fee qty contains 2 portions:
// (1) new lock fee qty from last action to now
// (2) remaining lock fee qty prior to last action performed
// new unlock time = proportionally weighted unlock times of the 2 portions
// (1)'s unlock time = currentTime + vestingPeriod
// (2)'s unlock time = current unlock time
// If (1) and (2) are 0, then update to block.timestamp
self.unlockTime = (_self.feesLocked == 0)
? currentTime
: (((_self.lockTime + vestingPeriod) *
feesSinceLastAction *
(C.FEE_UNITS - feesClaimableSinceLastActionFeeUnits) +
_self.unlockTime *
feesLockedBeforeUpdate *
(C.FEE_UNITS - feesClaimableVestedFeeUnits)) / (_self.feesLocked * C.FEE_UNITS))
.toUint32();
}
uint256 updatedLiquidity = isAddLiquidity
? currentLiquidity + liquidityDelta
: currentLiquidity - liquidityDelta;
// adding liquidity: update average start time
// removing liquidity: calculate and burn portion of locked fees
if (isAddLiquidity) {
self.lockTime = Math
.ceilDiv(
Math.max(_self.lockTime, currentTime - vestingPeriod) *
uint256(currentLiquidity) +
uint256(uint128(liquidityDelta)) *
currentTime,
updatedLiquidity
).toUint32();
} else if (_self.feesLocked > 0 && liquidityDelta != 0) {
feesBurnable = (_self.feesLocked * liquidityDelta) / uint256(currentLiquidity);
_self.feesLocked -= feesBurnable;
}
// update other variables
self.feesLocked = _self.feesLocked;
self.lastActionTime = currentTime;
}
function calcFeeProportions(
uint256 currentFees,
uint256 nextFees,
uint256 currentClaimableFeeUnits,
uint256 nextClaimableFeeUnits
) internal pure returns (uint256 feesLockedNew, uint256 feesClaimable) {
uint256 totalFees = currentFees + nextFees;
feesClaimable =
(currentClaimableFeeUnits * currentFees + nextClaimableFeeUnits * nextFees) /
C.FEE_UNITS;
feesLockedNew = totalFees - feesClaimable;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to uint32, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint32
function toUint32(uint256 y) internal pure returns (uint32 z) {
require((z = uint32(y)) == y);
}
/// @notice Cast a uint128 to a int128, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt128(uint128 y) internal pure returns (int128 z) {
require(y < 2**127);
z = int128(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 int128 to a uint128 and reverses the sign.
/// @param y The int128 to be casted
/// @return z = -y, now type uint128
function revToUint128(int128 y) internal pure returns (uint128 z) {
unchecked {
return type(uint128).max - uint128(y) + 1;
}
}
/// @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 int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
/// @notice Cast a uint256 to a int256 and reverses the sign, revert on overflow
/// @param y The uint256 to be casted
/// @return z = -y, now type int256
function revToInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = -int256(y);
}
/// @notice Cast a int256 to a uint256 and reverses the sign.
/// @param y The int256 to be casted
/// @return z = -y, now type uint256
function revToUint256(int256 y) internal pure returns (uint256 z) {
unchecked {
return type(uint256).max - uint256(y) + 1;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
pragma abicoder v2;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {PoolAddress} from './libraries/PoolAddress.sol';
import {MathConstants as C} from '../libraries/MathConstants.sol';
import {FullMath} from '../libraries/FullMath.sol';
import {QtyDeltaMath} from '../libraries/QtyDeltaMath.sol';
import {IPool} from '../interfaces/IPool.sol';
import {IFactory} from '../interfaces/IFactory.sol';
import {IBasePositionManager} from '../interfaces/periphery/IBasePositionManager.sol';
import {INonfungibleTokenPositionDescriptor} from '../interfaces/periphery/INonfungibleTokenPositionDescriptor.sol';
import {IRouterTokenHelper} from '../interfaces/periphery/IRouterTokenHelper.sol';
import {LiquidityHelper} from './base/LiquidityHelper.sol';
import {RouterTokenHelper} from './base/RouterTokenHelper.sol';
import {Multicall} from './base/Multicall.sol';
import {DeadlineValidation} from './base/DeadlineValidation.sol';
import {ERC721Permit} from './base/ERC721Permit.sol';
contract BasePositionManager is
IBasePositionManager,
Multicall,
ERC721Permit('KyberSwap v2 NFT Positions Manager', 'KS2-NPM', '1'),
LiquidityHelper
{
address internal immutable _tokenDescriptor;
uint80 public override nextPoolId = 1;
uint256 public override nextTokenId = 1;
// pool id => pool info
mapping(uint80 => PoolInfo) internal _poolInfoById;
// tokenId => position
mapping(uint256 => Position) internal _positions;
mapping(address => bool) public override isRToken;
// pool address => pool id
mapping(address => uint80) public override addressToPoolId;
modifier isAuthorizedForToken(uint256 tokenId) {
require(_isApprovedOrOwner(msg.sender, tokenId), 'Not approved');
_;
}
constructor(
address _factory,
address _WETH,
address _descriptor
) LiquidityHelper(_factory, _WETH) {
_tokenDescriptor = _descriptor;
}
function createAndUnlockPoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 currentSqrtP
) external payable override returns (address pool) {
require(token0 < token1);
pool = IFactory(factory).getPool(token0, token1, fee);
if (pool == address(0)) {
pool = IFactory(factory).createPool(token0, token1, fee);
}
(uint160 sqrtP, , , ) = IPool(pool).getPoolState();
if (sqrtP == 0) {
(uint256 qty0, uint256 qty1) = QtyDeltaMath.calcUnlockQtys(currentSqrtP);
_transferTokens(token0, msg.sender, pool, qty0);
_transferTokens(token1, msg.sender, pool, qty1);
IPool(pool).unlockPool(currentSqrtP);
}
}
function mint(MintParams calldata params)
public
payable
virtual
override
onlyNotExpired(params.deadline)
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
IPool pool;
uint256 feeGrowthInsideLast;
(liquidity, amount0, amount1, feeGrowthInsideLast, pool) = _addLiquidity(
AddLiquidityParams({
token0: params.token0,
token1: params.token1,
fee: params.fee,
recipient: address(this),
tickLower: params.tickLower,
tickUpper: params.tickUpper,
ticksPrevious: params.ticksPrevious,
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min
})
);
tokenId = nextTokenId++;
_mint(params.recipient, tokenId);
uint80 poolId = _storePoolInfo(address(pool), params.token0, params.token1, params.fee);
_positions[tokenId] = Position({
nonce: 0,
operator: address(0),
poolId: poolId,
tickLower: params.tickLower,
tickUpper: params.tickUpper,
liquidity: liquidity,
rTokenOwed: 0,
feeGrowthInsideLast: feeGrowthInsideLast
});
emit MintPosition(tokenId, poolId, liquidity, amount0, amount1);
}
function addLiquidity(IncreaseLiquidityParams calldata params)
external
payable
virtual
override
onlyNotExpired(params.deadline)
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
)
{
Position storage pos = _positions[params.tokenId];
PoolInfo memory poolInfo = _poolInfoById[pos.poolId];
IPool pool;
uint256 feeGrowthInsideLast;
(liquidity, amount0, amount1, feeGrowthInsideLast, pool) = _addLiquidity(
AddLiquidityParams({
token0: poolInfo.token0,
token1: poolInfo.token1,
fee: poolInfo.fee,
recipient: address(this),
tickLower: pos.tickLower,
tickUpper: pos.tickUpper,
ticksPrevious: params.ticksPrevious,
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min
})
);
uint128 tmpLiquidity = pos.liquidity;
additionalRTokenOwed = _updateRTokenOwedAndFeeGrowth(
params.tokenId,
pos.feeGrowthInsideLast,
feeGrowthInsideLast,
tmpLiquidity
);
pos.liquidity = tmpLiquidity + liquidity;
emit AddLiquidity(params.tokenId, liquidity, amount0, amount1, additionalRTokenOwed);
}
function removeLiquidity(RemoveLiquidityParams calldata params)
external
virtual
override
isAuthorizedForToken(params.tokenId)
onlyNotExpired(params.deadline)
returns (
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
)
{
Position storage pos = _positions[params.tokenId];
uint128 tmpLiquidity = pos.liquidity;
require(tmpLiquidity >= params.liquidity, 'Insufficient liquidity');
PoolInfo memory poolInfo = _poolInfoById[pos.poolId];
IPool pool = _getPool(poolInfo.token0, poolInfo.token1, poolInfo.fee);
uint256 feeGrowthInsideLast;
(amount0, amount1, feeGrowthInsideLast) = pool.burn(
pos.tickLower,
pos.tickUpper,
params.liquidity
);
require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Low return amounts');
additionalRTokenOwed = _updateRTokenOwedAndFeeGrowth(
params.tokenId,
pos.feeGrowthInsideLast,
feeGrowthInsideLast,
tmpLiquidity
);
pos.liquidity = tmpLiquidity - params.liquidity;
emit RemoveLiquidity(params.tokenId, params.liquidity, amount0, amount1, additionalRTokenOwed);
}
function syncFeeGrowth(uint256 tokenId)
external
virtual
override
isAuthorizedForToken(tokenId)
returns(uint256 additionalRTokenOwed)
{
Position storage pos = _positions[tokenId];
PoolInfo memory poolInfo = _poolInfoById[pos.poolId];
IPool pool = _getPool(poolInfo.token0, poolInfo.token1, poolInfo.fee);
uint256 feeGrowthInsideLast = pool.tweakPosZeroLiq(
pos.tickLower,
pos.tickUpper
);
additionalRTokenOwed = _updateRTokenOwedAndFeeGrowth(
tokenId,
pos.feeGrowthInsideLast,
feeGrowthInsideLast,
pos.liquidity
);
emit SyncFeeGrowth(tokenId, additionalRTokenOwed);
}
function burnRTokens(BurnRTokenParams calldata params)
external
override
isAuthorizedForToken(params.tokenId)
onlyNotExpired(params.deadline)
returns (
uint256 rTokenQty,
uint256 amount0,
uint256 amount1
)
{
Position storage pos = _positions[params.tokenId];
rTokenQty = pos.rTokenOwed;
require(rTokenQty > 0, 'No rToken to burn');
PoolInfo memory poolInfo = _poolInfoById[pos.poolId];
IPool pool = _getPool(poolInfo.token0, poolInfo.token1, poolInfo.fee);
pos.rTokenOwed = 0;
uint256 rTokenBalance = IERC20(address(pool)).balanceOf(address(this));
(amount0, amount1) = pool.burnRTokens(
rTokenQty > rTokenBalance ? rTokenBalance : rTokenQty,
false
);
require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Low return amounts');
emit BurnRToken(params.tokenId, rTokenQty);
}
/**
* @dev Burn the token by its owner
* @notice All liquidity should be removed before burning
*/
function burn(uint256 tokenId) external payable override isAuthorizedForToken(tokenId) {
require(_positions[tokenId].liquidity == 0, 'Should remove liquidity first');
require(_positions[tokenId].rTokenOwed == 0, 'Should burn rToken first');
delete _positions[tokenId];
_burn(tokenId);
emit BurnPosition(tokenId);
}
function positions(uint256 tokenId)
external
view
override
returns (Position memory pos, PoolInfo memory info)
{
pos = _positions[tokenId];
info = _poolInfoById[pos.poolId];
}
/**
* @dev Override this function to not allow transferring rTokens
* @notice it also means this PositionManager can not support LP of a rToken and another token
*/
function transferAllTokens(
address token,
uint256 minAmount,
address recipient
) public payable override(IRouterTokenHelper, RouterTokenHelper) {
require(!isRToken[token], 'Can not transfer rToken');
super.transferAllTokens(token, minAmount, recipient);
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), 'Nonexistent token');
return INonfungibleTokenPositionDescriptor(_tokenDescriptor).tokenURI(this, tokenId);
}
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), 'ERC721: approved query for nonexistent token');
return _positions[tokenId].operator;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Permit, IBasePositionManager)
returns (bool)
{
return
interfaceId == type(ERC721Permit).interfaceId ||
interfaceId == type(IBasePositionManager).interfaceId ||
super.supportsInterface(interfaceId);
}
function _updateRTokenOwedAndFeeGrowth(
uint256 tokenId,
uint256 feeGrowthOld,
uint256 feeGrowthNew,
uint128 liquidity)
internal
returns (uint256 additionalRTokenOwed)
{
if (feeGrowthNew != feeGrowthOld) {
uint256 feeGrowthInsideDiff;
unchecked {
feeGrowthInsideDiff = feeGrowthNew - feeGrowthOld;
}
additionalRTokenOwed = FullMath.mulDivFloor(liquidity, feeGrowthInsideDiff, C.TWO_POW_96);
_positions[tokenId].rTokenOwed += additionalRTokenOwed;
_positions[tokenId].feeGrowthInsideLast = feeGrowthNew;
}
}
function _storePoolInfo(
address pool,
address token0,
address token1,
uint24 fee
) internal returns (uint80 poolId) {
poolId = addressToPoolId[pool];
if (poolId == 0) {
addressToPoolId[pool] = (poolId = nextPoolId++);
_poolInfoById[poolId] = PoolInfo({token0: token0, fee: fee, token1: token1});
isRToken[pool] = true;
}
}
/// @dev Overrides _approve to use the operator in the position, which is packed with the position permit nonce
function _approve(address to, uint256 tokenId) internal override {
_positions[tokenId].operator = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
function _getAndIncrementNonce(uint256 tokenId) internal override returns (uint256) {
return uint256(_positions[tokenId].nonce++);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @title Contains constants needed for math libraries
library MathConstants {
uint256 internal constant TWO_FEE_UNITS = 200_000;
uint256 internal constant TWO_POW_96 = 2 ** 96;
uint128 internal constant MIN_LIQUIDITY = 100;
uint8 internal constant RES_96 = 96;
uint24 internal constant FEE_UNITS = 100000;
// it is strictly less than 5% price movement if jumping MAX_TICK_DISTANCE ticks
int24 internal constant MAX_TICK_DISTANCE = 480;
// max number of tick travel when inserting if data changes
uint256 internal constant MAX_TICK_TRAVEL = 10;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
/// @title Provides a function for deriving a pool address from the factory, tokens, and swap fee
library PoolAddress {
/// @notice Deterministically computes the pool address from the given data
/// @param factory the factory address
/// @param token0 One of the tokens constituting the token pair, regardless of order
/// @param token1 The other token constituting the token pair, regardless of order
/// @param swapFee Fee to be collected upon every swap in the pool, in fee units
/// @param poolInitHash The keccak256 hash of the Pool creation code
/// @return pool the pool address
function computeAddress(
address factory,
address token0,
address token1,
uint24 swapFee,
bytes32 poolInitHash
) internal pure returns (address pool) {
(token0, token1) = token0 < token1 ? (token0, token1) : (token1, token0);
bytes32 hashed = keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(token0, token1, swapFee)),
poolInitHash
)
);
pool = address(uint160(uint256(hashed)));
}
}
// 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
/// @dev Code has been modified to be compatible with sol 0.8
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 mulDivFloor(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0, '0 denom');
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1, 'denom <= prod1');
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = denominator & (~denominator + 1);
// 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)
}
unchecked {
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
}
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivCeiling(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDivFloor(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
result++;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {MathConstants as C} from './MathConstants.sol';
import {TickMath} from './TickMath.sol';
import {FullMath} from './FullMath.sol';
import {SafeCast} from './SafeCast.sol';
/// @title Contains helper functions for calculating
/// token0 and token1 quantites from differences in prices
/// or from burning reinvestment tokens
library QtyDeltaMath {
using SafeCast for uint256;
using SafeCast for int128;
function calcUnlockQtys(uint160 initialSqrtP)
internal
pure
returns (uint256 qty0, uint256 qty1)
{
qty0 = FullMath.mulDivCeiling(C.MIN_LIQUIDITY, C.TWO_POW_96, initialSqrtP);
qty1 = FullMath.mulDivCeiling(C.MIN_LIQUIDITY, initialSqrtP, C.TWO_POW_96);
}
/// @notice Gets the qty0 delta between two prices
/// @dev Calculates liquidity / sqrt(lower) - liquidity / sqrt(upper),
/// i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// rounds up if adding liquidity, rounds down if removing liquidity
/// @param lowerSqrtP The lower sqrt price.
/// @param upperSqrtP The upper sqrt price. Should be >= lowerSqrtP
/// @param liquidity Liquidity quantity
/// @param isAddLiquidity true = add liquidity, false = remove liquidity
/// @return token0 qty required for position with liquidity between the 2 sqrt prices
function calcRequiredQty0(
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint128 liquidity,
bool isAddLiquidity
) internal pure returns (int256) {
uint256 numerator1 = uint256(liquidity) << C.RES_96;
uint256 numerator2;
unchecked {
numerator2 = upperSqrtP - lowerSqrtP;
}
return
isAddLiquidity
? (divCeiling(FullMath.mulDivCeiling(numerator1, numerator2, upperSqrtP), lowerSqrtP))
.toInt256()
: (FullMath.mulDivFloor(numerator1, numerator2, upperSqrtP) / lowerSqrtP).revToInt256();
}
/// @notice Gets the token1 delta quantity between two prices
/// @dev Calculates liquidity * (sqrt(upper) - sqrt(lower))
/// rounds up if adding liquidity, rounds down if removing liquidity
/// @param lowerSqrtP The lower sqrt price.
/// @param upperSqrtP The upper sqrt price. Should be >= lowerSqrtP
/// @param liquidity Liquidity quantity
/// @param isAddLiquidity true = add liquidity, false = remove liquidity
/// @return token1 qty required for position with liquidity between the 2 sqrt prices
function calcRequiredQty1(
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint128 liquidity,
bool isAddLiquidity
) internal pure returns (int256) {
unchecked {
return
isAddLiquidity
? (FullMath.mulDivCeiling(liquidity, upperSqrtP - lowerSqrtP, C.TWO_POW_96)).toInt256()
: (FullMath.mulDivFloor(liquidity, upperSqrtP - lowerSqrtP, C.TWO_POW_96)).revToInt256();
}
}
/// @notice Calculates the token0 quantity proportion to be sent to the user
/// for burning reinvestment tokens
/// @param sqrtP Current pool sqrt price
/// @param liquidity Difference in reinvestment liquidity due to reinvestment token burn
/// @return token0 quantity to be sent to the user
function getQty0FromBurnRTokens(uint160 sqrtP, uint256 liquidity)
internal
pure
returns (uint256)
{
return FullMath.mulDivFloor(liquidity, C.TWO_POW_96, sqrtP);
}
/// @notice Calculates the token1 quantity proportion to be sent to the user
/// for burning reinvestment tokens
/// @param sqrtP Current pool sqrt price
/// @param liquidity Difference in reinvestment liquidity due to reinvestment token burn
/// @return token1 quantity to be sent to the user
function getQty1FromBurnRTokens(uint160 sqrtP, uint256 liquidity)
internal
pure
returns (uint256)
{
return FullMath.mulDivFloor(liquidity, sqrtP, C.TWO_POW_96);
}
/// @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 divCeiling(uint256 x, uint256 y) internal pure returns (uint256 z) {
// return x / y + ((x % y == 0) ? 0 : 1);
require(y > 0);
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IPoolActions} from './pool/IPoolActions.sol';
import {IPoolEvents} from './pool/IPoolEvents.sol';
import {IPoolStorage} from './pool/IPoolStorage.sol';
interface IPool is IPoolActions, IPoolEvents, IPoolStorage {}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @title KyberSwap v2 factory
/// @notice Deploys KyberSwap v2 pools and manages control over government fees
interface IFactory {
/// @notice Emitted when a pool is created
/// @param token0 First pool token by address sort order
/// @param token1 Second pool token by address sort order
/// @param swapFeeUnits Fee to be collected upon every swap in the pool, in fee units
/// @param tickDistance Minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed swapFeeUnits,
int24 tickDistance,
address pool
);
/// @notice Emitted when a new fee is enabled for pool creation via the factory
/// @param swapFeeUnits Fee to be collected upon every swap in the pool, in fee units
/// @param tickDistance Minimum number of ticks between initialized ticks for pools created with the given fee
event SwapFeeEnabled(uint24 indexed swapFeeUnits, int24 indexed tickDistance);
/// @notice Emitted when vesting period changes
/// @param vestingPeriod The maximum time duration for which LP fees
/// are proportionally burnt upon LP removals
event VestingPeriodUpdated(uint32 vestingPeriod);
/// @notice Emitted when configMaster changes
/// @param oldConfigMaster configMaster before the update
/// @param newConfigMaster configMaster after the update
event ConfigMasterUpdated(address oldConfigMaster, address newConfigMaster);
/// @notice Emitted when fee configuration changes
/// @param feeTo Recipient of government fees
/// @param governmentFeeUnits Fee amount, in fee units,
/// to be collected out of the fee charged for a pool swap
event FeeConfigurationUpdated(address feeTo, uint24 governmentFeeUnits);
/// @notice Emitted when whitelist feature is enabled
event WhitelistEnabled();
/// @notice Emitted when whitelist feature is disabled
event WhitelistDisabled();
/// @notice Returns the maximum time duration for which LP fees
/// are proportionally burnt upon LP removals
function vestingPeriod() external view returns (uint32);
/// @notice Returns the tick distance for a specified fee.
/// @dev Once added, cannot be updated or removed.
/// @param swapFeeUnits Swap fee, in fee units.
/// @return The tick distance. Returns 0 if fee has not been added.
function feeAmountTickDistance(uint24 swapFeeUnits) external view returns (int24);
/// @notice Returns the address which can update the fee configuration
function configMaster() external view returns (address);
/// @notice Returns the keccak256 hash of the Pool creation code
/// This is used for pre-computation of pool addresses
function poolInitHash() external view returns (bytes32);
/// @notice Returns the pool oracle contract for twap
function poolOracle() external view returns (address);
/// @notice Fetches the recipient of government fees
/// and current government fee charged in fee units
function feeConfiguration() external view returns (address _feeTo, uint24 _governmentFeeUnits);
/// @notice Returns the status of whitelisting feature of NFT managers
/// If true, anyone can mint liquidity tokens
/// Otherwise, only whitelisted NFT manager(s) are allowed to mint liquidity tokens
function whitelistDisabled() external view returns (bool);
//// @notice Returns all whitelisted NFT managers
/// If the whitelisting feature is turned on,
/// only whitelisted NFT manager(s) are allowed to mint liquidity tokens
function getWhitelistedNFTManagers() external view returns (address[] memory);
/// @notice Checks if sender is a whitelisted NFT manager
/// If the whitelisting feature is turned on,
/// only whitelisted NFT manager(s) are allowed to mint liquidity tokens
/// @param sender address to be checked
/// @return true if sender is a whistelisted NFT manager, false otherwise
function isWhitelistedNFTManager(address sender) external view returns (bool);
/// @notice Returns the pool address for a given pair of tokens and a swap fee
/// @dev Token order does not matter
/// @param tokenA Contract address of either token0 or token1
/// @param tokenB Contract address of the other token
/// @param swapFeeUnits Fee to be collected upon every swap in the pool, in fee units
/// @return pool The pool address. Returns null address if it does not exist
function getPool(
address tokenA,
address tokenB,
uint24 swapFeeUnits
) external view returns (address pool);
/// @notice Fetch parameters to be used for pool creation
/// @dev Called by the pool constructor to fetch the parameters of the pool
/// @return factory The factory address
/// @return poolOracle The pool oracle for twap
/// @return token0 First pool token by address sort order
/// @return token1 Second pool token by address sort order
/// @return swapFeeUnits Fee to be collected upon every swap in the pool, in fee units
/// @return tickDistance Minimum number of ticks between initialized ticks
function parameters()
external
view
returns (
address factory,
address poolOracle,
address token0,
address token1,
uint24 swapFeeUnits,
int24 tickDistance
);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param swapFeeUnits Desired swap fee for the pool, in fee units
/// @dev Token order does not matter. tickDistance is determined from the fee.
/// Call will revert under any of these conditions:
/// 1) pool already exists
/// 2) invalid swap fee
/// 3) invalid token arguments
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB,
uint24 swapFeeUnits
) external returns (address pool);
/// @notice Enables a fee amount with the given tickDistance
/// @dev Fee amounts may never be removed once enabled
/// @param swapFeeUnits The fee amount to enable, in fee units
/// @param tickDistance The distance between ticks to be enforced for all pools created with the given fee amount
function enableSwapFee(uint24 swapFeeUnits, int24 tickDistance) external;
/// @notice Updates the address which can update the fee configuration
/// @dev Must be called by the current configMaster
function updateConfigMaster(address) external;
/// @notice Updates the vesting period
/// @dev Must be called by the current configMaster
function updateVestingPeriod(uint32) external;
/// @notice Updates the address receiving government fees and fee quantity
/// @dev Only configMaster is able to perform the update
/// @param feeTo Address to receive government fees collected from pools
/// @param governmentFeeUnits Fee amount, in fee units,
/// to be collected out of the fee charged for a pool swap
function updateFeeConfiguration(address feeTo, uint24 governmentFeeUnits) external;
/// @notice Enables the whitelisting feature
/// @dev Only configMaster is able to perform the update
function enableWhitelist() external;
/// @notice Disables the whitelisting feature
/// @dev Only configMaster is able to perform the update
function disableWhitelist() external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
import {IERC721Metadata} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import {IRouterTokenHelper} from './IRouterTokenHelper.sol';
import {IBasePositionManagerEvents} from './base_position_manager/IBasePositionManagerEvents.sol';
import {IERC721Permit} from './IERC721Permit.sol';
interface IBasePositionManager is IRouterTokenHelper, IBasePositionManagerEvents {
struct Position {
// the nonce for permits
uint96 nonce;
// the address that is approved for spending this token
address operator;
// the ID of the pool with which this token is connected
uint80 poolId;
// the tick range of the position
int24 tickLower;
int24 tickUpper;
// the liquidity of the position
uint128 liquidity;
// the current rToken that the position owed
uint256 rTokenOwed;
// fee growth per unit of liquidity as of the last update to liquidity
uint256 feeGrowthInsideLast;
}
struct PoolInfo {
address token0;
uint24 fee;
address token1;
}
/// @notice Params for the first time adding liquidity, mint new nft to sender
/// @param token0 the token0 of the pool
/// @param token1 the token1 of the pool
/// - must make sure that token0 < token1
/// @param fee the pool's fee in fee units
/// @param tickLower the position's lower tick
/// @param tickUpper the position's upper tick
/// - must make sure tickLower < tickUpper, and both are in tick distance
/// @param ticksPrevious the nearest tick that has been initialized and lower than or equal to
/// the tickLower and tickUpper, use to help insert the tickLower and tickUpper if haven't initialized
/// @param amount0Desired the desired amount for token0
/// @param amount1Desired the desired amount for token1
/// @param amount0Min min amount of token 0 to add
/// @param amount1Min min amount of token 1 to add
/// @param recipient the owner of the position
/// @param deadline time that the transaction will be expired
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
int24[2] ticksPrevious;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Params for adding liquidity to the existing position
/// @param tokenId id of the position to increase its liquidity
/// @param ticksPrevious the nearest tick that has been initialized and lower than or equal to
/// the tickLower and tickUpper, use to help insert the tickLower and tickUpper if haven't initialized
/// only needed if the position has been closed and the owner wants to add more liquidity
/// @param amount0Desired the desired amount for token0
/// @param amount1Desired the desired amount for token1
/// @param amount0Min min amount of token 0 to add
/// @param amount1Min min amount of token 1 to add
/// @param deadline time that the transaction will be expired
struct IncreaseLiquidityParams {
uint256 tokenId;
int24[2] ticksPrevious;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Params for remove liquidity from the existing position
/// @param tokenId id of the position to remove its liquidity
/// @param amount0Min min amount of token 0 to receive
/// @param amount1Min min amount of token 1 to receive
/// @param deadline time that the transaction will be expired
struct RemoveLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Burn the rTokens to get back token0 + token1 as fees
/// @param tokenId id of the position to burn r token
/// @param amount0Min min amount of token 0 to receive
/// @param amount1Min min amount of token 1 to receive
/// @param deadline time that the transaction will be expired
struct BurnRTokenParams {
uint256 tokenId;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Creates a new pool if it does not exist, then unlocks if it has not been unlocked
/// @param token0 the token0 of the pool
/// @param token1 the token1 of the pool
/// @param fee the fee for the pool
/// @param currentSqrtP the initial price of the pool
/// @return pool returns the pool address
function createAndUnlockPoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 currentSqrtP
) external payable returns (address pool);
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
function addLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
function removeLiquidity(RemoveLiquidityParams calldata params)
external
returns (
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
function burnRTokens(BurnRTokenParams calldata params)
external
returns (
uint256 rTokenQty,
uint256 amount0,
uint256 amount1
);
/**
* @dev Burn the token by its owner
* @notice All liquidity should be removed before burning
*/
function burn(uint256 tokenId) external payable;
function syncFeeGrowth(uint256 tokenId) external returns (uint256 additionalRTokenOwed);
function positions(uint256 tokenId)
external
view
returns (Position memory pos, PoolInfo memory info);
function addressToPoolId(address pool) external view returns (uint80);
function isRToken(address token) external view returns (bool);
function nextPoolId() external view returns (uint80);
function nextTokenId() external view returns (uint256);
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
import './IBasePositionManager.sol';
/// @title Describes position NFT tokens via URI
interface INonfungibleTokenPositionDescriptor {
/// @notice Produces the URI describing a particular token ID for a position manager
/// @dev Note this URI may be a data: URI with the JSON contents directly inlined
/// @param positionManager The position manager for which to describe the token
/// @param tokenId The ID of the token for which to produce a description, which may not be valid
/// @return The URI of the ERC721-compliant metadata
function tokenURI(IBasePositionManager positionManager, uint256 tokenId)
external
view
returns (string memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
interface IRouterTokenHelper {
/// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH.
/// @dev The minAmount parameter prevents malicious contracts from stealing WETH from users.
/// @param minAmount The minimum amount of WETH to unwrap
/// @param recipient The address receiving ETH
function unwrapWeth(uint256 minAmount, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundEth() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The minAmount parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param minAmount The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function transferAllTokens(
address token,
uint256 minAmount,
address recipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
pragma abicoder v2;
import {LiquidityMath} from '../libraries/LiquidityMath.sol';
import {PoolAddress} from '../libraries/PoolAddress.sol';
import {TickMath} from '../../libraries/TickMath.sol';
import {IPool} from '../../interfaces/IPool.sol';
import {IFactory} from '../../interfaces/IFactory.sol';
import {IMintCallback} from '../../interfaces/callback/IMintCallback.sol';
import {RouterTokenHelper} from './RouterTokenHelper.sol';
abstract contract LiquidityHelper is IMintCallback, RouterTokenHelper {
constructor(address _factory, address _WETH) RouterTokenHelper(_factory, _WETH) {}
struct AddLiquidityParams {
address token0;
address token1;
uint24 fee;
address recipient;
int24 tickLower;
int24 tickUpper;
int24[2] ticksPrevious;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
}
struct CallbackData {
address token0;
address token1;
uint24 fee;
address source;
}
function mintCallback(
uint256 deltaQty0,
uint256 deltaQty1,
bytes calldata data
) external override {
CallbackData memory callbackData = abi.decode(data, (CallbackData));
require(callbackData.token0 < callbackData.token1, 'LiquidityHelper: wrong token order');
address pool = address(_getPool(callbackData.token0, callbackData.token1, callbackData.fee));
require(msg.sender == pool, 'LiquidityHelper: invalid callback sender');
if (deltaQty0 > 0)
_transferTokens(callbackData.token0, callbackData.source, msg.sender, deltaQty0);
if (deltaQty1 > 0)
_transferTokens(callbackData.token1, callbackData.source, msg.sender, deltaQty1);
}
/// @dev Add liquidity to a pool given params
/// @param params add liquidity params, token0, token1 should be in the correct order
/// @return liquidity amount of liquidity has been minted
/// @return amount0 amount of token0 that is needed
/// @return amount1 amount of token1 that is needed
/// @return feeGrowthInsideLast position manager's updated feeGrowthInsideLast value
/// @return pool address of the pool
function _addLiquidity(AddLiquidityParams memory params)
internal
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 feeGrowthInsideLast,
IPool pool
)
{
require(params.token0 < params.token1, 'LiquidityHelper: invalid token order');
pool = _getPool(params.token0, params.token1, params.fee);
// compute the liquidity amount
{
(uint160 currentSqrtP, , , ) = pool.getPoolState();
uint160 lowerSqrtP = TickMath.getSqrtRatioAtTick(params.tickLower);
uint160 upperSqrtP = TickMath.getSqrtRatioAtTick(params.tickUpper);
liquidity = LiquidityMath.getLiquidityFromQties(
currentSqrtP,
lowerSqrtP,
upperSqrtP,
params.amount0Desired,
params.amount1Desired
);
}
(amount0, amount1, feeGrowthInsideLast) = pool.mint(
params.recipient,
params.tickLower,
params.tickUpper,
params.ticksPrevious,
liquidity,
_callbackData(params.token0, params.token1, params.fee)
);
require(
amount0 >= params.amount0Min && amount1 >= params.amount1Min,
'LiquidityHelper: price slippage check'
);
}
function _callbackData(
address token0,
address token1,
uint24 fee
) internal view returns (bytes memory) {
return
abi.encode(CallbackData({token0: token0, token1: token1, fee: fee, source: msg.sender}));
}
/**
* @dev Returns the pool address for the requested token pair swap fee
* Because the function calculates it instead of fetching the address from the factory,
* the returned pool address may not be in existence yet
*/
function _getPool(
address tokenA,
address tokenB,
uint24 fee
) internal view returns (IPool) {
return IPool(PoolAddress.computeAddress(factory, tokenA, tokenB, fee, poolInitHash));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {TokenHelper} from '../libraries/TokenHelper.sol';
import {IRouterTokenHelper} from '../../interfaces/periphery/IRouterTokenHelper.sol';
import {IWETH} from '../../interfaces/IWETH.sol';
import {ImmutablePeripheryStorage} from './ImmutablePeripheryStorage.sol';
abstract contract RouterTokenHelper is IRouterTokenHelper, ImmutablePeripheryStorage {
constructor(address _factory, address _WETH) ImmutablePeripheryStorage(_factory, _WETH) {}
receive() external payable {
require(msg.sender == WETH, 'Not WETH');
}
/// @dev Unwrap all ETH balance and send to the recipient
function unwrapWeth(uint256 minAmount, address recipient) external payable override {
uint256 balanceWETH = IWETH(WETH).balanceOf(address(this));
require(balanceWETH >= minAmount, 'Insufficient WETH');
if (balanceWETH > 0) {
IWETH(WETH).withdraw(balanceWETH);
TokenHelper.transferEth(recipient, balanceWETH);
}
}
/// @dev Transfer all tokens from the contract to the recipient
function transferAllTokens(
address token,
uint256 minAmount,
address recipient
) public payable virtual override {
uint256 balanceToken = IERC20(token).balanceOf(address(this));
require(balanceToken >= minAmount, 'Insufficient token');
if (balanceToken > 0) {
TokenHelper.transferToken(IERC20(token), balanceToken, address(this), recipient);
}
}
/// @dev Send all ETH balance of this contract to the sender
function refundEth() external payable override {
if (address(this).balance > 0) TokenHelper.transferEth(msg.sender, address(this).balance);
}
/// @dev Transfer tokenAmount amount of token from the sender to the recipient
function _transferTokens(
address token,
address sender,
address recipient,
uint256 tokenAmount
) internal {
if (token == WETH && address(this).balance >= tokenAmount) {
IWETH(WETH).deposit{value: tokenAmount}();
IWETH(WETH).transfer(recipient, tokenAmount);
} else {
TokenHelper.transferToken(IERC20(token), tokenAmount, sender, recipient);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
pragma abicoder v2;
import {IMulticall} from '../../interfaces/periphery/IMulticall.sol';
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data)
external
payable
override
returns (bytes[] memory results)
{
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
/// @title Validate if the transaction is still valid
abstract contract DeadlineValidation {
modifier onlyNotExpired(uint256 deadline) {
require(_blockTimestamp() <= deadline, 'Expired');
_;
}
/// @dev Override this function to test easier with block timestamp
function _blockTimestamp() internal view virtual returns (uint256) {
return block.timestamp;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
import {ERC721} from '@openzeppelin/contracts/token/ERC721/ERC721.sol';
import {ERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import {Address} from '@openzeppelin/contracts/utils/Address.sol';
import {IERC721Permit} from '../../interfaces/periphery/IERC721Permit.sol';
import {DeadlineValidation} from './DeadlineValidation.sol';
/// @title Interface for verifying contract-based account signatures
/// @notice Interface that verifies provided signature for the data
/// @dev Interface defined by EIP-1271
interface IERC1271 {
/// @notice Returns whether the provided signature is valid for the provided data
/// @dev MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5).
/// MUST allow external calls.
/// @param hash Hash of the data to be signed
/// @param signature Signature byte array associated with _data
/// @return magicValue The bytes4 magic value 0x1626ba7e
function isValidSignature(bytes32 hash, bytes memory signature)
external
view
returns (bytes4 magicValue);
}
/// @title ERC721 with permit
/// @notice Nonfungible tokens that support an approve via signature, i.e. permit
abstract contract ERC721Permit is DeadlineValidation, ERC721Enumerable, IERC721Permit {
/// @dev Value is equal to keccak256("Permit(address spender,uint256 tokenId,uint256 nonce,uint256 deadline)");
bytes32 public constant override PERMIT_TYPEHASH =
0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad;
/// @dev The hash of the name used in the permit signature verification
bytes32 private immutable nameHash;
/// @dev The hash of the version string used in the permit signature verification
bytes32 private immutable versionHash;
/// @return The domain seperator used in encoding of permit signature
bytes32 public immutable override DOMAIN_SEPARATOR;
/// @notice Computes the nameHash and versionHash
constructor(
string memory name_,
string memory symbol_,
string memory version_
) ERC721(name_, symbol_) {
bytes32 _nameHash = keccak256(bytes(name_));
bytes32 _versionHash = keccak256(bytes(version_));
nameHash = _nameHash;
versionHash = _versionHash;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)')
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
_nameHash,
_versionHash,
_getChainId(),
address(this)
)
);
}
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override onlyNotExpired(deadline) {
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(
abi.encode(PERMIT_TYPEHASH, spender, tokenId, _getAndIncrementNonce(tokenId), deadline)
)
)
);
address owner = ownerOf(tokenId);
require(spender != owner, 'ERC721Permit: approval to current owner');
if (Address.isContract(owner)) {
require(
IERC1271(owner).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e,
'Unauthorized'
);
} else {
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), 'Invalid signature');
require(recoveredAddress == owner, 'Unauthorized');
}
_approve(spender, tokenId);
}
/// @dev Gets the current nonce for a token ID and then increments it, returning the original value
function _getAndIncrementNonce(uint256 tokenId) internal virtual returns (uint256);
/// @dev Gets the current chain ID
/// @return chainId The current chain ID
function _getChainId() internal view returns (uint256 chainId) {
assembly {
chainId := chainid()
}
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable, IERC721Permit)
returns (bool)
{
return
interfaceId == type(ERC721Enumerable).interfaceId ||
interfaceId == type(IERC721Permit).interfaceId ||
super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtP 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 sqrtP) {
unchecked {
uint256 absTick = uint256(tick < 0 ? -int256(tick) : int256(tick));
require(absTick <= uint256(int256(MAX_TICK)), 'T');
// do bitwise comparison, if i-th bit is turned on,
// multiply ratio by hardcoded values of sqrt(1.0001^-(2^i)) * 2^128
// where 0 <= i <= 19
uint256 ratio = (absTick & 0x1 != 0)
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
// take reciprocal for positive tick values
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtP = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtP < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtP 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 sqrtP) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtP >= MIN_SQRT_RATIO && sqrtP < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtP) << 32;
uint256 r = ratio;
uint256 msb = 0;
unchecked {
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) <= sqrtP ? tickHi : tickLow;
}
}
function getMaxNumberTicks(int24 _tickDistance) internal pure returns (uint24 numTicks) {
return uint24(TickMath.MAX_TICK / _tickDistance) * 2;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IPoolActions {
/// @notice Sets the initial price for the pool and seeds reinvestment liquidity
/// @dev Assumes the caller has sent the necessary token amounts
/// required for initializing reinvestment liquidity prior to calling this function
/// @param initialSqrtP the initial sqrt price of the pool
/// @param qty0 token0 quantity sent to and locked permanently in the pool
/// @param qty1 token1 quantity sent to and locked permanently in the pool
function unlockPool(uint160 initialSqrtP) external returns (uint256 qty0, uint256 qty1);
/// @notice Adds liquidity for the specified recipient/tickLower/tickUpper position
/// @dev Any token0 or token1 owed for the liquidity provision have to be paid for when
/// the IMintCallback#mintCallback is called to this method's caller
/// The quantity of token0/token1 to be sent depends on
/// tickLower, tickUpper, the amount of liquidity, and the current price of the pool.
/// Also sends reinvestment tokens (fees) to the recipient for any fees collected
/// while the position is in range
/// Reinvestment tokens have to be burnt via #burnRTokens in exchange for token0 and token1
/// @param recipient Address for which the added liquidity is credited to
/// @param tickLower Recipient position's lower tick
/// @param tickUpper Recipient position's upper tick
/// @param ticksPrevious The nearest tick that is initialized and <= the lower & upper ticks
/// @param qty Liquidity quantity to mint
/// @param data Data (if any) to be passed through to the callback
/// @return qty0 token0 quantity sent to the pool in exchange for the minted liquidity
/// @return qty1 token1 quantity sent to the pool in exchange for the minted liquidity
/// @return feeGrowthInside position's updated feeGrowthInside value
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
int24[2] calldata ticksPrevious,
uint128 qty,
bytes calldata data
)
external
returns (
uint256 qty0,
uint256 qty1,
uint256 feeGrowthInside
);
/// @notice Remove liquidity from the caller
/// Also sends reinvestment tokens (fees) to the caller for any fees collected
/// while the position is in range
/// Reinvestment tokens have to be burnt via #burnRTokens in exchange for token0 and token1
/// @param tickLower Position's lower tick for which to burn liquidity
/// @param tickUpper Position's upper tick for which to burn liquidity
/// @param qty Liquidity quantity to burn
/// @return qty0 token0 quantity sent to the caller
/// @return qty1 token1 quantity sent to the caller
/// @return feeGrowthInside position's updated feeGrowthInside value
function burn(
int24 tickLower,
int24 tickUpper,
uint128 qty
)
external
returns (
uint256 qty0,
uint256 qty1,
uint256 feeGrowthInside
);
/// @notice Burns reinvestment tokens in exchange to receive the fees collected in token0 and token1
/// @param qty Reinvestment token quantity to burn
/// @param isLogicalBurn true if burning rTokens without returning any token0/token1
/// otherwise should transfer token0/token1 to sender
/// @return qty0 token0 quantity sent to the caller for burnt reinvestment tokens
/// @return qty1 token1 quantity sent to the caller for burnt reinvestment tokens
function burnRTokens(uint256 qty, bool isLogicalBurn)
external
returns (uint256 qty0, uint256 qty1);
/// @notice Swap token0 -> token1, or vice versa
/// @dev This method's caller receives a callback in the form of ISwapCallback#swapCallback
/// @dev swaps will execute up to limitSqrtP or swapQty is fully used
/// @param recipient The address to receive the swap output
/// @param swapQty The swap quantity, which implicitly configures the swap as exact input (>0), or exact output (<0)
/// @param isToken0 Whether the swapQty is specified in token0 (true) or token1 (false)
/// @param limitSqrtP the limit of sqrt price after swapping
/// could be MAX_SQRT_RATIO-1 when swapping 1 -> 0 and MIN_SQRT_RATIO+1 when swapping 0 -> 1 for no limit swap
/// @param data Any data to be passed through to the callback
/// @return qty0 Exact token0 qty sent to recipient if < 0. Minimally received quantity if > 0.
/// @return qty1 Exact token1 qty sent to recipient if < 0. Minimally received quantity if > 0.
function swap(
address recipient,
int256 swapQty,
bool isToken0,
uint160 limitSqrtP,
bytes calldata data
) external returns (int256 qty0, int256 qty1);
/// @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 IFlashCallback#flashCallback
/// @dev Fees collected are sent to the feeTo address if it is set in Factory
/// @param recipient The address which will receive the token0 and token1 quantities
/// @param qty0 token0 quantity to be loaned to the recipient
/// @param qty1 token1 quantity to be loaned to the recipient
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 qty0,
uint256 qty1,
bytes calldata data
) external;
/// @notice sync fee of position
/// @param tickLower Position's lower tick
/// @param tickUpper Position's upper tick
function tweakPosZeroLiq(int24 tickLower, int24 tickUpper)
external returns(uint256 feeGrowthInsideLast);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IPoolEvents {
/// @notice Emitted only once per pool when #initialize is first called
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtP The initial price of the pool
/// @param tick The initial tick of the pool
event Initialize(uint160 sqrtP, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @dev transfers reinvestment tokens for any collected fees earned by the position
/// @param sender address that minted the liquidity
/// @param owner address of owner of the position
/// @param tickLower position's lower tick
/// @param tickUpper position's upper tick
/// @param qty liquidity minted to the position range
/// @param qty0 token0 quantity needed to mint the liquidity
/// @param qty1 token1 quantity needed to mint the liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 qty,
uint256 qty0,
uint256 qty1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev transfers reinvestment tokens for any collected fees earned by the position
/// @param owner address of owner of the position
/// @param tickLower position's lower tick
/// @param tickUpper position's upper tick
/// @param qty liquidity removed
/// @param qty0 token0 quantity withdrawn from removal of liquidity
/// @param qty1 token1 quantity withdrawn from removal of liquidity
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 qty,
uint256 qty0,
uint256 qty1
);
/// @notice Emitted when reinvestment tokens are burnt
/// @param owner address which burnt the reinvestment tokens
/// @param qty reinvestment token quantity burnt
/// @param qty0 token0 quantity sent to owner for burning reinvestment tokens
/// @param qty1 token1 quantity sent to owner for burning reinvestment tokens
event BurnRTokens(address indexed owner, uint256 qty, uint256 qty0, uint256 qty1);
/// @notice Emitted for swaps by the pool between token0 and token1
/// @param sender Address that initiated the swap call, and that received the callback
/// @param recipient Address that received the swap output
/// @param deltaQty0 Change in pool's token0 balance
/// @param deltaQty1 Change in pool's token1 balance
/// @param sqrtP Pool's sqrt price after the swap
/// @param liquidity Pool's liquidity after the swap
/// @param currentTick Log base 1.0001 of pool's price after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 deltaQty0,
int256 deltaQty1,
uint160 sqrtP,
uint128 liquidity,
int24 currentTick
);
/// @notice Emitted by the pool for any flash loans of token0/token1
/// @param sender The address that initiated the flash loan, and that received the callback
/// @param recipient The address that received the flash loan quantities
/// @param qty0 token0 quantity loaned to the recipient
/// @param qty1 token1 quantity loaned to the recipient
/// @param paid0 token0 quantity paid for the flash, which can exceed qty0 + fee
/// @param paid1 token1 quantity paid for the flash, which can exceed qty0 + fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 qty0,
uint256 qty1,
uint256 paid0,
uint256 paid1
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IFactory} from '../IFactory.sol';
import {IPoolOracle} from '../oracle/IPoolOracle.sol';
interface IPoolStorage {
/// @notice The contract that deployed the pool, which must adhere to the IFactory interface
/// @return The contract address
function factory() external view returns (IFactory);
/// @notice The oracle contract that stores necessary data for price oracle
/// @return The contract address
function poolOracle() external view returns (IPoolOracle);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (IERC20);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (IERC20);
/// @notice The fee to be charged for a swap in basis points
/// @return The swap fee in basis points
function swapFeeUnits() external view returns (uint24);
/// @notice The pool tick distance
/// @dev Ticks can only be initialized and used at multiples of this value
/// It remains an int24 to avoid casting even though it is >= 1.
/// e.g: a tickDistance of 5 means ticks can be initialized every 5th tick, i.e., ..., -10, -5, 0, 5, 10, ...
/// @return The tick distance
function tickDistance() external view returns (int24);
/// @notice Maximum gross liquidity that an initialized tick can have
/// @dev This is to prevent overflow the pool's active base liquidity (uint128)
/// 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 maxTickLiquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross total liquidity amount from positions that uses this tick as a lower or upper tick
/// liquidityNet how much liquidity changes when the pool tick crosses above the tick
/// feeGrowthOutside the fee growth on the other side of the tick relative to the current tick
/// secondsPerLiquidityOutside the seconds per unit of liquidity spent on the other side of the tick relative to the current tick
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside,
uint128 secondsPerLiquidityOutside
);
/// @notice Returns the previous and next initialized ticks of a specific tick
/// @dev If specified tick is uninitialized, the returned values are zero.
/// @param tick The tick to look up
function initializedTicks(int24 tick) external view returns (int24 previous, int24 next);
/// @notice Returns the information about a position by the position's key
/// @return liquidity the liquidity quantity of the position
/// @return feeGrowthInsideLast fee growth inside the tick range as of the last mint / burn action performed
function getPositions(
address owner,
int24 tickLower,
int24 tickUpper
) external view returns (uint128 liquidity, uint256 feeGrowthInsideLast);
/// @notice Fetches the pool's prices, ticks and lock status
/// @return sqrtP sqrt of current price: sqrt(token1/token0)
/// @return currentTick pool's current tick
/// @return nearestCurrentTick pool's nearest initialized tick that is <= currentTick
/// @return locked true if pool is locked, false otherwise
function getPoolState()
external
view
returns (
uint160 sqrtP,
int24 currentTick,
int24 nearestCurrentTick,
bool locked
);
/// @notice Fetches the pool's liquidity values
/// @return baseL pool's base liquidity without reinvest liqudity
/// @return reinvestL the liquidity is reinvested into the pool
/// @return reinvestLLast last cached value of reinvestL, used for calculating reinvestment token qty
function getLiquidityState()
external
view
returns (
uint128 baseL,
uint128 reinvestL,
uint128 reinvestLLast
);
/// @return feeGrowthGlobal All-time fee growth per unit of liquidity of the pool
function getFeeGrowthGlobal() external view returns (uint256);
/// @return secondsPerLiquidityGlobal All-time seconds per unit of liquidity of the pool
/// @return lastUpdateTime The timestamp in which secondsPerLiquidityGlobal was last updated
function getSecondsPerLiquidityData()
external
view
returns (uint128 secondsPerLiquidityGlobal, uint32 lastUpdateTime);
/// @notice Calculates and returns the active time per unit of liquidity until current block.timestamp
/// @param tickLower The lower tick (of a position)
/// @param tickUpper The upper tick (of a position)
/// @return secondsPerLiquidityInside active time (multiplied by 2^96)
/// between the 2 ticks, per unit of liquidity.
function getSecondsPerLiquidityInside(int24 tickLower, int24 tickUpper)
external
view
returns (uint128 secondsPerLiquidityInside);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IPoolOracle {
/// @notice Owner withdrew funds in the pool oracle in case some funds are stuck there
event OwnerWithdrew(
address indexed owner,
address indexed token,
uint256 indexed amount
);
/// @notice Emitted by the Pool Oracle for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param pool The pool address to update
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
address pool,
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Initalize observation data for the caller.
function initializeOracle(uint32 time)
external
returns (uint16 cardinality, uint16 cardinalityNext);
/// @notice Write a new oracle entry into the array
/// and update the observation index and cardinality
/// Read the Oralce.write function for more details
function writeNewEntry(
uint16 index,
uint32 blockTimestamp,
int24 tick,
uint128 liquidity,
uint16 cardinality,
uint16 cardinalityNext
)
external
returns (uint16 indexUpdated, uint16 cardinalityUpdated);
/// @notice Write a new oracle entry into the array, take the latest observaion data as inputs
/// and update the observation index and cardinality
/// Read the Oralce.write function for more details
function write(
uint32 blockTimestamp,
int24 tick,
uint128 liquidity
)
external
returns (uint16 indexUpdated, uint16 cardinalityUpdated);
/// @notice Increase the maximum number of price observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param pool The pool address to be updated
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(
address pool,
uint16 observationCardinalityNext
)
external;
/// @notice Returns the accumulator values as of each time seconds ago from the latest block time in the array of `secondsAgos`
/// @dev Reverts if `secondsAgos` > oldest observation
/// @dev It fetches the latest current tick data from the pool
/// Read the Oracle.observe function for more details
function observeFromPool(
address pool,
uint32[] memory secondsAgos
)
external view
returns (int56[] memory tickCumulatives);
/// @notice Returns the accumulator values as the time seconds ago from the latest block time of secondsAgo
/// @dev Reverts if `secondsAgo` > oldest observation
/// @dev It fetches the latest current tick data from the pool
/// Read the Oracle.observeSingle function for more details
function observeSingleFromPool(
address pool,
uint32 secondsAgo
)
external view
returns (int56 tickCumulative);
/// @notice Return the latest pool observation data given the pool address
function getPoolObservation(address pool)
external view
returns (bool initialized, uint16 index, uint16 cardinality, uint16 cardinalityNext);
/// @notice Returns data about a specific observation index
/// @param pool The pool address of the observations array to fetch
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function getObservationAt(address pool, uint256 index)
external view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
bool initialized
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IBasePositionManagerEvents {
/// @notice Emitted when a token is minted for a given position
/// @param tokenId the newly minted tokenId
/// @param poolId poolId of the token
/// @param liquidity liquidity minted to the position range
/// @param amount0 token0 quantity needed to mint the liquidity
/// @param amount1 token1 quantity needed to mint the liquidity
event MintPosition(
uint256 indexed tokenId,
uint80 indexed poolId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when a token is burned
/// @param tokenId id of the token
event BurnPosition(uint256 indexed tokenId);
/// @notice Emitted when add liquidity
/// @param tokenId id of the token
/// @param liquidity the increase amount of liquidity
/// @param amount0 token0 quantity needed to increase liquidity
/// @param amount1 token1 quantity needed to increase liquidity
/// @param additionalRTokenOwed additional rToken earned
event AddLiquidity(
uint256 indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
/// @notice Emitted when remove liquidity
/// @param tokenId id of the token
/// @param liquidity the decease amount of liquidity
/// @param amount0 token0 quantity returned when remove liquidity
/// @param amount1 token1 quantity returned when remove liquidity
/// @param additionalRTokenOwed additional rToken earned
event RemoveLiquidity(
uint256 indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
/// @notice Emitted when burn position's RToken
/// @param tokenId id of the token
/// @param rTokenBurn amount of position's RToken burnt
event BurnRToken(uint256 indexed tokenId, uint256 rTokenBurn);
/// @notice Emitted when sync fee growth
/// @param tokenId id of the token
/// @param additionalRTokenOwed additional rToken earned
event SyncFeeGrowth(uint256 indexed tokenId, uint256 additionalRTokenOwed);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {IERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721, IERC721Enumerable {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import {MathConstants as C} from '../../libraries/MathConstants.sol';
import {FullMath} from '../../libraries/FullMath.sol';
import {SafeCast} from '../../libraries/SafeCast.sol';
library LiquidityMath {
using SafeCast for uint256;
/// @notice Gets liquidity from qty 0 and the price range
/// qty0 = liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))
/// => liquidity = qty0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param lowerSqrtP A lower sqrt price
/// @param upperSqrtP An upper sqrt price
/// @param qty0 amount of token0
/// @return liquidity amount of returned liquidity to not exceed the qty0
function getLiquidityFromQty0(
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty0
) internal pure returns (uint128) {
uint256 liq = FullMath.mulDivFloor(lowerSqrtP, upperSqrtP, C.TWO_POW_96);
unchecked {
return FullMath.mulDivFloor(liq, qty0, upperSqrtP - lowerSqrtP).toUint128();
}
}
/// @notice Gets liquidity from qty 1 and the price range
/// @dev qty1 = liquidity * (sqrt(upper) - sqrt(lower))
/// thus, liquidity = qty1 / (sqrt(upper) - sqrt(lower))
/// @param lowerSqrtP A lower sqrt price
/// @param upperSqrtP An upper sqrt price
/// @param qty1 amount of token1
/// @return liquidity amount of returned liquidity to not exceed to qty1
function getLiquidityFromQty1(
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty1
) internal pure returns (uint128) {
unchecked {
return FullMath.mulDivFloor(qty1, C.TWO_POW_96, upperSqrtP - lowerSqrtP).toUint128();
}
}
/// @notice Gets liquidity given price range and 2 qties of token0 and token1
/// @param currentSqrtP current price
/// @param lowerSqrtP A lower sqrt price
/// @param upperSqrtP An upper sqrt price
/// @param qty0 amount of token0 - at most
/// @param qty1 amount of token1 - at most
/// @return liquidity amount of returned liquidity to not exceed the given qties
function getLiquidityFromQties(
uint160 currentSqrtP,
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty0,
uint256 qty1
) internal pure returns (uint128) {
if (currentSqrtP <= lowerSqrtP) {
return getLiquidityFromQty0(lowerSqrtP, upperSqrtP, qty0);
}
if (currentSqrtP >= upperSqrtP) {
return getLiquidityFromQty1(lowerSqrtP, upperSqrtP, qty1);
}
uint128 liq0 = getLiquidityFromQty0(currentSqrtP, upperSqrtP, qty0);
uint128 liq1 = getLiquidityFromQty1(lowerSqrtP, currentSqrtP, qty1);
return liq0 < liq1 ? liq0 : liq1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
/// @title Callback for IPool#mint
/// @notice Any contract that calls IPool#mint must implement this interface
interface IMintCallback {
/// @notice Called to `msg.sender` after minting liquidity via IPool#mint.
/// @dev This function's implementation must send pool tokens to the pool for the minted LP tokens.
/// The caller of this method must be checked to be a Pool deployed by the canonical Factory.
/// @param deltaQty0 The token0 quantity to be sent to the pool.
/// @param deltaQty1 The token1 quantity to be sent to the pool.
/// @param data Data passed through by the caller via the IPool#mint call
function mintCallback(
uint256 deltaQty0,
uint256 deltaQty1,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
/// @title Helper to transfer token or ETH
library TokenHelper {
using SafeERC20 for IERC20;
/// @dev Transfer token from the sender to the receiver
/// @notice If the sender is the contract address, should just call transfer token to receiver
/// otherwise, tansfer tokens from the sender to the receiver
function transferToken(
IERC20 token,
uint256 amount,
address sender,
address receiver
) internal {
if (sender == address(this)) {
token.safeTransfer(receiver, amount);
} else {
token.safeTransferFrom(sender, receiver, amount);
}
}
/// @dev Transfer ETh to the receiver
function transferEth(address receiver, uint256 amount) internal {
if (receiver == address(this)) return;
(bool success, ) = payable(receiver).call{value: amount}('');
require(success, 'transfer eth failed');
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
/// @title Interface for WETH
interface IWETH is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity 0.8.9;
import {IFactory} from '../../interfaces/IFactory.sol';
/// @title Immutable state
/// @notice Immutable state used by periphery contracts
abstract contract ImmutablePeripheryStorage {
address public immutable factory;
address public immutable WETH;
bytes32 internal immutable poolInitHash;
constructor(address _factory, address _WETH) {
factory = _factory;
WETH = _WETH;
poolInitHash = IFactory(_factory).poolInitHash();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.0;
pragma abicoder v2;
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}