im testing UNISWAP_V2_ROUTER.swapExactTokensForTokens using ether.js and this line: await swapInstances.connect(accounts[0]).swap(tokenIn, tokenOut, amountIn, amountOutMin, to);
cause this error : Transaction reverted: function returned an unexpected amount of data
.
why?
unit test :
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);
})
swap function :
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
);
}
You are deploying two new tokens. Hence, there are no uniswap pools available for those tokens yet.
I think you need to create a corresponding pair calling the uniswapV2Factory and then add liquidity: https://docs.uniswap.org/protocol/V2/reference/smart-contracts/factory#createpair
Second, where are you setting your amountOutMin?
third, Why are you transferring tokens to your swap contract?
await locandaToken.connect(accounts[0]).transfer(swapInstances.address, amountIn);
await rubiconPoolToken.connect(accounts[1]).transfer(swapInstances.address, amountIn);