文件 1 的 44:Address.sol
pragma solidity ^0.8.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
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);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
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);
}
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
文件 2 的 44:AntiSnipAttack.sol
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';
library AntiSnipAttack {
using SafeCast for uint256;
using SafeCast for int256;
using SafeCast for int128;
struct Data {
uint32 lastActionTime;
uint32 lockTime;
uint32 unlockTime;
uint256 feesLocked;
}
function initialize(uint32 currentTime) internal pure returns (Data memory data) {
data.lastActionTime = currentTime;
data.lockTime = currentTime;
data.unlockTime = currentTime;
data.feesLocked = 0;
}
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) {
if (_self.feesLocked == 0) return (feesSinceLastAction, 0);
self.feesLocked = 0;
return (_self.feesLocked + feesSinceLastAction, 0);
}
{
uint256 feesClaimableSinceLastActionFeeUnits = Math.min(
C.FEE_UNITS,
(uint256(currentTime - _self.lockTime) * C.FEE_UNITS) / vestingPeriod
);
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
);
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;
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) {
feesBurnable = (_self.feesLocked * liquidityDelta) / uint256(currentLiquidity);
_self.feesLocked -= feesBurnable;
}
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;
}
}
文件 3 的 44:AntiSnipAttackPositionManager.sol
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;
int24[2] memory ticksPrevious;
(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: 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;
}
(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');
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);
}
}
文件 4 的 44:BasePositionManager.sol
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;
mapping(uint80 => PoolInfo) internal _poolInfoById;
mapping(uint256 => Position) internal _positions;
mapping(address => bool) public override isRToken;
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;
int24[2] memory ticksPrevious;
(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: ticksPrevious,
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min
})
);
uint128 tmpLiquidity = pos.liquidity;
uint256 tmpFeeGrowthInsideLast = pos.feeGrowthInsideLast;
if (feeGrowthInsideLast != tmpFeeGrowthInsideLast) {
uint256 feeGrowthInsideDiff;
unchecked {
feeGrowthInsideDiff = feeGrowthInsideLast - tmpFeeGrowthInsideLast;
}
additionalRTokenOwed = FullMath.mulDivFloor(tmpLiquidity, feeGrowthInsideDiff, C.TWO_POW_96);
pos.rTokenOwed += additionalRTokenOwed;
pos.feeGrowthInsideLast = feeGrowthInsideLast;
}
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;
uint256 tmpFeeGrowthInsideLast = pos.feeGrowthInsideLast;
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');
if (feeGrowthInsideLast != tmpFeeGrowthInsideLast) {
uint256 feeGrowthInsideDiff;
unchecked {
feeGrowthInsideDiff = feeGrowthInsideLast - tmpFeeGrowthInsideLast;
}
additionalRTokenOwed = FullMath.mulDivFloor(tmpLiquidity, feeGrowthInsideDiff, C.TWO_POW_96);
pos.rTokenOwed += additionalRTokenOwed;
pos.feeGrowthInsideLast = feeGrowthInsideLast;
}
pos.liquidity = tmpLiquidity - params.liquidity;
emit RemoveLiquidity(params.tokenId, params.liquidity, amount0, amount1, 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;
(amount0, amount1) = pool.burnRTokens(rTokenQty, false);
require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Low return amounts');
}
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];
}
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;
}
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 _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;
}
}
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++);
}
}
文件 5 的 44:Context.sol
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
文件 6 的 44:DeadlineValidation.sol
pragma solidity 0.8.9;
abstract contract DeadlineValidation {
modifier onlyNotExpired(uint256 deadline) {
require(_blockTimestamp() <= deadline, 'Expired');
_;
}
function _blockTimestamp() internal view virtual returns (uint256) {
return block.timestamp;
}
}
文件 7 的 44:ERC165.sol
pragma solidity ^0.8.0;
import "./IERC165.sol";
abstract contract ERC165 is IERC165 {
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
文件 8 的 44:ERC721.sol
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";
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
mapping(uint256 => address) private _owners;
mapping(address => uint256) private _balances;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
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;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
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())) : "";
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
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);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
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);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
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);
}
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");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
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));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
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"
);
}
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);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
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);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
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;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
文件 9 的 44:ERC721Enumerable.sol
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
mapping(uint256 => uint256) private _ownedTokensIndex;
uint256[] private _allTokens;
mapping(uint256 => uint256) private _allTokensIndex;
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
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];
}
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
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);
}
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId;
_ownedTokensIndex[lastTokenId] = tokenIndex;
}
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId;
_allTokensIndex[lastTokenId] = tokenIndex;
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
文件 10 的 44:ERC721Permit.sol
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';
interface IERC1271 {
function isValidSignature(bytes32 hash, bytes memory signature)
external
view
returns (bytes4 magicValue);
}
abstract contract ERC721Permit is DeadlineValidation, ERC721Enumerable, IERC721Permit {
bytes32 public constant override PERMIT_TYPEHASH =
0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad;
bytes32 private immutable nameHash;
bytes32 private immutable versionHash;
bytes32 public immutable override DOMAIN_SEPARATOR;
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(
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);
}
function _getAndIncrementNonce(uint256 tokenId) internal virtual returns (uint256);
function _getChainId() internal view returns (uint256 chainId) {
assembly {
chainId := chainid()
}
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable, IERC721Permit)
returns (bool)
{
return
interfaceId == type(ERC721Enumerable).interfaceId ||
interfaceId == type(IERC721Permit).interfaceId ||
super.supportsInterface(interfaceId);
}
}
文件 11 的 44:FullMath.sol
pragma solidity >=0.8.0;
library FullMath {
function mulDivFloor(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 == 0) {
require(denominator > 0, '0 denom');
assembly {
result := div(prod0, denominator)
}
return result;
}
require(denominator > prod1, 'denom <= prod1');
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
uint256 twos = denominator & (~denominator + 1);
assembly {
denominator := div(denominator, twos)
}
assembly {
prod0 := div(prod0, twos)
}
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
unchecked {
prod0 |= prod1 * twos;
uint256 inv = (3 * denominator) ^ 2;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
inv *= 2 - denominator * inv;
result = prod0 * inv;
}
return 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++;
}
}
}
文件 12 的 44:IBasePositionManager.sol
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 {
uint96 nonce;
address operator;
uint80 poolId;
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
uint256 rTokenOwed;
uint256 feeGrowthInsideLast;
}
struct PoolInfo {
address token0;
uint24 fee;
address token1;
}
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;
}
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
struct RemoveLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
struct BurnRTokenParams {
uint256 tokenId;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
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
);
function burn(uint256 tokenId) external payable;
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);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
文件 13 的 44:IBasePositionManagerEvents.sol
pragma solidity >=0.8.0;
interface IBasePositionManagerEvents {
event MintPosition(
uint256 indexed tokenId,
uint80 indexed poolId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
event BurnPosition(uint256 indexed tokenId);
event AddLiquidity(
uint256 indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
event RemoveLiquidity(
uint256 indexed tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1,
uint256 additionalRTokenOwed
);
}
文件 14 的 44:IERC165.sol
pragma solidity ^0.8.0;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
文件 15 的 44:IERC20.sol
pragma solidity ^0.8.0;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
文件 16 的 44:IERC721.sol
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
文件 17 的 44:IERC721Enumerable.sol
pragma solidity ^0.8.0;
import "../IERC721.sol";
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
文件 18 的 44:IERC721Metadata.sol
pragma solidity ^0.8.0;
import "../IERC721.sol";
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
文件 19 的 44:IERC721Permit.sol
pragma solidity >=0.8.0;
import {IERC721} from '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import {IERC721Enumerable} from '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol';
interface IERC721Permit is IERC721, IERC721Enumerable {
function PERMIT_TYPEHASH() external pure returns (bytes32);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
文件 20 的 44:IERC721Receiver.sol
pragma solidity ^0.8.0;
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
文件 21 的 44:IFactory.sol
pragma solidity >=0.8.0;
interface IFactory {
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed swapFeeUnits,
int24 tickDistance,
address pool
);
event SwapFeeEnabled(uint24 indexed swapFeeUnits, int24 indexed tickDistance);
event VestingPeriodUpdated(uint32 vestingPeriod);
event ConfigMasterUpdated(address oldConfigMaster, address newConfigMaster);
event FeeConfigurationUpdated(address feeTo, uint24 governmentFeeUnits);
event WhitelistEnabled();
event WhitelistDisabled();
function vestingPeriod() external view returns (uint32);
function feeAmountTickDistance(uint24 swapFeeUnits) external view returns (int24);
function configMaster() external view returns (address);
function poolInitHash() external view returns (bytes32);
function feeConfiguration() external view returns (address _feeTo, uint24 _governmentFeeUnits);
function whitelistDisabled() external view returns (bool);
function getWhitelistedNFTManagers() external view returns (address[] memory);
function isWhitelistedNFTManager(address sender) external view returns (bool);
function getPool(
address tokenA,
address tokenB,
uint24 swapFeeUnits
) external view returns (address pool);
function parameters()
external
view
returns (
address factory,
address token0,
address token1,
uint24 swapFeeUnits,
int24 tickDistance
);
function createPool(
address tokenA,
address tokenB,
uint24 swapFeeUnits
) external returns (address pool);
function enableSwapFee(uint24 swapFeeUnits, int24 tickDistance) external;
function updateConfigMaster(address) external;
function updateVestingPeriod(uint32) external;
function updateFeeConfiguration(address feeTo, uint24 governmentFeeUnits) external;
function enableWhitelist() external;
function disableWhitelist() external;
}
文件 22 的 44:IMintCallback.sol
pragma solidity >=0.8.0;
interface IMintCallback {
function mintCallback(
uint256 deltaQty0,
uint256 deltaQty1,
bytes calldata data
) external;
}
文件 23 的 44:IMulticall.sol
pragma solidity >=0.8.0;
pragma abicoder v2;
interface IMulticall {
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
文件 24 的 44:INonfungibleTokenPositionDescriptor.sol
pragma solidity >=0.8.0;
import './IBasePositionManager.sol';
interface INonfungibleTokenPositionDescriptor {
function tokenURI(IBasePositionManager positionManager, uint256 tokenId)
external
view
returns (string memory);
}
文件 25 的 44:IPool.sol
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 {}
文件 26 的 44:IPoolActions.sol
pragma solidity >=0.8.0;
interface IPoolActions {
function unlockPool(uint160 initialSqrtP) external returns (uint256 qty0, uint256 qty1);
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
);
function burn(
int24 tickLower,
int24 tickUpper,
uint128 qty
)
external
returns (
uint256 qty0,
uint256 qty1,
uint256 feeGrowthInside
);
function burnRTokens(uint256 qty, bool isLogicalBurn)
external
returns (uint256 qty0, uint256 qty1);
function swap(
address recipient,
int256 swapQty,
bool isToken0,
uint160 limitSqrtP,
bytes calldata data
) external returns (int256 qty0, int256 qty1);
function flash(
address recipient,
uint256 qty0,
uint256 qty1,
bytes calldata data
) external;
}
文件 27 的 44:IPoolEvents.sol
pragma solidity >=0.8.0;
interface IPoolEvents {
event Initialize(uint160 sqrtP, int24 tick);
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 qty,
uint256 qty0,
uint256 qty1
);
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 qty,
uint256 qty0,
uint256 qty1
);
event BurnRTokens(address indexed owner, uint256 qty, uint256 qty0, uint256 qty1);
event Swap(
address indexed sender,
address indexed recipient,
int256 deltaQty0,
int256 deltaQty1,
uint160 sqrtP,
uint128 liquidity,
int24 currentTick
);
event Flash(
address indexed sender,
address indexed recipient,
uint256 qty0,
uint256 qty1,
uint256 paid0,
uint256 paid1
);
}
文件 28 的 44:IPoolStorage.sol
pragma solidity >=0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {IFactory} from '../IFactory.sol';
interface IPoolStorage {
function factory() external view returns (IFactory);
function token0() external view returns (IERC20);
function token1() external view returns (IERC20);
function swapFeeUnits() external view returns (uint24);
function tickDistance() external view returns (int24);
function maxTickLiquidity() external view returns (uint128);
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside,
uint128 secondsPerLiquidityOutside
);
function initializedTicks(int24 tick) external view returns (int24 previous, int24 next);
function getPositions(
address owner,
int24 tickLower,
int24 tickUpper
) external view returns (uint128 liquidity, uint256 feeGrowthInsideLast);
function getPoolState()
external
view
returns (
uint160 sqrtP,
int24 currentTick,
int24 nearestCurrentTick,
bool locked
);
function getLiquidityState()
external
view
returns (
uint128 baseL,
uint128 reinvestL,
uint128 reinvestLLast
);
function getFeeGrowthGlobal() external view returns (uint256);
function getSecondsPerLiquidityData()
external
view
returns (uint128 secondsPerLiquidityGlobal, uint32 lastUpdateTime);
function getSecondsPerLiquidityInside(int24 tickLower, int24 tickUpper)
external
view
returns (uint128 secondsPerLiquidityInside);
}
文件 29 的 44:IRouterTokenHelper.sol
pragma solidity >=0.8.0;
interface IRouterTokenHelper {
function unwrapWeth(uint256 minAmount, address recipient) external payable;
function refundEth() external payable;
function transferAllTokens(
address token,
uint256 minAmount,
address recipient
) external payable;
}
文件 30 的 44:IWETH.sol
pragma solidity >=0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IWETH is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
文件 31 的 44:ImmutablePeripheryStorage.sol
pragma solidity 0.8.9;
import {IFactory} from '../../interfaces/IFactory.sol';
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();
}
}
文件 32 的 44:LiquidityHelper.sol
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);
}
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);
{
(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}));
}
function _getPool(
address tokenA,
address tokenB,
uint24 fee
) internal view returns (IPool) {
return IPool(PoolAddress.computeAddress(factory, tokenA, tokenB, fee, poolInitHash));
}
}
文件 33 的 44:LiquidityMath.sol
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;
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();
}
}
function getLiquidityFromQty1(
uint160 lowerSqrtP,
uint160 upperSqrtP,
uint256 qty1
) internal pure returns (uint128) {
unchecked {
return FullMath.mulDivFloor(qty1, C.TWO_POW_96, upperSqrtP - lowerSqrtP).toUint128();
}
}
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;
}
}
文件 34 的 44:Math.sol
pragma solidity ^0.8.0;
library Math {
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function average(uint256 a, uint256 b) internal pure returns (uint256) {
return (a & b) + (a ^ b) / 2;
}
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b + (a % b == 0 ? 0 : 1);
}
}
文件 35 的 44:MathConstants.sol
pragma solidity >=0.8.0;
library MathConstants {
uint256 internal constant TWO_FEE_UNITS = 200_000;
uint256 internal constant TWO_POW_96 = 2**96;
uint128 internal constant MIN_LIQUIDITY = 100000;
uint8 internal constant RES_96 = 96;
uint24 internal constant BPS = 10000;
uint24 internal constant FEE_UNITS = 100000;
int24 internal constant MAX_TICK_DISTANCE = 480;
uint256 internal constant MAX_TICK_TRAVEL = 10;
}
文件 36 的 44:Multicall.sol
pragma solidity 0.8.9;
pragma abicoder v2;
import {IMulticall} from '../../interfaces/periphery/IMulticall.sol';
abstract contract Multicall is 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) {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
文件 37 的 44:PoolAddress.sol
pragma solidity 0.8.9;
library PoolAddress {
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)));
}
}
文件 38 的 44:QtyDeltaMath.sol
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';
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);
}
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();
}
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();
}
}
function getQty0FromBurnRTokens(uint160 sqrtP, uint256 liquidity)
internal
pure
returns (uint256)
{
return FullMath.mulDivFloor(liquidity, C.TWO_POW_96, sqrtP);
}
function getQty1FromBurnRTokens(uint160 sqrtP, uint256 liquidity)
internal
pure
returns (uint256)
{
return FullMath.mulDivFloor(liquidity, sqrtP, C.TWO_POW_96);
}
function divCeiling(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y > 0);
assembly {
z := add(div(x, y), gt(mod(x, y), 0))
}
}
}
文件 39 的 44:RouterTokenHelper.sol
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');
}
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);
}
}
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);
}
}
function refundEth() external payable override {
if (address(this).balance > 0) TokenHelper.transferEth(msg.sender, address(this).balance);
}
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);
}
}
}
文件 40 的 44:SafeCast.sol
pragma solidity >=0.8.0;
library SafeCast {
function toUint32(uint256 y) internal pure returns (uint32 z) {
require((z = uint32(y)) == y);
}
function toInt128(uint128 y) internal pure returns (int128 z) {
require(y < 2**127);
z = int128(y);
}
function toUint128(uint256 y) internal pure returns (uint128 z) {
require((z = uint128(y)) == y);
}
function revToUint128(int128 y) internal pure returns (uint128 z) {
unchecked {
return type(uint128).max - uint128(y) + 1;
}
}
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
function revToInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = -int256(y);
}
function revToUint256(int256 y) internal pure returns (uint256 z) {
unchecked {
return type(uint256).max - uint256(y) + 1;
}
}
}
文件 41 的 44:SafeERC20.sol
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
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));
}
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
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));
}
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
文件 42 的 44:Strings.sol
pragma solidity ^0.8.0;
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
function toString(uint256 value) internal pure returns (string memory) {
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);
}
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);
}
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);
}
}
文件 43 的 44:TickMath.sol
pragma solidity >=0.8.0;
library TickMath {
int24 internal constant MIN_TICK = -887272;
int24 internal constant MAX_TICK = -MIN_TICK;
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
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');
uint256 ratio = (absTick & 0x1 != 0)
? 0xfffcb933bd6fad37aa2d162d1a594001
: 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
sqrtP = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
function getTickAtSqrtRatio(uint160 sqrtP) internal pure returns (int24 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;
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;
}
}
文件 44 的 44:TokenHelper.sol
pragma solidity 0.8.9;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
library TokenHelper {
using SafeERC20 for IERC20;
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);
}
}
function transferEth(address receiver, uint256 amount) internal {
if (receiver == address(this)) return;
(bool success, ) = payable(receiver).call{value: amount}('');
require(success, 'transfer eth failed');
}
}
{
"compilationTarget": {
"contracts/periphery/AntiSnipAttackPositionManager.sol": "AntiSnipAttackPositionManager"
},
"evmVersion": "london",
"libraries": {},
"metadata": {
"bytecodeHash": "none"
},
"optimizer": {
"enabled": true,
"runs": 2000
},
"remappings": []
}
[{"inputs":[{"internalType":"address","name":"_factory","type":"address"},{"internalType":"address","name":"_WETH","type":"address"},{"internalType":"address","name":"_descriptor","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"additionalRTokenOwed","type":"uint256"}],"name":"AddLiquidity","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"approved","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"BurnPosition","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"uint80","name":"poolId","type":"uint80"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"MintPosition","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":false,"internalType":"uint128","name":"liquidity","type":"uint128"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"additionalRTokenOwed","type":"uint256"}],"name":"RemoveLiquidity","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"WETH","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"amount0Desired","type":"uint256"},{"internalType":"uint256","name":"amount1Desired","type":"uint256"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct IBasePositionManager.IncreaseLiquidityParams","name":"params","type":"tuple"}],"name":"addLiquidity","outputs":[{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"uint256","name":"additionalRTokenOwed","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"addressToPoolId","outputs":[{"internalType":"uint80","name":"","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"antiSnipAttackData","outputs":[{"internalType":"uint32","name":"lastActionTime","type":"uint32"},{"internalType":"uint32","name":"lockTime","type":"uint32"},{"internalType":"uint32","name":"unlockTime","type":"uint32"},{"internalType":"uint256","name":"feesLocked","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"approve","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"burn","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct IBasePositionManager.BurnRTokenParams","name":"params","type":"tuple"}],"name":"burnRTokens","outputs":[{"internalType":"uint256","name":"rTokenQty","type":"uint256"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"uint160","name":"currentSqrtP","type":"uint160"}],"name":"createAndUnlockPoolIfNecessary","outputs":[{"internalType":"address","name":"pool","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"getApproved","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isRToken","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"address","name":"token1","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"int24[2]","name":"ticksPrevious","type":"int24[2]"},{"internalType":"uint256","name":"amount0Desired","type":"uint256"},{"internalType":"uint256","name":"amount1Desired","type":"uint256"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct IBasePositionManager.MintParams","name":"params","type":"tuple"}],"name":"mint","outputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"uint256","name":"deltaQty0","type":"uint256"},{"internalType":"uint256","name":"deltaQty1","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"mintCallback","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes[]","name":"data","type":"bytes[]"}],"name":"multicall","outputs":[{"internalType":"bytes[]","name":"results","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextPoolId","outputs":[{"internalType":"uint80","name":"","type":"uint80"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"nextTokenId","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ownerOf","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"positions","outputs":[{"components":[{"internalType":"uint96","name":"nonce","type":"uint96"},{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint80","name":"poolId","type":"uint80"},{"internalType":"int24","name":"tickLower","type":"int24"},{"internalType":"int24","name":"tickUpper","type":"int24"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"rTokenOwed","type":"uint256"},{"internalType":"uint256","name":"feeGrowthInsideLast","type":"uint256"}],"internalType":"struct IBasePositionManager.Position","name":"pos","type":"tuple"},{"components":[{"internalType":"address","name":"token0","type":"address"},{"internalType":"uint24","name":"fee","type":"uint24"},{"internalType":"address","name":"token1","type":"address"}],"internalType":"struct IBasePositionManager.PoolInfo","name":"info","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"refundEth","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"uint128","name":"liquidity","type":"uint128"},{"internalType":"uint256","name":"amount0Min","type":"uint256"},{"internalType":"uint256","name":"amount1Min","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"}],"internalType":"struct IBasePositionManager.RemoveLiquidityParams","name":"params","type":"tuple"}],"name":"removeLiquidity","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"},{"internalType":"uint256","name":"additionalRTokenOwed","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes","name":"_data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"index","type":"uint256"}],"name":"tokenOfOwnerByIndex","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"tokenURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"uint256","name":"minAmount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"transferAllTokens","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"transferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"minAmount","type":"uint256"},{"internalType":"address","name":"recipient","type":"address"}],"name":"unwrapWeth","outputs":[],"stateMutability":"payable","type":"function"},{"stateMutability":"payable","type":"receive"}]