Skip to main content
This example shows how to implement single-path swaps using two functions:
  • swapExactInputSingle - swap a fixed input amount for maximum output
  • swapExactOutputSingle - swap minimum input for a fixed output amount
Both use the ISwapRouter interface. Note: The swap examples are not production ready code, and are implemented in a simplistic manner for the purpose of learning.

Set Up the Contract

Exact Input Swaps

The caller must approve the contract to withdraw tokens. Since the contract itself holds the tokens after safeTransferFrom, it must also approve the router.

Swap Input Parameters

Parameters for ExactInputSingleParams (reference):
  • fee - pool fee tier, used to determine the correct pool contract
  • amountOutMinimum - set to zero here, but in production use an oracle or the SDK to calculate this. Without slippage protection you are vulnerable to sandwich attacks.
  • sqrtPriceLimitX96 - set to zero (inactive). Can be used to cap the price impact of a swap. WARNING: A non-zero sqrtPriceLimitX96 can cause fewer tokens than amountIn to be swapped. Any contract using this must refund unswapped tokens.

Call the function

Exact Output Swaps

Swaps a minimum possible amount of the input token for a fixed amount of the outbound token. Any leftover input is refunded to the caller.

Call the function