⚪Implement a Swap
This guide will walk you through the process of swapping tokens using the Xfai protocol. The swapTokens
function allows you to execute token swaps with flexibility based on the specified trade type. The function signatures for swapping tokens are as follows:
To use the swapTokens
function effectively, follow the steps below:
Step 1: Choose the Trade Type
The swapTokens
function supports two trade types:
TradeType.EXACT_INPUT: In this trade type, you specify the exact amount of the input token and the minimum amount of the output token you expect to receive.
TradeType.EXACT_OUTPUT: In this trade type, you specify the maximum amount of the input token you are willing to spend and the minimum amount of the output token you expect to receive.
Choose the appropriate trade type based on your requirements.
Step 2: Define the Tokens
The tokenIn
and tokenOut
parameters represent the input and output tokens, respectively. You need to provide the relevant token objects for these parameters. Ensure that you have the necessary token information and instances before proceeding.
Step 3: Specify the Amounts
The amountIn
and minAmountOut
parameters are used when TradeType.EXACT_INPUT
is selected.
amountIn
represents the exact amount of the input token you want to swap.desiredAmountOut
represents the desired amount of the output token you expect to receive from the swap, the minimum amount out will be calcuated based on slippage parameter
Alternatively, when TradeType.EXACT_OUTPUT
is selected, you will use the maxAmountIn
parameter instead.
desiredAmountIn
represents the desired amount of the input token you are willing to spend, the maximum amount in will be calcuated based on slippage parameteramountOut
represents the amount of the output token you expect to receive.
Ensure that you have the required token amounts ready for the swap and you have given allowance to the periphery contract.
Step 4: Set Transaction Options
The options
parameter allows you to specify additional transaction options such as deadline, slippage and more. Review the available options and set them according to your needs.
Step 5: Perform the Token Swap
Call the swapTokens
function with the appropriate parameters to initiate the token swap. The function will return a PopulatedTransaction
object, which represents the populated transaction that can be executed.
Example Usage
Here's an example usage of the swapTokens
function:
Last updated