Skip to main content
Below are three methods available to swap tokens for tokens:
Consider the token’s decimal places when determining input and output values.Input and output amounts passed to the solidity function should all be in the token’s smallest unit. For the SAUCE token, which has 6 decimal places, an input of 123.45 SAUCE should be entered as 123450000 (123.45 multiplied by 10^6).
Granting a spender allowance to the router contract is required when the input token is not native HBAR for security reasons enforced at the native code layer. Ensure that the allowance amount is in token’s smallest unit.
Ensure that the “to” account has the output token id associated prior to executing the swap. Failure to do so will result in a TOKEN_NOT_ASSOCIATED_TO_ACCOUNT error.

Swap exact tokens for tokens

Swap an exact amount of tokens for a minimum token amount. Solidity function name: swapExactTokensForTokens
Set the minimum output token amount (amountOutMin) with caution.A high minimum might lead to a swap failure due to insufficient liquidity or rapid price movements. Conversely, setting the minimum too low can expose you to significant slippage, potentially resulting in a financial loss as you might receive far fewer tokens than expected.

Code overview

Resources:

Swap tokens for exact tokens

Swap a maximum amount of tokens to receive an exact tokens amount. Solidity function name: swapTokensForExactTokens
Set the maximum input token amount (amountInMax) with caution.A low maximum might lead to a swap failure if the required liquidity surpasses this limit or due to rapid price movements. Conversely, setting it too high can expose you to significant slippage, potentially leading to a financial loss as you might spend far more tokens than expected.

Code overview

Resources:

Swap exact tokens for tokens supporting custom fees

Swap an exact amount of tokens for a minimum token amount, supporting HTS tokens with custom fees on token transfer. Solidity function name: swapExactTokensForTokensSupportingFeeOnTransferTokens
Set the minimum output token amount (amountOutMin) with caution.A high minimum might lead to a swap failure due to insufficient liquidity or rapid price movements. Conversely, setting the minimum too low can expose you to significant slippage, potentially resulting in a financial loss as you might receive far fewer tokens than expected.

Code overview

Resources:

Next steps

Swap quote (V1)

Fetch expected amounts before you execute the swap.

Track swap events (V1)

Monitor executed swaps in near real time.

Swap tokens for tokens (V2)

Use V2 concentrated liquidity for the same operation.