Trade Entity

You can use the Trade Entity to safely calculate all the data required to interact with the Router. If you're using a custom router smart contract, this guide may not apply.

Let's consider trading 1 WR5 for as much TOKEN1 as possible:

import {
    ChainId,
    Token,
    WR5,
    CurrencyAmount,
    TradeType,
    Trade,
    Route,
     } from "r5-defi-engine"
     
const TOKEN1 = new Token(ChainId.R5, '0x123...', 18)

const route = new Route([pair], WR5[TOKEN1.chainId], TOKEN1)

const amountIn = '1000000000000000000' // 1 WR5

const trade = new Trade(route, CurrencyAmount.fromRawAmount(WR5[TOKEN1.chainId], amountIn), TradeType.EXACT_INPUT)

Now that you have constructed the trade entity, there are a few more steps to go through before sending the transaction.

The first step is to select the appropriate router function. In this case:

function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
  external
  payable
  returns (uint[] memory amounts);

Now, we can construct all the parameters so we can send the transaction to be processed:

import { Percent } from 'r5-defi-engine'

const slippageTolerance = new Percent('50', '10000') // 50 bips, or 0.50%

const amountOutMin = trade.minimumAmountOut(slippageTolerance).toExact() // needs to be converted to e.g. decimal string
const path = [WR5[TOKEN1.chainId].address, TOKEN1.address]
const to = '' // should be a checksummed recipient address
const deadline = Math.floor(Date.now() / 1000) + 60 * 20 // 20 minutes from the current Unix time
const value = trade.inputAmount.toExact() // // needs to be converted to e.g. decimal string

Last updated