Introduction
Hi, I'm cardene, a software engineer and technical writer focused on blockchain and AI.
I've also authored Japanese technical books on specification-driven development with LLMs and decentralized application (DApp) development.
I also build and publish a variety of tools, libraries, and open-source projects.
In this article, I explore the UniswapV3Factory contract of Uniswap V3 using Bunzz's DeCipher feature.
DeCipher is a service that automatically generates smart contract documentation using AI.
For a detailed guide to using the service, see the following article.
This article reflects my personal experience with DeCipher. If you notice any inaccuracies, please let me know in the comments.
The following is the DeCipher link used in this article.
The corresponding Etherscan link is below.
Overview
The UniswapV3Factory contract is a core component of the Uniswap V3 protocol. It provides a platform for creating liquidity pools and participating in them.
Its main purpose is to enable users to trade different tokens and provide liquidity (funds). For example, users who want to trade token A and token B can create a liquidity pool for those tokens through this contract and participate in trading.
The main responsibilities of UniswapV3Factory are described below.
Pool deployment
When creating a new liquidity pool, the contract deploys the pool with the necessary configuration and parameters. These include the trading fee and token pair.
Pool management
Manages configuration and information about existing pools. It provides access to pool information and functions for authorized fee-related configuration changes.
Pool interaction
The deployed pools allow users to trade, provide liquidity, and withdraw liquidity. Users can thereby trade and supply liquidity.
Security
Security measures help protect users' funds and prevent unauthorized operations. Access controls restrict privileged configuration changes to authorized accounts. The related pool implementation also considers the security of mathematical calculations.
Mathematical security plays an important role in the UniswapV3Factory deployment and pool implementation. In particular, calculations related to prices and token swaps must be accurate and secure.
The following are some mathematical security considerations for the factory and associated pool contracts.
Handling floating-point numbers Floating-point arithmetic can introduce rounding errors and precision problems. The contracts use techniques such as fixed-point and integer arithmetic to ensure accurate and safe calculations.
Preventing overflow and underflow Overflow and underflow may occur when calculating with large numbers. Checks help keep calculations within the appropriate numeric ranges.
Using safe mathematical libraries Contracts commonly use safe mathematical libraries and functions. This helps minimize vulnerabilities and errors and makes calculation results accurate and reliable.
Testing and verification Mathematical code is extensively tested and verified. Unit tests and practical execution tests help establish accurate and predictable behavior.
External audits External specialists may audit the security of protocols and contracts. Audits help identify security concerns so that they can be addressed.
The mathematical calculations in Uniswap V3 are carefully designed, tested, and verified for accuracy and security.
Usage
Overview
The UniswapV3Factory smart contract creates and manages Uniswap V3 pools. It enables operations such as creating new pools and retrieving information about existing pools.
Contract objective
The UniswapV3Factory contract aims to provide a decentralized platform for creating and managing Uniswap V3 pools. Users choose parameters such as token pairs and fee tiers to create pools, then use the relevant functions to interact with them.
Steps
The following steps describe how to create and manage a Uniswap V3 pool.
- Deploy the UniswapV3Factory contract.
- Call
createPoolto create a new pool using the specified parameters. - Use the factory's lookup functions and the deployed pool's functions to interact with the pool.
In this way, users can create and manage pools with UniswapV3Factory and use the Uniswap V3 protocol.
How to use it
Creating a new pool
Follow these steps to create a pool.
- Deploy the UniswapV3Factory contract.
- Call
createPoolwith the following parameters.
tokenA- Address of the first token in the pair.
tokenB- Address of the second token in the pair.
fee- Pool fee tier.
sqrtPriceX96- Initial square-root price of the token pair (set separately during pool initialization, rather than passed to the factory).
createPooldeploys a new UniswapV3Pool contract and returns its address.
- Initial square-root price of the token pair (set separately during pool initialization, rather than passed to the factory).
Retrieving pool information
The following functions are described for retrieving information about existing pools.
getPool- Returns the UniswapV3Pool contract address for a specific token pair and fee tier.
allPools- Described in the original overview as returning an array of all deployed pool addresses; this getter is not part of the factory implementation shown below.
Interacting with pools
Once a pool has been created, users can interact with it using functions provided by UniswapV3Pool. The principal functions include the following.
swap- Swaps tokens in the pool.
mint- Adds liquidity to the pool.
burn- Removes liquidity from the pool.
collect- Collects fees from the pool.
Users can create new pools with UniswapV3Factory, retrieve existing pool information, and interact with the pools.
Related EIPs and ERCs
The UniswapV3Factory contract is associated with the following EIPs and ERCs.
- ERC-173: Ownership Standard
- ERC-721: Non-Fungible Token Standard
- ERC-1155: Multi-Token Standard
- ERC-20: Token Standard
- ERC-721: Non-Fungible Token Standard
For details about UniswapV3Factory and related contracts and libraries, refer to their source files and documentation.
Parameters
None.
Contract
UniswapV3Factory
UniswapV3Factory
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
import './interfaces/IUniswapV3Factory.sol';
import './UniswapV3PoolDeployer.sol';
import './NoDelegateCall.sol';
import './UniswapV3Pool.sol';
/// @title Canonical Uniswap V3 factory
/// @notice Deploys Uniswap V3 pools and manages ownership and control over pool protocol fees
contract UniswapV3Factory is IUniswapV3Factory, UniswapV3PoolDeployer, NoDelegateCall {
/// @inheritdoc IUniswapV3Factory
address public override owner;
/// @inheritdoc IUniswapV3Factory
mapping(uint24 => int24) public override feeAmountTickSpacing;
/// @inheritdoc IUniswapV3Factory
mapping(address => mapping(address => mapping(uint24 => address))) public override getPool;
constructor() {
owner = msg.sender;
emit OwnerChanged(address(0), msg.sender);
feeAmountTickSpacing[500] = 10;
emit FeeAmountEnabled(500, 10);
feeAmountTickSpacing[3000] = 60;
emit FeeAmountEnabled(3000, 60);
feeAmountTickSpacing[10000] = 200;
emit FeeAmountEnabled(10000, 200);
}
/// @inheritdoc IUniswapV3Factory
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external override noDelegateCall returns (address pool) {
require(tokenA != tokenB);
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0));
int24 tickSpacing = feeAmountTickSpacing[fee];
require(tickSpacing != 0);
require(getPool[token0][token1][fee] == address(0));
pool = deploy(address(this), token0, token1, fee, tickSpacing);
getPool[token0][token1][fee] = pool;
// populate mapping in the reverse direction, deliberate choice to avoid the cost of comparing addresses
getPool[token1][token0][fee] = pool;
emit PoolCreated(token0, token1, fee, tickSpacing, pool);
}
/// @inheritdoc IUniswapV3Factory
function setOwner(address _owner) external override {
require(msg.sender == owner);
emit OwnerChanged(owner, _owner);
owner = _owner;
}
/// @inheritdoc IUniswapV3Factory
function enableFeeAmount(uint24 fee, int24 tickSpacing) public override {
require(msg.sender == owner);
require(fee < 1000000);
// tick spacing is capped at 16384 to prevent the situation where tickSpacing is so large that
// TickBitmap#nextInitializedTickWithinOneWord overflows int24 container from a valid tick
// 16384 ticks represents a >5x price change with ticks of 1 bips
require(tickSpacing > 0 && tickSpacing < 16384);
require(feeAmountTickSpacing[fee] == 0);
feeAmountTickSpacing[fee] = tickSpacing;
emit FeeAmountEnabled(fee, tickSpacing);
}
}owner
Overview A variable storing the UniswapV3Factory contract's owner address.
Details The owner has authority over privileged configuration changes, such as enabling new fee tiers.
feeAmountTickSpacing
Overview A mapping storing tick spacing for each fee tier.
Details This mapping stores the tick spacing configured for each fee tier. Tick spacing determines the permitted intervals for initialized ticks and thus the granularity of liquidity position boundaries.
Parameters
fee- Fee tier (fee rate).
Return value
int24- Tick spacing for the specified fee tier.
getPool
Overview A three-level mapping storing UniswapV3Pool contract addresses by token pair and fee tier.
Details This mapping stores the corresponding UniswapV3Pool address for a specific token pair and fee tier. It provides a convenient way to retrieve the pool address for a given token combination and fee tier.
Parameters
tokenA- Address of the first token in the pair.
tokenB- Address of the second token in the pair.
fee- Fee tier.
Return value
address- UniswapV3Pool address for the specified token pair and fee tier.
createPool
Overview Creates a new pool.
Parameters
tokenA- Address of the first token in the pair.
tokenB- Address of the second token in the pair.
fee- Fee tier.
Return value
address- Address of the created Uniswap V3 pool.
setOwner
Overview Sets the owner address.
Details Sets the contract owner. The owner has authority to perform specific operations. Only the current owner can change the owner.
Parameters
_owner- New owner address.
Return value None.
enableFeeAmount
Overview Sets tick spacing for a fee tier.
Details Enables a fee tier with a specified tick spacing. Only the owner may call this function. The spacing determines the permissible tick intervals for liquidity positions.
Parameters
fee- Fee tier.
tickSpacing- Tick spacing.
Return value None.
UniswapV3PoolDeployer
UniswapV3PoolDeployer
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
import './interfaces/IUniswapV3PoolDeployer.sol';
import './UniswapV3Pool.sol';
contract UniswapV3PoolDeployer is IUniswapV3PoolDeployer {
struct Parameters {
address factory;
address token0;
address token1;
uint24 fee;
int24 tickSpacing;
}
/// @inheritdoc IUniswapV3PoolDeployer
Parameters public override parameters;
/// @dev Deploys a pool with the given parameters by transiently setting the parameters storage slot and then
/// clearing it after deploying the pool.
/// @param factory The contract address of the Uniswap V3 factory
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The spacing between usable ticks
function deploy(
address factory,
address token0,
address token1,
uint24 fee,
int24 tickSpacing
) internal returns (address pool) {
parameters = Parameters({factory: factory, token0: token0, token1: token1, fee: fee, tickSpacing: tickSpacing});
pool = address(new UniswapV3Pool{salt: keccak256(abi.encode(token0, token1, fee))}());
delete parameters;
}
}Parameters
Overview A struct storing pool deployment parameters.
Parameters
factory- Uniswap V3 factory contract address.
token0- Address of the first token in the pair.
token1- Address of the second token in the pair.
fee- Fee tier.
tickSpacing- Tick spacing.
Return value None.
parameters
Overview A variable storing pool deployment parameters.
Details
It stores an instance of the Parameters struct containing information needed to deploy a pool.
Return value
Parameters- Struct instance containing pool deployment parameters.
deploy
Overview Deploys a pool.
Details Deploys a Uniswap V3 pool using the specified parameters. During deployment, it temporarily stores the parameters in storage and deletes them after deploying the pool.
Parameters
factory- Uniswap V3 factory contract address.
token0- Address of the first token in the pair.
token1- Address of the second token in the pair.
fee- Fee tier.
tickSpacing- Tick spacing.
Return value
address- Address of the deployed Uniswap V3 pool.
NoDelegateCall
Overview
A contract preventing inherited methods from being invoked through delegatecall.
Details
This abstract contract provides a modifier preventing protected methods from being called through delegatecall.
delegatecall executes another contract's code in the caller's context. This base contract helps prevent unintended execution in that context.
NoDelegateCall
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
/// @title Prevents delegatecall to a contract
/// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract
abstract contract NoDelegateCall {
/// @dev The original address of this contract
address private immutable original;
constructor() {
// Immutables are computed in the init code of the contract, and then inlined into the deployed bytecode.
// In other words, this variable won't change when it's checked at runtime.
original = address(this);
}
/// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method,
/// and the use of immutable means the address bytes are copied in every place the modifier is used.
function checkNotDelegateCall() private view {
require(address(this) == original);
}
/// @notice Prevents delegatecall into the modified method
modifier noDelegateCall() {
checkNotDelegateCall();
_;
}
}original
Overview A variable storing the contract's original address.
Details
It stores the original address at contract deployment.
It is immutable and cannot be modified after deployment.
Comparing it with the current execution address prevents execution through delegatecall.
Return value
address- Original address of this contract.
checkNotDelegateCall
Overview
A private function checking that execution is not through delegatecall.
Details
Checks that a delegate call is not being performed.
If the function is reached through a delegate call, its require statement causes execution to revert.
This prevents unintended execution in another contract's context.
Return value None.
noDelegateCall
Overview
A modifier preventing protected methods from being invoked through delegatecall.
Details Checks that the modified method was not invoked through a delegate call. Preventing delegate calls avoids unintended interactions between contract execution contexts.
UniswapV3Pool
UniswapV3Pool
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
import './interfaces/IUniswapV3Pool.sol';
import './NoDelegateCall.sol';
import './libraries/LowGasSafeMath.sol';
import './libraries/SafeCast.sol';
import './libraries/Tick.sol';
import './libraries/TickBitmap.sol';
import './libraries/Position.sol';
import './libraries/Oracle.sol';
import './libraries/FullMath.sol';
import './libraries/FixedPoint128.sol';
import './libraries/TransferHelper.sol';
import './libraries/TickMath.sol';
import './libraries/LiquidityMath.sol';
import './libraries/SqrtPriceMath.sol';
import './libraries/SwapMath.sol';
import './interfaces/IUniswapV3PoolDeployer.sol';
import './interfaces/IUniswapV3Factory.sol';
import './interfaces/IERC20Minimal.sol';
import './interfaces/callback/IUniswapV3MintCallback.sol';
import './interfaces/callback/IUniswapV3SwapCallback.sol';
import './interfaces/callback/IUniswapV3FlashCallback.sol';
contract UniswapV3Pool is IUniswapV3Pool, NoDelegateCall {
using LowGasSafeMath for uint256;
using LowGasSafeMath for int256;
using SafeCast for uint256;
using SafeCast for int256;
using Tick for mapping(int24 => Tick.Info);
using TickBitmap for mapping(int16 => uint256);
using Position for mapping(bytes32 => Position.Info);
using Position for Position.Info;
using Oracle for Oracle.Observation[65535];
/// @inheritdoc IUniswapV3PoolImmutables
address public immutable override factory;
/// @inheritdoc IUniswapV3PoolImmutables
address public immutable override token0;
/// @inheritdoc IUniswapV3PoolImmutables
address public immutable override token1;
/// @inheritdoc IUniswapV3PoolImmutables
uint24 public immutable override fee;
/// @inheritdoc IUniswapV3PoolImmutables
int24 public immutable override tickSpacing;
/// @inheritdoc IUniswapV3PoolImmutables
uint128 public immutable override maxLiquidityPerTick;
struct Slot0 {
// the current price
uint160 sqrtPriceX96;
// the current tick
int24 tick;
// the most-recently updated index of the observations array
uint16 observationIndex;
// the current maximum number of observations that are being stored
uint16 observationCardinality;
// the next maximum number of observations to store, triggered in observations.write
uint16 observationCardinalityNext;
// the current protocol fee as a percentage of the swap fee taken on withdrawal
// represented as an integer denominator (1/x)%
uint8 feeProtocol;
// whether the pool is locked
bool unlocked;
}
/// @inheritdoc IUniswapV3PoolState
Slot0 public override slot0;
/// @inheritdoc IUniswapV3PoolState
uint256 public override feeGrowthGlobal0X128;
/// @inheritdoc IUniswapV3PoolState
uint256 public override feeGrowthGlobal1X128;
// accumulated protocol fees in token0/token1 units
struct ProtocolFees {
uint128 token0;
uint128 token1;
}
/// @inheritdoc IUniswapV3PoolState
ProtocolFees public override protocolFees;
/// @inheritdoc IUniswapV3PoolState
uint128 public override liquidity;
/// @inheritdoc IUniswapV3PoolState
mapping(int24 => Tick.Info) public override ticks;
/// @inheritdoc IUniswapV3PoolState
mapping(int16 => uint256) public override tickBitmap;
/// @inheritdoc IUniswapV3PoolState
mapping(bytes32 => Position.Info) public override positions;
/// @inheritdoc IUniswapV3PoolState
Oracle.Observation[65535] public override observations;
/// @dev Mutually exclusive reentrancy protection into the pool to/from a method. This method also prevents entrance
/// to a function before the pool is initialized. The reentrancy guard is required throughout the contract because
/// we use balance checks to determine the payment status of interactions such as mint, swap and flash.
modifier lock() {
require(slot0.unlocked, 'LOK');
slot0.unlocked = false;
_;
slot0.unlocked = true;
}
/// @dev Prevents calling a function from anyone except the address returned by IUniswapV3Factory#owner()
modifier onlyFactoryOwner() {
require(msg.sender == IUniswapV3Factory(factory).owner());
_;
}
constructor() {
int24 _tickSpacing;
(factory, token0, token1, fee, _tickSpacing) = IUniswapV3PoolDeployer(msg.sender).parameters();
tickSpacing = _tickSpacing;
maxLiquidityPerTick = Tick.tickSpacingToMaxLiquidityPerTick(_tickSpacing);
}
/// @dev Common checks for valid tick inputs.
function checkTicks(int24 tickLower, int24 tickUpper) private pure {
require(tickLower < tickUpper, 'TLU');
require(tickLower >= TickMath.MIN_TICK, 'TLM');
require(tickUpper <= TickMath.MAX_TICK, 'TUM');
}
/// @dev Returns the block timestamp truncated to 32 bits, i.e. mod 2**32. This method is overridden in tests.
function _blockTimestamp() internal view virtual returns (uint32) {
return uint32(block.timestamp); // truncation is desired
}
/// @dev Get the pool's balance of token0
/// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize
/// check
function balance0() private view returns (uint256) {
(bool success, bytes memory data) =
token0.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));
require(success && data.length >= 32);
return abi.decode(data, (uint256));
}
/// @dev Get the pool's balance of token1
/// @dev This function is gas optimized to avoid a redundant extcodesize check in addition to the returndatasize
/// check
function balance1() private view returns (uint256) {
(bool success, bytes memory data) =
token1.staticcall(abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, address(this)));
require(success && data.length >= 32);
return abi.decode(data, (uint256));
}
/// @inheritdoc IUniswapV3PoolDerivedState
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
override
noDelegateCall
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
)
{
checkTicks(tickLower, tickUpper);
int56 tickCumulativeLower;
int56 tickCumulativeUpper;
uint160 secondsPerLiquidityOutsideLowerX128;
uint160 secondsPerLiquidityOutsideUpperX128;
uint32 secondsOutsideLower;
uint32 secondsOutsideUpper;
{
Tick.Info storage lower = ticks[tickLower];
Tick.Info storage upper = ticks[tickUpper];
bool initializedLower;
(tickCumulativeLower, secondsPerLiquidityOutsideLowerX128, secondsOutsideLower, initializedLower) = (
lower.tickCumulativeOutside,
lower.secondsPerLiquidityOutsideX128,
lower.secondsOutside,
lower.initialized
);
require(initializedLower);
bool initializedUpper;
(tickCumulativeUpper, secondsPerLiquidityOutsideUpperX128, secondsOutsideUpper, initializedUpper) = (
upper.tickCumulativeOutside,
upper.secondsPerLiquidityOutsideX128,
upper.secondsOutside,
upper.initialized
);
require(initializedUpper);
}
Slot0 memory _slot0 = slot0;
if (_slot0.tick < tickLower) {
return (
tickCumulativeLower - tickCumulativeUpper,
secondsPerLiquidityOutsideLowerX128 - secondsPerLiquidityOutsideUpperX128,
secondsOutsideLower - secondsOutsideUpper
);
} else if (_slot0.tick < tickUpper) {
uint32 time = _blockTimestamp();
(int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =
observations.observeSingle(
time,
0,
_slot0.tick,
_slot0.observationIndex,
liquidity,
_slot0.observationCardinality
);
return (
tickCumulative - tickCumulativeLower - tickCumulativeUpper,
secondsPerLiquidityCumulativeX128 -
secondsPerLiquidityOutsideLowerX128 -
secondsPerLiquidityOutsideUpperX128,
time - secondsOutsideLower - secondsOutsideUpper
);
} else {
return (
tickCumulativeUpper - tickCumulativeLower,
secondsPerLiquidityOutsideUpperX128 - secondsPerLiquidityOutsideLowerX128,
secondsOutsideUpper - secondsOutsideLower
);
}
}
/// @inheritdoc IUniswapV3PoolDerivedState
function observe(uint32[] calldata secondsAgos)
external
view
override
noDelegateCall
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s)
{
return
observations.observe(
_blockTimestamp(),
secondsAgos,
slot0.tick,
slot0.observationIndex,
liquidity,
slot0.observationCardinality
);
}
/// @inheritdoc IUniswapV3PoolActions
function increaseObservationCardinalityNext(uint16 observationCardinalityNext)
external
override
lock
noDelegateCall
{
uint16 observationCardinalityNextOld = slot0.observationCardinalityNext; // for the event
uint16 observationCardinalityNextNew =
observations.grow(observationCardinalityNextOld, observationCardinalityNext);
slot0.observationCardinalityNext = observationCardinalityNextNew;
if (observationCardinalityNextOld != observationCardinalityNextNew)
emit IncreaseObservationCardinalityNext(observationCardinalityNextOld, observationCardinalityNextNew);
}
/// @inheritdoc IUniswapV3PoolActions
/// @dev not locked because it initializes unlocked
function initialize(uint160 sqrtPriceX96) external override {
require(slot0.sqrtPriceX96 == 0, 'AI');
int24 tick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
(uint16 cardinality, uint16 cardinalityNext) = observations.initialize(_blockTimestamp());
slot0 = Slot0({
sqrtPriceX96: sqrtPriceX96,
tick: tick,
observationIndex: 0,
observationCardinality: cardinality,
observationCardinalityNext: cardinalityNext,
feeProtocol: 0,
unlocked: true
});
emit Initialize(sqrtPriceX96, tick);
}
struct ModifyPositionParams {
// the address that owns the position
address owner;
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// any change in liquidity
int128 liquidityDelta;
}
/// @dev Effect some changes to a position
/// @param params the position details and the change to the position's liquidity to effect
/// @return position a storage pointer referencing the position with the given owner and tick range
/// @return amount0 the amount of token0 owed to the pool, negative if the pool should pay the recipient
/// @return amount1 the amount of token1 owed to the pool, negative if the pool should pay the recipient
function _modifyPosition(ModifyPositionParams memory params)
private
noDelegateCall
returns (
Position.Info storage position,
int256 amount0,
int256 amount1
)
{
checkTicks(params.tickLower, params.tickUpper);
Slot0 memory _slot0 = slot0; // SLOAD for gas optimization
position = _updatePosition(
params.owner,
params.tickLower,
params.tickUpper,
params.liquidityDelta,
_slot0.tick
);
if (params.liquidityDelta != 0) {
if (_slot0.tick < params.tickLower) {
// current tick is below the passed range; liquidity can only become in range by crossing from left to
// right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it
amount0 = SqrtPriceMath.getAmount0Delta(
TickMath.getSqrtRatioAtTick(params.tickLower),
TickMath.getSqrtRatioAtTick(params.tickUpper),
params.liquidityDelta
);
} else if (_slot0.tick < params.tickUpper) {
// current tick is inside the passed range
uint128 liquidityBefore = liquidity; // SLOAD for gas optimization
// write an oracle entry
(slot0.observationIndex, slot0.observationCardinality) = observations.write(
_slot0.observationIndex,
_blockTimestamp(),
_slot0.tick,
liquidityBefore,
_slot0.observationCardinality,
_slot0.observationCardinalityNext
);
amount0 = SqrtPriceMath.getAmount0Delta(
_slot0.sqrtPriceX96,
TickMath.getSqrtRatioAtTick(params.tickUpper),
params.liquidityDelta
);
amount1 = SqrtPriceMath.getAmount1Delta(
TickMath.getSqrtRatioAtTick(params.tickLower),
_slot0.sqrtPriceX96,
params.liquidityDelta
);
liquidity = LiquidityMath.addDelta(liquidityBefore, params.liquidityDelta);
} else {
// current tick is above the passed range; liquidity can only become in range by crossing from right to
// left, when we'll need _more_ token1 (it's becoming more valuable) so user must provide it
amount1 = SqrtPriceMath.getAmount1Delta(
TickMath.getSqrtRatioAtTick(params.tickLower),
TickMath.getSqrtRatioAtTick(params.tickUpper),
params.liquidityDelta
);
}
}
}
/// @dev Gets and updates a position with the given liquidity delta
/// @param owner the owner of the position
/// @param tickLower the lower tick of the position's tick range
/// @param tickUpper the upper tick of the position's tick range
/// @param tick the current tick, passed to avoid sloads
function _updatePosition(
address owner,
int24 tickLower,
int24 tickUpper,
int128 liquidityDelta,
int24 tick
) private returns (Position.Info storage position) {
position = positions.get(owner, tickLower, tickUpper);
uint256 _feeGrowthGlobal0X128 = feeGrowthGlobal0X128; // SLOAD for gas optimization
uint256 _feeGrowthGlobal1X128 = feeGrowthGlobal1X128; // SLOAD for gas optimization
// if we need to update the ticks, do it
bool flippedLower;
bool flippedUpper;
if (liquidityDelta != 0) {
uint32 time = _blockTimestamp();
(int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128) =
observations.observeSingle(
time,
0,
slot0.tick,
slot0.observationIndex,
liquidity,
slot0.observationCardinality
);
flippedLower = ticks.update(
tickLower,
tick,
liquidityDelta,
_feeGrowthGlobal0X128,
_feeGrowthGlobal1X128,
secondsPerLiquidityCumulativeX128,
tickCumulative,
time,
false,
maxLiquidityPerTick
);
flippedUpper = ticks.update(
tickUpper,
tick,
liquidityDelta,
_feeGrowthGlobal0X128,
_feeGrowthGlobal1X128,
secondsPerLiquidityCumulativeX128,
tickCumulative,
time,
true,
maxLiquidityPerTick
);
if (flippedLower) {
tickBitmap.flipTick(tickLower, tickSpacing);
}
if (flippedUpper) {
tickBitmap.flipTick(tickUpper, tickSpacing);
}
}
(uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) =
ticks.getFeeGrowthInside(tickLower, tickUpper, tick, _feeGrowthGlobal0X128, _feeGrowthGlobal1X128);
position.update(liquidityDelta, feeGrowthInside0X128, feeGrowthInside1X128);
// clear any tick data that is no longer needed
if (liquidityDelta < 0) {
if (flippedLower) {
ticks.clear(tickLower);
}
if (flippedUpper) {
ticks.clear(tickUpper);
}
}
}
/// @inheritdoc IUniswapV3PoolActions
/// @dev noDelegateCall is applied indirectly via _modifyPosition
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external override lock returns (uint256 amount0, uint256 amount1) {
require(amount > 0);
(, int256 amount0Int, int256 amount1Int) =
_modifyPosition(
ModifyPositionParams({
owner: recipient,
tickLower: tickLower,
tickUpper: tickUpper,
liquidityDelta: int256(amount).toInt128()
})
);
amount0 = uint256(amount0Int);
amount1 = uint256(amount1Int);
uint256 balance0Before;
uint256 balance1Before;
if (amount0 > 0) balance0Before = balance0();
if (amount1 > 0) balance1Before = balance1();
IUniswapV3MintCallback(msg.sender).uniswapV3MintCallback(amount0, amount1, data);
if (amount0 > 0) require(balance0Before.add(amount0) <= balance0(), 'M0');
if (amount1 > 0) require(balance1Before.add(amount1) <= balance1(), 'M1');
emit Mint(msg.sender, recipient, tickLower, tickUpper, amount, amount0, amount1);
}
/// @inheritdoc IUniswapV3PoolActions
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external override lock returns (uint128 amount0, uint128 amount1) {
// we don't need to checkTicks here, because invalid positions will never have non-zero tokensOwed{0,1}
Position.Info storage position = positions.get(msg.sender, tickLower, tickUpper);
amount0 = amount0Requested > position.tokensOwed0 ? position.tokensOwed0 : amount0Requested;
amount1 = amount1Requested > position.tokensOwed1 ? position.tokensOwed1 : amount1Requested;
if (amount0 > 0) {
position.tokensOwed0 -= amount0;
TransferHelper.safeTransfer(token0, recipient, amount0);
}
if (amount1 > 0) {
position.tokensOwed1 -= amount1;
TransferHelper.safeTransfer(token1, recipient, amount1);
}
emit Collect(msg.sender, recipient, tickLower, tickUpper, amount0, amount1);
}
/// @inheritdoc IUniswapV3PoolActions
/// @dev noDelegateCall is applied indirectly via _modifyPosition
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external override lock returns (uint256 amount0, uint256 amount1) {
(Position.Info storage position, int256 amount0Int, int256 amount1Int) =
_modifyPosition(
ModifyPositionParams({
owner: msg.sender,
tickLower: tickLower,
tickUpper: tickUpper,
liquidityDelta: -int256(amount).toInt128()
})
);
amount0 = uint256(-amount0Int);
amount1 = uint256(-amount1Int);
if (amount0 > 0 || amount1 > 0) {
(position.tokensOwed0, position.tokensOwed1) = (
position.tokensOwed0 + uint128(amount0),
position.tokensOwed1 + uint128(amount1)
);
}
emit Burn(msg.sender, tickLower, tickUpper, amount, amount0, amount1);
}
struct SwapCache {
// the protocol fee for the input token
uint8 feeProtocol;
// liquidity at the beginning of the swap
uint128 liquidityStart;
// the timestamp of the current block
uint32 blockTimestamp;
// the current value of the tick accumulator, computed only if we cross an initialized tick
int56 tickCumulative;
// the current value of seconds per liquidity accumulator, computed only if we cross an initialized tick
uint160 secondsPerLiquidityCumulativeX128;
// whether we've computed and cached the above two accumulators
bool computedLatestObservation;
}
// the top level state of the swap, the results of which are recorded in storage at the end
struct SwapState {
// the amount remaining to be swapped in/out of the input/output asset
int256 amountSpecifiedRemaining;
// the amount already swapped out/in of the output/input asset
int256 amountCalculated;
// current sqrt(price)
uint160 sqrtPriceX96;
// the tick associated with the current price
int24 tick;
// the global fee growth of the input token
uint256 feeGrowthGlobalX128;
// amount of input token paid as protocol fee
uint128 protocolFee;
// the current liquidity in range
uint128 liquidity;
}
struct StepComputations {
// the price at the beginning of the step
uint160 sqrtPriceStartX96;
// the next tick to swap to from the current tick in the swap direction
int24 tickNext;
// whether tickNext is initialized or not
bool initialized;
// sqrt(price) for the next tick (1/0)
uint160 sqrtPriceNextX96;
// how much is being swapped in in this step
uint256 amountIn;
// how much is being swapped out
uint256 amountOut;
// how much fee is being paid in
uint256 feeAmount;
}
/// @inheritdoc IUniswapV3PoolActions
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external override noDelegateCall returns (int256 amount0, int256 amount1) {
require(amountSpecified != 0, 'AS');
Slot0 memory slot0Start = slot0;
require(slot0Start.unlocked, 'LOK');
require(
zeroForOne
? sqrtPriceLimitX96 < slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 > TickMath.MIN_SQRT_RATIO
: sqrtPriceLimitX96 > slot0Start.sqrtPriceX96 && sqrtPriceLimitX96 < TickMath.MAX_SQRT_RATIO,
'SPL'
);
slot0.unlocked = false;
SwapCache memory cache =
SwapCache({
liquidityStart: liquidity,
blockTimestamp: _blockTimestamp(),
feeProtocol: zeroForOne ? (slot0Start.feeProtocol % 16) : (slot0Start.feeProtocol >> 4),
secondsPerLiquidityCumulativeX128: 0,
tickCumulative: 0,
computedLatestObservation: false
});
bool exactInput = amountSpecified > 0;
SwapState memory state =
SwapState({
amountSpecifiedRemaining: amountSpecified,
amountCalculated: 0,
sqrtPriceX96: slot0Start.sqrtPriceX96,
tick: slot0Start.tick,
feeGrowthGlobalX128: zeroForOne ? feeGrowthGlobal0X128 : feeGrowthGlobal1X128,
protocolFee: 0,
liquidity: cache.liquidityStart
});
// continue swapping as long as we haven't used the entire input/output and haven't reached the price limit
while (state.amountSpecifiedRemaining != 0 && state.sqrtPriceX96 != sqrtPriceLimitX96) {
StepComputations memory step;
step.sqrtPriceStartX96 = state.sqrtPriceX96;
(step.tickNext, step.initialized) = tickBitmap.nextInitializedTickWithinOneWord(
state.tick,
tickSpacing,
zeroForOne
);
// ensure that we do not overshoot the min/max tick, as the tick bitmap is not aware of these bounds
if (step.tickNext < TickMath.MIN_TICK) {
step.tickNext = TickMath.MIN_TICK;
} else if (step.tickNext > TickMath.MAX_TICK) {
step.tickNext = TickMath.MAX_TICK;
}
// get the price for the next tick
step.sqrtPriceNextX96 = TickMath.getSqrtRatioAtTick(step.tickNext);
// compute values to swap to the target tick, price limit, or point where input/output amount is exhausted
(state.sqrtPriceX96, step.amountIn, step.amountOut, step.feeAmount) = SwapMath.computeSwapStep(
state.sqrtPriceX96,
(zeroForOne ? step.sqrtPriceNextX96 < sqrtPriceLimitX96 : step.sqrtPriceNextX96 > sqrtPriceLimitX96)
? sqrtPriceLimitX96
: step.sqrtPriceNextX96,
state.liquidity,
state.amountSpecifiedRemaining,
fee
);
if (exactInput) {
state.amountSpecifiedRemaining -= (step.amountIn + step.feeAmount).toInt256();
state.amountCalculated = state.amountCalculated.sub(step.amountOut.toInt256());
} else {
state.amountSpecifiedRemaining += step.amountOut.toInt256();
state.amountCalculated = state.amountCalculated.add((step.amountIn + step.feeAmount).toInt256());
}
// if the protocol fee is on, calculate how much is owed, decrement feeAmount, and increment protocolFee
if (cache.feeProtocol > 0) {
uint256 delta = step.feeAmount / cache.feeProtocol;
step.feeAmount -= delta;
state.protocolFee += uint128(delta);
}
// update global fee tracker
if (state.liquidity > 0)
state.feeGrowthGlobalX128 += FullMath.mulDiv(step.feeAmount, FixedPoint128.Q128, state.liquidity);
// shift tick if we reached the next price
if (state.sqrtPriceX96 == step.sqrtPriceNextX96) {
// if the tick is initialized, run the tick transition
if (step.initialized) {
// check for the placeholder value, which we replace with the actual value the first time the swap
// crosses an initialized tick
if (!cache.computedLatestObservation) {
(cache.tickCumulative, cache.secondsPerLiquidityCumulativeX128) = observations.observeSingle(
cache.blockTimestamp,
0,
slot0Start.tick,
slot0Start.observationIndex,
cache.liquidityStart,
slot0Start.observationCardinality
);
cache.computedLatestObservation = true;
}
int128 liquidityNet =
ticks.cross(
step.tickNext,
(zeroForOne ? state.feeGrowthGlobalX128 : feeGrowthGlobal0X128),
(zeroForOne ? feeGrowthGlobal1X128 : state.feeGrowthGlobalX128),
cache.secondsPerLiquidityCumulativeX128,
cache.tickCumulative,
cache.blockTimestamp
);
// if we're moving leftward, we interpret liquidityNet as the opposite sign
// safe because liquidityNet cannot be type(int128).min
if (zeroForOne) liquidityNet = -liquidityNet;
state.liquidity = LiquidityMath.addDelta(state.liquidity, liquidityNet);
}
state.tick = zeroForOne ? step.tickNext - 1 : step.tickNext;
} else if (state.sqrtPriceX96 != step.sqrtPriceStartX96) {
// recompute unless we're on a lower tick boundary (i.e. already transitioned ticks), and haven't moved
state.tick = TickMath.getTickAtSqrtRatio(state.sqrtPriceX96);
}
}
// update tick and write an oracle entry if the tick change
if (state.tick != slot0Start.tick) {
(uint16 observationIndex, uint16 observationCardinality) =
observations.write(
slot0Start.observationIndex,
cache.blockTimestamp,
slot0Start.tick,
cache.liquidityStart,
slot0Start.observationCardinality,
slot0Start.observationCardinalityNext
);
(slot0.sqrtPriceX96, slot0.tick, slot0.observationIndex, slot0.observationCardinality) = (
state.sqrtPriceX96,
state.tick,
observationIndex,
observationCardinality
);
} else {
// otherwise just update the price
slot0.sqrtPriceX96 = state.sqrtPriceX96;
}
// update liquidity if it changed
if (cache.liquidityStart != state.liquidity) liquidity = state.liquidity;
// update fee growth global and, if necessary, protocol fees
// overflow is acceptable, protocol has to withdraw before it hits type(uint128).max fees
if (zeroForOne) {
feeGrowthGlobal0X128 = state.feeGrowthGlobalX128;
if (state.protocolFee > 0) protocolFees.token0 += state.protocolFee;
} else {
feeGrowthGlobal1X128 = state.feeGrowthGlobalX128;
if (state.protocolFee > 0) protocolFees.token1 += state.protocolFee;
}
(amount0, amount1) = zeroForOne == exactInput
? (amountSpecified - state.amountSpecifiedRemaining, state.amountCalculated)
: (state.amountCalculated, amountSpecified - state.amountSpecifiedRemaining);
// do the transfers and collect payment
if (zeroForOne) {
if (amount1 < 0) TransferHelper.safeTransfer(token1, recipient, uint256(-amount1));
uint256 balance0Before = balance0();
IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);
require(balance0Before.add(uint256(amount0)) <= balance0(), 'IIA');
} else {
if (amount0 < 0) TransferHelper.safeTransfer(token0, recipient, uint256(-amount0));
uint256 balance1Before = balance1();
IUniswapV3SwapCallback(msg.sender).uniswapV3SwapCallback(amount0, amount1, data);
require(balance1Before.add(uint256(amount1)) <= balance1(), 'IIA');
}
emit Swap(msg.sender, recipient, amount0, amount1, state.sqrtPriceX96, state.liquidity, state.tick);
slot0.unlocked = true;
}
/// @inheritdoc IUniswapV3PoolActions
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override lock noDelegateCall {
uint128 _liquidity = liquidity;
require(_liquidity > 0, 'L');
uint256 fee0 = FullMath.mulDivRoundingUp(amount0, fee, 1e6);
uint256 fee1 = FullMath.mulDivRoundingUp(amount1, fee, 1e6);
uint256 balance0Before = balance0();
uint256 balance1Before = balance1();
if (amount0 > 0) TransferHelper.safeTransfer(token0, recipient, amount0);
if (amount1 > 0) TransferHelper.safeTransfer(token1, recipient, amount1);
IUniswapV3FlashCallback(msg.sender).uniswapV3FlashCallback(fee0, fee1, data);
uint256 balance0After = balance0();
uint256 balance1After = balance1();
require(balance0Before.add(fee0) <= balance0After, 'F0');
require(balance1Before.add(fee1) <= balance1After, 'F1');
// sub is safe because we know balanceAfter is gt balanceBefore by at least fee
uint256 paid0 = balance0After - balance0Before;
uint256 paid1 = balance1After - balance1Before;
if (paid0 > 0) {
uint8 feeProtocol0 = slot0.feeProtocol % 16;
uint256 fees0 = feeProtocol0 == 0 ? 0 : paid0 / feeProtocol0;
if (uint128(fees0) > 0) protocolFees.token0 += uint128(fees0);
feeGrowthGlobal0X128 += FullMath.mulDiv(paid0 - fees0, FixedPoint128.Q128, _liquidity);
}
if (paid1 > 0) {
uint8 feeProtocol1 = slot0.feeProtocol >> 4;
uint256 fees1 = feeProtocol1 == 0 ? 0 : paid1 / feeProtocol1;
if (uint128(fees1) > 0) protocolFees.token1 += uint128(fees1);
feeGrowthGlobal1X128 += FullMath.mulDiv(paid1 - fees1, FixedPoint128.Q128, _liquidity);
}
emit Flash(msg.sender, recipient, amount0, amount1, paid0, paid1);
}
/// @inheritdoc IUniswapV3PoolOwnerActions
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external override lock onlyFactoryOwner {
require(
(feeProtocol0 == 0 || (feeProtocol0 >= 4 && feeProtocol0 <= 10)) &&
(feeProtocol1 == 0 || (feeProtocol1 >= 4 && feeProtocol1 <= 10))
);
uint8 feeProtocolOld = slot0.feeProtocol;
slot0.feeProtocol = feeProtocol0 + (feeProtocol1 << 4);
emit SetFeeProtocol(feeProtocolOld % 16, feeProtocolOld >> 4, feeProtocol0, feeProtocol1);
}
/// @inheritdoc IUniswapV3PoolOwnerActions
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external override lock onlyFactoryOwner returns (uint128 amount0, uint128 amount1) {
amount0 = amount0Requested > protocolFees.token0 ? protocolFees.token0 : amount0Requested;
amount1 = amount1Requested > protocolFees.token1 ? protocolFees.token1 : amount1Requested;
if (amount0 > 0) {
if (amount0 == protocolFees.token0) amount0--; // ensure that the slot is not cleared, for gas savings
protocolFees.token0 -= amount0;
TransferHelper.safeTransfer(token0, recipient, amount0);
}
if (amount1 > 0) {
if (amount1 == protocolFees.token1) amount1--; // ensure that the slot is not cleared, for gas savings
protocolFees.token1 -= amount1;
TransferHelper.safeTransfer(token1, recipient, amount1);
}
emit CollectProtocol(msg.sender, recipient, amount0, amount1);
}
}The following sections explain the variables, events, and functions in the pool contract.
factory
Overview A variable storing a contract address.
Details Stores the address of the factory that deployed the UniswapV3Pool contract.
token0
Overview A variable storing the address of token0.
Details Token0 is one token in the trading pair, and this variable stores its address.
token1
Overview A variable storing the address of token1.
Details Token1 is the other token in the trading pair, and this variable stores its address.
fee
Overview A variable storing the swap fee rate.
Details Represents the proportion charged as a fee during swaps.
tickSpacing
Overview A variable storing tick spacing.
Details Ticks represent price levels; tick spacing determines the interval between permissible initialized ticks.
maxLiquidityPerTick
Overview A variable storing the maximum liquidity per tick.
Details Indicates the maximum liquidity permitted at each tick.
slot0
Overview A struct storing slot0 information.
Details Stores pool state such as the current price, tick, and oracle observation information.
Parameters
sqrtPriceX96- Fixed-point representation of the square root of the current price.
tick- Current tick value.
observationIndex- Index of the most recently updated observation.
observationCardinality- Current observation cardinality.
observationCardinalityNext- Target observation cardinality.
feeProtocol- Integer denominator representing the protocol fee share.
unlocked- Boolean indicating whether the pool is unlocked.
feeGrowthGlobal0X128
Overview A variable storing cumulative fee growth for token0.
Details Represents token0 cumulative fee growth in Q128 fixed-point precision.
feeGrowthGlobal1X128
Overview A variable storing cumulative fee growth for token1.
Details Represents token1 cumulative fee growth in Q128 fixed-point precision.
protocolFees
Overview A struct storing protocol fee information.
Details Stores protocol fees for token0 and token1.
Parameters
token0- Accumulated protocol fees in token0.
token1- Accumulated protocol fees in token1.
liquidity
Overview A variable storing current liquidity.
Details Represents current in-range pool liquidity.
ticks
Overview A mapping storing tick information.
Details Stores detailed information for each tick.
tickBitmap
Overview A mapping storing the tick bitmap.
Details Stores bits indicating initialized ticks.
positions
Overview A mapping storing position information.
Details Stores detailed position data.
observations
Overview An array storing observation information.
Details Stores price oracle observations.
lock
Overview A modifier protecting against reentrancy attacks.
Details Checks that the pool is unlocked, locks it before execution, and unlocks it afterward.
onlyFactoryOwner
Overview A modifier restricting calls to the factory owner.
Details Checks that the function is called only by the Uniswap V3 factory owner.
The following sections explain the constructor, variables, events, and functions in the supplied code.
constructor
Overview The contract constructor.
Details
This initialization function runs when the contract is deployed. It obtains _tickSpacing and initializes factory, token0, token1, fee, tickSpacing, and maxLiquidityPerTick.
checkTicks
Overview An internal function checking the validity of ticks.
Details
Validates the supplied tick values.
Checks that tickLower is below tickUpper and that both are within the minimum and maximum tick bounds.
Parameters
tickLower- Lower tick.
tickUpper- Upper tick.
snapshotCumulativesInside
Overview Takes a snapshot of cumulative data within a specified tick range.
Details Takes a snapshot of cumulative tick and time data for the specified tick range.
Parameters
tickLower- Lower tick.
tickUpper- Upper tick.
Return value
tickCumulativeInside- Cumulative tick value inside the range.
secondsPerLiquidityInsideX128- Seconds per unit of liquidity inside the range (Q128 fixed-point precision).
secondsInside- Seconds inside the range.
observe
Overview Retrieves cumulative data for past times.
Details Retrieves cumulative tick values and time data at the specified historical offsets.
Parameters
secondsAgos- Array of historical offsets in seconds.
Return value
tickCumulatives- Array of cumulative tick values for those times.
secondsPerLiquidityCumulativeX128s- Array of cumulative seconds per liquidity values at those times (Q128 fixed-point precision).
increaseObservationCardinalityNext
Overview Increases the target observation cardinality.
Details Increases the next observation cardinality and emits an event if the value changes.
Parameters
observationCardinalityNext- New target observation cardinality.
initialize
Overview Initializes the pool.
Details
- Initializes the pool if it has not already been initialized and sets
slot0.
Parameters
sqrtPriceX96- Initial square-root price in fixed-point format.
ModifyPositionParams
Overview
- A struct storing parameters for modifying a position.
Details
- Stores parameters including position owner address, tick range, and liquidity change.
Parameters
owner: Position owner's addresstickLower: Lower ticktickUpper: Upper tickliquidityDelta: Change in liquidity
_modifyPosition
Overview An internal function modifying a position.
Details
Calculates amount0 and amount1 resulting from the position change and updates position information.
Parameters
params- Struct containing position modification parameters.
Return value
position- Storage pointer to the modified position information.
amount0- Signed token0 amount associated with the position change.
amount1- Signed token1 amount associated with the position change.
_updatePosition
Overview An internal function updating position information.
Details Updates position information and makes the associated tick and liquidity changes.
Parameters
owner- Position owner's address.
tickLower- Lower tick.
tickUpper- Upper tick.
liquidityDelta- Change in liquidity.
tick- Current tick.
Return value
position- Storage pointer to the updated position information.
mint
Overview Increases a position by providing new liquidity.
Details Adds liquidity over the specified tick range and returns the amounts of token0 and token1 required by the pool.
Parameters
recipient- Recipient of the liquidity position.
tickLower- Lower tick.
tickUpper- Upper tick.
amount- Amount of liquidity to provide.
data- Callback data.
Return value
amount0- Amount of token0 required by the pool.
amount1- Amount of token1 required by the pool.
collect
Overview Collects tokens owed to a position.
Details Collects token0 and token1 owed to the position and returns the amounts received.
Parameters
recipient- Address receiving the tokens.
tickLower- Lower tick.
tickUpper- Upper tick.
amount0Requested- Requested amount of token0 to collect.
amount1Requested- Requested amount of token1 to collect.
Return value
amount0- Actual amount of token0 collected.
amount1- Actual amount of token1 collected.
burn
Overview Reduces liquidity in a position.
Details Reduces liquidity over the specified tick range and calculates the corresponding amounts of token0 and token1.
Parameters
tickLower- Lower tick.
tickUpper- Upper tick.
amount- Amount of liquidity to remove.
Return value
amount0- Amount of token0 corresponding to the removed liquidity.
amount1- Amount of token1 corresponding to the removed liquidity.
SwapCache
Overview
- A struct storing cached swap information.
Details
- Caches information about swap execution, including computed values and flags.
Parameters
feeProtocol: Protocol fee configuration for the input tokenliquidityStart: Liquidity at the start of the swapblockTimestamp: Current block timestamptickCumulative: Current cumulative tick value (computed only when crossing an initialized tick)secondsPerLiquidityCumulativeX128: Current cumulative seconds per liquidity (computed only when crossing an initialized tick)computedLatestObservation: Flag indicating whether the cumulative tick and seconds per liquidity values have been computed
SwapState
Overview A struct storing the top-level swap state.
Details Stores top-level swap state, including token swap amounts and the current price.
Parameters
amountSpecifiedRemaining- Remaining input or output token amount to swap.
amountCalculated- Calculated output or input token amount.
sqrtPriceX96- Current square-root price.
tick- Current tick.
feeGrowthGlobalX128- Global fee growth of the input token.
protocolFee- Amount of the input token owed as protocol fees.
liquidity- Current in-range liquidity.
StepComputations
Overview A struct storing step calculation information.
Details Stores calculation information for each swap step.
Parameters
sqrtPriceStartX96- Square-root price at the beginning of the step.
tickNext- Next tick in the swap direction.
initialized- Flag indicating whether
tickNextis initialized.
- Flag indicating whether
sqrtPriceNextX96- Square-root price of the next tick.
amountIn- Input token amount for this step.
amountOut- Output token amount for this step.
feeAmount- Fee amount paid in this step.
swap
Overview Executes a token swap.
Details Performs the swap according to the specified conditions.
Parameters
recipient- Address receiving the tokens.
zeroForOne- Swap direction (
true: token0 → token1,false: token1 → token0).
- Swap direction (
amountSpecified- Token amount to swap.
sqrtPriceLimitX96- Swap price limit.
data- Callback data.
Return value
amount0- Signed token0 balance delta.
amount1- Signed token1 balance delta.
flash
Overview
Executes a flash operation.
Details A flash operation borrows specified token amounts, requires repayment with fees, and invokes additional callback processing. It calculates fees and post-operation balances and emits the corresponding event.
Parameters
recipient- Address receiving the borrowed tokens.
amount0- Amount of token0 to borrow.
amount1- Amount of token1 to borrow.
data- Additional callback data.
Return value
None.
What is a flash swap?
Overview A flash swap is a DeFi (decentralized finance) mechanism that allows users to obtain tokens temporarily within a transaction. By borrowing tokens and repaying them immediately within the transaction, users may use them in swaps that take advantage of temporary price differences.
Details A typical flash-funded swap involves the following steps.
-
Borrow The user temporarily borrows tokens from the protocol. The tokens are used to execute a swap.
-
Swap The user executes a swap using the borrowed tokens. Such swaps typically seek to take advantage of price movements or differences in a particular token pair. The objective is to account for the swap's price impact and maximize the resulting profit.
-
Repay If the swap succeeds, the user immediately repays the borrowed tokens using the proceeds. There may be a profit, but if repayment fails, the entire transaction reverts.
Mechanism A flash-funded swap aims to borrow tokens temporarily and use a swap to profit from a price difference. Because the operation takes place within one transaction, accurate assessment of price differences is important for profitability. The borrowed tokens must be repaid within the transaction.
Considerations Flash-funded swaps involve risks related to price changes and successful transaction execution. Depending on the protocol, fees may also apply. Users must understand these risks before execution and proceed carefully.
Use cases Flash-funded swaps can be useful for traders and arbitrageurs seeking to profit from price differences. Liquidity providers may also earn fees through flash operations.
Typical process:
- Borrow tokens.
- Execute a swap to seek a profit.
- Immediately repay the borrowed tokens.
Flash-funded swaps are a DeFi mechanism that may offer opportunities for short-term profits, but their risks must be considered.
setFeeProtocol
Overview Sets the protocol fee configuration.
Details Configures the protocol fee for the swap pool. The protocol fee is configured separately for token0 and token1. Only the protocol's authorized owner may call this function. The protocol fee configuration controls the protocol's share of swap fees.
Parameters
feeProtocol0- Protocol fee configuration for token0.
feeProtocol1- Protocol fee configuration for token1.
Return value
None.
collectProtocol
Overview Collects protocol fees.
Details Collects protocol fees from the swap pool. Only the protocol's authorized owner may call this function. Collects protocol fees up to the specified amounts of token0 and token1. The collected fees are sent to the designated recipient.
Parameters
recipient- Address receiving the fees.
amount0Requested- Amount of token0 to collect.
amount1Requested- Amount of token1 to collect.
Return value
amount0- Actual amount of token0 collected.
- `amount1:
- Actual amount of token1 collected.
Events
OwnerChanged
Overview An event emitted when the factory owner changes.
Parameters
oldOwner- Previous owner address.
newOwner- New owner address.
PoolCreated
Overview An event emitted when a new pool is created.
Parameters
token0- Address of the first token in the pool, based on address sorting.
token1- Address of the second token in the pool, based on address sorting.
fee- Fee for each swap in the pool (expressed in hundredths of a basis point).
tickSpacing- Minimum number of ticks between initialized ticks.
pool- Address of the created pool.
FeeAmountEnabled
Overview An event emitted when a new fee tier is enabled for pool creation through the factory.
Parameters
fee- Enabled fee tier (expressed in hundredths of a basis point).
tickSpacing- Tick spacing associated with the fee tier.
Code
Interfaces
- The
interfacesdirectory.
Libraries
- The
librariesdirectory.
Conclusion
This article explored the UniswapV3Factory contract of Uniswap V3 using Bunzz's DeCipher feature. I hope it helped clarify the contract. I plan to continue covering particular NFTs and smart contracts.
I also publish articles about blockchain and AI on my blog and Qiita.






