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, we translate and supplement the Technical Reference section of the official Uniswap V3 documentation.
The official documentation is available below.
Overview
Uniswap V3 is a binary smart contract system composed of many libraries, organized into Core and Periphery.
The Core contracts define the logic for creating Uniswap pools, the pools themselves, and interactions involving their assets.
The Periphery contracts interact with one or more Core contracts but are not part of Core. They provide functionality for interacting with Core and are designed to improve clarity and user safety.
External callers primarily use the Periphery interfaces. Externally accessible functions can be found in the reference documentation. Internal functions, meanwhile, can be found in the Uniswap V3 GitHub repositories.
Core
Core consists of a single Factory, a Pool Deployer, and the many pools created by the factory.
Gas optimization in the Core contracts significantly reduces gas costs across protocol interactions compared with V2, at the expense of more complex code.
Factory
The Factory defines the logic for creating pools.
A pool is defined by two tokens forming an asset pair and a specified fee. Multiple pools can exist for the same asset pair, distinguished solely by their swap fee.
Pool
A pool primarily serves as an automated market maker for its asset pair. It also exposes price oracle data and can serve as a source of assets for flash transactions.
A pool automatically creates a market for two different assets, allowing users to exchange them. It also provides market price information that other smart contracts can use. Furthermore, a pool serves as a source of assets for flash transactions, facilitating efficient token trading.
Periphery
A collection of smart contracts designed to support domain-specific interactions with Core. Because the Uniswap protocol is permissionless, the contracts described below have no special privileges and are used to perform particular operations in conjunction with Core.
SwapRouter
SwapRouter supports all the basic requirements of a frontend offering swaps.
It natively supports single-hop swaps (x→y) and multi-hop swaps (such as x→y→z).
Nonfungible Position Manager
The position manager handles logic and transactions involving the creation, adjustment, or closing of positions.
Oracle
Oracles provide price and liquidity data useful for various system designs and are available in every pool.
Periphery Libraries
Libraries provide developers with various helper functions, such as pool address computation and safe transfers.
Core
UniswapV3Factory
Deploys Uniswap V3 pools and manages ownership and control of pool protocol fees.
createPool
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool)Creates a pool for the given two tokens and fee.
tokenA and tokenB can be supplied in either order: token0/token1 or token1/token0.
Execution fails if the pool already exists, the fee is invalid, or the token arguments are invalid.
Parameters
| Name | Type | Description |
|---|---|---|
tokenA |
address | One of the assets in the pool. |
tokenB |
address | The other asset in the pool. |
fee |
uint24 | The desired pool fee. |
Return values
| Name | Type | Description |
|---|---|---|
pool |
address | The address of the newly created pool. |
setOwner
function setOwner(
address _owner
) externalUpdates the factory owner.
Only the current owner can execute this function.
Parameters
| Name | Type | Description |
|---|---|---|
_owner |
address | The address of the new owner. |
enableFeeAmount
function enableFeeAmount(
uint24 fee,
int24 tickSpacing
) publicEnables a fee with the specified tickSpacing.
Once enabled, a fee cannot be removed.
Parameters
| Name | Type | Description |
|---|---|---|
fee |
uint24 | The fee to set for pools, expressed in hundredths of a bip (i.e., 1e-6). |
tickSpacing |
int24 | The spacing between ticks enforced for all pools created with the specified fee. |
UniswapV3Pool
_blockTimestamp
function _blockTimestamp(
) internal view virtual returns (uint32)Returns the block timestamp truncated to 32 bits, using mod 2**32.
snapshotCumulativesInside
function snapshotCumulativesInside(
int24 tickLower,
int24 tickUpper
) external view override noDelegateCall returns (int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside)Returns snapshots of the tick cumulative, seconds per liquidity, and seconds inside a tick range.
Snapshots can only be compared with other snapshots taken over a period during which the position existed. In other words, snapshots cannot be compared if the position was not held throughout the period between the first and second snapshots.
The parameters and return values are shown in the following tables.
Parameters
| Name | Type | Description |
|---|---|---|
tickLower |
int24 | The lower tick of the range. |
tickUpper |
int24 | The upper tick of the range. |
Return values
| Name | Type | Description |
|---|---|---|
tickCumulativeInside |
int56 | A snapshot of the tick accumulator inside the range. |
secondsPerLiquidityInsideX128 |
uint160 | A snapshot of seconds per liquidity inside the range. |
secondsInside |
uint32 | A snapshot of seconds spent inside the range. |
observe
function observe(
uint32[] secondsAgos
) external view override noDelegateCall returns (int56[] tickCumulatives, uint160[] secondsPerLiquidityCumulativeX128s)Returns the cumulative tick and liquidity values at each timestamp a specified number of seconds before the current block timestamp.
To obtain a time-weighted average tick or in-range liquidity, the function must be called with two values.
One represents the start of the period, and the other represents its end.
For example, to obtain the time-weighted average tick over the last hour, call it with secondsAgos = [3600, 0].
The time-weighted average tick represents the pool's geometric time-weighted average price and expresses the token1 / token0 ratio using log base sqrt(1.0001).
The TickMath library can be used to convert a tick value into a ratio.
Parameters
| Name | Type | Description |
|---|---|---|
secondsAgos |
uint32[] | The number of seconds ago at which to retrieve each cumulative tick and liquidity value. |
Return values
| Name | Type | Description |
|---|---|---|
tickCumulatives |
int56[] | The cumulative tick values at each secondsAgos before the current block timestamp. |
secondsPerLiquidityCumulativeX128s |
uint160[] | The cumulative seconds per in-range liquidity at each secondsAgos before the current block timestamp. |
increaseObservationCardinalityNext
function increaseObservationCardinalityNext(
uint16 observationCardinalityNext
) external override lock noDelegateCallIncreases the maximum number of price and liquidity observations stored by the pool.
However, if the pool already has an observationCardinalityNext greater than or equal to the supplied observationCardinalityNext, nothing happens.
In other words, nothing changes when the pool already stores at least the required number of observations.
Parameters
| Name | Type | Description |
|---|---|---|
observationCardinalityNext |
uint16 | The minimum number of observations the pool should store. |
initialize
function initialize(
uint160 sqrtPriceX96
) external overrideSets the initial price of the pool. The pool is initialized in an unlocked state.
Parameters
| Name | Type | Description |
|---|---|---|
sqrtPriceX96 |
uint160 | The initial square-root price of the pool. |
mint
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes data
) external override lock returns (uint256 amount0, uint256 amount1)Adds liquidity for the specified recipient (recipient) and position bounds (tickLower and tickUpper).
Parameters
| Name | Type | Description |
|---|---|---|
recipient |
address | The recipient address for which liquidity is created. |
tickLower |
int24 | The lower tick of the position to which liquidity is added. |
tickUpper |
int24 | The upper tick of the position to which liquidity is added. |
amount |
uint128 | The amount of liquidity to create. |
data |
bytes | Arbitrary data to pass to the callback. |
Return values
| Name | Type | Description |
|---|---|---|
amount0 |
uint256 | The amount of token0 used to create the specified liquidity, matching the value in the callback. |
amount1 |
uint256 | The amount of token1 used to create the specified liquidity, matching the value in the callback. |
collect
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external override lock returns (uint128 amount0, uint128 amount1)Collects tokens owed to a position. Can only be executed by the position owner.
Parameters
| Name | Type | Description |
|---|---|---|
recipient |
address | The address receiving the collected fees. |
tickLower |
int24 | The lower tick of the position from which fees are collected. |
tickUpper |
int24 | The upper tick of the position from which fees are collected. |
amount0Requested |
uint128 | The amount of token0 fees to withdraw. |
amount1Requested |
uint128 | The amount of token1 fees to withdraw. |
Return values
| Name | Type | Description |
|---|---|---|
amount0 |
uint128 | The amount of fees collected in token0. |
amount1 |
uint128 | The amount of fees collected in token1. |
burn
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external override lock returns (uint256 amount0, uint256 amount1)Burns liquidity within the specified range and sends the proceeds to the executing address, as described in the source.
Parameters
| Name | Type | Description |
|---|---|---|
tickLower |
int24 | The lower tick of the position from which liquidity is burned. |
tickUpper |
int24 | The upper tick of the position from which liquidity is burned. |
amount |
uint128 | The amount of liquidity to burn. |
Return values
| Name | Type | Description |
|---|---|---|
amount0 |
uint256 | The amount of token0 to be sent to the recipient. |
amount1 |
uint256 | The amount of token1 to be sent to the recipient. |
swap
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes data
) external override noDelegateCall returns (int256 amount0, int256 amount1)Swaps token0 for token1, or token1 for token0.
Parameters
| Name | Type | Description |
|---|---|---|
recipient |
address | The address receiving the swap output. |
zeroForOne |
bool | The swap direction: true for token0 to token1, and false for token1 to token0. |
amountSpecified |
int256 | The swap amount. A positive value specifies an exact input, and a negative value specifies an exact output. |
sqrtPriceLimitX96 |
uint160 | The Q64.96 square-root price limit. If zeroForOne is true, the price after the swap cannot be below this value. If zeroForOne is false, the price cannot exceed it. |
data |
bytes | Arbitrary data to pass to the callback. |
Return values
| Name | Type | Description |
|---|---|---|
amount0 |
int256 | The change in the pool's token0 balance, exact when negative and minimum when positive. |
amount1 |
int256 | The change in the pool's token1 balance, exact when negative and minimum when positive. |
flash
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes data
) external override lock noDelegateCallReceives token0 and/or token1 and repays them with fees in the callback.
Parameters
| Name | Type | Description |
|---|---|---|
recipient |
address | The address receiving the amounts of token0 and token1. |
| amount0 | uint256 | The amount of token0 to send. |
| amount1 | uint256 | The amount of token1 to send. |
| data | bytes | Arbitrary data to pass to the callback. |
setFeeProtocol
function setFeeProtocol(
uint8 feeProtocol0,
uint8 feeProtocol1
) external override lock onlyFactoryOwnerSets the proportion of fees received by the protocol.
Parameters
| Name | Type | Description |
|---|---|---|
feeProtocol0 |
uint8 | The new protocol fee for token0 in the pool. |
feeProtocol1 |
uint8 | The new protocol fee for token1 in the pool. |
collectProtocol
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external override lock onlyFactoryOwner returns (uint128 amount0, uint128 amount1)Collects protocol fees accumulated in the pool.
Parameters
| Name | Type | Description |
|---|---|---|
recipient |
address | The address to which the collected protocol fees are sent. |
amount0Requested |
uint128 | The maximum amount of token0 to send; can be zero to collect only token1 fees. |
amount1Requested |
uint128 | The maximum amount of token1 to send; can be zero to collect only token0 fees. |
Return values
| Name | Type | Description |
|---|---|---|
amount0 |
uint128 | The protocol fees collected in token0. |
amount1 |
uint128 | The protocol fees collected in token1. |
UniswapV3PoolDeployer
deploy
function deploy(
address factory,
address token0,
address token1,
uint24 fee,
int24 tickSpacing
) internal returns (address pool)Deploys a pool with the specified parameters. The parameter storage slots are set temporarily for deployment and cleared after pool deployment is complete.
Parameters
| Name | Type | Description |
|---|---|---|
factory |
address | The Uniswap V3 factory contract address. |
token0 |
address | The first token of the pool, sorted by address. |
token1 |
address | The second token of the pool, sorted by address. |
fee |
uint24 | The fee charged on each swap in the pool, in hundredths of a bip. |
tickSpacing |
int24 | The spacing between usable ticks. |
Interfaces
IUniswapV3Factory
owner
function owner() external view returns (address)Returns the current factory owner.
The owner can be changed through setOwner.
Return values
| Type | Description |
|---|---|
address |
The factory owner's address. |
feeAmountTickSpacing
function feeAmountTickSpacing(
uint24 fee
) external view returns (int24)Returns the tick spacing for the specified fee amount.
Returns its value if the fee is enabled, or 0 otherwise.
Parameters
| Name | Type | Description |
|---|---|---|
fee |
uint24 | The fee amount, in hundredths of a bip. Returns 0 if not enabled. |
Return values
| Type | Description |
|---|---|
int24 |
The tick spacing. |
getPool
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool)Returns the pool address for the specified token pair and fee.
Returns address 0 if the pool does not exist.
Token A and token B can be supplied in either token0/token1 or token1/token0 order.
Parameters
| Name | Type | Description |
|---|---|---|
tokenA |
address | The contract address of token0 or token1. |
tokenB |
address | The contract address of the other token. |
fee |
uint24 | The fee, in hundredths of a bip. |
Return values
| Name | Type | Description |
|---|---|---|
pool |
address | The pool address. |
IUniswapV3PoolDeployer
A contract constructing a pool must implement the following functionality to pass arguments to the pool. This allows the pool contract to avoid constructor arguments. As a result, the pool's initializer code hash is constant, and its CREATE2 address can be computed on-chain without the cost of varying initialization code.
parameters
function parameters() external view returns (address factory, address token0, address token1, uint24 fee, int24 tickSpacing)Retrieves the parameters used to construct a pool.
Return values
| Name | Type | Description |
|---|---|---|
factory |
address | The factory address. |
token0 |
address | The first token of the pool, sorted by address. |
token1 |
address | The second token of the pool, sorted by address. |
fee |
uint24 | The fee charged on each swap in the pool, expressed in hundredths of a bip. |
tickSpacing |
int24 | The minimum number of ticks between initialized ticks. |
IUniswapV3FlashCallback
uniswapV3FlashCallback
function uniswapV3FlashCallback(
uint256 fee0,
uint256 fee1,
bytes data
) externalRepays the tokens received from IUniswapV3Pool's flash function together with the calculated fees.
The caller must be verified as a UniswapV3Pool deployed by the UniswapV3Factory.
Parameters
| Name | Type | Description |
|---|---|---|
fee0 |
uint256 | The token0 fee owed to the pool at the end of the flash operation. |
fee1 |
uint256 | The token1 fee owed to the pool at the end of the flash operation. |
data |
bytes | Arbitrary data supplied by the caller of IUniswapV3PoolActions#flash. |
IUniswapV3MintCallback
uniswapV3MintCallback
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes data
) externalCalled on msg.sender after executing IUniswapV3Pool's mint function to mint liquidity into a position.
The tokens owed to the pool for the liquidity minted must be paid.
The caller must be verified as a UniswapV3Pool deployed by the UniswapV3Factory.
Parameters
| Name | Type | Description |
|---|---|---|
amount0Owed |
uint256 | The amount of token0 owed to the pool for the minted liquidity. |
amount1Owed |
uint256 | The amount of token1 owed to the pool for the minted liquidity. |
data |
bytes | Data supplied by the caller of IUniswapV3PoolActions#mint. |
IUniswapV3SwapCallback
uniswapV3SwapCallback
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes data
) externalCalled on msg.sender after executing a swap through IUniswapV3Pool's swap function.
The tokens owed to the pool as a result of the swap must be repaid. The caller must be verified as a UniswapV3Pool deployed by the UniswapV3Factory.
| Name | Type | Description |
|---|---|---|
amount0Delta |
int256 | The amount of token0 sent by the pool (negative) or received by the pool (positive) at the end of the swap. If positive, the callback must send that amount of token0 to the pool. |
amount1Delta |
int256 | The amount of token1 sent by the pool (negative) or received by the pool (positive) at the end of the swap. If positive, the callback must send that amount of token1 to the pool. |
data |
bytes | Arbitrary data supplied by the caller of IUniswapV3PoolActions#swap. |
Pool
See the following reference.
Libraries
BitMath
A library providing functionality for computing bit properties of unsigned integers.
mostSignificantBit
function mostSignificantBit(
uint256 x
) internal pure returns (uint8 r)Returns the index of the most significant bit (the leftmost set bit) of a specified number.
The rightmost bit has index 0, and the leftmost bit has index 255.
This function satisfies the following conditions:
x >= 2^mostSignificantBit(x) and x < 2^(mostSignificantBit(x)+1).
It returns the position of the most significant bit in the given number, indicating that this bit is set to 1.
The most significant bit has the greatest place value; the source describes all lower bits as 0.
Set bit
A bit whose value is 1 in a binary representation.
For example, the integer 10 is represented in binary as 1010.
In this case, bits at positions 3 and 1 are set, with value 1. The remaining bits (positions 2 and 0) are 0.
The most significant bit is the leftmost bit with value 1.
Whether the most significant bit is 1 can determine the magnitude or properties of a number.
Identifying the position of the most significant bit is important for understanding numerical properties. It is also called the leftmost set bit.
Parameters
| Name | Type | Description |
|---|---|---|
x |
uint256 | The value for which to compute the most significant bit; must be greater than zero. |
Return values
| Name | Type | Description |
|---|---|---|
r |
unit8 | The index of the most significant bit. |
leastSignificantBit
function leastSignificantBit(
uint256 x
) internal pure returns (uint8 r)Returns the index of the rightmost (least significant) set bit of a given number.
The rightmost bit is at index 0, and the leftmost bit is at index 255.
This function verifies that the following properties hold for the given number x.
(x & 2^leastSignificantBit(x)) != 0Checks whether the rightmost (least significant) bit in the binary representation ofxis set to1.(x & (2^(leastSignificantBit(x)) - 1)) == 0Checks whether all bits other than the rightmost bit are set to0.
This function helps find the position of the rightmost (least significant) 1 bit in x.
The following tables show the parameters and return values of the function.
I apologize; I will make the requested correction.
Parameters
| Name | Type | Description |
|---|---|---|
x |
uint256 | The value for which to compute the rightmost set bit. Must be greater than zero. |
Return values
| Name | Type | Description |
|---|---|---|
r |
uint8 | The index of the rightmost (least significant) set bit. |
FullMath
A library for multiplication and division without loss of precision, even when an intermediate value overflows.
It handles intermediate values exceeding 256 bits and produces an exact result.
This is called phantom overflow.
The library produces accurate results even for large calculations that would overflow with ordinary integer arithmetic.
mulDiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result)Computes floor(a×b÷denominator) with full precision.
It reverts if the result overflows uint256 or if denominator is 0.
Multiplies a and b, divides the product by denominator, and rounds the result down.
Parameters
| Name | Type | Description |
|---|---|---|
a |
uint256 | A multiplicand. |
b |
uint256 | A multiplier. |
denominator |
uint256 | The divisor. |
Return values
| Name | Type | Description |
|---|---|---|
result |
uint256 | The 256-bit result. |
mulDivRoundingUp
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result)Computes ceil(a×b÷denominator) with full precision.
It reverts if the result overflows uint256 or if denominator is 0.
ceil(a×b÷denominator) rounds the fractional result up to the nearest integer.
Parameters
| Name | Type | Description |
|---|---|---|
a |
uint256 | A multiplicand. |
b |
uint256 | A multiplier. |
denominator |
uint256 | The divisor. |
Return values
| Name | Type | Description |
|---|---|---|
result |
uint256 | The 256-bit result. The source describes it as rounded down. |
LiquidityMath
addDelta
function addDelta(
uint128 x,
int128 y
) internal pure returns (uint128 z)Adds a signed liquidity delta to liquidity. Reverts on overflow or underflow.
Parameters
| Name | Type | Description |
|---|---|---|
x |
uint128 |
Liquidity before the change. |
y |
int128 |
The delta by which liquidity changes. |
Return Values:
| Name | Type | Description |
|---|---|---|
z |
uint128 |
The liquidity delta, as described in the source. |
LowGasSafeMath
add
function add(
uint256 x,
uint256 y
) internal pure returns (uint256 z)Takes two integers x and y and returns their sum.
Parameters
| Name | Type | Description |
|---|---|---|
x |
uint256 |
The augend. |
y |
uint256 |
The addend. |
Return values
| Name | Type | Description |
|---|---|---|
z |
uint256 |
The sum of x and y. |
sub
function sub(
uint256 x,
uint256 y
) internal pure returns (uint256 z)Takes two integers x and y and returns their difference.
Parameters
| Name | Type | Description |
|---|---|---|
x |
uint256 |
The minuend. |
y |
uint256 |
The subtrahend. |
Return values
| Name | Type | Description |
|---|---|---|
z |
uint256 |
The difference between x and y. |
mul
function mul(
uint256 x,
uint256 y
) internal pure returns (uint256 z)Takes two integers x and y and returns their product.
Parameters
| Name | Type | Description |
|---|---|---|
x |
uint256 |
The multiplicand. |
y |
uint256 |
The multiplier. |
Return values
| Name | Type | Description |
|---|---|---|
z |
uint256 |
The product of x and y. |
add
function add(
uint256 x,
uint256 y
) internal pure returns (uint256 z)Takes two integers x and y and returns their sum.
Calls revert on overflow or underflow.
Parameters
| Name | Type | Description |
|---|---|---|
x |
uint256 |
The augend. |
y |
uint256 |
The addend. |
Return values
| Name | Type | Description |
|---|---|---|
z |
uint256 |
The sum of x and y. |
sub
function sub(
uint256 x,
uint256 y
) internal pure returns (uint256 z)Takes two integers x and y and returns their difference.
Calls revert on overflow or underflow.
Parameters
| Name | Type | Description |
|---|---|---|
x |
uint256 |
The minuend. |
y |
uint256 |
The subtrahend. |
Return values
| Name | Type | Description |
|---|---|---|
z |
uint256 |
The difference between x and y. |
Oracle
This functionality provides price and liquidity data useful for various system designs.
Instances of stored oracle data, called observations, are collected in an oracle array.
Every pool is initialized with an oracle array of length 1.
Anyone can pay for SSTORE operations (which incur gas costs for storing data) to increase the maximum length of the oracle array.
When the oracle array is completely populated, new slots are added.
When observations fill the oracle array to its maximum length, older observations are overwritten.
Regardless of the oracle array's length, the most recent observation can be retrieved by passing 0 to observe().
initialize
function initialize(
struct Oracle.Observation[65535] self,
uint32 time
) internal returns (uint16 cardinality, uint16 cardinalityNext)Initializes the oracle array and writes data to its first slot. This function is called only once during the lifecycle of the observations array.
Parameters
| Name | Type | Description |
|---|---|---|
self |
struct Oracle.Observation[65535] | The stored oracle array. |
time |
uint32 | The time of oracle initialization, with block.timestamp truncated to uint32. |
Return Values:
| Name | Type | Description |
|---|---|---|
cardinality |
uint16 | The number of elements in the oracle array. |
cardinalityNext |
uint16 | The new length of the oracle array, regardless of the number of populated elements. |
write
function write(
struct Oracle.Observation[65535] self,
uint16 index,
uint32 blockTimestamp,
int24 tick,
uint128 liquidity,
uint16 cardinality,
uint16 cardinalityNext
) internal returns (uint16 indexUpdated, uint16 cardinalityUpdated)Writes an oracle observation to the array.
Only one write per block is permitted.
The array index identifies the last element written.
cardinality (the number of elements) and index (the current index position) must be tracked externally.
If index is at the end of the permitted array length (based on cardinality), and the next cardinality exceeds the current cardinality, cardinality can be increased.
This restriction is introduced to preserve ordering.
The following Markdown tables show the parameters and return values.
Parameters
| Name | Type | Description |
|---|---|---|
self |
struct Oracle.Observation[65535] |
The stored oracle array. |
index |
uint16 |
The position of the most recently updated observation. |
blockTimestamp |
uint32 |
The timestamp of the new observation. |
tick |
int24 |
The active tick at the time of the new observation. |
liquidity |
uint128 |
The total in-range liquidity at the time of the new observation. |
cardinality |
uint16 |
The number of elements in the oracle array. |
cardinalityNext |
uint16 |
The new length of the oracle array, independent of its population. |
Return values
| Name | Type | Description |
|---|---|---|
indexUpdated |
uint16 |
The new index of the most recently written element in the oracle array. |
cardinalityUpdated |
uint16 |
The new cardinality of the oracle array. |
grow
function grow(
struct Oracle.Observation[65535] self,
uint16 current,
uint16 next
) internal returns (uint16)Prepares the oracle array to store up to the next number of observations.
Parameters
| Name | Type | Description |
|---|---|---|
self |
struct Oracle.Observation[65535] | The stored oracle array. |
current |
uint16 | The current next cardinality of the oracle array. |
next |
uint16 | The proposed next cardinality to populate in the oracle array. |
Return values
| Name | Type | Description |
|---|---|---|
next |
uint16 | The next cardinality to populate in the oracle array. |
Populate This means that a new element is added to the oracle array.
It refers to how much the number of elements in the oracle array increases when a new element is added. Cardinality represents the number of elements in the oracle array and increases whenever a new element is added, as described in this explanation.
For example, if the current cardinality is 10 and a new element is added to the oracle array, the next cardinality becomes 11. If another element is added, the next cardinality becomes 12.
In other words, cardinality is a numerical value indicating how much the number of elements in the oracle array has increased.
observe
function observe(
struct Oracle.Observation[65535] self,
uint32 time,
uint32[] secondsAgos,
int24 tick,
uint16 index,
uint128 liquidity,
uint16 cardinality
) internal view returns (int56[] tickCumulatives, uint160[] liquidityCumulatives)Returns accumulator values from a specified number of seconds ago relative to the given time, for each entry in the secondsAgos array.
Reverts if a secondsAgos value refers to a time older than the oldest observation.
Suppose an oracle records data every minute, and secondsAgos is supplied as an array such as [30, 60, 90].
- For a seconds ago value of
30seconds, it returns the accumulator value30seconds before the given time. - For a seconds ago value of
60seconds, it returns the accumulator value60seconds before the given time. - For a seconds ago value of
90seconds, it returns the accumulator value90seconds before the given time.
However, an error occurs if a secondsAgos value refers to a time older than the oldest observation.
Parameters
| Name | Type | Description |
|---|---|---|
self |
struct Oracle.Observation[65535] | The stored oracle array. |
time |
uint32 | The current block timestamp. |
secondsAgos |
uint32[] | An array of time intervals, in seconds, for retrieving past observations. Each element specifies how far back to retrieve an observation. |
tick |
int24 | The current tick value. |
index |
uint16 | The position of a particular observation in the oracle array. |
liquidity |
uint128 | The current in-range pool liquidity. |
cardinality |
uint16 | The number of elements stored in the oracle array. |
Return values
| Name | Type | Description |
|---|---|---|
tickCumulatives |
int56[] | The cumulative tick × time value since the pool was first initialized, at each secondsAgo. |
liquidityCumulatives |
uint160[] | The cumulative liquidity × time value since the pool was first initialized, at each secondsAgo, as described in the source. |
Position
A position represents an owner's liquidity between lower and upper tick boundaries.
It indicates that a particular owner (address) holds liquidity for trading. This liquidity is provided within a particular price range, defined by lower and upper tick boundaries. In other words, a position represents information about the liquidity an owner provides within a particular price range.
A position stores additional state to track the fees owed to it.
This means that the position holds information needed to accurately track the fees associated with it. It tracks and manages how fees from trading and liquidity provision accrue to the position.
get
function get(
mapping(bytes32 => struct Position.Info) self,
address owner,
int24 tickLower,
int24 tickUpper
) internal view returns (struct Position.Info position)Returns position information (the Info struct) based on the specified owner and position boundaries.
The following tables show the parameters and return values.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(bytes32 => struct Position.Info) | The mapping containing all user positions. |
owner |
address | The address of the position owner. |
tickLower |
int24 | The lower tick boundary of the position. |
tickUpper |
int24 | The upper tick boundary of the position. |
Return values
| Name | Type | Description |
|---|---|---|
position |
struct Position.Info | The position information struct for the specified owner. |
update
function update(
struct Position.Info self,
int128 liquidityDelta,
uint256 feeGrowthInside0X128,
uint256 feeGrowthInside1X128
) internalCredits accrued fees to a user's position.
This refers to the operation of adding accumulated fees to a particular position owned by a user. Fees generated from swaps and other activities are added to the user's position, affecting its value. Crediting fees to the position may change its profit or loss.
Parameters
| Name | Type | Description |
|---|---|---|
self |
struct Position.Info | The mapping containing all user positions, as described in the source. |
liquidityDelta |
int128 | The change in pool liquidity resulting from the position update. |
feeGrowthInside0X128 |
uint256 | Cumulative fee growth per unit of liquidity in token0 within the position's tick boundaries. |
feeGrowthInside1X128 |
uint256 | Cumulative fee growth per unit of liquidity in token1 within the position's tick boundaries. |
SafeCast
Performs safe type casts.
toUint160
function toUint160(
uint256 y
) internal pure returns (uint160 z)Casts uint256 to uint160.
Calls revert if overflow occurs.
Parameters
| Name | Type | Description |
|---|---|---|
y |
uint256 | The uint256 value to downcast. |
Return values
| Name | Type | Description |
|---|---|---|
z |
uint160 | The downcast integer, of type uint160. |
toInt128
function toInt128(
int256 y
) internal pure returns (int128 z)Casts int256 to int128.
Calls revert on overflow or underflow.
Parameters
| Name | Type | Description |
|---|---|---|
y |
int256 | The int256 value to downcast. |
Return values
| Name | Type | Description |
|---|---|---|
z |
int128 | The downcast integer, of type int128. |
toInt256
function toInt256(
uint256 y
) internal pure returns (int256 z)Casts uint256 to int256.
Calls revert on overflow.
Parameters
| Name | Type | Description |
|---|---|---|
y |
uint256 | The uint256 value to cast. |
Return values
| Name | Type | Description |
|---|---|---|
z |
int256 | The cast integer, of type int256. |
SecondsOutside
This section describes methods associated with a particular mapping.
The mapping holds values from a tick (an integer representing a price interval) to a 32-bit timestamp value, primarily used to track time spent outside a tick.
The mapping uses int24 (a 24-bit integer) keys, with eight (2^3) values packed into each word.
It helps record time spent outside a particular tick.
An important point is that time spent outside a tick is always a relative measurement and is consistently valid only during periods when the total liquidity at the lower and upper tick is greater than 0.
Note that this measurement may become invalid when liquidity reaches 0.
Time spent outside a tick
This refers to the time spent trading outside the range of a tick, an integer representing a particular price range.
This time is typically recorded when transactions or operations occur in relation to a particular price range within a protocol or system.
For example, consider a trading platform where trades occur within a particular price range, and users are restricted from trading outside it.
If a user breaks this restriction and trades outside the price range, the time or duration of that trade is recorded as time spent trading outside a tick.
This information may be used to monitor compliance with trading rules and impose sanctions for violations. It can also help analyze trading activity within particular price ranges in relation to market liquidity and price fluctuations.
Suppose a trading platform calls a particular price range a tick and needs to record the associated trading time.
This trading time represents time during which trading took place outside a particular price range.
Consider the following example.
- The platform treats prices from
-100to100as thetickrange. - User A trades within the price range from
-50to0during a particular period. - User B trades within the price range from
0to50during the same period.
In this case, the outside-range values for users A and B represent the time their respective trades spent outside their price ranges.
For example, the source's inside-range value for user A is the sum of seconds spent trading in the ranges from -100 to -50 and from 0 to 100.
Similarly, user B's outside-range value is the sum of seconds spent trading in the ranges from -100 to 0 and from 50 to 100.
When liquidity is zero, no trades or operations take place in the price range, and the outside-range value becomes invalid, according to this explanation.
initialize
function initialize(
mapping(int24 => uint256) self,
int24 tick,
int24 tickCurrent,
int24 tickSpacing,
uint32 time
) internalSets time spent outside a tick when that tick is first used.
Assumes the tick is not initialized.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int24 => uint256) | Mapping from tick to time spent outside the tick. |
| tick | int24 | The tick to initialize. |
| tickCurrent | int24 | The current tick. |
| tickSpacing | int24 | The spacing between usable tick values. |
| time | uint32 | The current timestamp. |
clear
function clear(
mapping(int24 => uint256) self,
int24 tick,
int24 tickSpacing
) internalCalled when a tick is no longer used, clearing its time-spent-outside value.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int24 => uint256) | Mapping to time spent outside a tick. |
tick |
int24 | The tick to clear. |
tickSpacing |
int24 | The spacing between usable tick values. |
cross
function cross(
mapping(int24 => uint256) self,
int24 tick,
int24 tickSpacing,
uint32 time
) internalCalled when an initialized tick is crossed, updating the time spent outside that tick.
Must be called each time an initialized tick is crossed.
Crossing
Refers to an operation invoked when a tick (an element representing a price range) crosses a boundary.
Specifically, it updates the outside-range value when a tick is initialized and its range is crossed.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int24 => uint256) | Mapping from tick to time spent outside that tick. |
tick |
int24 | The tick being crossed. |
tickSpacing |
int24 | The spacing between usable tick values. |
time |
uint32 | The current block timestamp truncated to 32 bits. |
get
function get(
mapping(int24 => uint256) self,
int24 tick,
int24 tickSpacing
) internal view returns (uint32)Retrieves time spent outside an initialized tick.
Only initialized tick values can be queried.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int24 => uint256) | Mapping from tick to time spent outside that tick. |
tick |
int24 | The tick for which to retrieve the time value. |
tickSpacing |
int24 | The spacing between usable ticks. |
Return values
| Type | Description |
|---|---|
| uint32 | The time spent outside the specified tick. |
secondsInside
function secondsInside(
mapping(int24 => uint256) self,
int24 tickLower,
int24 tickUpper,
int24 tickCurrent,
int24 tickSpacing
) internal view returns (uint32)Retrieves time spent inside a tick range, assuming both tickLower and tickUpper are initialized.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int24 => uint256) | Mapping from tick to time spent outside that tick. |
tickLower |
int24 | The lower tick to query. |
tickUpper |
int24 | The upper tick to query. |
tickCurrent |
int24 | The current tick. |
tickSpacing |
int24 | The spacing between usable tick values. |
Return values
| Name | Type | Description |
|---|---|---|
a |
uint32 | The relative time-spent-inside value for a tick range, intended to be snapshotted and compared with a later snapshot. |
SqrtPriceMath
Uses the square root of the price as Q64.96 and computes deltas using liquidity.
getNextSqrtPriceFromAmount0RoundingUp
function getNextSqrtPriceFromAmount0RoundingUp(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amount,
bool add
) internal pure returns (uint160)Retrieves the next square-root price based on a change in token0 under specified conditions.
- Always rounds up
- This calculation always rounds the value up.
- Rounding up is necessary in both cases, when the price increases (exact output) and when the price decreases (exact input), to perform the appropriate operation.
- Calculation method
- The most accurate formula for calculating the square-root price is shown below.
- If overflow is a concern, an alternative calculation is used.
- Exact calculation
liquidity * sqrtPX96 / (liquidity +- amount * sqrtPX96)
- In case of overflow
liquidity / (liquidity / sqrtPX96 +- amount)
-
When the price increases (exact output)
- When the price increases, the price must be moved far enough to obtain the exact output amount.
- Rounding up is used in this case.
-
When the price decreases (exact input)
- When the price decreases, moving the price down by the appropriate amount is sufficient for the exact input.
- Rounding up is also used in this case.
Parameters
| Name | Type | Description |
|---|---|---|
sqrtPX96 |
uint160 | The starting price, before accounting for the change in token0. |
liquidity |
uint128 | The amount of available liquidity. |
amount |
uint256 | The amount of token0 to add to or remove from the virtual reserves. |
add |
bool | A boolean indicating whether to add or remove amount. |
Return values
| Type | Description |
|---|---|
| uint160 | The price after adding or removing amount. |
getNextSqrtPriceFromAmount1RoundingDown
Retrieves the next square-root price based on a change in token1 under specified conditions.
- Always rounds down
- This calculation always rounds the value down.
- In the exact output case (when the price decreases), the price needs to move at least far enough to obtain the desired output amount.
- In the exact input case (when the price increases), the price needs to move less to avoid sending excess output.
- Accuracy of the formula
- The calculation may differ slightly (by less than
1 wei) from the lossless version, but it is highly accurate. - The formula is as follows.
sqrtPX96 +- amount / liquidity。
- The calculation may differ slightly (by less than
Parameters
| Name | Type | Description |
|---|---|---|
sqrtPX96 |
uint160 | The starting price, before accounting for the change in token1. |
liquidity |
uint128 | The amount of available liquidity. |
amount |
uint256 | The amount of token1 to add to or remove from the virtual reserves. |
add |
bool | A boolean indicating whether to add or remove amount. |
Return values
| Type | Description |
|---|---|
| uint160 | The price after adding or removing amount. |
getNextSqrtPriceFromInput
function getNextSqrtPriceFromInput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountIn,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96)Retrieves the next sqrt price given an input amount of token0 or token1.
Reverts if the price or liquidity is 0, or if the next price is outside the permitted bounds.
Parameters
| Name | Type | Description |
|---|---|---|
sqrtPX96 |
uint160 | The starting price, before accounting for the input amount. |
liquidity |
uint128 | The amount of available liquidity. |
amountIn |
uint256 | The input amount of token0 or token1. |
zeroForOne |
bool | A boolean indicating whether the input amount is token0 or token1. |
Return values
| Name | Type | Description |
|---|---|---|
sqrtQX96 |
uint160 | The price after adding the input amount of token0 or token1. |
getNextSqrtPriceFromOutput
function getNextSqrtPriceFromOutput(
uint160 sqrtPX96,
uint128 liquidity,
uint256 amountOut,
bool zeroForOne
) internal pure returns (uint160 sqrtQX96)Retrieves the next sqrt price given an output amount of token0 or token1.
Reverts if the price or liquidity is 0, or if the next price is outside the permitted bounds.
Parameters
| Name | Type | Description |
|---|---|---|
sqrtPX96 |
uint160 | The starting price, before accounting for the output amount. |
liquidity |
uint128 | The amount of available liquidity. |
amountOut |
uint256 | The output amount of token0 or token1. |
zeroForOne |
bool | A boolean indicating whether the output amount is token0 or token1. |
Return values
| Name | Type | Description |
|---|---|---|
sqrtQX96 |
uint160 | The price after removing the output amount of token0 or token1. |
getAmount0Delta
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount0)Retrieves the amount0 delta between two prices.
liquidity / sqrt(lower) - liquidity / sqrt(upper), i.e. liquidity * (sqrt(upper) - sqrt(lower)) / (sqrt(upper) * sqrt(lower))The calculation uses the formulas above.
Parameters
| Name | Type | Description |
|---|---|---|
sqrtRatioAX96 |
uint160 | The first square-root price. |
sqrtRatioBX96 |
uint160 | The second square-root price. |
liquidity |
uint128 | The amount of available liquidity. |
roundUp |
bool | A boolean indicating whether to round the amount up or down. |
Return values
| Name | Type | Description |
|---|---|---|
amount0 |
uint256 | The amount of token0 required to cover the specified liquidity between the two square-root prices. |
getAmount1Delta
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity,
bool roundUp
) internal pure returns (uint256 amount1)Retrieves the amount1 delta between two prices.
Computes liquidity * (sqrt(upper) - sqrt(lower)).
Parameters
| Name | Type | Description |
|---|---|---|
sqrtRatioAX96 |
uint160 | The first square-root price. |
sqrtRatioBX96 |
uint160 | The second square-root price. |
liquidity |
uint128 | The amount of available liquidity. |
roundUp |
bool | A boolean indicating whether to round the amount up or down. |
Return values
| Name | Type | Description |
|---|---|---|
amount1 |
uint256 | The amount of token1 required to cover the specified liquidity between the two square-root prices. |
getAmount0Delta
function getAmount0Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount0)A helper function that retrieves a signed token0 delta.
Parameters
| Name | Type | Description |
|---|---|---|
sqrtRatioAX96 |
uint160 | The first square-root price. |
sqrtRatioBX96 |
uint160 | The second square-root price. |
liquidity |
int128 | The liquidity change to use in the calculation. |
Return values
| Name | Type | Description |
|---|---|---|
amount0 |
int256 | The amount of token0 corresponding to the liquidityDelta between the two specified square-root prices. |
getAmount1Delta
function getAmount1Delta(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
int128 liquidity
) internal pure returns (int256 amount1)A helper function that retrieves a signed token1 delta.
Parameters
| Name | Type | Description |
|---|---|---|
sqrtRatioAX96 |
uint160 | The first square-root price. |
sqrtRatioBX96 |
uint160 | The second square-root price. |
liquidity |
int128 | The liquidity change to use in the calculation. |
Return values
| Name | Type | Description |
|---|---|---|
amount0 |
int256 | The amount of token0 corresponding to the liquidityDelta between the two specified square-root prices, as labeled in the source. |
SwapMath
Computes the result of a swap within a single tick price range.
computeSwapStep
function computeSwapStep(
uint160 sqrtRatioCurrentX96,
uint160 sqrtRatioTargetX96,
uint128 liquidity,
int256 amountRemaining,
uint24 feePips
) internal pure returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut, uint256 feeAmount)Calculates the result of swapping a given amount of tokens based on specified parameters.
- Computes the result of exchanging a particular amount of tokens based on the swap parameters.
- The sum of fees and input amount is guaranteed not to exceed the remaining amount when the swap's
amountSpecifiedis positive.- This is a security mechanism that ensures the swap proceeds as intended and prevents incorrect trades.
The following tables show the parameters and return values.
Parameters
| Name | Type | Description |
|---|---|---|
sqrtRatioCurrentX96 |
uint160 | The current square-root price of the pool. |
sqrtRatioTargetX96 |
uint160 | The price that must not be exceeded. It is used to indicate the swap direction. |
liquidity |
uint128 | Available liquidity. |
amountRemaining |
int256 | The remaining input or output amount to exchange. |
feePips |
uint24 | The fee taken from the input amount, expressed as a percentage in the source. |
Return values
| Name | Type | Description |
|---|---|---|
sqrtRatioNextX96 |
uint160 | The price after swapping the input or output amount, constrained not to exceed the target price. |
amountIn |
uint256 | The amount swapped in (token0 or token1), calculated based on the swap direction. |
amountOut |
uint256 | The amount received (token0 or token1), calculated based on the swap direction. |
feeAmount |
uint256 | The input amount taken as fees. |
Tick
tickSpacingToMaxLiquidityPerTick
function tickSpacingToMaxLiquidityPerTick(
int24 tickSpacing
) internal pure returns (uint128)Derives the maximum liquidity per tick from the given tickSpacing.
Parameters
| Name | Type | Description |
|---|---|---|
tickSpacing |
int24 | The required tick spacing. Initialized ticks must be multiples of the spacing. For example, if tickSpacing is 3, a tick must be initialized every 3tick, at -6, -3, 0, 3, 6, .... |
Return values
| Type | Description |
|---|---|
| uint128 | The maximum liquidity per tick. |
getFeeGrowthInside
function getFeeGrowthInside(
mapping(int24 => struct Tick.Info) self,
int24 tickLower,
int24 tickUpper,
int24 tickCurrent,
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128
) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128)Retrieves fee growth data.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int24 => struct Tick.Info) | The mapping containing initialized tick information. |
tickLower |
int24 | The lower tick boundary of the position. |
tickUpper |
int24 | The upper tick boundary of the position. |
tickCurrent |
int24 | The current tick. |
feeGrowthGlobal0X128 |
uint256 | Global fee growth in token0 per unit of liquidity. |
feeGrowthGlobal1X128 |
uint256 | Global fee growth in token1 per unit of liquidity. |
Return values
| Name | Type | Description |
|---|---|---|
feeGrowthInside0X128 |
uint256 | Cumulative fee growth in token0 per unit of liquidity within the position's tick boundaries. |
feeGrowthInside1X128 |
uint256 | Cumulative fee growth in token1 per unit of liquidity within the position's tick boundaries. |
update
function update(
mapping(int24 => struct Tick.Info) self,
int24 tick,
int24 tickCurrent,
int128 liquidityDelta,
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128,
bool upper,
uint128 maxLiquidity
) internal returns (bool flipped)Updates a tick and returns true (written as ture in the source) if the tick flips from initialized to uninitialized, or vice versa.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int24 => struct Tick.Info) | The mapping containing initialized tick information. |
tick |
int24 | The tick to update. |
tickCurrent |
int24 | The current tick. |
liquidityDelta |
int128 | The new liquidity amount added or removed when a tick is crossed from left to right or right to left. |
feeGrowthGlobal0X128 |
uint256 | Global fee growth in token0 per unit of liquidity. |
feeGrowthGlobal1X128 |
uint256 | Global fee growth in token1 per unit of liquidity. |
upper |
bool | True when updating the position's upper tick; false when updating its lower tick. |
maxLiquidity |
uint128 | The maximum liquidity allocation for a single tick. |
Return values
| Name | Type | Description |
|---|---|---|
flipped |
bool | True if the tick changed from initialized to uninitialized, or vice versa. |
clear
function clear(
mapping(int24 => struct Tick.Info) self,
int24 tick
) internalResets tick data.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int24 => struct Tick.Info) | The mapping containing initialized tick information. |
tick |
int24 | The tick to clear. |
cross
function cross(
mapping(int24 => struct Tick.Info) self,
int24 tick,
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128
) internal returns (int128 liquidityNet)Transitions to the next tick according to price movement.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int24 => struct Tick.Info) | The mapping containing initialized tick information. |
tick |
int24 | The tick being crossed. |
feeGrowthGlobal0X128 |
uint256 | Global fee growth in token0 per unit of liquidity. |
feeGrowthGlobal1X128 |
uint256 | Global fee growth in token1 per unit of liquidity. |
Return values
| Name | Type | Description |
|---|---|---|
liquidityNet |
int128 | The amount of liquidity added or removed when a tick is crossed from left to right or right to left. |
TickBitmap
Stores a packed mapping of tick indices and their initialization states.
A tick is represented by int24, and each word contains 256(2^8) values, so the mapping uses int16 keys.
flipTick
function flipTick(
mapping(int16 => uint256) self,
int24 tick,
int24 tickSpacing
) internalFlips the initialization state of the specified tick from false to true, or vice versa.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int16 => uint256) | The mapping in which to flip the tick. |
tick |
int24 | The tick to flip. |
tickSpacing |
int24 | The spacing between usable tick values. |
nextInitializedTickWithinOneWord
function nextInitializedTickWithinOneWord(
mapping(int16 => uint256) self,
int24 tick,
int24 tickSpacing,
bool lte
) internal view returns (int24 next, bool initialized)Returns the next initialized tick to the left (less than or equal to) or right (greater than or equal to) of the specified tick, in the same or an adjacent word.
Parameters
| Name | Type | Description |
|---|---|---|
self |
mapping(int16 => uint256) | The mapping used to compute the next initialized tick. |
tick |
int24 | The starting tick. |
tickSpacing |
int24 | The spacing between usable tick values. |
lte |
bool | Whether to search for the next initialized tick less than or equal to the starting tick. |
Return values
| Name | Type | Description |
|---|---|---|
next |
int24 | The next initialized or uninitialized tick up to 256 tick steps from the current tick. |
initialized |
bool | Whether the next tick is initialized, since the function searches only up to 256 tick steps. |
TickMath
Computes the sqrt price for tick increments of size 1.0001, i.e., sqrt(1.0001^tick) as a fixed-point Q64.96 number.
Supports prices from 2-128 to 2128 (2 to the power of -128 through 2 to the power of 128).
getSqrtRatioAtTick
function getSqrtRatioAtTick(
int24 tick
) internal pure returns (uint160 sqrtPriceX96)Computes sqrt(1.0001^tick) * 2^96.
Throws an error if tick exceeds the maximum tick.
getTickAtSqrtRatio
function getTickAtSqrtRatio(
uint160 sqrtPriceX96
) internal pure returns (int24 tick)Computes the greatest tick satisfying getRatioAtTick(tick) <= ratio.
Throws an error if sqrtPriceX96 < MIN_SQRT_RATIO.
MIN_SQRT_RATIO is the lowest possible value returned by getRatioAtTick.
The following tables show the parameters and return values.
Parameters
| Name | Type | Description |
|---|---|---|
tick |
int24 | The input tick used in the formula above. |
Return values
| Name | Type | Description |
|---|---|---|
sqrtPriceX96 |
uint160 | A fixed-point Q64.96 number representing the square root of the ratio between the two assets (token1/token0). |
TransferHelper
See the following reference.
UnsafeMath
Performs common mathematical operations without checking for overflow or underflow.
divRoundingUp
function divRoundingUp(
uint256 x,
uint256 y
) internal pure returns (uint256 z)Returns ceil(x / y).
Throws an error when y is 0.
Parameters
| Name | Type | Description |
|---|---|---|
x |
uint256 | The dividend. |
y |
uint256 | The divisor. |
Return values
| Name | Type | Description |
|---|---|---|
z |
uint256 | The quotient, rounded up as in ceil(x / y). |
Governance
The Uniswap protocol is governed and updated by users who hold UNI tokens. Three components are important to governing this protocol: the UNI token, the governance module, and the Timelock.
- UNI token
- The UNI token is used in the Uniswap network and serves as a key to protocol governance.
- Holders of UNI tokens have the right to propose and vote on changes to the protocol.
- Governance module
- Software that manages Uniswap governance.
- Accounts holding a certain quantity of UNI tokens (2.5 million UNI, at least 0.25% of the total supply) can use this module to propose changes to the protocol, as described at the time of writing.
- Proposals contain executable code.
- Timelock
- The Timelock manages the waiting period before a proposal is executed.
- If a proposal is approved by a vote, the Timelock imposes a waiting period of at least two days before executing the proposal.
- This ensures the community has time to consider the proposal.
The process proceeds as follows.
- A UNI token holder creates a change proposal.
- The community has a seven-day voting period for the proposal. If it receives sufficient votes in favor, it is approved.
- The approved proposal is queued in the Timelock and executed no sooner than two days later.
Timelock
Source: https://docs.uniswap.org/contracts/v3/reference/governance/overview
The Uniswap protocol uses a mechanism called a timelock to change system settings, rules, and programs. This mechanism enables selective changes with a time delay.
Timelock contract
A special smart contract that manages important changes within the Uniswap protocol. The minimum notice period for governance actions (proposed protocol changes) is hardcoded in this contract. The source describes a waiting period of at least two days after a proposal is made. This rule ensures the community is informed of changes and has time to discuss them.
Changing the delay period
For particularly important changes (such as changes to the risk system), a delay period of up to 30 days can also be set. This ensures a longer period of discussion and review for major changes.
Control by the governance module
The timelock contract is controlled by the Uniswap governance module. In other words, authority over changes, including proposing governance actions and setting delay periods, rests with the Uniswap community.
Monitoring and transparency
A dashboard provides information on pending and completed governance actions in the timelock contract. This enables community members to monitor the progress of changes and ensures transparency.
Functions and events
See the following article for functions and events.
Conclusion
In this article, we translated and supplemented the following Technical Reference section.
What did you think?
I regularly publish articles about blockchain and AI on my blog and Qiita, so feel free to check them out!






