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.
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!!
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
$ npm install simple-uniswap-sdk$ yarn add simple-uniswap-sdkThe 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.
export class UniswapPair {
constructor(
private _uniswapPairContext:
| UniswapPairContextForChainId
| UniswapPairContextForProviderUrl
| UniswapPairContextForEthereumProvider
)……This will use a infura endpoint without you having to pass in a node
…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.
…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.
…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.
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;
}
}…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.
/**
* 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): PromiseTrade direction is a way to ask for quotes for input and output.
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.
…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',
}……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:
ETH/TOKEN > TOKEN_YOU_WANTETH/TOKEN > TOKEN > TOKEN_YOU_WANTETH/TOKEN > TOKEN > OTHER_TOKEN > TOKEN_YOU_WANTeth_estimateGas those 3 transactions and takes off the tx fee from the expected quoteDo 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.
………This exposes the to token contract information, like decimals, symbol and name.
get toToken(): Tokenexport interface Token {
chainId: ChainId;
contractAddress: string;
decimals: number;
symbol: string;
name: string;
}…This exposes the from token contract information, like decimals, symbol and name.
get fromToken(): Tokenexport interface Token {
chainId: ChainId;
contractAddress: string;
decimals: number;
symbol: string;
name: string;
}…This exposes the provider url it is using will be undefined if you injected a ethereum provider
get providerUrl(): string | undefined…Along side the above we also have exposed some helpful erc20 token calls.
This method will return you the token information like decimals, name etc.
async getToken(): Promiseexport interface Token {
chainId: ChainId;
contractAddress: string;
decimals: number;
symbol: string;
name: string;
}…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.
async allowance(uniswapVersion: UniswapVersion, ethereumAddress: string): Promise…This method will return the balance this user holds of this token. This always returned as a hex and not formatted for you.
async balanceOf(ethereumAddress: string): Promise…This method will return the total supply of tokens which exist. This always returned as a hex.
async totalSupply(): Promiseimport { 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';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.
generateApproveAllowanc暂无开放 Issues,或尚未同步最近议题。