Trading | Uniswap (2024)

Looking for a quickstart?

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 Uniswap. Nearly everything you need to safely transact with Uniswap 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 latest Uniswap V2 router

Let's say we want to trade 1 WETH for as much DAI as possible:

import { ChainId, Token, WETH9, CurrencyAmount, TradeType } from '@uniswap/sdk-core'
import {Trade, Route} from '@uniswap/v2-sdk'

const DAI = new Token(ChainId.MAINNET, '0x6B175474E89094C44Da98b954EedeAC495271d0F', 18)

// See the Fetching Data guide to learn how to get Pair data
const pair = await createPair(DAI, WETH9[DAI.chainId])

const route = new Route([pair], WETH9[DAI.chainId], DAI)

const amountIn = '1000000000000000000' // 1 WETH

const trade = new Trade(route, CurrencyAmount.fromRawAmount(WETH9[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 Uniswap V2 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 '@uniswap/sdk-core'

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 = [WETH9[DAI.chainId].address, DAI.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

The slippage tolerance encodes how large of a price movement we're willing to tolerate before our trade will fail to execute. Since Ethereum transactions are broadcast and confirmed in an adversarial environment, this tolerance is the best we can do to protect ourselves against price movements. We use this slippage tolerance to calculate the minumum amount of DAI we must receive before our trade reverts, thanks to minimumAmountOut. Note that this code calculates this worst-case outcome assuming that the current price, i.e the route's mid price, is fair (usually a good assumption because of arbitrage).

The path is simply the ordered list of token addresses we're trading through, in our case WETH and DAI (note that we use the WETH address, even though we're using ETH).

The to address is the address that will receive the DAI.

The deadline is the Unix timestamp after which the transaction will fail, to protect us in the case that our transaction takes a long time to confirm and we wish to rescind our trade.

The value is the amount of ETH that must be included as the msg.value in our transaction.

Trading | Uniswap (2024)
Top Articles
Transfer Play Balance from your child’s account
Import journal entries in QuickBooks Online
Television Archive News Search Service
13 Easy Ways to Get Level 99 in Every Skill on RuneScape (F2P)
Ati Capstone Orientation Video Quiz
Plus Portals Stscg
Qhc Learning
Wisconsin Women's Volleyball Team Leaked Pictures
Google Feud Unblocked 6969
Apus.edu Login
Rams vs. Lions highlights: Detroit defeats Los Angeles 26-20 in overtime thriller
Roster Resource Orioles
ARK: Survival Evolved Valguero Map Guide: Resource Locations, Bosses, & Dinos
Pekin Soccer Tournament
Plan Z - Nazi Shipbuilding Plans
V-Pay: Sicherheit, Kosten und Alternativen - BankingGeek
The Ultimate Guide to Extras Casting: Everything You Need to Know - MyCastingFile
Self-Service ATMs: Accessibility, Limits, & Features
Unionjobsclearinghouse
Greyson Alexander Thorn
fft - Fast Fourier transform
55Th And Kedzie Elite Staffing
Cars & Trucks - By Owner near Kissimmee, FL - craigslist
New Stores Coming To Canton Ohio 2022
27 Fantastic Things to do in Lynchburg, Virginia - Happy To Be Virginia
Play It Again Sports Forsyth Photos
Askhistorians Book List
Khatrimmaza
Lucky Larry's Latina's
B.k. Miller Chitterlings
Ark Unlock All Skins Command
Maybe Meant To Be Chapter 43
The Minneapolis Journal from Minneapolis, Minnesota
Pokemon Reborn Locations
Gold Dipping Vat Terraria
Easy Pigs in a Blanket Recipe - Emmandi's Kitchen
Express Employment Sign In
The All-New MyUMobile App - Support | U Mobile
Improving curriculum alignment and achieving learning goals by making the curriculum visible | Semantic Scholar
Florida Lottery Claim Appointment
Jammiah Broomfield Ig
Sam's Club Gas Price Sioux City
Bank Of America Appointments Near Me
The Quiet Girl Showtimes Near Landmark Plaza Frontenac
Missed Connections Dayton Ohio
The top 10 takeaways from the Harris-Trump presidential debate
Used Auto Parts in Houston 77013 | LKQ Pick Your Part
Tyrone Unblocked Games Bitlife
Sdn Dds
Elizabethtown Mesothelioma Legal Question
Latest Posts
Article information

Author: Manual Maggio

Last Updated:

Views: 6460

Rating: 4.9 / 5 (69 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Manual Maggio

Birthday: 1998-01-20

Address: 359 Kelvin Stream, Lake Eldonview, MT 33517-1242

Phone: +577037762465

Job: Product Hospitality Supervisor

Hobby: Gardening, Web surfing, Video gaming, Amateur radio, Flag Football, Reading, Table tennis

Introduction: My name is Manual Maggio, I am a thankful, tender, adventurous, delightful, fantastic, proud, graceful person who loves writing and wants to share my knowledge and understanding with you.