Skip to content

Instantly share code, notes, and snippets.

@adamazad
Last active May 18, 2022 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamazad/48b26ba186c759b34b08c47458ebd391 to your computer and use it in GitHub Desktop.
Save adamazad/48b26ba186c759b34b08c47458ebd391 to your computer and use it in GitHub Desktop.
Swapr Uniswap V2 integration
import {
ChainId,
Percent,
Token,
TokenAmount,
UniswapV2RoutablePlatform,
UniswapV2Trade,
} from '@swapr/sdk'
import { getAllCommonPairs } from '@swapr/sdk/dist/entities/trades/uniswap-v2/contracts'
import { utils, providers } from 'ethers'
// RPC provider must match the tokens' chainId
const provider = new providers.JsonRpcProvider('https://rpc.gnosischain.com/')
// Define the tokens
// This can be obtained in JSON from token lists
const tokenWXDAI = new Token(
ChainId.XDAI,
'0xe91D153E0b41518A2Ce8Dd3D7944Fa863463a97d',
18,
'WXDAI',
'WXDAI',
)
const tokenUSDC = new Token(
ChainId.XDAI,
'0xDDAfbb505ad214D7b80b1f830fcCc89B60fb7A83',
6,
'USDC',
'USDC',
)
const tokenWXDAIAmount = new TokenAmount(
tokenWXDAI,
utils.parseUnits('1', tokenWXDAI.decimals).toBigInt(),
)
const tokenUSDCAmount = new TokenAmount(
tokenUSDC,
utils.parseUnits('1', tokenUSDC.decimals).toBigInt(),
)
// Get all common pairs between WXDAI and USDC
getAllCommonPairs({
currencyA: tokenWXDAI,
currencyB: tokenUSDC,
platform: UniswapV2RoutablePlatform.SWAPR,
provider: provider as any,
})
.then(async (pairs) => {
// Compute list of routes between XWDAI and USDC such that
// the input amount of WXDAI spend must equal 1
const tradeListExactIn = UniswapV2Trade.computeTradesExactIn({
currencyAmountIn: tokenWXDAIAmount,
currencyOut: tokenUSDC,
maximumSlippage: new Percent('30', '10000'), // 0.3%
maxHops: {
maxHops: 3,
maxNumResults: 1,
},
pairs,
})
// Compute list of routes between XWDAI and USDC such that
// the output amount of WXDAI spend must equal 1
const tradeListExactOut = UniswapV2Trade.computeTradesExactOut({
currencyAmountOut: tokenWXDAIAmount,
currencyIn: tokenUSDC,
maximumSlippage: new Percent('30', '10000'), // 0.3%
maxHops: {
maxHops: 3,
maxNumResults: 1,
},
pairs,
})
const [bestTradeExactIn] = tradeListExactIn
const [bestTradeExactOut] = tradeListExactOut
// Get unsigned transaction
const bestTradeExactInUnsignedTx = await bestTradeExactIn.swapTransaction({
recipient: '0x0000000000000000000000000000000000000000', // Address of the recipient
ttl: 60 * 30, // 30 minutes
})
// Get unsigned transaction
const bestTradeExactOutUnsignedTx = await bestTradeExactOut.swapTransaction(
{
recipient: '0x0000000000000000000000000000000000000000', // Address of the recipient
ttl: 60 * 30, // 30 minutes
},
)
})
.catch((error) => {
console.error(error)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment