While testing UNISWAP_V2_ROUTER.swapExactTokensForTokens with ether.js, I encountered an error when executing this line of code:
await swapInstances.connect(accounts[0]).swap(tokenIn, tokenOut, amountIn, amountOutMin, to);
. The error message reads: Transaction reverted: function returned an unexpected amount of data
.
Any idea why this is happening?
Here is the unit test in question:
it("should be able to swap tokens", async function () {
accounts = await ethers.getSigners()
to = await accounts[1].getAddress();
const Swap = await ethers.getContractFactory("Swap", accounts[0]);
const swapInstances = await Swap.deploy();
const LocandaToken = await ethers.getContractFactory("LocandaToken", accounts[0]); //ERC20
const locandaToken = await LocandaToken.deploy();
const RubiconPoolToken = await ethers.getContractFactory("RubiconPoolToken", accounts[1]); //ERC20
const rubiconPoolToken = await RubiconPoolToken.deploy();
tokenIn = locandaToken.address;
tokenOut = rubiconPoolToken.address;
await locandaToken.connect(accounts[0]).transfer(swapInstances.address, amountIn);
await rubiconPoolToken.connect(accounts[1]).transfer(swapInstances.address, amountIn);
const ethBalance = await ethers.provider.getBalance(accounts[0].address);
console.log("eth balance" + ethBalance);
await locandaToken.connect(accounts[0]).approve(swapInstances.address, amountIn)
const test = await swapInstances.connect(accounts[0]).swap(tokenIn, tokenOut, amountIn, amountOutMin, to);
})
This is the swap function being called:
function swap(
address _tokenIn,
address _tokenOut,
uint256 _amountIn,
uint256 _amountOutMin,
address _to // address where sending the tokenout
) external {
IERC20(_tokenIn).transferFrom(msg.sender, address(this), _amountIn); // transfer from user wallet to this contract
IERC20(_tokenIn).approve(UNISWAP_V2_ROUTER, _amountIn); // aprove the router to spend _tokenin
address[] memory path; //represents the path/flow of the swap
if (_tokenIn == WETH || _tokenOut == WETH) {
path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
} else {
path = new address[](3);
path[0] = _tokenIn;
path[1] = WETH;
path[2] = _tokenOut;
}
IUniswapV2Router(UNISWAP_V2_ROUTER).swapExactTokensForTokens(
_amountIn,
_amountOutMin,
path,
_to,
block.timestamp
);
}