Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

simple-uniswap-sdk

> 编程语言
Open source

Uniswap SDK which handles the routes automatically for you, changes in trade quotes reactive subscriptions, exposure to formatted easy to understand information

190 stars0 likes0 views
WebsiteGitHub

About

Uniswap SDK which handles the routes automatically for you, changes in trade quotes reactive subscriptions, exposure to formatted easy to understand information

simple-uniswap-sdk

Uniswap SDK which handles the routes automatically for you, changes in trade quotes reactive subscriptions, exposure to formatted easy to understand information, bringing back the best trade quotes automatically, generating transactions for you and much more. All the uniswap logic for you in a simple to easy understand interface to hook straight into your dApp without having to understand how it all works.

Please note this is not owned or maintained by uniswap and is a open source package for anyone to use freely.

Features

Supports uniswap v2 and v3 prices together and returns you the best price, so you do not need to query both yourself

Queries all the best routes and finds the best price for you

Exposes all the route paths it tried so you can see every detail in how it worked out the best price

Factor in the cost of the transaction into the quotes with 1 config change

Easy subscriptions to get alerted when the price moves or the trade expires

The transaction is generated for you, just fill it with the gas details and send it on its way

All the figures are all formatted for you, no need to worry about timing it back to its decimal formatted place, just render it straight onto your UI

Exposes all the tokens metadata for you, name, symbol, decimals

Uses multicall for every on chain lookup, so even though it could be doing 100 JSONRPC calls it is all put into a few calls meaning it can stay very fast

Tidy bundle size

Fully typescript supported with full generated typings

query many tokens in 1 jsonrpc call perfect to get token metadata fast

and much more!!

Motivation

As a ethereum dApp developer you try to get your dApp experience as integrated as possible, Ethereum right now is hard to show in a web2.0 world as it is. On top of this as a developer you have to learn all the complex stuff for the blockchain which can take its toll on you.

When I was integrating uniswap on our wallet I found that their SDK was a bit too much for what I needed. Deepdown from the dApp point of view I only really cared about getting the best price for the user with all the fees related. I also found myself having to write a lot of custom code which I thought could be abstracted away so nobody has to deal with that again. A lot of the uniswap features like routing is all done in their client itself which is great but not when you want to use it in a more integrated approach in your on dApp.

Uniswap is one of the BEST projects on ethereum and one of my favourites. My motivation here is to create a library which allows more people to integrate it on their dApp without having to worry about how their amazing software links together. This makes the whole user experience better and allows more developers to get involved integrating uniswap in their dApp with a web2.0 experience, and on top of this also growing the usage of it.

p.s I have huge love for unicorns

Installing

npm

bash
$ npm install simple-uniswap-sdk

yarn

bash
$ yarn add simple-uniswap-sdk

SDK guide

Creating a uniswap pair factory

The uniswap pair factory is an instance which is joint together with the from token and the to token, it is all self contained in the instance and exposes easy methods for you to call to start using uniswap.

typescript
export class UniswapPair {
  constructor(
    private _uniswapPairContext:
      | UniswapPairContextForChainId
      | UniswapPairContextForProviderUrl
      | UniswapPairContextForEthereumProvider
)
…
…

With only the chainId

This will use a infura endpoint without you having to pass in a node

…

With your own provider url

This will use your node you pass in you must pass us the chainId as well, this stops the ethers instance calling pointless JSONRPC calls to get the chain id before every JSONRPC call.

…

Custom Ethereum provider

This will use your ethereum provider you pass in. This will work with any web3 provider, ethers provider or custom provider. For example when using MetaMask you can pass in the window.ethereum and it work. You must supply the ethereum address and the wallet be approved to use for the dApp and unlocked before passing it in. The uniswap sdk makes those assumptions without them it will not work as MetaMask is not allowed access to your dApp. Any change of network or ethereum address change you will need to handle in your dApp and regenerate the uniswap pair context. Most the time the contract addresses for your tokens are different anyway.

…

Catching error

I know randomly throwing errors with no error codes is a pain when writing dApps. In this package when we throw we have our own custom error. This has error codes you can map to what actually happened to allow your dApp to handle them gracefully.

typescript
export class UniswapError extends Error {
  public name = 'UniswapError';
  public code: ErrorCodes;
  public message: string;
  constructor(message: string, code: ErrorCodes) {
    super(message);
    this.message = message;
    this.code = code;
  }
}
…

Uniswap pair factory

Trade

This will generate you the trade with all the information you need to show to the user on the dApp. It will find the best route price for you automatically. we generate the transaction for you but you will still need to sign and send the transaction on your dApp once they confirm the swap.

Please note ROPSTEN, RINKEBY, GÖRLI and KOVAN will only use ETH as a main currency unlike MAINNET which uses everything, so you will get less routes on those testnets.

typescript
 /**
   * Generate trade - this will return amount but you still need to send the transaction
   * if you want it to be executed on the blockchain
   * @param amount The amount you want to swap formatted. Aka if you want to swap 1 AAVE you pass in 1
   * @param direction The direction you want to get the quote from
   */
async trade(amount: string, direction: TradeDirection = TradeDirection.input): Promise

Trade direction

Trade direction is a way to ask for quotes for input and output.

  • input = information for the quote from the FROM
  • ouput = information for the quote from the TO

for example if i was swapping AAVE > ETH if i pass in amount 1 and trade direction input, the information would be how much ETH you will get back from 1 AAVE. if i pass in amount 1 and trade direction ouput, the information would be how much AAVE you will get back from 1 ETH.

…
typescript
export interface Token {
  chainId: ChainId;
  contractAddress: string;
  decimals: number;
  symbol: string;
  name: string;
}

export enum ChainId {
  MAINNET = 1,
  ROPSTEN = 3,
  RINKEBY = 4,
  GÖRLI = 5,
  KOVAN = 42,
}

export enum UniswapVersion {
  v2 = 'v2',
  v3 = 'v3',
}

Usage

ethers example

…

web3 example

…

Including gas fees in the trade response

The library has the ability to work out the best trade including gas fees. As expected this does add around about 700MS onto the response time due to the need to have to query eth_estimateGas an the top 3 quotes to work out the best result. How it works is:

  • It gets the best expected trade quotes as it normally does
  • IF you do not have enough balance or enough allowance it will not estimate gas because it be a always failing transaction and the node will throw an error.
  • ALSO IF the token your swapping does not have a fiat price in coin gecko then again it ignores the below as it can not do the math without a base currency.
  • IF you have enough balance and allowance then finds the best 3 of the different hop options:
    • best direct trade aka ETH/TOKEN > TOKEN_YOU_WANT
    • best trade which jumps 2 hops aka ETH/TOKEN > TOKEN > TOKEN_YOU_WANT
    • beat trade which jumps 3 hops aka ETH/TOKEN > TOKEN > OTHER_TOKEN > TOKEN_YOU_WANT
  • It then eth_estimateGas those 3 transactions and takes off the tx fee from the expected quote
  • It then returns the trade which is the highest left amount, meaning it has taken into consideration gas within the quote

Do not worry if you want to use this feature but worried that first time customers before they approve ability for uniswap to move the tokens will not be able to benefit from this, as soon as you have approved uniswap to be able to move tokens on their behalf a new trade will be emitted within the quoteChanged$ stream so you can still get all the benefit on first time swaps.

The beauty of this is its very easy to setup just pass in a gasSettings object including a getGasPrice async function (IT MUST BE A PROMISE) which returns the gas price in Gwei which you want to use for the working out. This must be a string number aka 30 = 30 Gwei it does not handle passing in hex strings. This can be dynamic aka we call this everytime we go and work out the trades, so if you want this to hit an API or etherscan or return a fixed gas price, its completely up to you.

…

That's it now you get trades which bring you back the best trades minus the tx cost.

ERC20 > ERC20 Output example

…

ETH > ERC20 Output example

…

ERC20 > ETH Output example

…

toToken

This exposes the to token contract information, like decimals, symbol and name.

typescript
get toToken(): Token
typescript
export interface Token {
  chainId: ChainId;
  contractAddress: string;
  decimals: number;
  symbol: string;
  name: string;
}

Usage

…

fromToken

This exposes the from token contract information, like decimals, symbol and name.

typescript
get fromToken(): Token
typescript
export interface Token {
  chainId: ChainId;
  contractAddress: string;
  decimals: number;
  symbol: string;
  name: string;
}

Usage

…

providerUrl

This exposes the provider url it is using will be undefined if you injected a ethereum provider

typescript
get providerUrl(): string | undefined

Usage

…

TokenFactoryPublic

Along side the above we also have exposed some helpful erc20 token calls.

getToken

This method will return you the token information like decimals, name etc.

typescript
async getToken(): Promise
typescript
export interface Token {
  chainId: ChainId;
  contractAddress: string;
  decimals: number;
  symbol: string;
  name: string;
}

Usage

…

allowance

This method will return the allowance the user has allowed to be able to be moved on his behalf. Uniswap needs this allowance to be higher then the amount swapping for it to be able to move the tokens for the user. This is always returned as a hex and not formatted for you.

typescript
async allowance(uniswapVersion: UniswapVersion, ethereumAddress: string): Promise

Usage

…

balanceOf

This method will return the balance this user holds of this token. This always returned as a hex and not formatted for you.

typescript
async balanceOf(ethereumAddress: string): Promise

Usage

…

totalSupply

This method will return the total supply of tokens which exist. This always returned as a hex.

typescript
async totalSupply(): Promise

Usage

typescript
import { TokenFactoryPublic, ChainId } from 'simple-uniswap-sdk';

const tokenContractAddress = '0x419D0d8BdD9aF5e606Ae2232ed285Aff190E711b';

const tokenFactoryPublic = new TokenFactoryPublic(toTokenContractAddress, {
  chainId: ChainId.MAINNET,
  // you can pass in the provider url as well if you want
  // providerUrl: YOUR_PROVIDER_URL,
});

const totalSupply = await tokenFactoryPublic.totalSupply();
console.log(totalSupply);
// '0x09195731e2ce35eb000000';

generateApproveAllowanceData

This method will generate the data for the approval of being able to move tokens for the user. You have to send the transaction yourself, this only generates the data for you to send.

typescript
generateApproveAllowanc

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言