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 → Token13 amountSpecified: -1 ether, // Negative = exact output4 sqrtPriceLimitX96: maxPrice // Slippage protection5});67BalanceDelta 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:
- Iterative calculation: The protocol must work backwards from the desired output to determine the required input
- Multiple tick traversals: May need to probe multiple price levels to accumulate sufficient output
- 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-chain2uint256 expectedInput = quoter.quoteExactOutput(tokenOut, amountOut);34// Set maximum acceptable input (e.g., 0.5% slippage tolerance)5uint256 maxInput = expectedInput * 10050 / 10000;67// Execute swap8BalanceDelta delta = poolManager.swap(key, params, hookData);910// Validate result11require(-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 loan2uint256 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 WETH2uint256 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 collateral2uint256 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 gas2uint256 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);23// amount0 will be negative (tokens spent)4int256 amountSpent = -delta.amount0();56require(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 liquidity2// 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:
- Exactly how much output you need
- 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 decimals2uint256 outputAmount = 100 ether;34// CORRECT: Use actual token decimals5uint256 outputAmount = 100 * 10**outputToken.decimals();
Comparison with exact input swaps
| Aspect | Exact Input | Exact Output |
|---|---|---|
| User specifies | Amount to spend | Amount to receive |
| amountSpecified | Positive | Negative |
| Gas cost | Lower | Higher |
| Use case | "Spend X tokens" | "Need exactly Y tokens" |
| Risk | Receive less than expected | Spend 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 recipient7) external returns (uint256 amountIn) {8 // Validate and execute swap9 // Return any excess input tokens10}
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 maxAmountIn2// Actual amount spent may be less3uint256 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.
Articles Using This Term
Learn more about Exact Output Swap in these articles:
Related Terms
Exact Input Swap
A swap type where the user specifies exactly how much of the input token to spend, receiving whatever amount of output token the market provides.
Slippage
The difference between the expected price of a trade and the actual execution price, caused by market movement or liquidity constraints.
BalanceDelta
A struct in Uniswap v4 that represents the net change in token balances resulting from pool operations like swaps or liquidity modifications.
Automated Market Maker (AMM)
A decentralized exchange protocol that uses mathematical formulas to price assets instead of order books.
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

