In this post we’ll be using the Uniswap SDK to do a swap between Ether and DAI. This was done in an earlier post here. However this was using Uniswap V1 and there is now an SDK for Uniswap V2 which we’ll look at.
The first thing we’ll do is use a forked version of the mainnet, so we get an exact view of what we can do. Go to https://cryptocam.tech/2020/06/29/aave-deposit-borrowing-tutorial-part-i/ to see how to do that.
The forked mainnet is a clever way of using a real mainnet without the expense 🙂 After updating .env with your account details and running fork_main.sh, you should get 100 Ether.
The Uniswap V2 SDK uses the ethers library and if you examine the Uniswap source code, calls are made to the provider to get the token and pair data. This is why we need to supply the provider in the pair/token requests:
const provider = new ethers.providers.JsonRpcProvider(url);
const dai = await Fetcher.fetchTokenData(chainId, daiAddress, provider, "DAI", "Dai Stablecoin");
const weth = WETH[chainId];
const pair = await Fetcher.fetchPairData(dai, weth, provider);
const route = new Route([pair], weth);
// swap 1 ether
const trade = new Trade(route, new TokenAmount(weth, ethers.utils.parseEther("1.0")), TradeType.EXACT_INPUT);
console.log("execution price: $" + trade.executionPrice.toSignificant(6));
console.log("price impact: " + trade.priceImpact.toSignificant(6) + "%");
The slippage needs to be calculated and some prep work on the inputs:
const slippageTolerance = new Percent('50', '10000'); // 0.5%
const amountOutMin = trade.minimumAmountOut(slippageTolerance).raw;
const amountOutMinHex = ethers.BigNumber.from(amountOutMin.toString()).toHexString();
const path = [weth.address, dai.address];
const deadline = Math.floor(Date.now() / 1000) + 60 * 20; // 20 mins time
const inputAmount = trade.inputAmount.raw;
const inputAmountHex = ethers.BigNumber.from(inputAmount.toString()).toHexString();
Now we do the swap:
const tx = await uniswap.swapExactETHForTokens(
amountOutMinHex,
path,
account.address,
deadline,
{
value: inputAmountHex,
gasPrice: gasPrice.toHexString(),
gasLimit: ethers.BigNumber.from(150000).toHexString()
}
);
This code can be downloaded here: https://github.com/cryptocamtech/uniswap-sdk-tutorial
When run you should see something similar to the below:
url: http://localhost:8545
Token {
decimals: 18,
symbol: 'DAI',
name: 'Dai Stablecoin',
chainId: 1,
address: '0x6B175474E89094C44Da98b954EedeAC495271d0F' }
execution price: $381.473
price impact: 0.300392%
initial balance: 0.0
final balance: 381.473361365850668308
Enjoy!