Making a Trade

This guide demonstrates how to execute a swap. In this example, we will be swapping 20 USDC for AVAX.

1. Required imports for this guide

import {
  ChainId,
  WNATIVE,
  Token,
  TokenAmount,
  Percent,
} from "@traderjoe-xyz/sdk-core";
import {
  PairV2,
  RouteV2,
  TradeV2,
  TradeOptions,
  LB_ROUTER_V22_ADDRESS,
  jsonAbis,
} from "@traderjoe-xyz/sdk-v2";
import {
  createPublicClient,
  createWalletClient,
  http,
  parseUnits,
  BaseError,
  ContractFunctionRevertedError,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { avalanche } from "viem/chains";
import { config } from "dotenv";

2. Declare required constants

Note that in your project, you most likely will not hardcode the private key at any time. You would be using libraries like web3reactarrow-up-right or wagmiarrow-up-right to connect to a wallet, sign messages, interact with contracts, and get the above constants.

3. Create Viem clients

4. Declare user inputs and initialize TokenAmount

5. Use PairV2 and RouteV2 functions to generate all possible routes

6. Generate TradeV2 instances and get the best trade

7. Check trade information

8. Declare slippage tolerance and swap method/parameters

9. Execute trade using Viem

Remember to approve spending ERC20 tokens by router before execution

Last updated