Uniswap Swap – How to Swap Between Sepolia and Custom ERC-20 Token using ethers.js

ethers.jsreactsepoliaswapsuniswap

I am working on a React-Native crypto application for fun, and I am trying to swap my Sepolia native token with my erc-20 token that I recently deployed on remix ide on the sepolia network using metamask injection.

Upon research, it turns out I have to use uniswap, and create a pool and provide liquidity and deploy on there too, creating a pair between Sepolia Eth and my erc-2o token, which I have already done.

Next, step is to write the code to implement the uniswap and I can't seem to figure out what I am missing that is throwing these errors.

I am using ether.js (latest version), infuria as my network provider.

  const sepoliaProviderUrl = `https://sepolia.infura.io/v3/${infuraApiKey}`;  

const sepoliaProvider = new ethers.providers.JsonRpcProvider(sepoliaProviderUrl);

const uniswapRouterAddress = '0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008';
const uniswapRouterContract = new ethers.Contract(
uniswapRouterAddress,
uniswapRouterAbi,
sepoliaProvider
);

It throws an error saying that it cannot read property 'JsonRpcProvider' of undefined. I looked online, and someone said to remove the providers part, and then the next error is this:

Cannot read property 'format' of undefined.

It seems this part is not working:

  const uniswapRouterAddress = '0xC532a74256D3Db42D0Bf7a0400fEFDbad7694008';
  const uniswapRouterContract = new ethers.Contract(
    uniswapRouterAddress,
    uniswapRouterAbi,
    sepoliaProvider
  );

I suspect it may have to do with the uniswapRouterAbi. But, I have searched online for these values, so I am not sure if it is outdated or why it is difficult to find the correct one?

If anyone knows how to fix this, or if there is some other code that can allow me to simply swap SepoliaETH with my deployed erc-20 token then please let me know. It should not be hard. Thanks.

Note: I have read that there is uniswap v2 or v3 that has Factory contract and Router contract. Also, some people say to downgrade the version of ethers.js to 5 because it is not stable for some reason in the latest version. I would prefer if we not do that.

Best Answer

get provider in ethers v6:

const provider = new ethers.JsonRpcProvider("");

get provider in ethers v5:

const provider = new ethers.providers.JsonRpcProvider("");

Related Topic