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.
This article uses Bunzz's DeCipher feature to examine the QuoterV2 contract in Uniswap V3.
DeCipher is a service that automatically generates contract documentation using AI.
For detailed instructions on using the service, see the following article.
This article reflects my own experience using DeCipher. If you notice any inaccuracies, please let me know in the comments.
The DeCipher link used in this article is below.
The Etherscan link is below.
Overview
The QuoterV2 contract provides token swap estimates for the Uniswap V3 protocol. It supports efficient and reliable token swaps on Uniswap.
Its primary purpose is to calculate the amounts of tokens sent and received in a swap. The calculation takes into account factors such as the token balances and price of the liquidity pool, as well as the applicable price limit and potential slippage. Users can obtain a quote for the token swap they want to perform.
Its specific roles include the following.
-
Calculating quotes The QuoterV2 contract uses the libraries and interfaces required for complex calculations to determine token amounts accurately. Calculations consider the current state of the pool, including liquidity and token prices.
-
Accuracy The objective is to provide accurate estimates based on the relevant market state. Mathematical methods and data from the Uniswap V3 protocol enable precise quotes.
-
Callback handling The contract uses callbacks to perform additional processing based on the result of a simulated swap. This enables specific actions in response to swap execution.
-
Support for multiple tokens To accommodate swaps between different tokens, QuoterV2 supports multiple token pairs. It can therefore provide quotes for various token combinations.
Usage
QuoterV2 is a smart contract for estimating the amount of token0 or token1 involved in a swap within a Uniswap V3 pool. It is part of the Uniswap V3 protocol and is used by developers to obtain token swap estimates.
Objective
The contract aims to provide accurate estimates for token swaps in Uniswap V3 pools. Specifically, it calculates the amount of token0 or token1 received for a specified input amount.
The following steps illustrate the process.
-
Deploy the QuoterV2 contract.
-
Call
quoteExactInputSinglewith a specified input token amount. The function calculates the expected output amount from swapping the specified input for token0 or token1. -
Call
quoteExactOutputSinglewith a specified output token amount. The function works backward from the desired output amount to estimate the required input amount for the swap.
Functions
quoteExactInputSingle
Estimates the output token amount (amountOut) obtainable from a swap in a Uniswap V3 pool given a specified input token amount (amountIn).
The path (path) represents the swap route.
The first token in the route is the input token, and the last is the output token.
A square root price limit (sqrtPriceLimitX96) can also be specified for a single-pool quote.
Return Value The amount of output tokens received for the specified input amount.
quoteExactOutputSingle
This function estimates the input token amount (amountIn) required to obtain a specified output token amount (amountOut) through a swap in a Uniswap V3 pool.
The parameters describe the swap route (path) and, for a single-pool quote, the square root price limit (sqrtPriceLimitX96).
Return Value The input token amount required to receive the specified output amount.
Events
Quoted
An event described as being emitted when a specific token swap quote is generated. It conveys estimated token input and output amounts for a swap.
Parameters
path- The token addresses representing the swap route.
- The first token is the input token and the last is the output token.
amountIn- The input token amount used in the quote.
- Indicates the amount of tokens used as input for a particular swap.
amountOut- The output token amount obtainable for the specified input amount.
- Indicates the amount of tokens that can be received from the swap.
Related EIPs and ERCs
- EIP-1620: Money Streaming Standard
- [ERC-20: Token Standard(https://eips.ethereum.org/EIPS/eip-20)
- ERC-721: Non-Fungible Token Standard
- ERC-1155: Multi-Token Standard
Parameters
_factory
The address of the Uniswap V3 factory contract. The contract is part of Uniswap V3 and is used to create liquidity pools for different token combinations. It is the entry point for creating new token-pair pools.
_WETH9
The address of the WETH9 contract. WETH9 is an ERC20 token representing ether (ETH) on Ethereum. ETH is the native currency, wrapped as an ERC20 token to improve interoperability with smart contracts. This allows DeFi projects and token swap protocols to work with ETH through an ERC20-compatible interface.
Contract
QuoterV2
amountOutCached
amountOutCached
uint256 private amountOutCached;Overview A temporary storage variable used to check the validity of a token swap.
Details It is used to check a token swap within a particular transaction. The variable is used in conditional checks to validate the swap result.
getPool
getPool
function getPool(
address tokenA,
address tokenB,
uint24 fee
) private view returns (IUniswapV3Pool) {
return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)));
}Overview Retrieves a Uniswap V3 pool.
Details Computes the corresponding pool address from the specified tokens and fee tier and returns the pool instance.
Arguments
tokenA- The address of token A.
tokenB- The address of token B.
fee- The fee tier.
Return Value
IUniswapV3Pool- The Uniswap V3 pool instance corresponding to the specified tokens and fee tier.
uniswapV3SwapCallback
uniswapV3SwapCallback
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes memory path
) external view override {
require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee);
(bool isExactInput, uint256 amountToPay, uint256 amountReceived) =
amount0Delta > 0
? (tokenIn < tokenOut, uint256(amount0Delta), uint256(-amount1Delta))
: (tokenOut < tokenIn, uint256(amount1Delta), uint256(-amount0Delta));
IUniswapV3Pool pool = getPool(tokenIn, tokenOut, fee);
(uint160 sqrtPriceX96After, int24 tickAfter, , , , , ) = pool.slot0();
if (isExactInput) {
assembly {
let ptr := mload(0x40)
mstore(ptr, amountReceived)
mstore(add(ptr, 0x20), sqrtPriceX96After)
mstore(add(ptr, 0x40), tickAfter)
revert(ptr, 96)
}
} else {
// if the cache has been populated, ensure that the full output amount has been received
if (amountOutCached != 0) require(amountReceived == amountOutCached);
assembly {
let ptr := mload(0x40)
mstore(ptr, amountToPay)
mstore(add(ptr, 0x20), sqrtPriceX96After)
mstore(add(ptr, 0x40), tickAfter)
revert(ptr, 96)
}
}
}Overview The Uniswap V3 swap callback. It is called during a swap and processes token amount deltas and the path.
Details
- Check for an error when a swap occurs entirely within a
0-liquidityregion. - Decode the input token, output token, and fee tier.
- Retrieve the pool instance.
- Handle exact-input and exact-output swaps differently.
Arguments
amount0Delta- The change in the amount of token0.
amount1Delta- The change in the amount of token1.
path- The token path.
-
Check for an error when a swap occurs entirely within a zero-liquidity region The function checks whether the swap occurs within a
0-liquidityregion.amount0Deltaandamount1Deltarepresent the changes in token0 and token1 amounts, respectively. The condition rejects swaps for which the relevant token deltas are not positive. This is because swaps occurring entirely within0-liquidityregions are unsupported. -
Decode the input token, output token, and fee tier
pathrepresents the swap route and is decoded to obtain the input token, output token, and fee tier. Decoding identifies the input and output tokens and the fee tier used. -
Retrieve the pool instance The
getPoolfunction retrieves the Uniswap V3 pool instance corresponding to the specified tokens and fee tier. This gives access to the details of the pool where the swap occurs. -
Handle exact-input and exact-output swaps differently The function determines whether the swap is exact-input or exact-output and handles it accordingly. For exact-input swaps, it calculates the output amount and returns the resulting price and tick through a revert. For exact-output swaps, it checks whether the output amount is cached. If so, it verifies that the received amount matches the expected amount. If the cache is absent, it uses the swap result to report the corresponding amount and price tick.
The function thus handles different requirements and conditions during swap processing. It distinguishes exact-input from exact-output swaps and calculates the corresponding amounts, price, and tick to produce the quote.
parseRevertReason
parseRevertReason
function parseRevertReason(bytes memory reason)
private
pure
returns (
uint256 amount,
uint160 sqrtPriceX96After,
int24 tickAfter
)
{
if (reason.length != 96) {
if (reason.length < 68) revert('Unexpected error');
assembly {
reason := add(reason, 0x04)
}
revert(abi.decode(reason, (string)));
}
return abi.decode(reason, (uint256, uint160, int24));
}Overview Parses revert data to extract a numeric quote and price information.
Details
If the revert data is not 96 bytes long, the function performs error checks.
It then extracts numeric information from the 96-byte quote payload and returns it.
Arguments
reason- The revert data.
Return Value
amount- The amount.
sqrtPriceX96After- The square root price in X96 format.
tickAfter- The price tick.
parseRevertReason works as follows.
- Check whether
reasonis96bytes long. If it is shorter than68bytes, revert with Unexpected error. - If
reasonis96bytes long, extract numeric information from the byte array. The values are decoded usingabi.decode.
handleRevert
handleRevert
function handleRevert(
bytes memory reason,
IUniswapV3Pool pool,
uint256 gasEstimate
)
private
view
returns (
uint256 amount,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256
)
{
int24 tickBefore;
int24 tickAfter;
(, tickBefore, , , , , ) = pool.slot0();
(amount, sqrtPriceX96After, tickAfter) = parseRevertReason(reason
);
initializedTicksCrossed = pool.countInitializedTicksCrossed(tickBefore, tickAfter);
return (amount, sqrtPriceX96After, initializedTicksCrossed, gasEstimate);
}Overview Extracts and returns information from revert data when a simulated swap reverts.
Details
- Retrieve the pool's price tick information.
- Parse numeric information from revert data.
- Calculate the number of initialized ticks crossed.
- Return the parsed information.
Arguments
reason- The revert data.
pool- The Uniswap V3 pool instance.
gasEstimate- The gas estimate.
Return Value
amount- The amount.
sqrtPriceX96After- The square root price in X96 format.
initializedTicksCrossed- The number of initialized ticks crossed.
gasEstimate- The gas estimate.
quoteExactInputSingle
quoteExactInputSingle
function quoteExactInputSingle(QuoteExactInputSingleParams memory params)
public
override
returns (
uint256 amountOut,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate
)
{
bool zeroForOne = params.tokenIn < params.tokenOut;
IUniswapV3Pool pool = getPool(params.tokenIn, params.tokenOut, params.fee);
uint256 gasBefore = gasleft();
try
pool.swap(
address(this), // address(0) might cause issues with some tokens
zeroForOne,
params.amountIn.toInt256(),
params.sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: params.sqrtPriceLimitX96,
abi.encodePacked(params.tokenIn, params.fee, params.tokenOut)
)
{} catch (bytes memory reason) {
gasEstimate = gasBefore - gasleft();
return handleRevert(reason, pool, gasEstimate);
}
}Overview Provides a quote for a swap with an exact input amount.
Details
- Determine the input and output token ordering.
- Retrieve the pool instance.
- Attempt the swap and measure gas consumption.
- If the swap reverts, process the revert data.
Arguments
params- A struct containing the swap parameters.
Return Value
amountOut- The output amount.
sqrtPriceX96After- The square root price in X96 format.
initializedTicksCrossed- The number of initialized ticks crossed.
gasEstimate- Estimated gas consumption.
quoteExactInputSingle
quoteExactInputSingle
function quoteExactInputSingle(QuoteExactInputSingleParams memory params)
public
override
returns (
uint256 amountOut,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate
)
{
// スワップの入力トークンが出力トークンよりも小さいかどうかを判定
bool zeroForOne = params.tokenIn < params.tokenOut;
// プールのインスタンスを取得
IUniswapV3Pool pool = getPool(params.tokenIn, params.tokenOut, params.fee);
// ガス消費量の計測を開始
uint256 gasBefore = gasleft();
try
// スワップを試行
pool.swap(
address(this), // address(0) might cause issues with some tokens
zeroForOne,
params.amountIn.toInt256(),
params.sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: params.sqrtPriceLimitX96,
abi.encodePacked(params.tokenIn, params.fee, params.tokenOut)
)
{} catch (bytes memory reason) {
// ガス消費量の計測を終了
gasEstimate = gasBefore - gasleft();
// リバートの理由を処理して戻り値を返す
return handleRevert(reason, pool, gasEstimate);
}
}Overview Provides a quote for a swap with a specified input amount.
Details
- Determine whether the input token address is smaller than the output token address and set the
zeroForOneflag. - Retrieve the pool instance.
- Attempt the swap and measure gas consumption.
- If the swap reverts, process the revert data and return the result.
Arguments
params- A struct containing the swap parameters.
Return Value
amountOut- The output amount.
sqrtPriceX96After- The square root price in X96 format.
initializedTicksCrossed- The number of initialized ticks crossed.
gasEstimate- Estimated gas consumption.
quoteExactInput
quoteExactInput
function quoteExactInput(bytes memory path, uint256 amountIn)
public
override
returns (
uint256 amountOut,
uint160[] memory sqrtPriceX96AfterList,
uint32[] memory initializedTicksCrossedList,
uint256 gasEstimate
)
{
sqrtPriceX96AfterList = new uint160[](path.numPools());
initializedTicksCrossedList = new uint32[](path.numPools());
uint256 i = 0;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
// 前のスワップの出力を次のスワップの入力として使用
(uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed, uint256 _gasEstimate) =
quoteExactInputSingle(
QuoteExactInputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
fee: fee,
amountIn: amountIn,
sqrtPriceLimitX96: 0
})
);
sqrtPriceX96AfterList[i] = _sqrtPriceX96After;
initializedTicksCrossedList[i] = _initializedTicksCrossed;
amountIn = _amountOut;
gasEstimate += _gasEstimate;
i++;
// 続行するか終了するかを判断
if (path.hasMultiplePools()) {
path = path.skipToken();
} else {
return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, gasEstimate);
}
}
}Overview Provides a quote for a sequence of swaps.
Details
- Initialize the output amount and price tick lists according to the number of tokens in the path.
- Simulate swaps through all pools in the path and record each swap's details.
- Use the previous swap's output as the next swap's input.
- Append the resulting quote details to the lists.
- Process revert data to obtain the quote results.
Arguments
path- The token path for the swap.
amountIn- The input amount.
Return Value
amountOut- The output amount.
sqrtPriceX96AfterList- A list of square root prices (X96 format) after each swap.
initializedTicksCrossedList- A list of initialized tick counts crossed in each swap.
gasEstimate- Estimated gas consumption.
quoteExactOutputSingle
quoteExactOutputSingle
function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)
public
override
returns (
uint256 amountIn,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate
)
{
// スワップの出力トークンが入力トークンよりも小さいかどうかを判定
bool zeroForOne = params.tokenIn < params.tokenOut;
// プールのインスタンスを取得
IUniswapV3Pool pool = getPool(params.tokenIn, params.tokenOut, params.fee);
// 価格制限が指定されていない場合、出力量をキャッシュして後続のスワップで比較できるようにする
if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;
uint256 gasBefore = gasleft();
try
// スワップを試行
pool.swap(
address(this), // address(0) might cause issues with some tokens
zeroForOne,
-params.amount.toInt256(),
params.sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: params.sqrtPriceLimitX96,
abi.encodePacked(params.tokenOut, params.fee, params.tokenIn)
)
{} catch (bytes memory reason) {
// ガス消費量の計測を終了
gasEstimate = gasBefore - gasleft();
// 価格制限が指定されていない場合、キャッシュをクリア
if (params.sqrtPriceLimitX96 == 0) delete amountOutCached;
// リバートの理由を処理して戻り値を返す
return handleRevert(reason, pool, gasEstimate);
}
}Overview Provides a quote for a swap with a specified output amount.
Details
- Determine whether the output token address is smaller than the input token address and set the
zeroForOneflag accordingly. - Retrieve the pool instance.
- If no price limit is specified, cache the output amount for comparison during the simulated swap.
- Attempt the swap and measure gas consumption.
- If the swap reverts, process the revert data and return the result.
Arguments
params- A struct containing the swap parameters.
Return Value
amountIn- The input amount.
sqrtPriceX96After- The square root price in X96 format.
initializedTicksCrossed- The number of initialized ticks crossed.
gasEstimate- Estimated gas consumption.
quoteExactOutput
quoteExactOutput
function quoteExactOutput(bytes memory path, uint256 amountOut)
public
override
returns (
uint256 amountIn,
uint160[] memory sqrtPriceX96AfterList,
uint32[] memory initializedTicksCrossedList,
uint256 gasEstimate
)
{
sqrtPriceX96AfterList = new uint160[](path.numPools());
initializedTicksCrossedList = new uint32[](path.numPools());
uint256 i = 0;
while (true) {
(address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();
// 前のスワップの入力を次のスワップの出力として使用
(uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed, uint256 _gasEstimate) =
quoteExactOutputSingle(
QuoteExactOutputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
amount: amountOut,
fee: fee,
sqrtPriceLimitX96: 0
})
);
sqrtPriceX96AfterList[i] = _sqrtPriceX96After;
initializedTicksCrossedList[i] = _initializedTicksCrossed;
amountOut = _amountIn;
gasEstimate += _gasEstimate;
i++;
// 続行するか終了するかを判断
if (path.hasMultiplePools()) {
path = path.skipToken();
} else {
return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, gasEstimate);
}
}
}Overview Provides a quote for a sequence of swaps given a specified amount.
Details
- Initialize the price and initialized tick lists according to the number of pools in the path.
- Simulate swaps through all pools in the path and record each swap's details.
- Use the input required by the previous swap as the output of the next swap in the reverse path.
- Append the resulting quote details to the lists.
- Process revert data to obtain the quote results.
Arguments
path- The token path for the swap.
amountOut- The output amount.
PoolTicksCounter
countInitializedTicksCrossed
countInitializedTicksCrossed
function countInitializedTicksCrossed(
IUniswapV3Pool self,
int24 tickBefore,
int24 tickAfter
) internal view returns (uint32 initializedTicksCrossed) {
// 各種変数とフラグの初期化
int16 wordPosLower;
int16 wordPosHigher;
uint8 bitPosLower;
uint8 bitPosHigher;
bool tickBeforeInitialized;
bool tickAfterInitialized;
// ローカルスコープで変数を計算
{
// スワップ前と後のアクティブティックのキーとオフセットを取得
int16 wordPos = int16((tickBefore / self.tickSpacing()) >> 8);
uint8 bitPos = uint8((tickBefore / self.tickSpacing()) % 256);
int16 wordPosAfter = int16((tickAfter / self.tickSpacing()) >> 8);
uint8 bitPosAfter = uint8((tickAfter / self.tickSpacing()) % 256);
// スワップ後のティックが初期化されている場合、スワップが下向きであるかどうかを確認
tickAfterInitialized =
((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0) &&
((tickAfter % self.tickSpacing()) == 0) &&
(tickBefore > tickAfter);
// スワップ前のティックが初期化されている場合、スワップが上向きであるかどうかを確認
tickBeforeInitialized =
((self.tickBitmap(wordPos) & (1 << bitPos)) > 0) &&
((tickBefore % self.tickSpacing()) == 0) &&
(tickBefore < tickAfter);
if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {
wordPosLower = wordPos;
bitPosLower = bitPos;
wordPosHigher = wordPosAfter;
bitPosHigher = bitPosAfter;
} else {
wordPosLower = wordPosAfter;
bitPosLower = bitPosAfter;
wordPosHigher = wordPos;
bitPosHigher = bitPos;
}
}
// ティックビットマップをイテレートして初期化されたティックの数を数える
// 最初のマスクには、下向きティックとその左側のティックを含める
uint256 mask = type(uint256).max << bitPosLower;
while (wordPosLower <= wordPosHigher) {
// 最後のティックビットマップページの場合、終了ティックまでのカウントに制限
if (wordPosLower == wordPosHigher) {
mask = mask & (type(uint256).max >> (255 - bitPosHigher));
}
uint256 masked = self.tickBitmap(wordPosLower) & mask;
initializedTicksCrossed += countOneBits(masked);
wordPosLower++;
// 次のイテレーションですべてのビットを考慮するためにマスクをリセット
mask = type(uint256).max;
}
if (tickAfterInitialized) {
initializedTicksCrossed -= 1;
}
if (tickBeforeInitialized) {
initializedTicksCrossed -= 1;
}
return initializedTicksCrossed;
}Overview Counts the initialized ticks crossed by a swap.
Details
- Initialize the variables and flags for counting initialized ticks.
- In a local scope, calculate the bitmap keys and offsets for the ticks before and after the swap.
- If the post-swap tick is initialized, determine whether to exclude it from the count based on swap direction.
- If the pre-swap tick is initialized, determine whether to exclude it from the count based on swap direction.
- Iterate through the tick bitmaps and count the initialized ticks crossed.
- Subtract one from the count when the post-swap tick must be excluded.
- Subtract one from the count when the pre-swap tick must be excluded.
- Return the number of initialized ticks counted.
Arguments
self- An IUniswapV3Pool instance.
tickBefore- The tick before the swap.
tickAfter- The tick after the swap.
Return Value
initializedTicksCrossed- The number of initialized ticks counted.
Consider the following situation.
tickBefore:1000tickAfter:2000
Overview
Counts the initialized ticks between the specified tickBefore and tickAfter.
Details
- Calculate the tick spacing and locate
tickBeforeandtickAfterwithin their corresponding bitmaps. - If
tickBeforeis initialized, check whether the swap moves upward. - If
tickAfteris initialized, check whether the swap moves downward. - Iterate through the range to count initialized ticks between
tickBeforeandtickAfter. - Return the number of initialized ticks counted.
In this example, tickBefore is 1000 and tickAfter is 2000; the tick increases.
The function counts initialized ticks within the range crossed by the swap, accounting for the direction of the swap.
countOneBits
countOneBits
function countOneBits(uint256 x) private pure returns (uint16) {
uint16 bits = 0;
while (x != 0) {
bits++;
x &= (x - 1);
}
return bits;
}
}Overview Counts the number of set bits in the binary representation of a given integer.
Details
- Initialize
bitsto count the1bits. - While the representation is nonzero, count set bits and increment
bitsaccordingly. - Return
bitsonce all set bits have been counted.
Arguments
x- The integer representing the bit pattern.
Return Value
bits- The number of set bits in the binary representation.
Events
None.
Code
QuoterV2.sol
QuoterV2.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '@uniswap/v3-periphery/contracts/base/PeripheryImmutableState.sol';
import '@uniswap/v3-core/contracts/libraries/SafeCast.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/libraries/TickBitmap.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
import '@uniswap/v3-periphery/contracts/libraries/Path.sol';
import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';
import '@uniswap/v3-periphery/contracts/libraries/CallbackValidation.sol';
import '../interfaces/IQuoterV2.sol';
import '../libraries/PoolTicksCounter.sol';
/// @title Provides quotes for swaps
/// @notice Allows getting the expected amount out or amount in for a given swap without executing the swap
/// @dev These functions are not gas efficient and should _not_ be called on chain. Instead, optimistically execute
/// the swap and check the amounts in the callback.
contract QuoterV2 is IQuoterV2, IUniswapV3SwapCallback, PeripheryImmutableState {
using Path for bytes;
using SafeCast for uint256;
using PoolTicksCounter for IUniswapV3Pool;
/// @dev Transient storage variable used to check a safety condition in exact output swaps.
uint256 private amountOutCached;
constructor(address _factory, address _WETH9) PeripheryImmutableState(_factory, _WETH9) {}
function getPool(
address tokenA,
address tokenB,
uint24 fee
) private view returns (IUniswapV3Pool) {
return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)));
}
/// @inheritdoc IUniswapV3SwapCallback
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes memory path
) external view override {
require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee);
(bool isExactInput, uint256 amountToPay, uint256 amountReceived) =
amount0Delta > 0
? (tokenIn < tokenOut, uint256(amount0Delta), uint256(-amount1Delta))
: (tokenOut < tokenIn, uint256(amount1Delta), uint256(-amount0Delta));
IUniswapV3Pool pool = getPool(tokenIn, tokenOut, fee);
(uint160 sqrtPriceX96After, int24 tickAfter, , , , , ) = pool.slot0();
if (isExactInput) {
assembly {
let ptr := mload(0x40)
mstore(ptr, amountReceived)
mstore(add(ptr, 0x20), sqrtPriceX96After)
mstore(add(ptr, 0x40), tickAfter)
revert(ptr, 96)
}
} else {
// if the cache has been populated, ensure that the full output amount has been received
if (amountOutCached != 0) require(amountReceived == amountOutCached);
assembly {
let ptr := mload(0x40)
mstore(ptr, amountToPay)
mstore(add(ptr, 0x20), sqrtPriceX96After)
mstore(add(ptr, 0x40), tickAfter)
revert(ptr, 96)
}
}
}
/// @dev Parses a revert reason that should contain the numeric quote
function parseRevertReason(bytes memory reason)
private
pure
returns (
uint256 amount,
uint160 sqrtPriceX96After,
int24 tickAfter
)
{
if (reason.length != 96) {
if (reason.length < 68) revert('Unexpected error');
assembly {
reason := add(reason, 0x04)
}
revert(abi.decode(reason, (string)));
}
return abi.decode(reason, (uint256, uint160, int24));
}
function handleRevert(
bytes memory reason,
IUniswapV3Pool pool,
uint256 gasEstimate
)
private
view
returns (
uint256 amount,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256
)
{
int24 tickBefore;
int24 tickAfter;
(, tickBefore, , , , , ) = pool.slot0();
(amount, sqrtPriceX96After, tickAfter) = parseRevertReason(reason);
initializedTicksCrossed = pool.countInitializedTicksCrossed(tickBefore, tickAfter);
return (amount, sqrtPriceX96After, initializedTicksCrossed, gasEstimate);
}
function quoteExactInputSingle(QuoteExactInputSingleParams memory params)
public
override
returns (
uint256 amountOut,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate
)
{
bool zeroForOne = params.tokenIn < params.tokenOut;
IUniswapV3Pool pool = getPool(params.tokenIn, params.tokenOut, params.fee);
uint256 gasBefore = gasleft();
try
pool.swap(
address(this), // address(0) might cause issues with some tokens
zeroForOne,
params.amountIn.toInt256(),
params.sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: params.sqrtPriceLimitX96,
abi.encodePacked(params.tokenIn, params.fee, params.tokenOut)
)
{} catch (bytes memory reason) {
gasEstimate = gasBefore - gasleft();
return handleRevert(reason, pool, gasEstimate);
}
}
function quoteExactInput(bytes memory path, uint256 amountIn)
public
override
returns (
uint256 amountOut,
uint160[] memory sqrtPriceX96AfterList,
uint32[] memory initializedTicksCrossedList,
uint256 gasEstimate
)
{
sqrtPriceX96AfterList = new uint160[](path.numPools());
initializedTicksCrossedList = new uint32[](path.numPools());
uint256 i = 0;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
// the outputs of prior swaps become the inputs to subsequent ones
(uint256 _amountOut, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed, uint256 _gasEstimate) =
quoteExactInputSingle(
QuoteExactInputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
fee: fee,
amountIn: amountIn,
sqrtPriceLimitX96: 0
})
);
sqrtPriceX96AfterList[i] = _sqrtPriceX96After;
initializedTicksCrossedList[i] = _initializedTicksCrossed;
amountIn = _amountOut;
gasEstimate += _gasEstimate;
i++;
// decide whether to continue or terminate
if (path.hasMultiplePools()) {
path = path.skipToken();
} else {
return (amountIn, sqrtPriceX96AfterList, initializedTicksCrossedList, gasEstimate);
}
}
}
function quoteExactOutputSingle(QuoteExactOutputSingleParams memory params)
public
override
returns (
uint256 amountIn,
uint160 sqrtPriceX96After,
uint32 initializedTicksCrossed,
uint256 gasEstimate
)
{
bool zeroForOne = params.tokenIn < params.tokenOut;
IUniswapV3Pool pool = getPool(params.tokenIn, params.tokenOut, params.fee);
// if no price limit has been specified, cache the output amount for comparison in the swap callback
if (params.sqrtPriceLimitX96 == 0) amountOutCached = params.amount;
uint256 gasBefore = gasleft();
try
pool.swap(
address(this), // address(0) might cause issues with some tokens
zeroForOne,
-params.amount.toInt256(),
params.sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: params.sqrtPriceLimitX96,
abi.encodePacked(params.tokenOut, params.fee, params.tokenIn)
)
{} catch (bytes memory reason) {
gasEstimate = gasBefore - gasleft();
if (params.sqrtPriceLimitX96 == 0) delete amountOutCached; // clear cache
return handleRevert(reason, pool, gasEstimate);
}
}
function quoteExactOutput(bytes memory path, uint256 amountOut)
public
override
returns (
uint256 amountIn,
uint160[] memory sqrtPriceX96AfterList,
uint32[] memory initializedTicksCrossedList,
uint256 gasEstimate
)
{
sqrtPriceX96AfterList = new uint160[](path.numPools());
initializedTicksCrossedList = new uint32[](path.numPools());
uint256 i = 0;
while (true) {
(address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();
// the inputs of prior swaps become the outputs of subsequent ones
(uint256 _amountIn, uint160 _sqrtPriceX96After, uint32 _initializedTicksCrossed, uint256 _gasEstimate) =
quoteExactOutputSingle(
QuoteExactOutputSingleParams({
tokenIn: tokenIn,
tokenOut: tokenOut,
amount: amountOut,
fee: fee,
sqrtPriceLimitX96: 0
})
);
sqrtPriceX96AfterList[i] = _sqrtPriceX96After;
initializedTicksCrossedList[i] = _initializedTicksCrossed;
amountOut = _amountIn;
gasEstimate += _gasEstimate;
i++;
// decide whether to continue or terminate
if (path.hasMultiplePools()) {
path = path.skipToken();
} else {
return (amountOut, sqrtPriceX96AfterList, initializedTicksCrossedList, gasEstimate);
}
}
}
}PoolTicksCounter
PoolTicksCounter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
library PoolTicksCounter {
/// @dev This function counts the number of initialized ticks that would incur a gas cost between tickBefore and tickAfter.
/// When tickBefore and/or tickAfter themselves are initialized, the logic over whether we should count them depends on the
/// direction of the swap. If we are swapping upwards (tickAfter > tickBefore) we don't want to count tickBefore but we do
/// want to count tickAfter. The opposite is true if we are swapping downwards.
function countInitializedTicksCrossed(
IUniswapV3Pool self,
int24 tickBefore,
int24 tickAfter
) internal view returns (uint32 initializedTicksCrossed) {
int16 wordPosLower;
int16 wordPosHigher;
uint8 bitPosLower;
uint8 bitPosHigher;
bool tickBeforeInitialized;
bool tickAfterInitialized;
{
// Get the key and offset in the tick bitmap of the active tick before and after the swap.
int16 wordPos = int16((tickBefore / self.tickSpacing()) >> 8);
uint8 bitPos = uint8((tickBefore / self.tickSpacing()) % 256);
int16 wordPosAfter = int16((tickAfter / self.tickSpacing()) >> 8);
uint8 bitPosAfter = uint8((tickAfter / self.tickSpacing()) % 256);
// In the case where tickAfter is initialized, we only want to count it if we are swapping downwards.
// If the initializable tick after the swap is initialized, our original tickAfter is a
// multiple of tick spacing, and we are swapping downwards we know that tickAfter is initialized
// and we shouldn't count it.
tickAfterInitialized =
((self.tickBitmap(wordPosAfter) & (1 << bitPosAfter)) > 0) &&
((tickAfter % self.tickSpacing()) == 0) &&
(tickBefore > tickAfter);
// In the case where tickBefore is initialized, we only want to count it if we are swapping upwards.
// Use the same logic as above to decide whether we should count tickBefore or not.
tickBeforeInitialized =
((self.tickBitmap(wordPos) & (1 << bitPos)) > 0) &&
((tickBefore % self.tickSpacing()) == 0) &&
(tickBefore < tickAfter);
if (wordPos < wordPosAfter || (wordPos == wordPosAfter && bitPos <= bitPosAfter)) {
wordPosLower = wordPos;
bitPosLower = bitPos;
wordPosHigher = wordPosAfter;
bitPosHigher = bitPosAfter;
} else {
wordPosLower = wordPosAfter;
bitPosLower = bitPosAfter;
wordPosHigher = wordPos;
bitPosHigher = bitPos;
}
}
// Count the number of initialized ticks crossed by iterating through the tick bitmap.
// Our first mask should include the lower tick and everything to its left.
uint256 mask = type(uint256).max << bitPosLower;
while (wordPosLower <= wordPosHigher) {
// If we're on the final tick bitmap page, ensure we only count up to our
// ending tick.
if (wordPosLower == wordPosHigher) {
mask = mask & (type(uint256).max >> (255 - bitPosHigher));
}
uint256 masked = self.tickBitmap(wordPosLower) & mask;
initializedTicksCrossed += countOneBits(masked);
wordPosLower++;
// Reset our mask so we consider all bits on the next iteration.
mask = type(uint256).max;
}
if (tickAfterInitialized) {
initializedTicksCrossed -= 1;
}
if (tickBeforeInitialized) {
initializedTicksCrossed -= 1;
}
return initializedTicksCrossed;
}
function countOneBits(uint256 x) private pure returns (uint16) {
uint16 bits = 0;
while (x != 0) {
bits++;
x &= (x - 1);
}
return bits;
}
}Conclusion
This article examined the QuoterV2 contract of Uniswap V3 using Bunzz's DeCipher feature. I hope you found it useful. I plan to continue exploring selected NFTs and smart contracts in future articles.
I also publish articles on blockchain and AI on my blog and Qiita.




