Trading
The SDK cannot execute trades or send transactions on your behalf. Rather, it offers utility classes and functions which make it easy to calculate the data required to safely interact with WhiteSwap. Nearly everything you need to safely transact with WhiteSwap is provided by the Trade entity. However, it is your responsibility to use this data to send transactions in whatever context makes sense for your application.
This guide will focus exclusively on sending a transaction to the currently recommended WhiteSwap router.
Let’s say we want to trade 1 WETH for as much DAI as possible:
import { ChainId, Token, WETH, Fetcher, Trade, Route, TokenAmount, TradeType } from '@whiteswap/sdk'
const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18)
// note that you may want/need to handle this async code differently,
// for example if top-level await is not an option
const pair = await Fetcher.fetchPairData(DAI, WETH[DAI.chainId])
const route = new Route([pair], WETH[DAI.chainId])
const amountIn = '1000000000000000000' // 1 WETH
const trade = new Trade(route, new TokenAmount(WETH[DAI.chainId], amountIn), TradeType.EXACT_INPUT)
So, we’ve constructed a trade entity, but how do we use it to actually send a transaction? There are still a few pieces we need to put in place.
Before going on, we should explore how ETH works in the context of trading. Internally, the SDK uses WETH, as all WhiteSwap pairs use WETH under the hood. However, it’s perfectly possible for you as an end user to use ETH, and rely on the router to handle converting to/from WETH. So, let’s use ETH.
The first step is selecting the appropriate router function. The names of router functions are intended to be self-explanatory; in this case we want swapExactETHForTokens, because we’re…swapping an exact amount of ETH for tokens.
That Solidity interface for this function is:
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
Jumping back to our trading code, we can construct all the necessary parameters:
import { Percent } from '@whiteswap/sdk'