Solidity Error – Transaction Reverted: Function Call to a Non-Contract Account When Adding Liquidity Through UniswapV2Router

errorhardhatsolidityuniswap

I've been testing around UniswapV2 using hardhat and I always get this error when I try to add liquidity through the addLiquidity function on UniswapV2Router.

For the test, I deployed mock tokens, deployed UniswapV2Factory, then deployed Router.

here's the deployment code

const token = await ethers.getContractFactory("Token");
weth = await token.deploy('WETH', 'WETH', 6, owner.address);
mim = await token.deploy('MIM', 'MIM', 18, owner.address);
dai = await token.deploy('DAI', 'DAI', 18, owner.address);

const Factory = await ethers.getContractFactory("UniswapV2Factory");
const factory = await Factory.deploy(owner.address);

const Router = await ethers.getContractFactory("UniswapV2Router02");
const router = await Router.deploy(factory.address, weth.address);

const mim_100000000 = ethers.BigNumber.from("100000000000000000000000000");
const dai_100000000 = ethers.BigNumber.from("100000000000000000000000000");
await dai.approve(router.address, dai_100000000);
await mim.approve(router.address, mim_100000000);

await router.addLiquidity(mim.address, dai.address, mim_100000000, dai_100000000, mim_100000000, dai_100000000, owner.address, Date.now());

and it always produces this error:

Error: Transaction reverted: function call to a non-contract account
    at UniswapV2Router02.getReserves (contracts/libraries/UniswapV2Library.sol:31)
    at UniswapV2Router02._addLiquidity (contracts/UniswapV2Router02.sol:45)
    at UniswapV2Router02.addLiquidity (contracts/UniswapV2Router02.sol:71)
    at HardhatNode._mineBlockWithPendingTxs 

Can someone help please?

Best Answer

The error is getting triggered in line 45 of the router contract https://github.com/Uniswap/v2-periphery/blob/master/contracts/UniswapV2Router02.sol#L45

It means that UniswapV2Library is not a correct contract reference inside the Smart Contract, so calling getReserves fails.

Looking at the code, you are not deploying and linking the library properly, so when it tries to call the function, it tries to call the function from address 0x0, giving that error.

You can find tons of docs on how to use libraries, I suggest this one to get started: https://www.tutorialspoint.com/solidity/solidity_libraries.htm

Although if what you want is just to make it work hardhat has tools to deploy and link libraries: https://hardhat.org/plugins/nomiclabs-hardhat-ethers#library-linking

Best of luck!

Related Topic