Exact Output Swap

A swap type where the user specifies exactly how much of the output token to receive, paying whatever amount of input token the market requires.

Exact Output Swap (also called "exactOutputForInput") is a swap type in automated market makers where the trader specifies precisely how much of the output token they want to receive, paying whatever amount of the input token the market requires. This contrasts with exact input swaps where the input amount is fixed and the output varies.

Conceptual understanding

An exact output swap is analogous to visiting a currency exchange with a specific need: "I need exactly 100 euros—how many dollars will that cost me?" The exchange rate determines what you pay, but you know precisely what you'll receive.

In DeFi context:

  • You control: The exact amount of tokens entering your wallet
  • Market determines: How many tokens you must spend
  • Risk exposure: Paying more than expected due to slippage

Implementation in Uniswap v4

In Uniswap v4, exact output swaps are indicated by a negative amountSpecified value in the SwapParams struct:

1SwapParams memory params = SwapParams({
2 zeroForOne: true, // Direction: Token0 → Token1
3 amountSpecified: -1 ether, // Negative = exact output
4 sqrtPriceLimitX96: maxPrice // Slippage protection
5});
6
7BalanceDelta delta = poolManager.swap(key, params, hookData);

The negative sign tells the Pool Manager that 1 ether represents the desired output amount, and the input should be calculated based on available liquidity.

Why exact output swaps cost more gas

Exact output swaps require reverse computation through the AMM pricing formula, making them more computationally expensive:

  1. Iterative calculation: The protocol must work backwards from the desired output to determine the required input
  2. Multiple tick traversals: May need to probe multiple price levels to accumulate sufficient output
  3. Rounding considerations: Ensuring exact output often requires additional precision handling

For high-frequency trading or gas-sensitive applications, this overhead can be significant. Consider whether exact input swaps could meet your requirements instead.

Slippage protection

Since the input amount is market-determined, traders must implement slippage protection to avoid paying significantly more than expected:

1// Calculate expected input off-chain
2uint256 expectedInput = quoter.quoteExactOutput(tokenOut, amountOut);
3
4// Set maximum acceptable input (e.g., 0.5% slippage tolerance)
5uint256 maxInput = expectedInput * 10050 / 10000;
6
7// Execute swap
8BalanceDelta delta = poolManager.swap(key, params, hookData);
9
10// Validate result
11require(-delta.amount0() <= int256(maxInput), "Slippage exceeded");

The sqrtPriceLimitX96 parameter provides additional protection by reverting if the price moves beyond acceptable bounds.

Common use cases

Debt repayment

When repaying a loan denominated in a specific token, exact output ensures you receive precisely enough:

1// Need exactly 1000 USDC to repay loan
2uint256 debtAmount = 1000e6;
3// Pay whatever ETH is required

NFT purchases

When buying an NFT priced in a specific token, you need exactly that amount:

1// NFT costs exactly 0.5 WETH
2uint256 nftPrice = 0.5 ether;
3// Convert USDC to exactly 0.5 WETH

Collateral requirements

Meeting precise collateral requirements for DeFi protocols:

1// Position requires exactly 150 tokens as collateral
2uint256 requiredCollateral = 150e18;
3// Swap to receive exactly this amount

Gas token acquisition

Acquiring exactly enough native token for gas costs:

1// Need exactly 0.01 ETH for gas
2uint256 gasNeeded = 0.01 ether;
3// Swap from stablecoin to exact ETH amount

Security considerations

Maximum input validation

Always validate that the required input doesn't exceed acceptable bounds:

1BalanceDelta delta = poolManager.swap(key, params, hookData);
2
3// amount0 will be negative (tokens spent)
4int256 amountSpent = -delta.amount0();
5
6require(
7 amountSpent <= int256(maxAcceptableInput),
8 "Input exceeds maximum"
9);

Failing to validate can result in paying significantly more than intended during volatile market conditions.

Liquidity depth awareness

Exact output swaps can fail or execute at poor prices if insufficient liquidity exists:

1// Requesting 1M tokens when pool only has 100K liquidity
2// Will either fail or execute at extremely poor price

Always check pool liquidity depth before executing large exact output swaps.

Front-running and MEV

Exact output swaps are particularly vulnerable to MEV extraction because attackers know:

  1. Exactly how much output you need
  2. That you're willing to pay variable input

This creates opportunities for sophisticated sandwich attacks where attackers manipulate the price knowing you'll pay the higher cost to get your required output.

Decimal precision

Ensure exact output amounts account for token decimals correctly:

1// WRONG: Assumes 18 decimals
2uint256 outputAmount = 100 ether;
3
4// CORRECT: Use actual token decimals
5uint256 outputAmount = 100 * 10**outputToken.decimals();

Comparison with exact input swaps

AspectExact InputExact Output
User specifiesAmount to spendAmount to receive
amountSpecifiedPositiveNegative
Gas costLowerHigher
Use case"Spend X tokens""Need exactly Y tokens"
RiskReceive less than expectedSpend more than expected

Choose exact output when you need a precise amount of the output token (debt repayment, specific purchases); choose exact input when you care more about controlling your spending.

Protocol integration patterns

Router contracts

Routers often wrap exact output functionality with additional safety checks:

1function swapForExactOutput(
2 address tokenIn,
3 address tokenOut,
4 uint256 amountOut,
5 uint256 maxAmountIn,
6 address recipient
7) external returns (uint256 amountIn) {
8 // Validate and execute swap
9 // Return any excess input tokens
10}

Refund mechanisms

Since the exact input isn't known beforehand, protocols should implement refund logic for any excess tokens approved or sent:

1// User approves maxAmountIn
2// Actual amount spent may be less
3uint256 refund = maxAmountIn - actualAmountSpent;
4if (refund > 0) {
5 tokenIn.transfer(msg.sender, refund);
6}

This ensures users don't lose funds when market conditions are more favorable than their maximum tolerance.

Need expert guidance on Exact Output Swap?

Our team at Zealynx has deep expertise in blockchain security and DeFi protocols. Whether you need an audit or consultation, we're here to help.

Get a Quote

oog
zealynx

Smart Contract Security Digest

Monthly exploit breakdowns, audit checklists, and DeFi security research — straight to your inbox

© 2026 Zealynx