ohmygoddess
ohmygoddess

Reputation: 657

uniswap low level swap call

I can use the router02 function to swap tokens on uniswap:

route02.swapExactTokensForTokens(amtIn, amtOut,
         [t1.address, t2.address], addr, deadline(), {gasLimit: 4000000});

But how to call the low level swap function for uniswap directly? Here is my code but it didn't work. I have already send tokens to uni_v2_address before this function call.

const ethers = require('ethers');
const uni = new ethers.Contract(UNI_V2_ADDRESS, IUniswapV2Pair.abi, wallet);
let amt0out = BigInt(1) * BigInt(10**16);
let amt1out = BigInt(0);

//do swap
let tx = await uni.swap(amt0out, amt1out,
    addr, 0x0, {gasLimit: 4000000});

Upvotes: 3

Views: 1000

Answers (2)

Crypto_Rachel
Crypto_Rachel

Reputation: 154

This really needs to be done from a contract, hence the router. This is not safe to do without a contract, as you either have to handle the callback (like above using flashswap) or you have to send the tokens to the contract and then call the swap function. If not done in same transaction you will lose the tokens

Upvotes: 0

user3431805
user3431805

Reputation: 121

Remove the fourth parameter "data" like this:

let tx = await uni.swap(amt0out, amt1out, addr, {gasLimit: 4000000});

Passing anything in the fourth "data" parameter initiates a Flash Swap, optimistically transferring tokens to addr and attempting to call a function named "uniswapV2Call" on the addr as described here:

Uniswap Flash Swaps Documentation

Upvotes: 0

Related Questions