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 examines the SwapRouter contract of Uniswap V3 using Bunzz's DeCipher feature.
DeCipher is a service that uses AI to generate smart contract documentation.
For a detailed guide to using DeCipher, see the following article.
This article reflects my personal experience using DeCipher. If you notice inaccuracies, please let me know in the comments.
The DeCipher page used in this article is linked below.
The corresponding Etherscan page is available below.
Overview
The SwapRouter is a core component of Uniswap V3's periphery contracts, executing token swaps on Ethereum. It connects traders with liquidity provided through the pools selected for their swaps.
Its principal purpose is to execute swaps through one or more specified liquidity pools. Route selection and price optimization are normally performed outside this router.
Supporting contracts and libraries such as SafeCast, TickMath, and Path handle numerical conversions, price boundaries, and encoded routes. Together, they support accurate and efficient execution of the selected swap route.
SafeCast
Performs checked numeric casts.
Numeric conversions on the blockchain require care because incorrect conversions can produce overflow, underflow, or truncation.
SafeCast checks whether values fit in their target types.
TickMath A library for calculations involving pool prices and ticks. It provides conversions and boundaries used to represent prices in the concentrated-liquidity model.
Path
A library for processing encoded multihop swap paths.
Swaps between two tokens may pass through several pools.
Path decodes and traverses the supplied route; it does not search for an optimal route.
Uniswap V3 provides liquidity pools through which different tokens can be exchanged.
Traders swap against these pools using their liquidity. The SwapRouter interacts with the pools through the IUniswapV3Pool interface.
IUniswapV3Pool defines methods for interacting with a pool.
The interface supports the following operations, although the router primarily uses its swap functionality.
-
Access liquidity information Through the pool interface, integrations can inspect information such as current liquidity and price. These data can inform external swap calculations and route selection.
-
Execute swaps The pool interface provides the function used to execute the actual token swap. The requested exchange is executed according to the selected pool's state and the supplied parameters.
-
Inspect pool state Uniswap V3 pool prices and liquidity can change dynamically. The interface allows integrations to retrieve current pool state.
-
Handle actions and events Uniswap V3 pools support actions and events beyond token swaps. The pool interface exposes the relevant operations and event definitions for integrations.
SwapRouter includes validation mechanisms that support safe swap execution.
The PeripheryValidation contract provides validation such as checking the transaction deadline.
The CallbackValidation library verifies the origin of swap callbacks to mitigate risks from interactions with external contracts.
PeripheryValidation
This mechanism validates applicable constraints on a transaction.
Users supply token amounts and, where supported, price limits when requesting swaps.
Invalid inputs can lead to failed or undesirable execution. PeripheryValidation checks the deadline, while other swap-specific checks enforce the supplied constraints.
These checks help reject transactions that fail their specified conditions.
CallbackValidation
This mechanism reduces risks when receiving callbacks from other contracts.
Executing a swap requires interactions with liquidity pool contracts.
Interactions with external contracts introduce security considerations.
CallbackValidation verifies that the callback caller is the expected authentic pool, preventing unauthorized callers from using the callback's payment logic.
This limits a critical risk associated with external callbacks.
SwapRouter also handles token payments and supports fee-related payment helpers.
The inherited PeripheryPaymentsWithFee and PeripheryPayments contracts provide functions for wrapping, unwrapping, transferring, and distributing tokens.
PeripheryPaymentsWithFee Provides payment helpers that calculate and distribute a configured fee. For applicable operations, it calculates the fee from the token amount and transfers the fee to a designated recipient. This supports payment settlement with an explicit fee allocation.
PeripheryPayments Provides payment-related functionality for transferring and unwrapping tokens. Unlike the fee-specific extension, it provides ordinary payment helpers without an additional fee allocation.
SwapRouter uses these payment contracts to handle token transfers associated with swap execution. Their functions specify how token amounts and applicable fees are transferred. Correct use of these mechanisms supports predictable settlement between participants.
SwapRouter also integrates functionality intended to improve usability and transaction efficiency.
Multicall supports executing multiple calls in a single transaction, potentially reducing transaction overhead.
SelfPermit supports granting token allowances to the router through signed permit authorizations.
Multicall contract This mechanism groups multiple function calls into a single transaction. Executing separate transactions for multiple function calls incurs separate transaction overhead. Multicall can execute the calls together in one transaction, potentially reducing this overhead. This supports more efficient transaction execution.
SelfPermit contract This mechanism simplifies authorizing the router to spend tokens owned by the caller. An allowance is commonly granted in a separate approval transaction, whereas SelfPermit can submit a signed permit as part of the transaction that uses the allowance. This can simplify the user's interaction with the router.
These additional functions are integrated into SwapRouter to improve usability and efficiency. Batching calls and submitting token permits within a transaction reduce the need for separate interactions.
Usage
Overview
SwapRouter is a smart contract supporting token swaps on the Uniswap V3 decentralized exchange. It exposes functions for executing swaps through selected liquidity pools.
Objective
The router supports efficient token swaps across one or more Uniswap V3 pools. Selecting a suitable route and configuring slippage constraints can help control execution costs and unfavorable price movements.
Usage
1. Initialize SwapRouter
A SwapRouter deployment must exist on the Ethereum network before it can be used. The original overview lists the following items; only the factory and WETH9 addresses are constructor parameters of the V3 SwapRouter discussed here.
factory- Address of the Uniswap V3 factory contract.
- `weth
- Address of the Wrapped Ether (WETH9) contract.
- `quoter
- Quoter contract address, useful for separate quote requests but not a router constructor argument.
- `refundee
- Address receiving an ETH refund, determined by the relevant payment operation rather than a constructor argument.
2. Execute a token swap
Follow these steps to execute token swaps with SwapRouter.
- Grant SwapRouter a token allowance using
approveon the input token contract, or use a supported permit mechanism. - Call
exactInputorexactOutputon SwapRouter to specify the input or output amount, respectively.- The choice depends on whether the input amount or output amount is fixed.
- Supply the appropriate parameter struct to
exactInputorexactOutput. It contains information such as the following.SwapParameters- Swap details, including the relevant amounts and recipient address.
Path- Encoded token path and fee tiers identifying the pools to use.
deadline- Execution deadline.
- SwapRouter executes the swap, transfers output tokens to the recipient, and returns the output amount for exact input or the input amount for exact output.
3. Estimate the output amount
The original overview refers to getAmountsOut, which belongs to the V2-style interface rather than this V3 SwapRouter. Use a suitable V3 Quoter or SDK for estimates without executing the swap.
An exact-input quote requires information such as the following.
amountIn- Input token amount.
Path- Route identifying the tokens and pools used by the swap. The quote reports the estimated output token amount.
4. Estimate the input amount
Similarly, the original getAmountsIn reference is a V2-style function. Estimate the required input using an appropriate V3 Quoter or SDK.
An exact-input quote requires information such as the following.
amountOut- Desired output token amount.
Path- Route identifying the tokens and pools used by the swap. The quote reports the estimated input token amount.
5. Retrieve a pool address
The router's getPool helper derives a pool address internally. To query a pool externally, use the factory's getPool with the token addresses and fee tier.
An exact-input quote requires information such as the following.
tokenA- Address of the first token in the pair.
tokenB- Address of the second token in the pair. The factory query identifies the corresponding deployed pool; the internal address computation alone does not guarantee a pool exists.
Events
The following event names appear in the original AI-generated overview. They are not events declared or emitted by the SwapRouter implementation shown below; observe the pool and token events for actual execution records.
Swap
sender- Address of the user initiating the swap.
SwapInfo- Structure containing swap information.
- Includes input and output tokens, amounts, and the recipient.
RefundETH
recipient- Address receiving refunded ETH.
amount- Amount of ETH refunded.
RefundERC20
token- Address of the ERC20 token being refunded.
recipient- Address receiving surplus tokens.
amount- Amount of tokens refunded.
ExactInput
SwapInfo- Structure containing swap information.
- Includes input and output tokens, amounts, and the recipient.
ExactOutput
SwapInfo- Structure containing swap information.
- Includes input and output tokens, amounts, and the recipient.
Multicall
data- Multicall data.
Related EIPs and ERCs
Parameters
_factory
Address of the factory that deploys the pools.
The factory implements the relevant IUniswapV3Factory interface.
The interface defines functionality for creating and identifying Uniswap V3 pools.
_WETH9
Address of the Wrapped Ether (WETH9) contract.
WETH represents Ethereum's native Ether (ETH) in an ERC20-compatible form.
Wrapping ETH allows integrations using ERC20 interfaces to handle native currency value in token form.
The _WETH9 constructor argument specifies the contract used to wrap and unwrap ETH.
SwapRouter
Variables
DEFAULT_AMOUNT_IN_CACHED
A sentinel constant used by exact-output swap accounting.
The router supports two primary swap modes.
- Exact input swap (swap using a specified input amount).
- Exact output swap (swap to obtain a specified output amount).
DEFAULT_AMOUNT_IN_CACHED is relevant to exact-output swaps.
An exact-output swap determines the input amount required for the specified output.
The constant represents the default, unset state of the cached input amount rather than a quoted or estimated amount.
Consider a swap from token A to token B. The exact-output mode aims to obtain the specified quantity of token B. The actual required input depends on pool state and swap execution.
The cache starts in the state represented by DEFAULT_AMOUNT_IN_CACHED; it is populated with the actual amount owed at the appropriate callback.
After execution, the router obtains the actual amount of input required.
The external exact-output function checks that amount against the maximum authorized input and resets the cache.
amountInCached
A variable temporarily recording the actual input amount owed for an exact-output swap.
It is especially relevant to exact-output swaps.
Consider the following illustration.
- Swap token A for token B.
- The desired output is 10 token B.
- Suppose execution requires 15 token A.
The router uses amountInCached when executing an exact-output swap.
- The swap targets the specified output and determines the actual input owed.
- In the final payment callback, the required 15 token A can be recorded in
amountInCached.
- In the final payment callback, the required 15 token A can be recorded in
- The callback pays the amount owed by the relevant payer.
- The illustrated swap spends 15 token A to obtain the requested 10 token B.
- The swap returns its actual input amount.
- The original example's suggestion that 12 token B may be obtained instead of the requested 10 does not describe normal exact-output execution.
- The router compares the recorded input amount with the caller's maximum input constraint.
- The transaction reverts if the maximum is exceeded.
Structs
SwapCallbackData
Overview
SwapCallbackData is a struct holding information used by the swap callback.
It contains two principal fields describing the swap.
Parameters
path- Encodes the swap route as a byte sequence.
- Specifies the token sequence used in the swap.
- Includes token addresses and associated pool fee tiers.
payer- Address responsible for paying for the swap.
- Identifies the source of the required payment.
Purpose
SwapCallbackData carries the encoded path and payer information into the callback.
These fields allow the router to identify the relevant pool and handle the required payments.
Functions
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 the pool corresponding to the supplied token pair and fee.
The computed pool address is not guaranteed to contain a deployed contract.
Details Computes a Uniswap V3 pool address and treats the address as a pool contract interface. Uses token A, token B, and the fee tier to derive the pool address.
Parameters
tokenA- Address of token A.
tokenB- Address of token B.
fee- Pool fee tier.
Return value
IUniswapV3Pool- Pool contract interface at the derived address for the specified pair and fee.
uniswapV3SwapCallback
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external override {
require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee);
(bool isExactInput, uint256 amountToPay) =
amount0Delta > 0
? (tokenIn < tokenOut, uint256(amount0Delta))
: (tokenOut < tokenIn, uint256(amount1Delta));
if (isExactInput) {
pay(tokenIn, data.payer, msg.sender, amountToPay);
} else {
// either initiate the next swap or pay
if (data.path.hasMultiplePools()) {
data.path = data.path.skipToken();
exactOutputInternal(amountToPay, msg.sender, 0, data);
} else {
amountInCached = amountToPay;
tokenIn = tokenOut; // swap in/out because exact output swaps are reversed
pay(tokenIn, data.payer, msg.sender, amountToPay);
}
}
}Overview Handles a Uniswap V3 swap callback. The pool invokes it during swap execution to settle token amounts owed.
Details The callback receives information about the token balance deltas associated with the swap. It verifies the calling pool and uses the deltas and callback data to determine the necessary payment or subsequent swap.
Parameters
amount0Delta- Signed change in the pool's token0 balance.
amount1Delta- Signed change in the pool's token1 balance.
calldata _data- Encoded swap callback data.
Return value The function has no return value.
uniswapV3SwapCallback is invoked by the pool during the execution of its swap, before the swap completes.
The callback performs the required settlement logic and, for some exact-output routes, initiates further swaps.
Uniswap V3 swaps are executed by the pool contracts. Swapping changes token balances and may move the pool price. The callback runs within that same swap transaction and supports the following responsibilities.
- Check the swap deltas and caller Verify the calling pool and determine the positive amount owed.
- Handle the required payment The callback pays the required tokens to the pool or starts the next nested exact-output swap. It does not itself emit the hypothetical events listed in the earlier overview.
- Perform additional route processing Where necessary, continue through the encoded path before finalizing payment.
Because the callback is invoked within the pool's swap execution, settlement and nested swaps can be composed atomically.
This implementation uses uniswapV3SwapCallback to validate the caller and settle the swap.
exactInputInternal
function exactInputInternal(
uint256 amountIn,
address recipient,
uint160 sqrtPriceLimitX96,
SwapCallbackData memory data
) private returns (uint256 amountOut) {
// allow swapping to the router address with address 0
if (recipient == address(0)) recipient = address(this);
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
(int256 amount0, int256 amount1) =
getPool(tokenIn, tokenOut, fee).swap(
recipient,
zeroForOne,
amountIn.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encode(data)
);
return uint256(-(zeroForOne ? amount1 : amount0));
}Overview Executes a swap using the specified input amount.
Details Implements the internal exact-input swap logic. The swap uses the input amount, recipient, price limit, and callback data.
Parameters
amountIn- Input amount for the swap.
recipient- Address receiving the tokens.
sqrtPriceLimitX96- Price limit.
SwapCallbackData- Encoded swap callback data.
Return value
amountOut- Output amount obtained from the swap.
sqrtPriceLimitX96 is a price-limit parameter used by Uniswap V3.
It constrains how far the pool price may move during the swap.
The pool price can change as trades execute.
Uniswap V3 represents price using its square root in fixed-point form, exposed as sqrtPriceX96.
Because pool prices can change, callers can specify sqrtPriceLimitX96 to bound price movement during their swap.
The parameter has the following effects.
- The pool's resulting square-root price cannot cross the specified limit in the direction of the swap.
- This bounds permitted price movement.
- The limit is a lower bound for zero-for-one swaps and an upper bound for one-for-zero swaps. It does not guarantee stability of the broader market.
Consider these possible uses.
- When large price movements are a concern, choose an appropriate
sqrtPriceLimitX96to constrain execution. - A value of zero in this router selects the protocol's near-extreme default boundary, rather than guaranteeing execution near the current price.
sqrtPriceLimitX96 is therefore an important parameter for controlling the permitted price movement of a Uniswap V3 swap.
exactInputSingle
function exactInputSingle(ExactInputSingleParams calldata params)
external
payable
override
checkDeadline(params.deadline)
returns (uint256 amountOut)
{
amountOut = exactInputInternal(
params.amountIn,
params.recipient,
params.sqrtPriceLimitX96,
SwapCallbackData({path: abi.encodePacked(params.tokenIn, params.fee, params.tokenOut), payer: msg.sender})
);
require(amountOut >= params.amountOutMinimum, 'Too little received');
}Overview Executes a single-pool swap using a specified input amount. The swap may specify a price limit and returns the resulting output amount.
Details The function executes a swap using the supplied input amount and calculates the output. It supports a price limit and checks that the output meets the configured minimum.
Parameters
ExactInputSingleParams- Struct containing the swap parameters, including the following fields.
amountIn- Input token amount.
recipient- Swap recipient address.
sqrtPriceLimitX96- Swap price limit in square-root price form.
tokenIn- Input token address.
tokenOut- Output token address.
fee- Pool fee tier.
amountOutMinimum- Minimum output amount.
Return value
amountOut- Output token amount obtained from the swap.
exactInputSingle executes a single-pool swap using the specified input amount and checks the result against the minimum output amount.
Consider the following illustrative values.
- Input token: token A
- Output token: token B
- Fee: 0.3%
- Input amount: 100 token A
- Minimum output amount: 200 token B
- Illustrative square-root price limit: 1500000000000 (actual values must use Q64.96 encoding and the correct swap direction).
The example requests a swap using 100 token A and requires at least 200 token B as output.
- Execute the swap
- Populate
ExactInputSingleParamswith the 100 token A input, the 200 token B minimum output, and the appropriate square-root price limit. - The function executes the swap to obtain token B.
- Execution takes the supplied price limit into account.
- Suppose the resulting output is 250 token B.
- Check the minimum output amount
- The executed swap returns 250 token B in this illustration.
- This exceeds the minimum output requirement of 200 token B.
In this way, exactInputSingle uses the specified input to obtain output through one pool and checks that the output satisfies the minimum.
The swap succeeds only if the output is at least the specified minimum and the other required conditions hold.
exactInput
function exactInput(ExactInputParams memory params)
external
payable
override
checkDeadline(params.deadline)
returns (uint256 amountOut)
{
address payer = msg.sender; // msg.sender pays for the first hop
while (true) {
bool hasMultiplePools = params.path.hasMultiplePools();
// the outputs of prior swaps become the inputs to subsequent ones
params.amountIn = exactInputInternal(
params.amountIn,
hasMultiplePools ? address(this) : params.recipient, // for intermediate swaps, this contract custodies
0,
SwapCallbackData({
path: params.path.getFirstPool(), // only the first pool in the path is necessary
payer: payer
})
);
// decide whether to continue or terminate
if (hasMultiplePools) {
payer = address(this); // at this point, the caller has paid
params.path = params.path.skipToken();
} else {
amountOut = params.amountIn;
break;
}
}
require(amountOut >= params.amountOutMinimum, 'Too little received');
}Overview Executes an exact-input swap that may combine multiple pool swaps.
Details This function combines swaps along the specified route using the supplied input amount. When traversing multiple pools, the output of each swap becomes the input of the following swap.
Parameters
ExactInputParams- Struct containing the swap parameters.
- Its fields include the following.
amountIn- Input token amount.
recipient- Swap recipient address.
sqrtPriceLimitX96- Swap price limit in square-root price form.
path- Encoded swap path.
amountOutMinimum- Minimum output amount.
deadline- Transaction deadline.
Return value
amountOut- Output token amount obtained from the swap.
The function combines successive swaps using a specified initial input amount. The following example illustrates how successive swaps consume the output of previous swaps.
Consider the following illustrative values.
- Input token: token A
- Output token: token B
- Fee: 0.3%
- Input amount: 100 token A
- Minimum output amount: 200 token B
- Illustrative square-root price limit: 1500000000000 (actual values must use Q64.96 encoding and the correct swap direction).
The original example starts with token A and targets token B.
It describes using exactInput to exchange 100 token A for at least 200 token B.
- First swap
ExactInputParamsspecifies the initial input of 100 token A, the minimum final output of 200 token B, and the encoded route. It does not includesqrtPriceLimitX96.- The first pool swaps token A into token B.
- Suppose its output is 250 token B.
- Second swap
- If the route continues, the 250 token B obtained from the first pool becomes the input for the next pool.
- The router advances the path internally; it does not construct a new externally supplied
ExactInputParamsfor each hop. - The original illustration then swaps token B back into token A.
- Suppose this returns 100 token A.
This particular two-hop illustration ends in token A, not token B, so it cannot demonstrate a final output of at least 200 token B. The final token and minimum output must match the encoded route.
The exactInput function nevertheless demonstrates how multiple swaps can be combined atomically along a supplied route.
exactOutputInternal
function exactOutputInternal(
uint256 amountOut,
address recipient,
uint160 sqrtPriceLimitX96,
SwapCallbackData memory data
) private returns (uint256 amountIn) {
// allow swapping to the router address with address 0
if (recipient == address(0)) recipient = address(this);
(address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
(int256 amount0Delta, int256 amount1Delta) =
getPool(tokenIn, tokenOut, fee).swap(
recipient,
zeroForOne,
-amountOut.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encode(data)
);
uint256 amountOutReceived;
(amountIn, amountOutReceived) = zeroForOne
? (uint256(amount0Delta), uint256(-amount1Delta))
: (uint256(amount1Delta), uint256(-amount0Delta));
// it's technically possible to not receive the full output amount,
// so if no price limit has been specified, require this possibility away
if (sqrtPriceLimitX96 == 0) require(amountOutReceived == amountOut);
}Overview Executes a swap targeting the specified output amount and calculates the required input.
Details The function executes a swap for the requested output and determines the corresponding input amount. It supports a price limit, which constrains the swap execution.
Parameters
amountOut- Desired output token amount.
recipient- Recipient address for the swap output.
sqrtPriceLimitX96- Swap price limit in square-root price form.
SwapCallbackData- Swap callback data.
Return value
amountIn- Input token amount required by the swap.
exactOutputInternal executes a swap targeting a specified output amount, using a reverse-encoded path.
The required input is determined by the desired output and pool execution.
Consider the following illustrative values.
- Input token: token A
- Output token: token B
- Fee: 0.3%
- Desired output: 200 token B
- Illustrative square-root price limit: 1500000000000 (actual values must use Q64.96 encoding and the correct swap direction).
This example uses exactOutputInternal to determine the input token amount required to obtain 200 token B.
- Execute the swap
- Supply the 200 token B output amount, recipient address, price limit, and callback data to
exactOutputInternal. - The function executes the swap and determines the required input amount.
- Suppose the resulting input requirement is 150 token A.
- Swap result
- The swap delivers 200 token B to the recipient in this illustration.
- It consumes 150 token A as input.
exactOutputInternal thus determines the required input while executing a swap targeting the specified output.
It is also used when recursively executing reverse-encoded exact-output routes.
exactOutputSingle
function exactOutputSingle(ExactOutputSingleParams calldata params)
external
payable
override
checkDeadline(params.deadline)
returns (uint256 amountIn)
{
// avoid an SLOAD by using the swap return data
amountIn = exactOutputInternal(
params.amountOut,
params.recipient,
params.sqrtPriceLimitX96,
SwapCallbackData({path: abi.encodePacked(params.tokenOut, params.fee, params.tokenIn), payer: msg.sender})
);
require(amountIn <= params.amountInMaximum, 'Too much requested');
// has to be reset even though we don't use it in the single hop case
amountInCached = DEFAULT_AMOUNT_IN_CACHED;
}Overview Executes a single-pool swap targeting a specified output amount.
Details The function uses the supplied parameters to execute the swap. It determines the input required to obtain the desired output and checks the maximum input constraint.
Parameters
params- Struct containing the swap parameters.
- Its fields include the following.
amountOut- Desired output amount.
recipient- Address receiving the output.
sqrtPriceLimitX96- Swap price limit.
tokenOut- Output token address.
fee- Pool fee tier.
tokenIn- Input token address.
amountInMaximum- Maximum permitted input amount.
deadline- Swap deadline.
Return value
amountIn- Input amount required for the swap.
Consider an example using exactOutputSingle.
Assume the following scenario.
- The desired output is 100 token A.
- Token B is used as the input token.
- The fee tier is 0.3% (3000), and the deadline is set to a timestamp on the following day.
Example parameters.
amountOut: 100 token Arecipient: 0xAddress (output recipient)sqrtPriceLimitX96: 0 (use the router's default price boundary)tokenOut: token A addressfee: 3000tokenIn: token B addressamountInMaximum: 1000 token Bdeadline: the following day (Unix timestamp)
ExactOutputSingleParams memory params = ExactOutputSingleParams({
tokenOut: address(tokenA),
tokenIn: address(tokenB),
fee: 3000,
recipient: 0xAddress,
amountOut: 100, // Receive 100 token A
amountInMaximum: 1000, // Allow at most 1000 token B
sqrtPriceLimitX96: 0, // Default price boundary
deadline: tomorrowTimestamp // Timestamp on the following day
});
uint256 amountIn = swapRouter.exactOutputSingle(params);The example targets an output of 100 token A while allowing at most 1000 token B as input.
The required input amount reflects the pool fee and swap execution, subject to the configured price limit.
On success, amountIn contains the actual input amount.
exactOutput
function exactOutput(ExactOutputParams calldata params)
external
payable
override
checkDeadline(params.deadline)
returns (uint256 amountIn)
{
// it's okay that the payer is fixed to msg.sender here, as they're only paying for the "final" exact output
// swap, which happens first, and subsequent swaps are paid for within nested callback frames
exactOutputInternal(
params.amountOut,
params.recipient,
0,
SwapCallbackData({path: params.path, payer: msg.sender})
);
amountIn = amountInCached;
require(amountIn <= params.amountInMaximum, 'Too much requested');
amountInCached = DEFAULT_AMOUNT_IN_CACHED;
}Overview Executes successive swaps targeting a specified output amount.
Details Combines swaps across pools to obtain the specified final output. Exact-output swaps execute through nested callbacks in reverse path order. Intermediate payments are settled by the relevant nested swaps, with the original caller paying the required initial input.
Parameters
params- Struct containing the swap parameters.
- Its fields include the following.
path- Byte sequence encoding the swap path in reverse order.
amountOut- Desired output amount.
recipient- Address receiving the output.
deadline- Swap deadline.
Return value
amountIn- Input amount required for the swap.
Consider the following example.
Assume the following scenario.
- The desired output is 200 token A.
- Token B is used as the input token.
- The fee tier is 0.3% (3000), and the deadline is set to a timestamp on the following day.
Example parameters.
amountOut: 200 token Arecipient: 0xAddress (output recipient)path: token A to token B (reverse encoding for a token B to token A swap)amountInMaximum: 1000 token Bdeadline: the following day (Unix timestamp)
ExactOutputParams memory params = ExactOutputParams({
path: abi.encodePacked(address(tokenB), 3000, address(tokenA)), // Original example encodes the forward direction; exactOutput requires the reverse direction
recipient: 0xAddress,
amountOut: 200, // Receive 200 token A
amountInMaximum: 1000, // Allow at most 1000 token B
deadline: tomorrowTimestamp // Timestamp on the following day
});
uint256 amountIn = swapRouter.exactOutput(params);The intended example targets 200 token A with at most 1000 token B as input. The preserved illustrative code has a forward-encoded path and an untyped fee literal; a valid exact-output path would encode token A, a uint24 fee tier, and token B in that order.
The required input amount reflects the pool fee and swap execution, subject to the configured price limit.
On success, amountIn contains the actual input amount.
PeripheryValidation
PeripheryValidation
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import './BlockTimestamp.sol';
abstract contract PeripheryValidation is BlockTimestamp {
modifier checkDeadline(uint256 deadline) {
require(_blockTimestamp() <= deadline, 'Transaction too old');
_;
}
}Modifiers
checkDeadline
Validates the specified deadline.
Before execution, compares the current block timestamp with deadline to ensure the deadline has not passed.
If the deadline has passed, the transaction reverts with the message Transaction too old.
PeripheryPaymentsWithFee
Functions
PeripheryPaymentsWithFee
function unwrapWETH9WithFee(
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) public payable override {
require(feeBips > 0 && feeBips <= 100);
uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));
require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');
if (balanceWETH9 > 0) {
IWETH9(WETH9).withdraw(balanceWETH9);
uint256 feeAmount = balanceWETH9.mul(feeBips) / 10_000;
if (feeAmount > 0) TransferHelper.safeTransferETH(feeRecipient, feeAmount);
TransferHelper.safeTransferETH(recipient, balanceWETH9 - feeAmount);
}
}Overview Unwraps WETH9 into ETH and distributes a configured fee and the remaining ETH.
Details Converts the router's WETH9 balance to ETH and sends the fee to the fee recipient and the remainder to the designated recipient. The fee is calculated at the specified rate and deducted from the amount sent to the recipient.
Parameters
amountMinimum- Minimum WETH9 balance required.
- The function reverts if the WETH9 balance is below this amount.
recipient- ETH recipient address.
feeBips- Fee rate in basis points.
- Valid values range from
1to100inclusive.
feeRecipient- Fee recipient address.
Return value No return value.
Example: Consider the following illustrative parameters.
- Token address:
0x123...(the unwrap function itself uses WETH9 rather than accepting a token address). - Minimum amount:
200units. - Recipient address:
0x456... - Fee rate:
2%(200basis points). This exceeds the implementation's limit of 100 basis points and would revert. - Fee recipient address:
0x789...
The original example gives the following call; it is not valid for the shown unwrap function and fee limit.
sweepTokenWithFee(0x123..., 200, 0x456..., 200, 0x789...);The following arithmetic illustrates fee distribution only; this particular 200-basis-point call would revert before payment.
- A hypothetical fee of 200 basis points represents 2%.
- Suppose the balance is 1000 units.
- The hypothetical fee would be
1000 * 200 / 10000 = 20.- This would deduct 20 units as a fee.
- Compare the balance with the minimum amount of 200.
- A balance of 1000 would satisfy the minimum balance condition.
- Calculate the remainder after deducting the fee.
- The hypothetical remaining amount would be 980 units (
1000 - 20).
- Under valid fee settings, the fee and remainder are sent to
feeRecipientandrecipient, respectively.
sweepTokenWithFee
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) public payable override {
require(feeBips > 0 && feeBips <= 100);
uint256 balanceToken = IERC20(token).balanceOf(address(this));
require(balanceToken >= amountMinimum, 'Insufficient token');
if (balanceToken > 0) {
uint256 feeAmount = balanceToken.mul(feeBips) / 10_000;
if (feeAmount > 0) TransferHelper.safeTransfer(token, feeRecipient, feeAmount);
TransferHelper.safeTransfer(token, recipient, balanceToken - feeAmount);
}
}Overview Transfers a specified token balance while accounting for a configured fee.
Details The function transfers the token to the recipient and fee recipient. The main recipient receives the balance remaining after the fee is deducted.
Parameters
token- Address of the token to transfer.
amountMinimum- Minimum token balance required.
- The function reverts if the balance is below this amount.
recipient(address)- Address receiving the tokens.
feeBips- Fee rate in basis points.
- Valid values range from
1to100inclusive.
feeRecipient- Fee recipient address.
Return value No return value.
Example Consider the following scenario.
- Token address:
0xabc... - Minimum amount:
500tokens. - Recipient address:
0xdef... - Fee rate:
1%(100basis points). - Fee recipient address:
0xghi...
The following illustrates calling the function.
sweepTokenWithFee(0xabc..., 500, 0xdef..., 100, 0xghi...);The following arithmetic illustrates fee distribution only; this particular 200-basis-point call would revert before payment.
- The configured
feeBipsvalue of 100 represents a 1% fee.
- Suppose the contract's
balanceTokenis 1000 tokens. - Calculate
feeAmountas1000 * 100 / 10000 = 10.- The fee is 10 tokens.
- Check that the balance satisfies
amountMinimum, which is 500. A balance of 1000 tokens satisfies the condition. - Calculate the balance remaining after deducting the fee.
The remaining amount is 990 tokens (
1000 - 10). - Transfer 10 tokens to
0xghi..., the fee recipient. - Transfer the remaining 990 tokens to
0xdef..., the recipient.
sweepTokenWithFee thus transfers the contract's specified token balance after deducting a configured fee.
The fee portion is sent to the fee recipient.
The remainder is sent to the specified recipient.
Multicall
Functions
multicall
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}Overview
Executes multiple function calls in one operation.
It uses the supplied calldata array to execute calls sequentially through delegatecall and returns the results together.
For more about delegatecall, see the following resource.
https://chaldene.net/solidity-delegatecall
Parameters:
data- Array containing calldata for the functions to execute through delegate calls.
- Each element contains the byte-encoded calldata of a function call.
Return value:
results- Array of byte strings containing the results of the calls.
- Each element contains the result of its corresponding call.
Execution
- Initialize the
resultsarray to the length ofdata. - Iterate over the calldata in order, using
ias the loop index. - Execute the calldata stored in
data[i]through a delegate call to this contract's own address. The call uses the current contract's context. - The
successvalue indicates whether the delegate call succeeded. - Handle any call failure. This implementation attempts to decode a revert reason and reverts the entire multicall.
- On success, store the returned bytes in
results[i].
BlockTimestamp
Functions
_blockTimestamp
function _blockTimestamp() internal view virtual returns (uint256) {
return block.timestamp;
}Overview Returns the block timestamp.
Details
This helper is designed to support testing.
Tests can override it to simulate a chosen block timestamp.
The ordinary implementation returns the current block.timestamp.
Return value
Unsigned integer (uint256) representing the block timestamp.
SelfPermit
Functions
selfPermit
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s);
}Overview Submits an ERC20 permit granting the router an allowance from the token owner.
Details The token owner can use a signed permit to authorize the router to spend a specified token amount. This allows the router to spend tokens on behalf of the owner within the allowance.
Parameters:
token- Address of the token.
value- Amount to authorize.
deadline- Permit deadline.
v- ECDSA signature
vvalue.
- ECDSA signature
r- ECDSA signature
rvalue.
- ECDSA signature
s- ECDSA signature
svalue.
- ECDSA signature
selfPermitIfNecessary
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (IERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
}Overview Checks a token allowance and submits a permit when necessary.
Details
Checks whether the router already has sufficient allowance to spend the specified token amount.
If the allowance is insufficient, invokes selfPermit to submit the signed authorization.
Parameters:
token- Address of the token.
value- Required token amount.
deadline- Permit deadline.
v- ECDSA signature
vvalue.
- ECDSA signature
r- ECDSA signature
rvalue.
- ECDSA signature
s- ECDSA signature
svalue.
- ECDSA signature
selfPermitAllowed
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
}Overview Submits a DAI-style permit authorizing the router to spend the owner's tokens.
Details
The token owner can use a signed permit to authorize the router to spend a specified token amount.
This function invokes permit through IERC20PermitAllowed, using the Boolean-approval variant rather than the standard EIP2612 value-based permit interface.
Parameters:
token- Address of the token.
nonce- Permit nonce.
expiry- Permit expiration.
v- ECDSA signature
vvalue.
- ECDSA signature
r- ECDSA signature
rvalue.
- ECDSA signature
s- ECDSA signature
svalue.
- ECDSA signature
selfPermitAllowedIfNecessary
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (IERC20(token).allowance(msg.sender, address(this)) < type(uint256).max)
selfPermitAllowed(token, nonce, expiry, v, r, s);
}Overview: Checks whether the existing allowance already satisfies the unlimited-approval requirement and submits a DAI-style permit if needed.
Details: If the router does not already have the required maximum allowance, the function invokes selfPermitAllowed. This uses the DAI-style IERC20PermitAllowed interface rather than the EIP2612 value-based permit interface.
Parameters:
token: Token address.nonce: Permit nonce.expiry: Permit expiration.v: ECDSA signature v value.r: ECDSA signature r value.s: ECDSA signature s value.
Return value: None.
PeripheryPayments
Functions
unwrapWETH9
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable override {
uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));
require(balanceWETH9 >= amountMinimum, 'Insufficient WETH9');
if (balanceWETH9 > 0) {
IWETH9(WETH9).withdraw(balanceWETH9);
TransferHelper.safeTransferETH(recipient, balanceWETH9);
}
}Overview Unwraps WETH9 into ETH. Checks that the contract holds the required minimum WETH9 balance, unwraps its WETH9, and sends the resulting ETH to the specified recipient.
Parameters
amountMinimum- Minimum WETH9 balance.
- The function reverts if the WETH9 balance is below this amount.
recipient- ETH recipient address.
sweepToken
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable override {
uint256 balanceToken = IERC20(token).balanceOf(address(this));
require(balanceToken >= amountMinimum, 'Insufficient token');
if (balanceToken > 0) {
TransferHelper.safeTransfer(token, recipient, balanceToken);
}
}Overview Transfers the contract's balance of a specified token to the designated recipient.
Parameters
token- Address of the token to transfer.
amountMinimum- Minimum token balance.
- The function reverts if the balance is below this amount.
recipient- Address receiving the tokens.
refundETH
function refundETH() external payable override {
if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance);
}Overview
Refunds the ETH remaining in the contract to the caller (msg.sender).
pay
function pay(
address token,
address payer,
address recipient,
uint256 value
) internal {
if (token == WETH9 && address(this).balance >= value) {
// pay with WETH9
IWETH9(WETH9).deposit{value: value}(); // wrap only what is needed to pay
IWETH9(WETH9).transfer(recipient, value);
} else if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
TransferHelper.safeTransfer(token, recipient, value);
} else {
// pull payment
TransferHelper.safeTransferFrom(token, payer, recipient, value);
}
}Overview Processes a token payment. Depending on the conditions, wraps ETH into WETH9, pays from the contract's existing token balance, or pulls tokens from the payer.
Parameters
token- Address of the token being paid.
payer- Payer address.
recipient- Recipient address.
value- Amount to pay.
Events
None.
Code
Contracts
- The
contractsdirectory.
Interfaces
- The
interfacesdirectory.
Base contracts
- The
basedirectory.
Libraries
- The
librariesdirectory.
Uniswap Core contracts
- The
@uniswapdirectory.
OpenZeppelin contracts
- The
@openzeppelindirectory.
Conclusion
This article examined the Uniswap V3 SwapRouter contract using Bunzz's DeCipher feature. I hope it helped clarify how the contract works. I plan to continue examining specific NFTs and smart contracts.
I also publish articles about blockchain and AI on my blog and Qiita.




