I'm trying to make a multiple swap function in my smart contract using solidity. For example we want to swap BNB->BUSD->USDT->ADA->BNB. The contract interacts with PancakeSwap. I deployed it on BSC testnet. Here's my code:
function multyswap(uint256 amountIn, address[] calldata path) external payable {
if (path[0] == WETH) {
require(amountIn == msg.value, "Germes: INVALID_INPUT");
} else {
IBEP20(path[0]).transferFrom(msg.sender, address(this), amountIn);
}
for (uint i = 0; i < path.length-1; ++i) {
address receiver;
address[] memory tempPath = new address[](2);
tempPath[0] = path[i];
tempPath[1] = path[i+1];
if (i == path.length-2) {
receiver = msg.sender;
} else {
receiver = address(this);
}
if (path[i] == WETH) {
router.swapExactETHForTokens{value: msg.value}(
0,
tempPath,
receiver,
block.timestamp + 100
);
amountIn = address(this).balance;
} else if (path[i+1] == WETH) {
IBEP20(path[i]).approve(routerAddress, amountIn);
router.swapExactTokensForETH(
amountIn,
0,
tempPath,
receiver,
block.timestamp + 100
);
amountIn = IBEP20(tempPath[1]).balanceOf(receiver);
} else {
IBEP20(path[i]).approve(routerAddress, amountIn);
router.swapExactTokensForTokens(
amountIn,
0,
tempPath,
receiver,
block.timestamp + 100
);
amountIn = IBEP20(tempPath[1]).balanceOf(receiver);
}
}
}
The problem is that i cant swap TOKEN for BNB , but I can swap BNB for TOKEN. Here is the error:
PancakeLibrary: INSUFFICIENT_INPUT_AMOUNT
I tried to use this contract on BSC mainnet, but it failed. I suppose the reason of this error is this function from PancakeLibrary.sol:
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'PancakeLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'PancakeLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(998);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
It raises an error when amountIn = 0 , but i definetly input correct value. Could anybody help me? I would appreciate it very much