// SPDX-License-Identifier: MIT// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)pragmasolidity ^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.
*/abstractcontractContext{
function_msgSender() internalviewvirtualreturns (address) {
returnmsg.sender;
}
function_msgData() internalviewvirtualreturns (bytescalldata) {
returnmsg.data;
}
}
Contract Source Code
File 2 of 25: EnumerableSet.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (utils/structs/EnumerableSet.sol)// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.pragmasolidity ^0.8.0;/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/libraryEnumerableSet{
// To implement this library for multiple types with as little code// repetition as possible, we write it in terms of a generic Set type with// bytes32 values.// The Set implementation uses private functions, and user-facing// implementations (such as AddressSet) are just wrappers around the// underlying Set.// This means that we can only create new EnumerableSets for types that fit// in bytes32.structSet {
// Storage of set valuesbytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0// means a value is not in the set.mapping(bytes32=>uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/function_add(Set storage set, bytes32 value) privatereturns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
returntrue;
} else {
returnfalse;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/function_remove(Set storage set, bytes32 value) privatereturns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slotuint256 valueIndex = set._indexes[value];
if (valueIndex !=0) {
// Equivalent to contains(set, value)// To delete an element from the _values array in O(1), we swap the element to delete with the last one in// the array, and then remove the last element (sometimes called as 'swap and pop').// This modifies the order of the array, as noted in {at}.uint256 toDeleteIndex = valueIndex -1;
uint256 lastIndex = set._values.length-1;
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slotdelete set._indexes[value];
returntrue;
} else {
returnfalse;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/function_contains(Set storage set, bytes32 value) privateviewreturns (bool) {
return set._indexes[value] !=0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/function_length(Set storage set) privateviewreturns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/function_at(Set storage set, uint256 index) privateviewreturns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/function_values(Set storage set) privateviewreturns (bytes32[] memory) {
return set._values;
}
// Bytes32SetstructBytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/functionadd(Bytes32Set storage set, bytes32 value) internalreturns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/functionremove(Bytes32Set storage set, bytes32 value) internalreturns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(Bytes32Set storage set, bytes32 value) internalviewreturns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(Bytes32Set storage set) internalviewreturns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/functionat(Bytes32Set storage set, uint256 index) internalviewreturns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionvalues(Bytes32Set storage set) internalviewreturns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
// AddressSetstructAddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/functionadd(AddressSet storage set, address value) internalreturns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/functionremove(AddressSet storage set, address value) internalreturns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(AddressSet storage set, address value) internalviewreturns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(AddressSet storage set) internalviewreturns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/functionat(AddressSet storage set, uint256 index) internalviewreturns (address) {
returnaddress(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionvalues(AddressSet storage set) internalviewreturns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
// UintSetstructUintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/functionadd(UintSet storage set, uint256 value) internalreturns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/functionremove(UintSet storage set, uint256 value) internalreturns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/functioncontains(UintSet storage set, uint256 value) internalviewreturns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/functionlength(UintSet storage set) internalviewreturns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/functionat(UintSet storage set, uint256 index) internalviewreturns (uint256) {
returnuint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/functionvalues(UintSet storage set) internalviewreturns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assemblyassembly {
result := store
}
return result;
}
}
Contract Source Code
File 3 of 25: FixedPoint96.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.4.0;/// @title FixedPoint96/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)/// @dev Used in SqrtPriceMath.sollibraryFixedPoint96{
uint8internalconstant RESOLUTION =96;
uint256internalconstant Q96 =0x1000000000000000000000000;
}
Contract Source Code
File 4 of 25: FullMath.sol
// SPDX-License-Identifier: MIT// Sourced from OpenZepplin but edited to remove un-needed functions// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.solpragmasolidity ^0.8.0;/**
* @dev Standard math utilities missing in the Solidity language.
*/libraryFullMath{
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/functionmulDiv(uint256 x, uint256 y, uint256 denominator) internalpurereturns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use// 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 productuint256 prod1; // Most significant 256 bits of the productassembly {
let mm :=mulmod(x, y, not(0))
prod0 :=mul(x, y)
prod1 :=sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.if (prod1 ==0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.// The surrounding unchecked block does not change this fact.// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////// 512 by 256 division.///////////////////////////////////////////////// Make division exact by subtracting the remainder from [prod1 prod0].uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder :=mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 :=sub(prod1, gt(remainder, prod0))
prod0 :=sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.// See https://cs.stackexchange.com/q/138556/92363.// Does not overflow because the denominator cannot be zero at this stage in the function.uint256 twos = denominator & (~denominator +1);
assembly {
// Divide denominator by twos.
denominator :=div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 :=div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos :=add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
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 for// four bits. That is, denominator * inv = 1 mod 2^4.uint256 inverse = (3* denominator) ^2;
// Use the 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.
inverse *=2- denominator * inverse; // inverse mod 2^8
inverse *=2- denominator * inverse; // inverse mod 2^16
inverse *=2- denominator * inverse; // inverse mod 2^32
inverse *=2- denominator * inverse; // inverse mod 2^64
inverse *=2- denominator * inverse; // inverse mod 2^128
inverse *=2- denominator * inverse; // inverse mod 2^256// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1// is no longer required.
result = prod0 * inverse;
return result;
}
}
}
Contract Source Code
File 5 of 25: ICountryList.sol
// SPDX-License-Identifier: UNLICENSEDpragmasolidity 0.8.19;/**
* @dev Interface of the CountryList contract
*/interfaceICountryList{
functioncountryIsValid (uint16 _countryCode) externalviewreturns (bool);
}
Contract Source Code
File 6 of 25: IERC20.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)pragmasolidity ^0.8.0;/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/interfaceIERC20{
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/eventTransfer(addressindexedfrom, addressindexed 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.
*/eventApproval(addressindexed owner, addressindexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/functiontotalSupply() externalviewreturns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/functionbalanceOf(address account) externalviewreturns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/functiontransfer(address to, uint256 amount) externalreturns (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.
*/functionallowance(address owner, address spender) externalviewreturns (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.
*/functionapprove(address spender, uint256 amount) externalreturns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` 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.
*/functiontransferFrom(addressfrom,
address to,
uint256 amount
) externalreturns (bool);
}
Contract Source Code
File 7 of 25: IERC721Receiver.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)pragmasolidity ^0.8.0;/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/interfaceIERC721Receiver{
/**
* @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 `IERC721Receiver.onERC721Received.selector`.
*/functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externalreturns (bytes4);
}
// SPDX-License-Identifier: UNLICENSEDpragmasolidity ^0.8.9;// Importing from @uniswap doesnt work with @openzepplins latest release so this is refactored// Source: https://github.com/Uniswap/v3-periphery/blob/main/contracts/interfaces/INonfungiblePositionManager.solinterfaceINonfungiblePositionManager{
functionapprove(address to, uint256 tokenId) external;
functionsafeTransferFrom(addressfrom,
address to,
uint256 tokenId
) external;
structMintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
functionmint(
MintParams calldata params
)
externalpayablereturns (uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
structPosition {
uint96 nonce;
address operator;
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
uint128 tokensOwed0;
uint128 tokensOwed1;
}
functionpositions(uint256 tokenId
)
externalviewreturns (uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
structIncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`/// @param params tokenId The ID of the token for which liquidity is being increased,/// amount0Desired The desired amount of token0 to be spent,/// amount1Desired The desired amount of token1 to be spent,/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,/// deadline The time by which the transaction must be included to effect the change/// @return liquidity The new liquidity amount as a result of the increase/// @return amount0 The amount of token0 to acheive resulting liquidity/// @return amount1 The amount of token1 to acheive resulting liquidityfunctionincreaseLiquidity(IncreaseLiquidityParams calldata params)
externalpayablereturns (uint128 liquidity,
uint256 amount0,
uint256 amount1
);
structDecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position/// @param params tokenId The ID of the token for which liquidity is being decreased,/// amount The amount by which liquidity will be decreased,/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,/// deadline The time by which the transaction must be included to effect the change/// @return amount0 The amount of token0 accounted to the position's tokens owed/// @return amount1 The amount of token1 accounted to the position's tokens owedfunctiondecreaseLiquidity(DecreaseLiquidityParams calldata params)
externalpayablereturns (uint256 amount0, uint256 amount1);
structCollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
functioncollect(
CollectParams calldata params
) externalpayablereturns (uint256 amount0, uint256 amount1);
functionfactory() externalviewreturns (address);
functionburn(uint256 tokenId) externalpayable;
}
Contract Source Code
File 10 of 25: IUNCX_LiquidityLocker_UniV3.sol
// SPDX-License-Identifier: UNLICENSED// ALL RIGHTS RESERVED// UNCX by SDDTech reserves all rights on this code. You may not copy these contracts.pragmasolidity 0.8.19;import"./uniswap-updated/INonfungiblePositionManager.sol";
/**
* @dev Interface of the UNCX UniswapV3 Liquidity Locker
*/interfaceIUNCX_LiquidityLocker_UniV3{
structFeeStruct {
string name; // name by which the fee is accesseduint256 lpFee; // 100 = 1%, 10,000 = 100%uint256 collectFee; // 100 = 1%, 10,000 = 100%uint256 flatFee; // in amount tokensaddress flatFeeToken; // address(0) = ETH otherwise ERC20 address expected
}
structLock {
uint256 lock_id; // unique nonce per lock
INonfungiblePositionManager nftPositionManager; // the nft position manager of the uniswap forkaddress pool; // the pool addressuint256 nft_id; // the nft token id of the nft belonging to the nftPositionManager (there could be two nfts with id = 1, belonging to different amm forks and position managers)address owner; // the owner who can collect and withdrawaddress pendingOwner; // two step process ownership transfer, the pending owner must accept ownership to own the lockaddress additionalCollector; // an additional address allowed to call collect (ideal for contracts to auto collect without having to use owner)address collectAddress; // The address to which automatic collections are sentuint256 unlockDate; // unlock date of the lock in secondsuint16 countryCode; // the country code of the locker / businessuint256 ucf; // collect fee
}
structLockParams {
INonfungiblePositionManager nftPositionManager; // the NFT Position manager of the Uniswap V3 forkuint256 nft_id; // the nft token_idaddress dustRecipient; // receiver of dust tokens which do not fit into liquidity and initial collection feesaddress owner; // owner of the lockaddress additionalCollector; // an additional address allowed to call collect (ideal for contracts to auto collect without having to use owner)address collectAddress; // The address to which automatic collections are sentuint256 unlockDate; // unlock date of the lock in secondsuint16 countryCode; // the country code of the locker / businessstring feeName; // The fee name key you wish to accept, use "DEFAULT" if in doubtbytes[] r; // use an empty array => []
}
// User functionsfunctionlock (LockParams calldata params) externalpayablereturns (uint256 lockId);
functioncollect (uint256 lockId, address recipient, uint128 amount0Max, uint128 amount1Max) externalreturns (uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1);
functionwithdraw (uint256 lockId, address receiver) external;
functionmigrate (uint256 lockId) external;
functionrelock(uint256 lockId, uint256 unlockDate) external;
functionsetAdditionalCollector (uint256 lockId, address additionalCollector) external;
functionsetCollectAddress (uint256 lockId, address collectAddress) external;
functiontransferLockOwnership (uint256 lockId, address newOwner) external;
functionacceptLockOwnership (uint256 lockId, address collectAddress) external;
functiondecreaseLiquidity(uint256 lockId, INonfungiblePositionManager.DecreaseLiquidityParams calldata params) externalpayablereturns (uint256 amount0, uint256 amount1);
functionincreaseLiquidity(uint256 lockId, INonfungiblePositionManager.IncreaseLiquidityParams calldata params) externalpayablereturns (uint128 liquidity, uint256 amount0, uint256 amount1);
// Admin functionsfunctionallowNftPositionManager (address nftPositionManager) external;
functionsetMigrator(address migrator) external;
functionsetUCF(uint256 lockId, uint256 ucf) external;
functionsetMigrateInContract (address migrateInContract) external;
// GettersfunctiongetLocksLength() externalviewreturns (uint256);
functiongetLock(uint256 lockId) externalviewreturns (Lock memory lock);
functiongetNumUserLocks(address user) externalviewreturns (uint256 numLocks);
functiongetUserLockAtIndex(address user, uint256 index) externalviewreturns (Lock memory lock);
functiongetFee (stringmemory name) externalviewreturns (FeeStruct memory);
functiongetAmountsForLiquidity (int24 currentTick, int24 tickLower, int24 tickHigher, uint128 liquidity) externalpurereturns (uint256 amount0, uint256 amount1);
functionnftPositionManagerIsAllowed (address nftPositionManager) externalviewreturns (bool);
// EventseventonLock(uint256 lock_id,
address nftPositionManager,
uint256 nft_id,
address owner,
address additionalCollector,
address collectAddress,
uint256 unlockDate,
uint16 countryCode,
uint256 collectFee,
address poolAddress,
INonfungiblePositionManager.Position position
);
eventonWithdraw(uint256 lock_id, address owner, address receiver);
eventonLockOwnershipTransferStarted(uint256 lockId, address currentOwner, address pendingOwner);
eventonTransferLockOwnership(uint256 lockId, address oldOwner, address newOwner, address newCollectAddress);
eventonMigrate(uint256 lockId);
eventonSetAdditionalCollector(uint256 lockId, address additionalCollector);
eventonSetCollectAddress(uint256 lockId, address collectAddress);
eventonSetMigrator(address migrator);
eventonRelock(uint256 lockId, uint256 unlockDate);
eventonIncreaseLiquidity(uint256 lockId);
eventonDecreaseLiquidity(uint256 lockId);
eventonRemoveFee(bytes32 nameHash);
eventonAddFee(bytes32 nameHash, string name, uint256 lpFee, uint256 collectFee, uint256 flatFee, address flatFeeToken);
eventonEditFee(bytes32 nameHash, string name, uint256 lpFee, uint256 collectFee, uint256 flatFee, address flatFeeToken);
eventonSetUCF(uint256 lockId, uint256 ucf);
eventOnAllowNftPositionManager(address nftPositionManager);
}
Contract Source Code
File 11 of 25: IUniswapV3Factory.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title The interface for the Uniswap V3 Factory/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol feesinterfaceIUniswapV3Factory{
/// @notice Emitted when the owner of the factory is changed/// @param oldOwner The owner before the owner was changed/// @param newOwner The owner after the owner was changedeventOwnerChanged(addressindexed oldOwner, addressindexed newOwner);
/// @notice Emitted when a pool is created/// @param token0 The first token of the pool by address sort order/// @param token1 The second token of the pool by address sort order/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip/// @param tickSpacing The minimum number of ticks between initialized ticks/// @param pool The address of the created pooleventPoolCreated(addressindexed token0,
addressindexed token1,
uint24indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory/// @param fee The enabled fee, denominated in hundredths of a bip/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given feeeventFeeAmountEnabled(uint24indexed fee, int24indexed tickSpacing);
/// @notice Returns the current owner of the factory/// @dev Can be changed by the current owner via setOwner/// @return The address of the factory ownerfunctionowner() externalviewreturns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee/// @return The tick spacingfunctionfeeAmountTickSpacing(uint24 fee) externalviewreturns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order/// @param tokenA The contract address of either token0 or token1/// @param tokenB The contract address of the other token/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip/// @return pool The pool addressfunctiongetPool(address tokenA,
address tokenB,
uint24 fee
) externalviewreturns (address pool);
/// @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 fee The desired fee for the pool/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments/// are invalid./// @return pool The address of the newly created poolfunctioncreatePool(address tokenA,
address tokenB,
uint24 fee
) externalreturns (address pool);
/// @notice Updates the owner of the factory/// @dev Must be called by the current owner/// @param _owner The new owner of the factoryfunctionsetOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing/// @dev Fee amounts may never be removed once enabled/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amountfunctionenableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
Contract Source Code
File 12 of 25: IUniswapV3Pool.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;import'./pool/IUniswapV3PoolImmutables.sol';
import'./pool/IUniswapV3PoolState.sol';
import'./pool/IUniswapV3PoolDerivedState.sol';
import'./pool/IUniswapV3PoolActions.sol';
import'./pool/IUniswapV3PoolOwnerActions.sol';
import'./pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform/// to the ERC20 specification/// @dev The pool interface is broken up into many smaller piecesinterfaceIUniswapV3PoolisIUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents{
}
Contract Source Code
File 13 of 25: IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title Permissionless pool actions/// @notice Contains pool methods that can be called by anyoneinterfaceIUniswapV3PoolActions{
/// @notice Sets the initial price for the pool/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96functioninitialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends/// on tickLower, tickUpper, the amount of liquidity, and the current price./// @param recipient The address for which the liquidity will be created/// @param tickLower The lower tick of the position in which to add liquidity/// @param tickUpper The upper tick of the position in which to add liquidity/// @param amount The amount of liquidity to mint/// @param data Any data that should be passed through to the callback/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callbackfunctionmint(address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytescalldata data
) externalreturns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity./// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity./// @param recipient The address which should receive the fees collected/// @param tickLower The lower tick of the position for which to collect fees/// @param tickUpper The upper tick of the position for which to collect fees/// @param amount0Requested How much token0 should be withdrawn from the fees owed/// @param amount1Requested How much token1 should be withdrawn from the fees owed/// @return amount0 The amount of fees collected in token0/// @return amount1 The amount of fees collected in token1functioncollect(address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) externalreturns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0/// @dev Fees must be collected separately via a call to #collect/// @param tickLower The lower tick of the position for which to burn liquidity/// @param tickUpper The upper tick of the position for which to burn liquidity/// @param amount How much liquidity to burn/// @return amount0 The amount of token0 sent to the recipient/// @return amount1 The amount of token1 sent to the recipientfunctionburn(int24 tickLower,
int24 tickUpper,
uint128 amount
) externalreturns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback/// @param recipient The address to receive the output of the swap/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this/// value after the swap. If one for zero, the price cannot be greater than this value after the swap/// @param data Any data to be passed through to the callback/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positivefunctionswap(address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytescalldata data
) externalreturns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling/// with 0 amount{0,1} and sending the donation amount(s) from the callback/// @param recipient The address which will receive the token0 and token1 amounts/// @param amount0 The amount of token0 to send/// @param amount1 The amount of token1 to send/// @param data Any data to be passed through to the callbackfunctionflash(address recipient,
uint256 amount0,
uint256 amount1,
bytescalldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to/// the input observationCardinalityNext./// @param observationCardinalityNext The desired minimum number of observations for the pool to storefunctionincreaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
Contract Source Code
File 14 of 25: IUniswapV3PoolDerivedState.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title Pool state that is not stored/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the/// blockchain. The functions here may have variable gas costs.interfaceIUniswapV3PoolDerivedState{
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,/// you must call it with secondsAgos = [3600, 0]./// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio./// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block/// timestampfunctionobserve(uint32[] calldata secondsAgos)
externalviewreturns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed./// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first/// snapshot is taken and the second snapshot is taken./// @param tickLower The lower tick of the range/// @param tickUpper The upper tick of the range/// @return tickCumulativeInside The snapshot of the tick accumulator for the range/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range/// @return secondsInside The snapshot of seconds per liquidity for the rangefunctionsnapshotCumulativesInside(int24 tickLower, int24 tickUpper)
externalviewreturns (int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
Contract Source Code
File 15 of 25: IUniswapV3PoolEvents.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title Events emitted by a pool/// @notice Contains all events emitted by the poolinterfaceIUniswapV3PoolEvents{
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pooleventInitialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position/// @param sender The address that minted the liquidity/// @param owner The owner of the position and recipient of any minted liquidity/// @param tickLower The lower tick of the position/// @param tickUpper The upper tick of the position/// @param amount The amount of liquidity minted to the position range/// @param amount0 How much token0 was required for the minted liquidity/// @param amount1 How much token1 was required for the minted liquidityeventMint(address sender,
addressindexed owner,
int24indexed tickLower,
int24indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees/// @param owner The owner of the position for which fees are collected/// @param tickLower The lower tick of the position/// @param tickUpper The upper tick of the position/// @param amount0 The amount of token0 fees collected/// @param amount1 The amount of token1 fees collectedeventCollect(addressindexed owner,
address recipient,
int24indexed tickLower,
int24indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect/// @param owner The owner of the position for which liquidity is removed/// @param tickLower The lower tick of the position/// @param tickUpper The upper tick of the position/// @param amount The amount of liquidity to remove/// @param amount0 The amount of token0 withdrawn/// @param amount1 The amount of token1 withdrawneventBurn(addressindexed owner,
int24indexed tickLower,
int24indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1/// @param sender The address that initiated the swap call, and that received the callback/// @param recipient The address that received the output of the swap/// @param amount0 The delta of the token0 balance of the pool/// @param amount1 The delta of the token1 balance of the pool/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96/// @param liquidity The liquidity of the pool after the swap/// @param tick The log base 1.0001 of price of the pool after the swapeventSwap(addressindexed sender,
addressindexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1/// @param sender The address that initiated the swap call, and that received the callback/// @param recipient The address that received the tokens from flash/// @param amount0 The amount of token0 that was flashed/// @param amount1 The amount of token1 that was flashed/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the feeeventFlash(addressindexed sender,
addressindexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index/// just before a mint/swap/burn./// @param observationCardinalityNextOld The previous value of the next observation cardinality/// @param observationCardinalityNextNew The updated value of the next observation cardinalityeventIncreaseObservationCardinalityNext(uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool/// @param feeProtocol0Old The previous value of the token0 protocol fee/// @param feeProtocol1Old The previous value of the token1 protocol fee/// @param feeProtocol0New The updated value of the token0 protocol fee/// @param feeProtocol1New The updated value of the token1 protocol feeeventSetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner/// @param sender The address that collects the protocol fees/// @param recipient The address that receives the collected protocol fees/// @param amount0 The amount of token0 protocol fees that is withdrawn/// @param amount0 The amount of token1 protocol fees that is withdrawneventCollectProtocol(addressindexed sender, addressindexed recipient, uint128 amount0, uint128 amount1);
}
Contract Source Code
File 16 of 25: IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title Pool state that never changes/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same valuesinterfaceIUniswapV3PoolImmutables{
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface/// @return The contract addressfunctionfactory() externalviewreturns (address);
/// @notice The first of the two tokens of the pool, sorted by address/// @return The token contract addressfunctiontoken0() externalviewreturns (address);
/// @notice The second of the two tokens of the pool, sorted by address/// @return The token contract addressfunctiontoken1() externalviewreturns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6/// @return The feefunctionfee() externalviewreturns (uint24);
/// @notice The pool tick spacing/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, .../// This value is an int24 to avoid casting even though it is always positive./// @return The tick spacingfunctiontickSpacing() externalviewreturns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool/// @return The max amount of liquidity per tickfunctionmaxLiquidityPerTick() externalviewreturns (uint128);
}
Contract Source Code
File 17 of 25: IUniswapV3PoolOwnerActions.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title Permissioned pool actions/// @notice Contains pool methods that may only be called by the factory ownerinterfaceIUniswapV3PoolOwnerActions{
/// @notice Set the denominator of the protocol's % share of the fees/// @param feeProtocol0 new protocol fee for token0 of the pool/// @param feeProtocol1 new protocol fee for token1 of the poolfunctionsetFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool/// @param recipient The address to which collected protocol fees should be sent/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0/// @return amount0 The protocol fee collected in token0/// @return amount1 The protocol fee collected in token1functioncollectProtocol(address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) externalreturns (uint128 amount0, uint128 amount1);
}
Contract Source Code
File 18 of 25: IUniswapV3PoolState.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;/// @title Pool state that can change/// @notice These methods compose the pool's state, and can change with any frequency including multiple times/// per transactioninterfaceIUniswapV3PoolState{
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas/// when accessed externally./// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value/// tick The current tick of the pool, i.e. according to the last tick transition that was run./// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick/// boundary./// observationIndex The index of the last oracle observation that was written,/// observationCardinality The current maximum number of observations stored in the pool,/// observationCardinalityNext The next maximum number of observations, to be updated when the observation./// feeProtocol The protocol fee for both tokens of the pool./// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee./// unlocked Whether the pool is currently locked to reentrancyfunctionslot0()
externalviewreturns (uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool/// @dev This value can overflow the uint256functionfeeGrowthGlobal0X128() externalviewreturns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool/// @dev This value can overflow the uint256functionfeeGrowthGlobal1X128() externalviewreturns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol/// @dev Protocol fees will never exceed uint128 max in either tokenfunctionprotocolFees() externalviewreturns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool/// @dev This value has no relationship to the total liquidity across all ticksfunctionliquidity() externalviewreturns (uint128);
/// @notice Look up information about a specific tick in the pool/// @param tick The tick to look up/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or/// tick upper,/// liquidityNet how much liquidity changes when the pool price crosses the tick,/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,/// secondsOutside the seconds spent on the other side of the tick from the current tick,/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false./// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0./// In addition, these values are only relative and must be used only in comparison to previous snapshots for/// a specific position.functionticks(int24 tick)
externalviewreturns (uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more informationfunctiontickBitmap(int16 wordPosition) externalviewreturns (uint256);
/// @notice Returns the information about a position by the position's key/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper/// @return _liquidity The amount of liquidity in the position,/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/pokefunctionpositions(bytes32 key)
externalviewreturns (uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index/// @param index The element of the observations array to fetch/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time/// ago, rather than at a specific index in the array./// @return blockTimestamp The timestamp of the observation,/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,/// Returns initialized whether the observation has been initialized and the values are safe to usefunctionobservations(uint256 index)
externalviewreturns (uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
Contract Source Code
File 19 of 25: LiquidityAmounts.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.5.0;import {FullMath} from"./FullMath.sol";
import'@uniswap/v3-core/contracts/libraries/FixedPoint96.sol';
/// @title Liquidity amount functions/// @notice Provides functions for computing liquidity amounts from token amounts and priceslibraryLiquidityAmounts{
/// @notice Downcasts uint256 to uint128/// @param x The uint258 to be downcasted/// @return y The passed value, downcasted to uint128functiontoUint128(uint256 x) privatepurereturns (uint128 y) {
require((y =uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary/// @param amount0 The amount0 being sent in/// @return liquidity The amount of returned liquidityfunctiongetLiquidityForAmount0(uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internalpurereturns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower))./// @param sqrtRatioAX96 A sqrt price representing the first tick boundary/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary/// @param amount1 The amount1 being sent in/// @return liquidity The amount of returned liquidityfunctiongetLiquidityForAmount1(uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internalpurereturns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current/// pool prices and the prices at the tick boundaries/// @param sqrtRatioX96 A sqrt price representing the current pool prices/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary/// @param amount0 The amount of token0 being sent in/// @param amount1 The amount of token1 being sent in/// @return liquidity The maximum amount of liquidity receivedfunctiongetLiquidityForAmounts(uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internalpurereturns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} elseif (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary/// @param liquidity The liquidity being valued/// @return amount0 The amount of token0functiongetAmount0ForLiquidity(uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internalpurereturns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary/// @param liquidity The liquidity being valued/// @return amount1 The amount of token1functiongetAmount1ForLiquidity(uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internalpurereturns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current/// pool prices and the prices at the tick boundaries/// @param sqrtRatioX96 A sqrt price representing the current pool prices/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary/// @param liquidity The liquidity being valued/// @return amount0 The amount of token0/// @return amount1 The amount of token1functiongetAmountsForLiquidity(uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internalpurereturns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} elseif (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
Contract Source Code
File 20 of 25: Ownable.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)pragmasolidity ^0.8.0;import"../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/abstractcontractOwnableisContext{
addressprivate _owner;
eventOwnershipTransferred(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/modifieronlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/functionowner() publicviewvirtualreturns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/function_checkOwner() internalviewvirtual{
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/functionrenounceOwnership() publicvirtualonlyOwner{
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualonlyOwner{
require(newOwner !=address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtual{
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
Contract Source Code
File 21 of 25: Ownable2Step.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (access/Ownable2Step.sol)pragmasolidity ^0.8.0;import"./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/abstractcontractOwnable2StepisOwnable{
addressprivate _pendingOwner;
eventOwnershipTransferStarted(addressindexed previousOwner, addressindexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/functionpendingOwner() publicviewvirtualreturns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/functiontransferOwnership(address newOwner) publicvirtualoverrideonlyOwner{
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/function_transferOwnership(address newOwner) internalvirtualoverride{
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/functionacceptOwnership() external{
address sender = _msgSender();
require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
_transferOwnership(sender);
}
}
Contract Source Code
File 22 of 25: ReentrancyGuard.sol
// SPDX-License-Identifier: MIT// OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol)pragmasolidity ^0.8.0;/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/abstractcontractReentrancyGuard{
// Booleans are more expensive than uint256 or any type that takes up a full// word because each write operation emits an extra SLOAD to first read the// slot's contents, replace the bits taken up by the boolean, and then write// back. This is the compiler's defense against contract upgrades and// pointer aliasing, and it cannot be disabled.// The values being non-zero value makes deployment a bit more expensive,// but in exchange the refund on every call to nonReentrant will be lower in// amount. Since refunds are capped to a percentage of the total// transaction's gas, it is best to keep them low in cases like this one, to// increase the likelihood of the full refund coming into effect.uint256privateconstant _NOT_ENTERED =1;
uint256privateconstant _ENTERED =2;
uint256private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/modifiernonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function_nonReentrantBefore() private{
// On the first call to nonReentrant, _status will be _NOT_ENTEREDrequire(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function_nonReentrantAfter() private{
// By storing the original value once again, a refund is triggered (see// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
Contract Source Code
File 23 of 25: TickMath.sol
// SPDX-License-Identifier: GPL-3.0pragmasolidity ^0.8.9;/// @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**128libraryTickMath{
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128int24internalconstant MIN_TICK =-887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128int24internalconstant MAX_TICK =-MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)uint160internalconstant MIN_SQRT_RATIO =4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)uint160internalconstant MAX_SQRT_RATIO =1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96/// @dev Throws if |tick| > max tick/// @param tick The input tick for the above formula/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)/// at the given tickfunctiongetSqrtRatioAtTick(int24 tick)
internalpurereturns (uint160 sqrtPriceX96)
{
uint256 absTick =
tick <0 ? uint256(-int256(tick)) : uint256(int256(tick));
// EDIT: 0.8 compatibilityrequire(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;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.// we then downcast because we know the result always fits within 160 bits due to our tick input constraint// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 =uint160(
(ratio >>32) + (ratio % (1<<32) ==0 ? 0 : 1)
);
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may/// ever return./// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96/// @return tick The greatest tick for which the ratio is less than or equal to the input ratiofunctiongetTickAtSqrtRatio(uint160 sqrtPriceX96)
internalpurereturns (int24 tick)
{
// second inequality must be < because the price can never reach the price at the max tickrequire(
sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO,
"R"
);
uint256 ratio =uint256(sqrtPriceX96) <<32;
uint256 r = ratio;
uint256 msb =0;
assembly {
let f :=shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(5, gt(r, 0xFFFFFFFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(4, gt(r, 0xFFFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(3, gt(r, 0xFF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(2, gt(r, 0xF))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=shl(1, gt(r, 0x3))
msb :=or(msb, f)
r :=shr(f, r)
}
assembly {
let f :=gt(r, 0x1)
msb :=or(msb, f)
}
if (msb >=128) r = ratio >> (msb -127);
else r = ratio << (127- msb);
int256 log_2 = (int256(msb) -128) <<64;
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(63, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(62, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(61, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(60, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(59, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(58, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(57, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(56, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(55, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(54, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(53, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(52, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(51, f))
r :=shr(f, r)
}
assembly {
r :=shr(127, mul(r, r))
let f :=shr(128, r)
log_2 :=or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 *255738958999603826347141; // 128.128 numberint24 tickLow =int24(
(log_sqrt10001 -3402992956809132418596140100660247210) >>128
);
int24 tickHi =int24(
(log_sqrt10001 +291339464771989622907027621153398088495) >>128
);
tick = tickLow == tickHi
? tickLow
: getSqrtRatioAtTick(tickHi) <= sqrtPriceX96
? tickHi
: tickLow;
}
}
Contract Source Code
File 24 of 25: TransferHelper.sol
// SPDX-License-Identifier: GPL-2.0-or-laterpragmasolidity >=0.6.0;import'@openzeppelin/contracts/token/ERC20/IERC20.sol';
libraryTransferHelper{
/// @notice Transfers tokens from the targeted address to the given destination/// @notice Errors with 'STF' if transfer fails/// @param token The contract address of the token to be transferred/// @param from The originating address from which the tokens will be transferred/// @param to The destination address of the transfer/// @param value The amount to be transferredfunctionsafeTransferFrom(address token,
addressfrom,
address to,
uint256 value
) internal{
(bool success, bytesmemory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length==0||abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient/// @dev Errors with ST if transfer fails/// @param token The contract address of the token which will be transferred/// @param to The recipient of the transfer/// @param value The value of the transferfunctionsafeTransfer(address token,
address to,
uint256 value
) internal{
(bool success, bytesmemory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length==0||abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token/// @dev Errors with 'SA' if transfer fails/// @param token The contract address of the token to be approved/// @param to The target of the approval/// @param value The amount of the given token the target will be allowed to spendfunctionsafeApprove(address token,
address to,
uint256 value
) internal{
(bool success, bytesmemory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length==0||abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers ETH to the recipient address/// @dev Fails with `STE`/// @param to The destination of the transfer/// @param value The value to be transferredfunctionsafeTransferETH(address to, uint256 value) internal{
(bool success, ) = to.call{value: value}(newbytes(0));
require(success, 'STE');
}
}
Contract Source Code
File 25 of 25: UNCX_LiquidityLocker_UniV3.sol
// SPDX-License-Identifier: UNLICENSED// ALL RIGHTS RESERVED// UNCX by SDDTech reserves all rights on this code. You may not copy these contracts.pragmasolidity 0.8.19;import {IERC20} from"@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC721Receiver} from"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import {ReentrancyGuard} from"@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {Ownable2Step} from"@openzeppelin/contracts/access/Ownable2Step.sol";
import {EnumerableSet} from"@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IUniswapV3Factory} from"@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol";
import {IUniswapV3Pool} from"@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {TransferHelper} from"@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol";
import {TickMath} from'./uniswap-updated/TickMath.sol';
import {LiquidityAmounts} from'./uniswap-updated/LiquidityAmounts.sol';
import {INonfungiblePositionManager} from"./uniswap-updated/INonfungiblePositionManager.sol";
import {ICountryList} from"./ICountryList.sol";
import {IMigrateV3NFT} from"./IMigrateV3NFT.sol";
import {IUNCX_LiquidityLocker_UniV3} from"./IUNCX_LiquidityLocker_UniV3.sol";
/*
Version 2.0
The UNCX UniV3 Liquidity Locker Contract locks whitelisted exact forks of Uniswap V3's liquidity NFT's in this contract.
This contract locks a Uniswap V3 forks NFT in the exact range it is when lock() is called, and the range cannot be changed until the lock has expired.
Lock owners are still free to collect fees as they please, and add liquidity to their position, while the liquidity remains locked.
You can also still view your NFT and its metrics on uniswap while it is locked. e.g. https://app.uniswap.org/#/pools/69
*/interfaceIFeeResolver{
functionuseFee(bytes[] memory r, address sender) externalreturns (IUNCX_LiquidityLocker_UniV3.FeeStruct memory fee);
}
contractUNCX_LiquidityLocker_UniV3isIUNCX_LiquidityLocker_UniV3, Ownable2Step, IERC721Receiver, ReentrancyGuard{
usingEnumerableSetforEnumerableSet.UintSet;
usingEnumerableSetforEnumerableSet.Bytes32Set;
usingEnumerableSetforEnumerableSet.AddressSet;
mapping(bytes32 nameHash => FeeStruct) private FEES; // map keccak(fee_name) to fee struct e.g. keccak256("DEFAULT") => FeeStruct
EnumerableSet.Bytes32Set private FEE_LOOKUP; // contains keccak(feeName)
EnumerableSet.AddressSet private allowedNftPositionManagers;
IFeeResolver public FEE_RESOLVER; // Resolve R feesaddresspublic AUTO_COLLECT_ACCOUNT; // account controlled by UNCX to auto collect fees if a fee option involving collection fees was acceptedaddresspayablepublic FEE_ADDR_LP; // LP fee destinationaddresspayablepublic FEE_ADDR_COLLECT; // collect fee destinationuint256publicconstant FEE_DENOMINATOR =10000; // denominator for all fees
ICountryList publicimmutable COUNTRY_LIST;
IMigrateV3NFT public MIGRATOR; // migrate to future amm versions while liquidity remains lockedaddresspublic MIGRATE_IN; // address of the migration in contractuint256public NONCE =0; // incremental lock nonce counter, this is the unique ID for the next lock// If a locks unlock date is set to ETERNAL_LOCK the lock is eternal and not ever withdrawable.// It can however be migrated by the owner to future AMMS and is therefore preferrable to burning liquidity, or sending liquidity NFT's to the dead address.uint256publicconstant ETERNAL_LOCK =type(uint256).max;
// a mapping of lock_id => Lockmapping(uint256 lockId => Lock) public LOCKS;
mapping(address userAddress => EnumerableSet.UintSet) private USER_LOCKS; // a set of all lock_ids owned by a user, useful for on chain enumeration.constructor(ICountryList _countryList, addresspayable _autoCollectAddress, addresspayable _lpFeeReceiver, addresspayable _collectFeeReceiver) {
COUNTRY_LIST = _countryList;
AUTO_COLLECT_ACCOUNT = _autoCollectAddress;
FEE_ADDR_LP = _lpFeeReceiver;
FEE_ADDR_COLLECT = _collectFeeReceiver;
addOrEditFee("DEFAULT", 50, 200, 0, address(0));
addOrEditFee("LVP", 80, 100, 0, address(0));
addOrEditFee("LLP", 30, 350, 0, address(0));
}
functionallowNftPositionManager (address _nftPositionManager) externalonlyOwner{
allowedNftPositionManagers.add(_nftPositionManager);
emit OnAllowNftPositionManager(_nftPositionManager);
}
functionsetFeeResolver (IFeeResolver _resolver) externalonlyOwner{
FEE_RESOLVER = _resolver;
}
functionsetFeeParams (address _autoCollectAccount, addresspayable _lpFeeReceiver, addresspayable _collectFeeReceiver) externalonlyOwner{
AUTO_COLLECT_ACCOUNT = _autoCollectAccount;
FEE_ADDR_LP = _lpFeeReceiver;
FEE_ADDR_COLLECT = _collectFeeReceiver;
}
functionaddOrEditFee(stringmemory _name, uint256 _lpFee, uint256 _collectFee, uint256 _flatFee, address _flatFeeToken) publiconlyOwner{
bytes32 nameHash =keccak256(abi.encodePacked(_name));
FeeStruct memory newFee = FeeStruct(_name, _lpFee, _collectFee, _flatFee, _flatFeeToken);
FEES[nameHash] = newFee;
if (!FEE_LOOKUP.contains(nameHash)) {
FEE_LOOKUP.add(nameHash);
emit onAddFee(nameHash, newFee.name, newFee.lpFee, newFee.collectFee, newFee.flatFee, newFee.flatFeeToken);
} else {
emit onEditFee(nameHash, newFee.name, newFee.lpFee, newFee.collectFee, newFee.flatFee, newFee.flatFeeToken);
}
}
functionremoveFee (stringmemory _name) externalonlyOwner{
bytes32 nameHash =keccak256(abi.encodePacked(_name));
require(nameHash !=keccak256(abi.encodePacked("DEFAULT")), "DEFAULT");
require(FEE_LOOKUP.contains(nameHash), "Fee not exists");
FEE_LOOKUP.remove(nameHash);
delete FEES[nameHash];
emit onRemoveFee(nameHash);
}
functiongetFee (stringmemory _name) publicoverrideviewreturns (FeeStruct memory) {
bytes32 feeHash =keccak256(abi.encodePacked(_name));
require(FEE_LOOKUP.contains(feeHash), "NOT FOUND");
return FEES[feeHash];
}
functiongetFeeOptionAtIndex (uint256 _index) externalviewreturns (FeeStruct memory) {
return FEES[FEE_LOOKUP.at(_index)];
}
functiongetFeeOptionLength () externalviewreturns (uint256) {
return FEE_LOOKUP.length();
}
functiondeductFlatFee (FeeStruct memory fee) private{
if (fee.flatFeeToken ==address(0)) { // fee in gas tokenrequire(msg.value== fee.flatFee, 'FLAT FEE');
(bool success, ) = FEE_ADDR_LP.call{value: fee.flatFee}("");
if (!success) {
revert("Gas token transfer failed");
}
} else { // fee in another token
TransferHelper.safeTransferFrom(fee.flatFeeToken, msg.sender, FEE_ADDR_LP, fee.flatFee);
}
}
/**
@dev locks nft in its current range and collects fees and sends them back to collector
@param params The locking params as seen in IUNCX_LiquidityLocker_UniV3.sol
*
* This will fail with rebasing tokens (liquidity nfts already stuck on univ3).
*/functionlock (LockParams calldata params) externalpayableoverridenonReentrantreturns (uint256) {
require(params.owner !=address(0), "OWNER CANNOT = address(0)");
require(params.collectAddress !=address(0), 'COLLECT_ADDR');
require(params.unlockDate <1e10|| params.unlockDate == ETERNAL_LOCK, 'MILLISECONDS'); // prevents errors when timestamp entered in millisecondsrequire(params.unlockDate >block.timestamp, 'DATE PASSED');
require(COUNTRY_LIST.countryIsValid(params.countryCode), 'COUNTRY');
require(allowedNftPositionManagers.contains(address(params.nftPositionManager)), 'INVALID NFT POSITION MANAGER');
FeeStruct memory fee;
if (msg.sender== MIGRATE_IN) {
fee.collectFee =abi.decode(params.r[0], (uint256));
} else {
if (params.r.length>0) {
fee = FEE_RESOLVER.useFee(params.r, msg.sender);
} else {
fee = getFee(params.feeName);
}
if (fee.flatFee >0) {
deductFlatFee(fee);
}
}
params.nftPositionManager.safeTransferFrom(msg.sender, address(this), params.nft_id);
INonfungiblePositionManager.Position memory position;
(,,position.token0,position.token1,position.fee,position.tickLower,position.tickUpper,position.liquidity,,,,) = params.nftPositionManager.positions(params.nft_id);
IUniswapV3Factory factory = IUniswapV3Factory(params.nftPositionManager.factory());
address pool = factory.getPool(position.token0, position.token1, position.fee);
// collect fees for user to prevent being charged a fee on existing fees
params.nftPositionManager.collect(INonfungiblePositionManager.CollectParams(params.nft_id, params.dustRecipient, type(uint128).max, type(uint128).max));
// Take lp feeif (fee.lpFee >0) {
uint128 liquidity = _getLiquidity(params.nftPositionManager, params.nft_id);
params.nftPositionManager.decreaseLiquidity(INonfungiblePositionManager.DecreaseLiquidityParams(params.nft_id, uint128(liquidity * fee.lpFee / FEE_DENOMINATOR), 0, 0, block.timestamp));
params.nftPositionManager.collect(INonfungiblePositionManager.CollectParams(params.nft_id, FEE_ADDR_LP, type(uint128).max, type(uint128).max));
}
Lock memory newLock;
newLock.lock_id = NONCE;
newLock.nftPositionManager = params.nftPositionManager;
newLock.pool = pool;
newLock.nft_id = params.nft_id;
newLock.owner = params.owner;
newLock.additionalCollector = params.additionalCollector;
newLock.collectAddress = params.collectAddress;
newLock.unlockDate = params.unlockDate;
newLock.countryCode = params.countryCode;
newLock.ucf = fee.collectFee;
LOCKS[NONCE] = newLock;
USER_LOCKS[params.owner].add(NONCE);
NONCE++;
emitLockEvent(newLock.lock_id);
return newLock.lock_id;
}
functionemitLockEvent (uint256 _lockId) private{
Lock memory newLock = LOCKS[_lockId];
INonfungiblePositionManager.Position memory position;
(,,position.token0,position.token1,position.fee,position.tickLower,position.tickUpper,position.liquidity,,,,) = newLock.nftPositionManager.positions(newLock.nft_id);
emit onLock(
newLock.lock_id,
address(newLock.nftPositionManager),
newLock.nft_id,
newLock.owner,
newLock.additionalCollector,
newLock.collectAddress,
newLock.unlockDate,
newLock.countryCode,
newLock.ucf,
newLock.pool,
position
);
}
/**
* @dev Collect fees to _recipient if msg.sender is the owner of _lockId
*/functioncollect (uint256 _lockId, address _recipient, uint128 _amount0Max, uint128 _amount1Max) externaloverridenonReentrantreturns (uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1) {
(amount0, amount1, fee0, fee1) = _collect(_lockId, _recipient, _amount0Max, _amount1Max);
}
/**
* @dev Private collect function, wrap this in re-entrancy guard calls
*/function_collect (uint256 _lockId, address _recipient, uint128 _amount0Max, uint128 _amount1Max) privatereturns(uint256 amount0, uint256 amount1, uint256 fee0, uint256 fee1) {
Lock memory userLock = LOCKS[_lockId];
bool collectorIsBot = AUTO_COLLECT_ACCOUNT ==msg.sender;
require(userLock.owner ==msg.sender|| userLock.additionalCollector ==msg.sender|| collectorIsBot, "OWNER");
if (userLock.ucf ==0) { // No Protocol fee
(amount0, amount1) = userLock.nftPositionManager.collect(INonfungiblePositionManager.CollectParams(userLock.nft_id, _recipient, _amount0Max, _amount1Max));
} else { // Protocol fees
(,,address _token0,address _token1,,,,,,,,) = userLock.nftPositionManager.positions(userLock.nft_id);
uint256 balance0 = IERC20(_token0).balanceOf(address(this));
uint256 balance1 = IERC20(_token1).balanceOf(address(this));
userLock.nftPositionManager.collect(INonfungiblePositionManager.CollectParams(userLock.nft_id, address(this), _amount0Max, _amount1Max));
balance0 = IERC20(_token0).balanceOf(address(this)) - balance0;
balance1 = IERC20(_token1).balanceOf(address(this)) - balance1;
address feeTo = collectorIsBot ? _recipient : FEE_ADDR_COLLECT;
address remainderTo = collectorIsBot ? userLock.collectAddress : _recipient;
if (balance0 >0) {
fee0 = balance0 * userLock.ucf / FEE_DENOMINATOR;
TransferHelper.safeTransfer(_token0, feeTo, fee0);
amount0 = balance0 - fee0;
TransferHelper.safeTransfer(_token0, remainderTo, amount0);
}
if (balance1 >0) {
fee1 = balance1 * userLock.ucf / FEE_DENOMINATOR;
TransferHelper.safeTransfer(_token1, feeTo, fee1);
amount1 = balance1 - fee1;
TransferHelper.safeTransfer(_token1, remainderTo, amount1);
}
}
}
/**
* @dev increases liquidity. Can be called by anyone.
* You should ideally call increaseLiquidity from the NftPositionManager directly for gas efficiency.
* This method is here just for convenience for some contracts which solely interact with the UNCX lockers / lockIds
*/functionincreaseLiquidity(uint256 _lockId, INonfungiblePositionManager.IncreaseLiquidityParams calldata params) externalpayableoverridenonReentrantreturns (uint128 liquidity, uint256 amount0, uint256 amount1) {
Lock memory userLock = LOCKS[_lockId];
require(userLock.nft_id == params.tokenId, "NFT ID");
(,,address token0,address token1,,,,,,,,) = userLock.nftPositionManager.positions(userLock.nft_id);
uint256 balance0Before = IERC20(token0).balanceOf(address(this));
uint256 balance1Before = IERC20(token1).balanceOf(address(this));
TransferHelper.safeTransferFrom(token0, msg.sender, address(this), params.amount0Desired);
TransferHelper.safeTransferFrom(token1, msg.sender, address(this), params.amount1Desired);
TransferHelper.safeApprove(token0, address(userLock.nftPositionManager), params.amount0Desired);
TransferHelper.safeApprove(token1, address(userLock.nftPositionManager), params.amount1Desired);
(liquidity, amount0, amount1) = userLock.nftPositionManager.increaseLiquidity(params);
uint256 balance0diff = IERC20(token0).balanceOf(address(this)) - balance0Before;
uint256 balance1diff = IERC20(token1).balanceOf(address(this)) - balance1Before;
if (balance0diff >0) {
TransferHelper.safeTransfer(token0, msg.sender, balance0diff);
}
if (balance1diff >0) {
TransferHelper.safeTransfer(token1, msg.sender, balance1diff);
}
emit onIncreaseLiquidity(_lockId); // This can be called directly from the NFT position manager in which case this event won't fire
}
/**
* @dev decrease liquidity if a lock has expired (useful before relocking)
*/functiondecreaseLiquidity(uint256 _lockId, INonfungiblePositionManager.DecreaseLiquidityParams calldata params) externalpayableoverridenonReentrantreturns (uint256 amount0, uint256 amount1) {
isLockAdmin(_lockId);
Lock memory userLock = LOCKS[_lockId];
require(userLock.nft_id == params.tokenId, 'NFT ID');
if (userLock.unlockDate == ETERNAL_LOCK) {
revert('ETERNAL_LOCK');
} else {
require(userLock.unlockDate <block.timestamp, 'NOT YET');
}
_collect(_lockId, msg.sender, type(uint128).max, type(uint128).max); // collect protocol fees
(amount0, amount1) = userLock.nftPositionManager.decreaseLiquidity(params);
userLock.nftPositionManager.collect(INonfungiblePositionManager.CollectParams(userLock.nft_id, msg.sender, type(uint128).max, type(uint128).max));
emit onDecreaseLiquidity(_lockId);
}
/**
* @dev set the unlock date further in the future
*/functionrelock(uint256 _lockId, uint256 _unlockDate) externaloverridenonReentrant{
isLockAdmin(_lockId);
Lock storage userLock = LOCKS[_lockId];
require(_unlockDate > userLock.unlockDate, 'DATE');
require(_unlockDate >block.timestamp, 'DATE PASSED');
require(_unlockDate <1e10|| _unlockDate == ETERNAL_LOCK, 'MILLISECONDS'); // prevents errors when timestamp entered in milliseconds
userLock.unlockDate = _unlockDate;
emit onRelock(_lockId, userLock.unlockDate);
}
/**
* @dev withdraw a UniV3 liquidity NFT and send it to _receiver
* Only callable once unlockDate has expired
*/functionwithdraw (uint256 _lockId, address _receiver) externaloverridenonReentrant{
isLockAdmin(_lockId);
Lock memory userLock = LOCKS[_lockId];
if (userLock.unlockDate == ETERNAL_LOCK) {
revert('ETERNAL_LOCK');
} else {
require(userLock.unlockDate <block.timestamp, 'NOT YET');
}
if (userLock.ucf >0) {
_collect(_lockId, _receiver, type(uint128).max, type(uint128).max);
}
userLock.nftPositionManager.safeTransferFrom(address(this), _receiver, userLock.nft_id);
USER_LOCKS[userLock.owner].remove(_lockId);
emit onWithdraw(_lockId, userLock.owner, _receiver);
delete LOCKS[_lockId]; // clear the state for this lock (reset all values to zero)
}
/**
* @dev set migrate in contract address
*/functionsetMigrateInContract (address _migrateIn) externaloverrideonlyOwner{
MIGRATE_IN = _migrateIn;
}
/**
* @dev migrate a lock to a new amm version (Uniswap V4)
*/functionmigrate (uint256 _lockId) externaloverridenonReentrant{
require(address(MIGRATOR) !=address(0), "NOT SET");
isLockAdmin(_lockId);
Lock memory userLock = LOCKS[_lockId];
userLock.nftPositionManager.approve(address(MIGRATOR), userLock.nft_id);
MIGRATOR.migrate(_lockId, userLock.nftPositionManager, userLock.nft_id);
USER_LOCKS[userLock.owner].remove(_lockId);
delete LOCKS[_lockId]; // clear the state for this lock (reset all values to zero)emit onMigrate(_lockId);
}
/**
* @dev allow a lock owner to add an additional address, usually a contract, to collect fees. Useful for bots
*/functionsetAdditionalCollector (uint256 _lockId, address _additionalCollector) externaloverridenonReentrant{
isLockAdmin(_lockId);
Lock storage userLock = LOCKS[_lockId];
userLock.additionalCollector = _additionalCollector;
emit onSetAdditionalCollector(_lockId, _additionalCollector);
}
/**
* @dev set the adress to which fees are automatically collected
*/functionsetCollectAddress (uint256 _lockId, address _collectAddress) externaloverridenonReentrant{
isLockAdmin(_lockId);
require(_collectAddress !=address(0), 'COLLECT_ADDR');
Lock storage userLock = LOCKS[_lockId];
userLock.collectAddress = _collectAddress;
emit onSetCollectAddress(_lockId, _collectAddress);
}
/**
* @dev transfer ownership of a lock to _newOwner
*/functiontransferLockOwnership (uint256 _lockId, address _newOwner) externaloverridenonReentrant{
isLockAdmin(_lockId);
require(msg.sender!= _newOwner, "SAME OWNER");
Lock storage userLock = LOCKS[_lockId];
userLock.pendingOwner = _newOwner;
emit onLockOwnershipTransferStarted(_lockId, msg.sender, _newOwner);
}
/**
* @dev accept lock ownership transfer
*/functionacceptLockOwnership (uint256 _lockId, address _collectAddress) externaloverridenonReentrant{
Lock storage userLock = LOCKS[_lockId];
require(userLock.pendingOwner ==msg.sender, "OWNER");
address oldOwner = userLock.owner;
USER_LOCKS[userLock.owner].remove(_lockId);
userLock.owner =msg.sender;
userLock.pendingOwner =address(0);
userLock.collectAddress = _collectAddress;
userLock.additionalCollector =address(0);
USER_LOCKS[msg.sender].add(_lockId);
emit onTransferLockOwnership(_lockId, oldOwner, msg.sender, _collectAddress);
}
/**
* @dev set the migrator contract which allows locked LP NFT's to be migrated to future AMM versions
*/functionsetMigrator(address _migrator) externaloverrideonlyOwner{
MIGRATOR = IMigrateV3NFT(_migrator);
emit onSetMigrator(_migrator);
}
/**
* @dev set ucf
*/functionsetUCF(uint256 _lockId, uint256 _ucf) externaloverrideonlyOwner{
Lock storage l = LOCKS[_lockId];
require(_ucf < l.ucf, "L");
l.ucf = _ucf;
emit onSetUCF(_lockId, _ucf);
}
/**
* @dev check if msg.sender is the owner of lock with _lockId
*/functionisLockAdmin (uint256 _lockId) privateview{
Lock memory userLock = LOCKS[_lockId];
require(userLock.owner ==msg.sender, "OWNER");
}
/**
* @dev returns a Lock struct for _lockId
*/functiongetLock(uint256 _lockId) externalviewoverridereturns (Lock memory _lock) {
_lock = LOCKS[_lockId];
}
/**
* @dev gets the number of unique locks in this contract, used to page through the lock array (includes expired and withdrawn locks)
*/functiongetLocksLength() externalviewoverridereturns (uint256) {
return NONCE;
}
/**
* @dev gets the number of locks for a user
*/functiongetNumUserLocks(address _user) externalviewoverridereturns (uint256) {
return USER_LOCKS[_user].length();
}
/**
* @dev gets the lock at a specific index for a user
*/functiongetUserLockAtIndex(address _user, uint256 _index) externalviewoverridereturns (Lock memory) {
return LOCKS[USER_LOCKS[_user].at(_index)];
}
function_setPartialMintParamsFromPosition (INonfungiblePositionManager _nftPositionManager, uint256 _tokenId) privateviewreturns (INonfungiblePositionManager.MintParams memory) {
INonfungiblePositionManager.MintParams memory m;
(,,m.token0,m.token1,m.fee,,,,,,,) = _nftPositionManager.positions(_tokenId);
return m;
}
/**
* @dev check if a nft position manager is whitelisted to lock
*/functionnftPositionManagerIsAllowed (address _nftPositionManager) externalviewreturns (bool) {
return allowedNftPositionManagers.contains(_nftPositionManager);
}
/**
* @dev get a locks liquidity in amounts of token0 and token1 for a generic position (not from state)
*/functiongetAmountsForLiquidity (int24 currentTick, int24 tickLower, int24 tickHigher, uint128 liquidity) publicpureoverridereturns (uint256, uint256) {
return LiquidityAmounts.getAmountsForLiquidity(
TickMath.getSqrtRatioAtTick(currentTick),
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickHigher),
liquidity
);
}
/**
* @dev returns just the liquidity value from a position
*/function_getLiquidity (INonfungiblePositionManager _nftPositionManager, uint256 _tokenId) privateviewreturns (uint128) {
(,,,,,,,uint128 liquidity,,,,) = _nftPositionManager.positions(_tokenId);
return liquidity;
}
/**
* @dev Allows admin to remove any eth mistakenly sent to the contract
*/functionadminRefundEth (uint256 _amount, addresspayable _receiver) externalonlyOwnernonReentrant{
(bool success, ) = _receiver.call{value: _amount}("");
if (!success) {
revert("Gas token transfer failed");
}
}
/**
* @dev Allows admin to remove any ERC20's mistakenly sent to the contract
* Since this contract is only for locking NFT liquidity, this allows removal of ERC20 tokens and cannot remove locked NFT liquidity.
*/functionadminRefundERC20 (address _token, address _receiver, uint256 _amount) externalonlyOwnernonReentrant{
// TransferHelper.safeTransfer = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));// Attempting to transfer nfts with this function (substituting a nft_id for _amount) wil fail with 'ST' as NFTS do not have the same interface
TransferHelper.safeTransfer(_token, _receiver, _amount);
}
functiononERC721Received(address operator,
addressfrom,
uint256 tokenId,
bytescalldata data
) externaloverridereturns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
}