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 Uniswap V3's Quoter contract.
DeCipher uses AI to automatically generate contract documentation.
See the following article for instructions on using the service.
This article reflects my own experience using DeCipher. If you notice any inaccuracies, please let me know in the comments.
Here is the DeCipher documentation used in this article.
The corresponding Etherscan page is available below.
Overview
The Quoter contract plays an important role in the Uniswap V3 protocol. It provides quotes for token swaps on the Uniswap decentralized exchange. Specifically, it calculates the amounts of tokens sent and received in a swap, giving users accurate information.
Quoter works with other contracts and libraries in the Uniswap V3 ecosystem. These include SafeCast, TickMath, IUniswapV3Pool, IUniswapV3SwapCallback, Path, PoolAddress, CallbackValidation, and BytesLib.
Through the IUniswapV3Pool interface, Quoter obtains the data it needs from Uniswap V3 pools. Calculations involving the pool's tick system use the TickMath library. The Path library is also used when handling the optimal route for a token swap.
Responsibilities
Providing accurate quotes
Predicts the amount of tokens to be received or sent during a swap based on market conditions. This provides users with accurate trade information.
Interacting with other contracts
Quoter works with various contracts and libraries in the Uniswap V3 ecosystem to retrieve the necessary data and perform calculations. This enables accurate quotes.
Ensuring security and validation
Quoter uses the CallbackValidation library to protect the security and validity of swap operations. This prevents unauthorized operations and supports safe token swaps.
Usage
Quoter is a smart contract that provides price quotes for token swaps in Uniswap V3 pools. It exposes functions that allow technical operators and developers to calculate token swap prices easily.
Goal
Obtain price quotes for token swaps in Uniswap V3 pools with minimal effort. This allows technical operators and developers to calculate the output amount for a given input amount based on the current state of a pool.
Steps
- Deploy the Quoter contract.
- Call
quoteExactInputSingleto obtain an output amount quote for a specified input amount in a single-hop swap. - Call
quoteExactOutputSingleto obtain the input amount required to receive a desired output amount in a single-hop swap. - Call
quoteExactInputto obtain an output amount quote for a specified input amount in a multi-hop swap. - Call
quoteExactOutputto obtain the input amount required to receive a desired output amount in a multi-hop swap.
Functions
The following functions on Quoter provide price quotes for token swaps.
quoteExactInputSingle
path- An array of token addresses representing the token swap path.
amountIn- The amount of input tokens to swap.
sqrtPriceLimitX96- The square root of the price limit within the pool's current tick range.
quoteExactOutputSingle
Calculates the input amount required to receive a desired output amount in a single-hop swap.
path- An array of token addresses representing the token swap path.
amountOut- The desired amount of output tokens.
sqrtPriceLimitX96- The square root of the price limit within the pool's current tick range.
quoteExactInput
Calculates the output amount for a given input amount in a multi-hop swap.
path- An array of token addresses representing the token swap path.
amountIn- The amount of input tokens to swap.
sqrtPriceLimitX96- The square root of the price limit within the pool's current tick range.
quoteExactOutput
Calculates the input amount required to receive a desired output amount in a multi-hop swap.
path- An array of token addresses representing the token swap path.
amountOut- The desired amount of output tokens.
sqrtPriceLimitX96- The square root of the price limit within the pool's current tick range.
Related EIPs and ERCs
- EIP-165: Standard Interface Detection
See the following article for more about ERC165.
- ERC-20: Token Standard
See the following article for more about ERC20.
- ERC-721: Non-Fungible Token Standard
See the following article for more about ERC721.
- ERC-1155: Multi-Token Standard
See the following article for more about ERC1155.
Parameters
_factory
Refers to the address of the Uniswap factory contract. This address is used to create new instances of Uniswap token pairs. The Uniswap factory plays an important role in creating pairs of different tokens and making them available for trading on the exchange. For example, it enables trading ETH against another token.
_WETH9 Refers to the address of the WETH9 contract. This represents the Wrapped Ether token on the Ethereum network. WETH wraps Ethereum's native token, ETH, so that it can be treated as an ERC20 token. This allows ETH to be used in a format that is more interoperable with smart contracts.
Contracts
Quoter
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));
if (isExactInput) {
assembly {
let ptr := mload(0x40)
mstore(ptr, amountReceived)
revert(ptr, 32)
}
} 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)
revert(ptr, 32)
}
}
}Overview Handles Uniswap V3 swap callbacks.
Details
- Receives the changes in token amounts resulting from the swap.
- Extracts the tokens and fee information associated with the swap from the
pathparameter. - Verifies the validity of the callback using the factory.
- Handles exact-input and exact-output swaps separately.
- For an exact-input swap, reverts with the amount of tokens received.
- Otherwise, checks that the output amount is correct if a cached value exists, and reverts.
Arguments
amount0Delta- Change in the amount of token 0.
amount1Delta- Change in the amount of token 1.
path- Token path for the swap.
parseRevertReason
parseRevertReason
function parseRevertReason(bytes memory reason) private pure returns (uint256) {
if (reason.length != 32) {
if (reason.length < 68) revert('Unexpected error');
assembly {
reason := add(reason, 0x04)
}
revert(abi.decode(reason, (string)));
}
return abi.decode(reason, (uint256));
}Overview Parses the bytes of a revert message to obtain a numerical value.
Details
- Receives and parses the revert reason (error message).
- If the byte sequence is not 32 bytes long and the error message is shorter than 68 bytes, reverts with an unexpected error.
- Advances the beginning of the error message by 4 bytes, decodes a string from that position, and obtains a numerical value.
Arguments
reason- The revert reason.
Return value
- The parsed numerical value.
quoteExactInputSingle
quoteExactInputSingle
function quoteExactInputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountIn,
uint160 sqrtPriceLimitX96
) public override returns (uint256 amountOut) {
bool zeroForOne = tokenIn < tokenOut;
try
getPool(tokenIn, tokenOut, fee).swap(
address(this),
zeroForOne,
amountIn.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encodePacked(tokenIn, fee, tokenOut)
)
{} catch (bytes memory reason) {
return parseRevertReason(reason);
}
}Overview Estimates the output amount of a Uniswap V3 token swap based on a specified input amount.
Details
- Receives the input token, output token, fee, input amount, and price limit information.
- Sets
zeroForOneto true if the input token address is smaller than the output token address. - Attempts the token swap and obtains the output amount if successful.
- If the attempt reverts, extracts the numerical value from the revert reason and returns it.
Arguments
tokenIn- Address of the input token.
tokenOut- Address of the output token.
fee- Fee.
amountIn- Input amount.
sqrtPriceLimitX96- Price limit information.
Return value
- Amount of output tokens.
quoteExactInput
quoteExactInput
function quoteExactInput(bytes memory path, uint256 amountIn) external override returns (uint256 amountOut) {
while (true) {
bool hasMultiplePools = path.hasMultiplePools();
(address tokenIn, address tokenOut,
uint24 fee) = path.decodeFirstPool();
amountIn = quoteExactInputSingle(tokenIn, tokenOut, fee, amountIn, 0);
if (hasMultiplePools) {
path = path.skipToken();
} else {
return amountIn;
}
}
}Overview Estimates the final output amount for a specified input amount across a series of token swaps.
Details
- Receives path information and the input amount.
- Checks whether the path contains multiple pools and estimates the output amount of each swap in a loop.
- Advances to the next token if the path contains multiple pools.
- Otherwise, returns the final output amount.
Arguments
path- Token path.
amountIn- Input amount.
Return value
- Final output amount.
quoteExactOutputSingle
quoteExactOutputSingle
function quoteExactOutputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountOut,
uint160 sqrtPriceLimitX96
) public override returns (uint256 amountIn) {
bool zeroForOne = tokenIn < tokenOut;
if (sqrtPriceLimitX96 == 0) amountOutCached = amountOut;
try
getPool(tokenIn, tokenOut, fee).swap(
address(this),
zeroForOne,
-amountOut.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encodePacked(tokenOut, fee, tokenIn)
)
{} catch (bytes memory reason) {
if (sqrtPriceLimitX96 == 0) delete amountOutCached;
return parseRevertReason(reason);
}
}Overview Estimates the input amount for a reverse-direction token swap in Uniswap V3 based on a specified output amount.
Details
- Receives the input token, output token, fee, output amount, and price limit information.
- Caches the output amount if the price limit is
0. - Attempts the token swap and obtains the input amount if successful.
- If the attempt reverts, extracts the numerical value from the revert reason and returns it.
Arguments
tokenIn- Address of the input token.
tokenOut- Address of the output token.
fee- Fee.
amountOut- Output amount.
sqrtPriceLimitX96- Price limit information.
Return value
- Amount of input tokens.
quoteExactOutput
quoteExactOutput
function quoteExactOutput(bytes memory path, uint256 amountOut) external override returns (uint256 amountIn) {
while (true) {
bool hasMultiplePools = path.hasMultiplePools();
(address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();
amountOut = quoteExactOutputSingle(tokenIn, tokenOut, fee, amountOut, 0);
if (hasMultiplePools) {
path = path.skipToken();
} else {
return amountOut;
}
}
}Overview Estimates the maximum input amount for a specified output amount. Works backward through a series of token swaps, calculating the input amount from the output amount.
Details
- Uses the given path and output amount to estimate the input amount through a sequence of reverse token swaps.
- Extracts the output token, input token, and fee for each swap.
- The output of the previous swap becomes the input of the subsequent swap; the swaps are processed in reverse to calculate the input amount.
- Checks whether the path contains multiple pools and repeats the loop as many times as necessary.
- Returns the final input amount after all swaps have been processed.
Arguments
path- Token path (byte sequence).
amountOut- Output amount.
Return value
- Maximum input amount.
Path
ADDR_SIZE
ADDR_SIZE
uint256 private constant ADDR_SIZE = 20;Overview A constant representing the length of a byte-encoded address.
Details Indicates the length used when encoding an address as bytes in Solidity code. An address normally has a fixed length of 20 bytes; this constant makes that length convenient to use in code.
FEE_SIZE
FEE_SIZE
uint256 private constant FEE_SIZE = 3;Overview A constant representing the length of a byte-encoded fee.
Details Indicates the length used when encoding a fee as bytes. A fee occupies 3 bytes. Fees normally have a fixed length, which this constant makes available for use in code.
NEXT_OFFSET
NEXT_OFFSET
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;Overview A constant representing the offset for a single token address and pool fee.
Details Used to locate the next token address and pool fee in a data structure that encodes addresses and fees. It is the sum of the address length and the fee length.
POP_OFFSET
POP_OFFSET
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;Overview A constant representing the offset of an encoded pool key.
Details Used to locate a pool key in an encoded data structure. It represents a value added to the combined length of the previous address and fee, and the next token address and pool fee.
MULTIPLE_POOLS_MIN_LENGTH
MULTIPLE_POOLS_MIN_LENGTH
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;Overview A constant representing the minimum encoded length for two or more pools.
Details Indicates the minimum encoded length of a data structure containing two or more pools. It specifies the minimum length required when pool keys, token addresses, and pool fees occur multiple times.
hasMultiplePools
hasMultiplePools
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}Overview Determines whether the specified swap path contains two or more pools.
Details
- If the length of the encoded swap path is at least the minimum length of a multi-pool encoding, the path is considered to contain two or more pools.
Arguments
path- Encoded swap path.
Return value
Returns true if the path contains two or more pools, otherwise false.
decodeFirstPool
decodeFirstPool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}Overview Decodes the first pool's information from an encoded swap path.
Details
- Decodes the first token address, the pool fee tier, and the second token address from the encoded swap path in that order.
Arguments
path- Encoded swap path.
Return value
tokenA- Address of the first token in the pool.
tokenB- Address of the second token in the pool.
fee- The pool's fee tier.
getFirstPool
getFirstPool
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}Overview Obtains the segment corresponding to the first pool in an encoded swap path.
Details
- Extracts a segment containing the data for the first pool in the encoded swap path.
Arguments
path- Encoded swap path.
Return value
- The segment containing the data for the first pool in the path.
skipToken
skipToken
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}Overview Skips the token and fee elements in an encoded swap path and returns the remainder of the path.
Details
- Skips the token and fee elements in the encoded swap path, returning the remaining path.
Arguments
path- Swap path.
Return value
- A byte sequence containing the remaining token and fee elements in the path.
PoolAddress
See the following reference.
CallbackValidation
See the following reference.
BytesLib
slice
slice
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
tempBytes := mload(0x40)
let lengthmod := and(_length, 31)
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
mstore(0x40, and(add(mc, 31), not(31)))
}
default {
tempBytes := mload(0x40)
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}Overview Extracts a subset of a byte sequence at a specified position and length.
Details
- Receives the byte sequence to slice, the starting position, and the length.
- Checks for overflow and ensures the requested slice is within the bounds of the byte sequence.
- Creates a new byte sequence (
tempBytes) and performs the slice using assembly code. - Because the first word of the byte sequence may contain part of the sliced data, writes the final byte sequence length into the first word.
Arguments
_bytes- Byte sequence to slice.
_start- Starting position.
_length- Length of the slice.
Return value
- The extracted byte sequence.
toAddress
toAddress
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, 'toAddress_overflow');
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}Overview Decodes an address from a byte sequence at a specified position.
Details
- Receives a byte sequence and a starting position, and decodes
20bytes of data from the specified position into an address. - Stores the decoded address in a temporary variable (
tempAddress) and performs the decoding using assembly code.
Arguments
_bytes- Byte sequence.
_start- Starting position.
Return value
- Decoded address.
toUint24
toUint24
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}Overview
Decodes a 24-bit integer from a byte sequence at a specified position.
Details
- Receives a byte sequence and a starting position, and decodes
3bytes of data from the specified position into a24-bit integer. - Stores the decoded integer in a temporary variable (
tempUint) and performs the decoding using assembly code.
Arguments
_bytes- Byte sequence.
_start- Starting position.
Return value
- Decoded
24-bit integer.
Code
Quoter
Quoter.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/libraries/SafeCast.sol';
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
import '../interfaces/IQuoter.sol';
import '../base/PeripheryImmutableState.sol';
import '../libraries/Path.sol';
import '../libraries/PoolAddress.sol';
import '../libraries/CallbackValidation.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 Quoter is IQuoter, IUniswapV3SwapCallback, PeripheryImmutableState {
using Path for bytes;
using SafeCast for uint256;
/// @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));
if (isExactInput) {
assembly {
let ptr := mload(0x40)
mstore(ptr, amountReceived)
revert(ptr, 32)
}
} 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)
revert(ptr, 32)
}
}
}
/// @dev Parses a revert reason that should contain the numeric quote
function parseRevertReason(bytes memory reason) private pure returns (uint256) {
if (reason.length != 32) {
if (reason.length < 68) revert('Unexpected error');
assembly {
reason := add(reason, 0x04)
}
revert(abi.decode(reason, (string)));
}
return abi.decode(reason, (uint256));
}
/// @inheritdoc IQuoter
function quoteExactInputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountIn,
uint160 sqrtPriceLimitX96
) public override returns (uint256 amountOut) {
bool zeroForOne = tokenIn < tokenOut;
try
getPool(tokenIn, tokenOut, fee).swap(
address(this), // address(0) might cause issues with some tokens
zeroForOne,
amountIn.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encodePacked(tokenIn, fee, tokenOut)
)
{} catch (bytes memory reason) {
return parseRevertReason(reason);
}
}
/// @inheritdoc IQuoter
function quoteExactInput(bytes memory path, uint256 amountIn) external override returns (uint256 amountOut) {
while (true) {
bool hasMultiplePools = path.hasMultiplePools();
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
// the outputs of prior swaps become the inputs to subsequent ones
amountIn = quoteExactInputSingle(tokenIn, tokenOut, fee, amountIn, 0);
// decide whether to continue or terminate
if (hasMultiplePools) {
path = path.skipToken();
} else {
return amountIn;
}
}
}
/// @inheritdoc IQuoter
function quoteExactOutputSingle(
address tokenIn,
address tokenOut,
uint24 fee,
uint256 amountOut,
uint160 sqrtPriceLimitX96
) public override returns (uint256 amountIn) {
bool zeroForOne = tokenIn < tokenOut;
// if no price limit has been specified, cache the output amount for comparison in the swap callback
if (sqrtPriceLimitX96 == 0) amountOutCached = amountOut;
try
getPool(tokenIn, tokenOut, fee).swap(
address(this), // address(0) might cause issues with some tokens
zeroForOne,
-amountOut.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encodePacked(tokenOut, fee, tokenIn)
)
{} catch (bytes memory reason) {
if (sqrtPriceLimitX96 == 0) delete amountOutCached; // clear cache
return parseRevertReason(reason);
}
}
/// @inheritdoc IQuoter
function quoteExactOutput(bytes memory path, uint256 amountOut) external override returns (uint256 amountIn) {
while (true) {
bool hasMultiplePools = path.hasMultiplePools();
(address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool();
// the inputs of prior swaps become the outputs of subsequent ones
amountOut = quoteExactOutputSingle(tokenIn, tokenOut, fee, amountOut, 0);
// decide whether to continue or terminate
if (hasMultiplePools) {
path = path.skipToken();
} else {
return amountOut;
}
}
}
}PeripheryImmutableState
PeripheryImmutableState.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import '../interfaces/IPeripheryImmutableState.sol';
/// @title Immutable state
/// @notice Immutable state used by periphery contracts
abstract contract PeripheryImmutableState is IPeripheryImmutableState {
/// @inheritdoc IPeripheryImmutableState
address public immutable override factory;
/// @inheritdoc IPeripheryImmutableState
address public immutable override WETH9;
constructor(address _factory, address _WETH9) {
factory = _factory;
WETH9 = _WETH9;
}
}Path
Path
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import './BytesLib.sol';
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}PoolAddress
PoolAddress
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}CallbackValidation
CallbackValidation
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import './PoolAddress.sol';
/// @notice Provides validation for callbacks from Uniswap V3 Pools
library CallbackValidation {
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The V3 pool contract address
function verifyCallback(
address factory,
address tokenA,
address tokenB,
uint24 fee
) internal view returns (IUniswapV3Pool pool) {
return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee));
}
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param poolKey The identifying key of the V3 pool
/// @return pool The V3 pool contract address
function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey)
internal
view
returns (IUniswapV3Pool pool)
{
pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey));
require(msg.sender == address(pool));
}
}BytesLib
BytesLib
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <goncalo.sa@consensys.net>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.5.0 <0.8.0;
library BytesLib {
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, 'toAddress_overflow');
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}Conclusion
This article examined Uniswap V3's Quoter contract using Bunzz's DeCipher feature. I plan to continue examining specific NFTs and contracts in future articles.






