Introduction
Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.
I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.
I also build and publish a variety of tools, libraries, and open-source projects.
In this article, I use Bunzz's new DeCipher feature to explore a Uniswap V3 contract, referred to as V3Migrator in the original introduction. The contract examined below is NonfungiblePositionManager.
DeCipher is a service that uses AI to automatically generate contract documentation.
For detailed instructions on using it, see the following article.
This article reflects my personal experience with DeCipher. There may be inaccuracies, so please point them out in the comments if you find any.
The following link leads to the DeCipher page used in this article.
The Etherscan link is below.
Overview
The NonfungiblePositionManager contract is a core component of the Uniswap v3 protocol that manages individual positions in Uniswap v3 liquidity pools. It is used in conjunction with various other contracts.
Individual positions These are non-fungible positions associated with particular price ranges within Uniswap v3 liquidity pools. The Uniswap v3 protocol allows more granular pricing than conventional liquidity pools, using price boundaries called ticks. Each tick represents a particular price interval, and liquidity can be provided within a range of these intervals.
By holding an individual position, users can provide liquidity within a specified price range and earn fees when trades take place in that range. This allows users to provide liquidity efficiently at different market prices and earn fees.
The NonfungiblePositionManager contract handles the creation, management, transfer, and retrieval of information about these positions. It is central to Uniswap v3 because users can create individual positions and modify existing ones through this contract.
Users can primarily perform two types of operations through this contract. First, they can create a position providing liquidity within a specified price range defined by ticks. Second, they can manage ownership and transfers of positions and retrieve information about them, such as token details.
The contract also verifies and executes various actions related to positions, including minting and burning. It works with other contracts to facilitate position creation and management. It includes verification mechanisms to ensure security and correctness.
Usage
The NonfungiblePositionManager smart contract manages non-fungible positions within Uniswap V3 liquidity pools. Users can use it to create, update, and remove positions in a pool. They can also perform other liquidity management operations.
Contract objective
The NonfungiblePositionManager contract aims to provide a standardized interface for managing non-fungible positions in Uniswap V3 liquidity pools. Developers can interact with the contract to create, update, and remove positions. They can also perform other operations related to liquidity management.
Usage instructions
To manage non-fungible positions in Uniswap V3 liquidity pools, follow these steps as described in the original overview.
- Deploy the NonfungiblePositionManager contract.
- Call
createAndInitializePoolIfNecessaryto create a new liquidity pool if it does not exist. - Call
createPositionto create a new non-fungible position within the specified liquidity pool. - Call
increasePositionto increase liquidity in an existing non-fungible position. - Call
decreasePositionto decrease liquidity in an existing non-fungible position. - Call
collectPositionto collect the fees accumulated by a non-fungible position. - Call
burnPositionto remove the non-fungible position and collect accumulated fees. - Call
mintto create a new ERC721 token representing a non-fungible position. - Call
burnto destroy an existing ERC721 token representing a non-fungible position.
Functions
createAndInitializePoolIfNecessary
Creates a new liquidity pool if one does not exist.
createPosition
Creates a new non-fungible position within a liquidity pool.
increasePosition
Increases liquidity in an existing non-fungible position.
decreasePosition
Decreases liquidity in an existing non-fungible position.
collectPosition
Collects fees accumulated by a non-fungible position.
burnPosition
Removes a non-fungible position and collects accumulated fees.
mint
Creates a new ERC721 token representing a non-fungible position.
burn
Destroys an existing ERC721 token representing a non-fungible position.
Events
PositionCreated
Emitted when a new non-fungible position is created.
PositionIncreased
Emitted when liquidity increases in an existing non-fungible position.
PositionDecreased
Emitted when liquidity decreases in an existing non-fungible position.
PositionCollected
Emitted when fees accumulated by a non-fungible position are collected.
PositionBurned
Emitted when a non-fungible position is removed and accumulated fees are collected.
TokenMinted
Emitted when a new ERC721 token is created.
TokenBurned
Emitted when an existing ERC721 token is burned and the token representing a non-fungible position is removed.
Parameters
_factory
_factory is the address of the Uniswap V3 factory contract. The factory contract provides the foundation for creating Uniswap V3 liquidity pools.
_WETH9
Address of the WETH9 contract. WETH9 stands for Wrapped Ether, representing Ethereum's ether (ETH) as the ERC20 token WETH. This allows ether to be handled like other tokens.
_tokenDescriptor
Address of the token descriptor contract. This contract provides detailed information and metadata about tokens (currencies or assets), such as their names and symbols, making them easier to understand and identify.
Contracts
NonfungiblePositionManager
The following sections explain the variables and mappings.
Position
Position
struct Position {
uint96 nonce;
address operator;
uint80 poolId;
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
uint256 feeGrowthInside0LastX128;
uint256 feeGrowthInside1LastX128;
uint128 tokensOwed0;
uint128 tokensOwed1;
}Overview A data structure holding detailed information about a Uniswap position.
Details
nonce- Nonce (unique identifier) used for permits.
operator- Address approved to transfer the token.
poolId- ID of the pool associated with the token.
tickLower、tickUpper- Tick range specifying the price range of the position.
liquidity- Liquidity supplied by the position.
feeGrowthInside0LastX128、feeGrowthInside1LastX128- Fee growth of the aggregate position as of the last action on the individual position.
tokensOwed0、tokensOwed1- Tokens owed to the position as of the last calculation.
Fee growth A concept used in liquidity protocols such as Uniswap V3, indicating how much trading fees have accumulated. Every trade within the liquidity pool increases the fees accumulated by that pool. Fee growth indicates the increase in accumulated fees.
-
Fee accumulation When a trade occurs in the pool, the resulting trading fees accumulate in the pool. These accumulated fees affect fee growth for each position in the pool.
-
Position fee growth Each position (a particular holding of tokens in a liquidity pool) records its fee growth. Position fee growth represents the increase in fees attributable to the position during the period it is held.
-
Fee growth updates Fee growth associated with a position changes as new trades take place. Specifically, fee growth is calculated based on the increase in fees since the previous trade and recorded for the position.
Fee growth is important when position owners collect fees. The amount of fees received by the position is calculated using its fee growth. Fee growth therefore reflects the impact of pool trades and is an important consideration when evaluating a position.
_poolIds
mapping(address => uint80) private _poolIds;Overview A private mapping storing the pool ID corresponding to an address.
_poolIdToPoolKey
mapping(uint80 => PoolAddress.PoolKey) private _poolIdToPoolKey;Overview A mapping storing the pool key corresponding to a pool ID.
_positions
mapping(uint256 => Position) private _positions;Overview A mapping storing position data corresponding to a token ID.
_nextId
uint176 private _nextId = 1;Overview A variable indicating the ID of the next token to be minted.
_nextPoolId
uint80 private _nextPoolId = 1;Overview A variable indicating the next pool ID to be used.
_tokenDescriptor
address private immutable _tokenDescriptor;Overview Address of the token descriptor contract used to generate position token URIs.
The following sections describe the functions in the supplied code.
positions
positions
function positions(uint256 tokenId)
external
view
override
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
Position memory position = _positions[tokenId];
require(position.poolId != 0, 'Invalid token ID');
PoolAddress.PoolKey memory poolKey = _poolIdToPoolKey[position.poolId];
return (
position.nonce,
position.operator,
poolKey.token0,
poolKey.token1,
poolKey.fee,
position.tickLower,
position.tickUpper,
position.liquidity,
position.feeGrowthInside0LastX128,
position.feeGrowthInside1LastX128,
position.tokensOwed0,
position.tokensOwed1
);
}Overview Retrieves detailed information about the position associated with a specified token ID.
Arguments
tokenId- Token ID of the position to retrieve.
Return values
nonce- Position nonce.
operator- Operator address.
token0- Token 0 address.
token1- Token 1 address.
fee- Trading fee.
tickLower- Lower bound of the price range.
tickUpper- Upper bound of the price range.
liquidity- Liquidity.
feeGrowthInside0LastX128- Fee growth for token 0.
feeGrowthInside1LastX128- Fee growth for token 1.
tokensOwed0- Amount of token 0 owed.
tokensOwed1- Amount of token 1 owed.
cachePoolKey
cachePoolKey
function cachePoolKey(address pool, PoolAddress.PoolKey memory poolKey) private returns (uint80 poolId) {
poolId = _poolIds[pool];
if (poolId == 0) {
_poolIds[pool] = (poolId = _nextPoolId++);
_poolIdToPoolKey[poolId] = poolKey;
}
}Overview Caches a pool address and its pool key.
Details Caches the specified pool address and pool key, then returns the pool ID. The cached pool key is stored for later reference.
Arguments
pool- Pool address.
poolKey- Pool key information to cache.
Return values
poolId- Cached pool ID.
mint
mint
function mint(MintParams calldata params)
external
payable
override
checkDeadline(params.deadline)
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
IUniswapV3Pool pool;
(liquidity, amount0, amount1, pool) = addLiquidity(
AddLiquidityParams({
token0: params.token0,
token1: params.token1,
fee: params.fee,
recipient: address(this),
tickLower: params.tickLower,
tickUpper: params.tickUpper,
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min
})
);
_mint(params.recipient, (tokenId = _nextId++));
bytes32 positionKey = PositionKey.compute(address(this), params.tickLower, params.tickUpper);
(, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(positionKey);
// idempotent set
uint80 poolId =
cachePoolKey(
address(pool),
PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee})
);
_positions[tokenId] = Position({
nonce: 0,
operator: address(0),
poolId: poolId,
tickLower: params.tickLower,
tickUpper: params.tickUpper,
liquidity: liquidity,
feeGrowthInside0LastX128: feeGrowthInside0LastX128,
feeGrowthInside1LastX128: feeGrowthInside1LastX128,
tokensOwed0: 0,
tokensOwed1: 0
});
emit IncreaseLiquidity(tokenId, liquidity, amount0, amount1);
}Overview Adds liquidity and mints a token.
Details Adds liquidity and mints a token based on the specified parameters. When adding liquidity, token 0 and token 1 are supplied according to the specified conditions. Fee growth for the supplied tokens is also updated.
Arguments
params- Parameters for adding liquidity.
Return values
tokenId- ID of the minted token.
liquidity- Liquidity added.
amount0- Amount of token 0 added.
amount1- Amount of token 1 added.
increaseLiquidity
increaseLiquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
override
checkDeadline(params.deadline)
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
Position storage position = _positions[params.tokenId];
PoolAddress.PoolKey memory poolKey = _poolIdToPoolKey[position.poolId];
IUniswapV3Pool pool;
(liquidity, amount0, amount1, pool) = addLiquidity(
AddLiquidityParams({
token0: poolKey.token0,
token1: poolKey.token1,
fee: poolKey.fee,
tickLower: position.tickLower,
tickUpper: position.tickUpper,
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired,
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
recipient: address(this)
})
);
bytes32 positionKey = PositionKey.compute(address(this), position.tickLower, position.tickUpper);
// this is now updated to the current transaction
(, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(positionKey);
position.tokensOwed0 += uint128(
FullMath.mulDiv(
feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128,
position.liquidity,
FixedPoint128.Q128
)
);
position.tokensOwed1 += uint128(
FullMath.mulDiv(
feeGrowthInside1LastX128 - position.feeGrowthInside1LastX128,
position.liquidity,
FixedPoint128.Q128
)
);
position.feeGrowthInside0LastX128 = feeGrowthInside0LastX128;
position.feeGrowthInside1LastX128 = feeGrowthInside1LastX128;
position.liquidity += liquidity;
emit IncreaseLiquidity(params.tokenId, liquidity, amount0, amount1);
}Overview Adds liquidity to an existing position.
Details Adds liquidity to an existing position based on the specified parameters. The liquidity added is calculated as token 0 and token 1 are supplied according to the specified conditions. Fee growth for the supplied tokens is also updated.
Arguments
params- Parameters for adding liquidity.
Return values
liquidity- Liquidity added.
amount0- Amount of token 0 added.
amount1- Amount of token 1 added.
decreaseLiquidity
decreaseLiquidity
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
override
isAuthorizedForToken(params.tokenId)
checkDeadline(params.deadline)
returns (uint256 amount0, uint256 amount1)
{
require(params.liquidity > 0);
Position storage position = _positions[params.tokenId];
uint128 positionLiquidity = position.liquidity;
require(positionLiquidity >= params.liquidity);
PoolAddress.PoolKey memory poolKey = _poolIdToPoolKey[position.poolId];
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
(amount0, amount1) = pool.burn(position.tickLower, position.tickUpper, params.liquidity);
require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Price slippage check');
bytes32 positionKey = PositionKey.compute(address(this), position.tickLower, position.tickUpper);
// this is now updated to the current transaction
(, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(positionKey);
position.tokensOwed0 +=
uint128(amount0) +
uint128(
FullMath.mulDiv(
feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128,
positionLiquidity,
FixedPoint128.Q128
)
);
position.tokensOwed1 +=
uint128(amount1) +
uint128(
FullMath.mulDiv(
feeGrowthInside1LastX128 - position.feeGrowthInside1LastX128,
positionLiquidity,
FixedPoint128.Q128
)
);
position.feeGrowthInside0LastX128 = feeGrowthInside0LastX128;
position.feeGrowthInside1LastX128 = feeGrowthInside1LastX128;
// subtraction is safe because we checked positionLiquidity is gte params.liquidity
position.liquidity = positionLiquidity - params.liquidity;
emit DecreaseLiquidity(params.tokenId, params.liquidity, amount0, amount1);
}Overview Decreases liquidity in an existing position.
Details Decreases liquidity in an existing position based on the specified parameters. The liquidity decrease is calculated according to the specified conditions, and the amounts of token 0 and token 1 are returned. Fee growth is also updated to account for the liquidity decrease.
Arguments
params- Parameters for decreasing liquidity.
Return values
amount0- Amount of token 0 withdrawn from liquidity.
amount1- Amount of token 1 withdrawn from liquidity.
tokenURI
tokenURI
function tokenURI(uint256 tokenId) public view override(ERC721, IERC721Metadata) returns (string memory) {
require(_exists(tokenId));
return INonfungibleTokenPositionDescriptor(_tokenDescriptor).tokenURI(this, tokenId);
}Overview Retrieves the metadata URI of the token associated with a specified token ID.
Details Retrieves the metadata URI associated with the specified token ID. This URI identifies the location of the token's external metadata.
Arguments
tokenId- Token ID to query.
Return values
string- Token metadata URI.
baseURI
baseURI
function baseURI() public pure override returns (string memory) {}Overview Retrieves the base URI.
Details Retrieves the base URI. The implementation of this function is omitted, so it can be customized.
Return values
string- Base URI.
isAuthorizedForToken
isAuthorizedForToken
modifier isAuthorizedForToken(uint256 tokenId) {
require(_isApprovedOrOwner(msg.sender, tokenId), 'Not approved');
_;
}Overview A modifier checking whether the caller is the owner or an approved address for the specified token ID.
Details
Before executing the function, it calls _isApprovedOrOwner to verify whether the caller (msg.sender) owns or is approved for the specified tokenId.
If the condition is not met, the require statement reverts with the error message "Not approved".
Parameters
tokenId- ID of the token checked by the function.
collect function
collect
function collect(CollectParams calldata params)
external
payable
override
isAuthorizedForToken(params.tokenId)
returns (uint256 amount0, uint256 amount1)
{
require(params.amount0Max > 0 || params.amount1Max > 0);
// allow collecting to the nft position manager address with address 0
address recipient = params.recipient == address(0) ? address(this) : params.recipient;
Position storage position = _positions[params.tokenId];
PoolAddress.PoolKey memory poolKey = _poolIdToPoolKey[position.poolId];
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
(uint128 tokensOwed0, uint128 tokensOwed1) = (position.tokensOwed0, position.tokensOwed1);
// trigger an update of the position fees owed and fee growth snapshots if it has any liquidity
if (position.liquidity > 0) {
pool.burn(position.tickLower, position.tickUpper, 0);
(, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) =
pool.positions(PositionKey.compute(address(this), position.tickLower, position.tickUpper));
tokensOwed0 += uint128(
FullMath.mulDiv(
feeGrowthInside0LastX128 - position.feeGrowthInside0LastX128,
position.liquidity,
FixedPoint128.Q128
)
);
tokensOwed1 += uint128(
FullMath.mulDiv(
feeGrowthInside1LastX128 - position.feeGrowthInside1LastX128,
position.liquidity,
FixedPoint128.Q128
)
);
position.feeGrowthInside0LastX128 = feeGrowthInside0LastX128;
position.feeGrowthInside1LastX128 = feeGrowthInside1LastX128;
}
// compute the arguments to give to the pool#collect method
(uint128 amount0Collect, uint128 amount1Collect) =
(
params.amount0Max > tokensOwed0 ? tokensOwed0 : params.amount0Max,
params.amount1Max > tokensOwed1 ? tokensOwed1 : params.amount1Max
);
// the actual amounts collected are returned
(amount0, amount1) = pool.collect(
recipient,
position.tickLower,
position.tickUpper,
amount0Collect,
amount1Collect
);
// sometimes there will be a few less wei than expected due to rounding down in core, but we just subtract the full amount expected
// instead of the actual amount so we can burn the token
(position.tokensOwed0, position.tokensOwed1) = (tokensOwed0 - amount0Collect, tokensOwed1 - amount1Collect);
emit Collect(params.tokenId, recipient, amount0Collect, amount1Collect);
}Overview Collects tokens owed to a position.
Details Collects tokens owed to a position based on the specified parameters. The amounts collected are capped by both the specified maximums and the amounts owed to the position. The recipient address and token amounts can also be specified when collecting. The amounts of tokens collected are returned.
Arguments
params- Collection parameters.
Return values
amount0- Amount of token 0 collected.
amount1- Amount of token 1 collected.
burn
burn
function burn(uint256 tokenId) external payable override isAuthorizedForToken(tokenId) {
Position storage position = _positions[tokenId];
require(position.liquidity == 0 && position.tokensOwed0 == 0 && position.tokensOwed1 == 0, 'Not cleared');
delete _positions[tokenId];
_burn(tokenId);
}Overview Removes the position corresponding to a specified token ID.
Details Removes the position corresponding to the specified token ID. Information associated with the position is cleared when it is removed.
Arguments
tokenId- Token ID of the position to remove.
_getAndIncrementNonce
_getAndIncrementNonce
function _getAndIncrementNonce(uint256 tokenId) internal override returns (uint256) {
return uint256(_positions[tokenId].nonce++);
}Overview
Retrieves and increments the nonce associated with a specified token ID.
Details
Retrieves the position's nonce associated with the specified token ID, then increments it.
Arguments
tokenId- Token ID of the position whose
nonceis retrieved and incremented.
- Token ID of the position whose
Return values
uint256- Retrieved
nonce.
- Retrieved
getApproved
getApproved
function getApproved(uint256 tokenId) public view override(ERC721, IERC721) returns (address) {
require(_exists(tokenId), 'ERC721: approved query for nonexistent token');
return _positions[tokenId].operator;
}Overview Retrieves the approved address for a specified token ID.
Details Retrieves the operator address of the position associated with the specified token ID. This allows the token's approval status to be checked.
Arguments
tokenId- Token ID whose approval information is queried.
Return values
address- Approved address.
_approve
_approve
function _approve(address to, uint256 tokenId) internal override(ERC721) {
_positions[tokenId].operator = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}Overview Approves a token for a specified address.
Details This function approves the token for the specified address and updates the position's operator address. This allows the token owner to authorize another address to operate on the token.
Arguments
to- Address receiving approval.
tokenId- ID of the token to approve.
Return values
- None.
LiquidityManagement
MintCallbackData
MintCallbackData
struct MintCallbackData {
PoolAddress.PoolKey poolKey;
address payer;
}Overview A struct storing data for a Uniswap V3 mint callback.
Parameters
poolKeyPoolAddress.PoolKeytype storing token and fee information.
payer- Address initiating the mint transaction.
uniswapV3MintCallback
uniswapV3MintCallback
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external override {
MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
CallbackValidation.verifyCallback(factory, decoded.poolKey);
if (amount0Owed > 0) pay(decoded.poolKey.token0, decoded.payer, msg.sender, amount0Owed);
if (amount1Owed > 0) pay(decoded.poolKey.token1, decoded.payer, msg.sender, amount1Owed);
}Overview Acts as the Uniswap V3 mint callback and is called when liquidity is minted in a pool.
Details It is defined as a callback for Uniswap V3 liquidity minting. Payments are made based on the amounts owed for the minted liquidity.
Arguments
amount0Owed- Amount of token 0 to pay.
amount1Owed- Amount of token 1 to pay.
data- Callback data.
Return values None.
AddLiquidityParams
AddLiquidityParams
struct AddLiquidityParams {
address token0;
address token1;
uint24 fee;
address recipient;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
}Overview A struct used when adding liquidity in Uniswap V3.
Details It groups the parameters needed to add liquidity in Uniswap V3. Each parameter provides information relevant to establishing a liquidity position.
Parameters
token0- Token 0 address.
token1- Token 1 address.
fee- Value indicating the trading fee tier.
recipient- Address of the liquidity pool token owner.
tickLower- Value indicating the lower price bound.
tickUpper- Value indicating the upper price bound.
amount0Desired- Desired amount of token 0 to supply.
amount1Desired- Desired amount of token 1 to supply.
amount0Min- Minimum amount of token 0 to supply.
amount1Min- Minimum amount of token 1 to supply.
addLiquidity
addLiquidity
function addLiquidity(AddLiquidityParams memory params)
internal
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1,
IUniswapV3Pool pool
)
{
PoolAddress.PoolKey memory poolKey =
PoolAddress.PoolKey({token0: params.token0, token1: params.token1, fee: params.fee});
pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
// compute the liquidity amount
{
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(params.tickLower);
uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(params.tickUpper);
liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
sqrtRatioAX96,
sqrtRatioBX96,
params.amount0Desired,
params.amount1Desired
);
}
(amount0, amount1) = pool.mint(
params.recipient,
params.tickLower,
params.tickUpper,
liquidity,
abi.encode(MintCallbackData({poolKey: poolKey, payer: msg.sender}))
);
require(amount0 >= params.amount0Min && amount1 >= params.amount1Min, 'Price slippage check');
}Overview Adds liquidity to an initialized pool.
Details Performs the steps for adding liquidity to a Uniswap V3 pool. It calculates the new liquidity amount and price range from the specified parameters and supplies liquidity to the pool. It also checks price slippage.
Arguments
params- Struct containing the parameters for adding liquidity.
Return values
liquidity- Amount of liquidity added.
amount0- Actual amount of token 0 supplied.
amount1- Actual amount of token 1 supplied.
pool- Uniswap V3 pool instance receiving the added liquidity.
Multicall
See the following reference.
ERC721Permit
_getAndIncrementNonce
_getAndIncrementNonce
function _getAndIncrementNonce(uint256 tokenId) internal virtual returns (uint256);Overview
Retrieves the current nonce for a token ID and returns its original value.
Details
Manages the nonce used in ERC721 token permit operations.
It accepts a token ID and retrieves its associated nonce.
It then increments that nonce by one.
This supports secure and correct operation.
Arguments
tokenId- Token identifier whose associated
nonceis retrieved and updated.
- Token identifier whose associated
Return values
uint256- Returns the retrieved
nonce. - The stored
noncehas been incremented by one.
- Returns the retrieved
nameHash, versionHash
Constructor
bytes32 private immutable nameHash;
bytes32 private immutable versionHash;Overview Variables storing hashes of the name and version information used for permit signature verification.
Details
nameHash holds the hash of the name used when verifying token permit signatures.
Similarly, versionHash holds the hash of the version information.
These hashes are used during signature verification to strengthen security.
constructor
constructor
constructor(
string memory name_,
string memory symbol_,
string memory version_
) ERC721(name_, symbol_) {
nameHash = keccak256(bytes(name_));
versionHash = keccak256(bytes(version_));
}Overview Accepts a token name, symbol, and version, and calculates and sets the relevant hashes.
Details
This constructor accepts the ERC721 token's name, symbol, and version information.
It calculates the relevant string hashes and stores them in nameHash and versionHash.
This prepares the hashes used by subsequent signature verification operations.
Arguments
name_- Token name.
symbol_- Token symbol.
version_- Token version.
DOMAIN_SEPARATOR
DOMAIN_SEPARATOR
function DOMAIN_SEPARATOR() public view override returns (bytes32) {
return
keccak256(
abi.encode(
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
nameHash,
versionHash,
ChainId.get(),
address(this)
)
);
}Overview Calculates and returns the EIP712 domain separator used for permit signature verification.
Details
Calculates the domain separator according to the EIP712 specification.
It generates a hash by combining nameHash, versionHash, the network's chain ID, and the contract address.
This produces the domain separator used in signature verification.
PERMIT_TYPEHASH
bytes32 public constant override PERMIT_TYPEHASH =
0x49ecf333e5b8c95c40fdafc95c1ad136e8914a8fb55e9dc8bb01eaa83a2df9ad;Overview A constant representing a particular type hash used in permit signature verification.
Details A hash representing a particular data type. The hash is used to verify permit signature data. During signature verification, it helps establish the validity of a particular data structure.
permit
permit
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
require(_blockTimestamp() <= deadline, 'Permit expired');
bytes32 digest =
keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, spender, tokenId, _getAndIncrementNonce(tokenId), deadline))
)
);
address owner = ownerOf(tokenId);
require(spender != owner, 'ERC721Permit: approval to current owner');
if (Address.isContract(owner)) {
require(IERC1271(owner).isValidSignature(digest, abi.encodePacked(r, s, v)) == 0x1626ba7e, 'Unauthorized');
} else {
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), 'Invalid signature');
require(recoveredAddress == owner, 'Unauthorized');
}
_approve(spender, tokenId);
}Overview Grants approval for an ERC721 token.
Details
It assumes authorization by the ERC721 token owner.
The parameters are the address receiving approval (spender), the token ID (tokenId), the permit expiration (deadline), and the signature's v, r, and s values.
The function first checks the deadline against the current block timestamp to ensure that the permit remains valid.
It then calculates a hash from a specific message and uses it to verify the signature.
It checks that the token owner is not the spender, then verifies the signature.
If the token owner is a contract address, the ERC1271 interface is used to verify the signature's validity.
If the owner is an EOA (externally owned account), ECDSA signature verification is used to verify the signature.
Finally, the token approval for the spender is set through _approve.
Arguments
spender- Address authorized to use the token.
tokenId- Identifier of the token to approve.
deadline- Permit expiration timestamp.
v- Signature v value.
r- Signature r value.
s- Signature s value.
PeripheryValidation
checkDeadline
checkDeadline
modifier checkDeadline(uint256 deadline) {
require(_blockTimestamp() <= deadline, 'Transaction too old');
_;
}Overview A modifier checking a timestamp deadline.
Details
Before executing the function, it uses _blockTimestamp() to retrieve the current block timestamp and checks it against the specified deadline.
If the timestamp is at or before the deadline, the function can execute (the _ placeholder executes the function body).
If the deadline has passed, execution stops with the error message "Transaction too old".
Parameters
deadline- Deadline timestamp.
- Compared with the current block timestamp within the function.
SelfPermit
See the following reference.
PoolInitializer
createAndInitializePoolIfNecessary
createAndInitializePoolIfNecessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable override returns (address pool) {
require(token0 < token1);
pool = IUniswapV3Factory(factory).getPool(token0, token1, fee);
if (pool == address(0)) {
pool = IUniswapV3Factory(factory).createPool(token0, token1, fee);
IUniswapV3Pool(pool).initialize(sqrtPriceX96);
} else {
(uint160 sqrtPriceX96Existing, , , , , , ) = IUniswapV3Pool(pool).slot0();
if (sqrtPriceX96Existing == 0) {
IUniswapV3Pool(pool).initialize(sqrtPriceX96);
}
}
}Overview Creates and initializes a Uniswap V3 pool if necessary.
Details
Accepts tokens token0 and token1, the fee tier fee, and the initial price sqrtPriceX96.
It first checks that token0 is smaller than token1.
It then retrieves the pool address from the factory contract.
If the retrieved pool address is the zero address (unassigned), it creates and initializes a new pool.
If a pool already exists, it retrieves the current price sqrtPriceX96Existing from the pool's slot information and checks whether it is zero.
If it is zero, the pool is initialized.
Arguments
token0- Token 0 address.
token1- Token 1 address.
fee- Fee tier.
sqrtPriceX96- Initial square-root price (X96).
Return values
pool- Address of the created or initialized pool.
PeripheryPayments
See the following reference.
BlockTimestamp
See the following reference.
PositionKey
compute
compute
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}Overview
Calculates and returns a hash based on a specified owner address and two integer values (tickLower and tickUpper).
Details
The function accepts three arguments.
owner is an address variable representing the user's account address.
tickLower and tickUpper are int24 integers specifying the price range.
These arguments are encoded using abi.encodePacked and hashed with keccak256 to calculate a unique hash.
Arguments
owner- Owner address used for hash calculation.
tickLower- Integer indicating the lower price bound.
tickUpper- Integer indicating the upper price bound.
Return values The calculated hash (bytes32).
PoolAddress
See the following reference.
CallbackValidation
verifyCallback
verifyCallback
function verifyCallback(
address factory,
address tokenA,
address tokenB,
uint24 fee
) internal view returns (IUniswapV3Pool pool) {
return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));
}Overview Verifies the validity of a Uniswap V3 pool and retrieves its contract address. It obtains the pool key from the supplied information, then uses it to calculate and verify the pool's contract address.
Details
This function accepts four arguments.
factory specifies the Uniswap V3 factory contract address, while tokenA and tokenB specify the addresses of token 0 and token 1.
fee represents the fee tier collected by the pool for each swap.
The function calls PoolAddress.getPoolKey to obtain the pool key from the supplied information.
It then uses the retrieved key to call another verifyCallback function.
The second function calculates the pool's contract address using PoolAddress.computeAddress and returns the address.
Arguments
factory- Uniswap V3 factory contract address.
tokenA- Address of token 0 or token 1.
tokenB- Address of the other token.
fee- Fee tier for each swap in the pool.
Return values Returns the verified Uniswap V3 pool contract address (the IUniswapV3Pool interface).
verifyCallback
verifyCallback
function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey)
internal
view
returns (IUniswapV3Pool pool)
{
pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
require(msg.sender == address(pool));
}Overview Verifies the validity of a Uniswap V3 pool and retrieves its contract address. Uses the supplied pool key to calculate and verify the pool's contract address.
Details
This function accepts two arguments.
factory specifies the Uniswap V3 factory contract address, and poolKey is a struct representing the pool key.
The function calls PoolAddress.computeAddress to calculate the pool contract address using the supplied factory address and pool key.
It then uses a require statement to verify that the calculated pool address matches the caller (msg.sender).
Arguments
factory- Uniswap V3 factory contract address.
poolKey- Pool key.
LiquidityAmounts
toUint128
toUint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}Overview
Downcasts a uint256 value to uint128.
Details
Downcasts the supplied uint256 value to uint128.
After downcasting, it checks that the original and downcast values are equal.
If they differ, the require statement fails and execution stops.
Arguments
x- Value to downcast from
uint256.
- Value to downcast from
Return values
y- Downcast
uint128value.
- Downcast
getLiquidityForAmount0
getLiquidityForAmount0
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}Overview Calculates the amount of liquidity received based on a specified quantity of token 0 and a price range.
Details
Calculates liquidity between the two specified price boundaries sqrtRatioAX96 and sqrtRatioBX96.
The calculation is based on the following formula.
amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))Here, sqrt(upper) and sqrt(lower) represent the square roots of the prices, and amount0 is the amount of token 0 supplied.
Arguments
sqrtRatioAX96- Square-root price representing the first price boundary.
sqrtRatioBX96- Square-root price representing the second price boundary.
amount0- Amount of token 0 supplied.
Return values
liquidity: calculated liquidity amount.
For example, consider a calculation using the following values.
sqrtRatioAX96:1000000000000000000000000
sqrtRatioBX96:1200000000000000000000000
amount0:50000000000000000000
First, calculate the upper and lower bounds of the price range.
sqrt(upper):sqrtRatioBX96 = 1200000000000000000000000
sqrt(lower):sqrtRatioAX96 = 1000000000000000000000000Next, calculate the intermediate value intermediate.
intermediate = sqrt(upper) * sqrt(lower) / 2^96
= 1200000000000000000000000 * 1000000000000000000000000 / 2^96
≈ 1154700533444385611846965.7895Finally, calculate liquidity.
liquidity = amount0 * intermediate / (sqrt(upper) - sqrt(lower))
= 50000000000000000000 * 1154700533444385611846965.7895 / (1200000000000000000000000 - 1000000000000000000000000)
≈ 9.7132256441937224018576820493According to the numerical example in the original article, a token 0 amount of 50000000000000000000 under these conditions yields approximately 9.71 liquidity.
getLiquidityForAmount1
getLiquidityForAmount1
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}Overview Calculates the amount of liquidity received based on a specified quantity of token 1 and a price range.
Details
Calculates liquidity between the two specified price boundaries sqrtRatioAX96 and sqrtRatioBX96.
The calculation is based on the following formula.
amount1 / (sqrt(upper) - sqrt(lower))Here, sqrt(upper) and sqrt(lower) represent the square roots of the prices, and amount1 is the amount of token 1 supplied.
Arguments
sqrtRatioAX96- Square-root price representing the first price boundary.
sqrtRatioBX96- Square-root price representing the second price boundary.
amount1- Amount of token 1 supplied.
Return values
liquidity- Calculated liquidity amount.
getLiquidityForAmounts
getLiquidityForAmounts
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}Overview Calculates the maximum liquidity received based on the specified amounts of token 0 and token 1, the current pool price, and the price boundaries.
Details
Calculates the maximum liquidity received between the three specified square-root prices sqrtRatioX96, sqrtRatioAX96, and sqrtRatioBX96.
The calculation proceeds as follows.
- If
sqrtRatioX96is less than or equal tosqrtRatioAX96, calculate liquidity usinggetLiquidityForAmount0. - If
sqrtRatioX96is greater thansqrtRatioAX96and less thansqrtRatioBX96, combinegetLiquidityForAmount0andgetLiquidityForAmount1to calculate the maximum liquidity. - If
sqrtRatioX96is greater than or equal tosqrtRatioBX96, calculate liquidity usinggetLiquidityForAmount1.
Arguments
sqrtRatioX96- Square-root price representing the current pool price.
sqrtRatioAX96- Square-root price representing the first price boundary.
sqrtRatioBX96- Square-root price representing the second price boundary.
amount0- Amount of token 0 supplied.
amount1- Amount of token 1 supplied.
Return values
liquidity- Calculated maximum liquidity amount.
getAmount0ForLiquidity
getAmount0ForLiquidity
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}Overview Calculates the amount of token 0 based on a specified amount of liquidity and a price range.
Details
Calculates the amount of token 0 based on liquidity within the specified price boundaries sqrtRatioAX96 and sqrtRatioBX96.
The calculation is based on the following formula.
(amount0 << 96) * (sqrt(upper) - sqrt(lower)) / sqrt(upper)Here, amount0 is the calculated amount of token 0, sqrt(upper) is the square-root price at the upper boundary, and sqrt(lower) is the square-root price at the lower boundary.
Arguments
sqrtRatioAX96- Square-root price representing the first price boundary.
sqrtRatioBX96- Square-root price representing the second price boundary.
liquidity- Liquidity amount used in the calculation.
Return values
amount0- Calculated amount of token 0.
getAmount1ForLiquidity
getAmount1ForLiquidity
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}Overview Calculates the amount of token 1 based on a specified amount of liquidity and a price range.
Details
Calculates the amount of token 1 based on liquidity within the specified price boundaries sqrtRatioAX96 and sqrtRatioBX96.
The calculation is based on the following formula.
liquidity * (sqrt(upper) - sqrt(lower)) / Q96Here, liquidity is the liquidity amount used in the calculation, sqrt(upper) is the square-root price at the upper boundary, and sqrt(lower) is the square-root price at the lower boundary.
Arguments
sqrtRatioAX96- Square-root price representing the first price boundary.
sqrtRatioBX96- Square-root price representing the second price boundary.
liquidity- Liquidity amount used in the calculation.
Return values
amount1- Calculated amount of token 1.
getAmountsForLiquidity
getAmountsForLiquidity
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}Overview Calculates the amounts of token 0 and token 1 based on a specified liquidity amount, price range, and current pool price.
Details
Calculates the amounts of token 0 and token 1 based on liquidity and the three specified square-root prices sqrtRatioX96, sqrtRatioAX96, and sqrtRatioBX96.
The calculation proceeds as follows.
- If
sqrtRatioX96is less than or equal tosqrtRatioAX96, calculate the amount of token 0 usinggetAmount0ForLiquidity. - If
sqrtRatioX96is greater thansqrtRatioAX96and less thansqrtRatioBX96, combinegetAmount0ForLiquidityandgetAmount1ForLiquidityto calculate the amounts of both tokens. - If
sqrtRatioX96is greater than or equal tosqrtRatioBX96, calculate the amount of token 1 usinggetAmount1ForLiquidity.
Arguments
sqrtRatioX96- Square-root price representing the current pool price.
sqrtRatioAX96- Square-root price representing the first price boundary.
sqrtRatioBX96- Square-root price representing the second price boundary.
liquidity- Liquidity amount used in the calculation.
Return values
amount0- Calculated amount of token 0.
amount1- Calculated amount of token 1.
TransferHelper
See the following reference.
ChainId
get
get
function get() internal pure returns (uint256 chainId) {
assembly {
chainId := chainid()
}
}Overview Retrieves the current chain identifier (chain ID).
Details Uses assembly to retrieve the identifier of the chain on which the contract is executing. Chain IDs distinguish different Ethereum networks and subnetworks.
Return values
chainId- Current chain identifier.
Note This function retrieves the chain ID using assembly. Assembly is a low-level programming language used to control computer instructions directly.
Conclusion
In this article, we explored Uniswap V3's NonfungiblePositionManager contract using Bunzz's new DeCipher feature. I hope this explanation was useful. I plan to continue covering specific NFTs and contracts in future articles.
I regularly share articles about blockchain and AI on my blog and Qiita, so feel free to explore those as well.






