v2-periphery
v2-periphery copied to clipboard
flash loan always revert with revert UniswapV2: K
I am writing a fairly simple smart contract in order to do a flash loan but my transaction always revert with the following error UniswapV2: K. I have read 10 000 times the doc explaining the error, but I still don't understand what can be wrong in my code.
function uniswapV2Call(
address _sender,
uint _amount0,
uint _amount1,
bytes calldata _data
) external {
address[] memory path = new address[](2);
address sender = _sender;
address token0 = IUniswapV2Pair(msg.sender).token0();
address token1 = IUniswapV2Pair(msg.sender).token1();
require(
msg.sender == UniswapV2Library.pairFor(dex1FactoryAddress, token0, token1),
'Unauthorized'
);
require(_amount0 == 0 || _amount1 == 0, 'one amout should be 0');
require(_amount0 != 0 || _amount1 != 0, 'one amout should be positive');
uint amoutStartingToken = _amount0 == 0 ? _amount1 : _amount0;
path[0] = _amount0 == 0 ? token1 : token0;
path[1] = _amount0 == 0 ? token0 : token1;
IERC20 startingToken = IERC20(path[0]);
IERC20 targetToken = IERC20(path[1]);
startingToken.approve(address(sushiRouter), amoutStartingToken);
uint amountRequired = UniswapV2Library.getAmountsIn(
dex1FactoryAddress,
amoutStartingToken,
path
)[0];
sushiRouter
.swapExactTokensForTokensSupportingFeeOnTransferTokens(
amoutStartingToken,
amountRequired,
path,
sender,
deadline
);
assert(targetToken.transfer(msg.sender, amountRequired));
uint remainingBalance= targetToken.balanceOf(sender);
assert(targetToken.transfer(tx.origin, remainingBalance));
}
For testing purpose I add a 'sync' and 'skim' on both pair before and after flash loan.
I had try this code on ganche-cli and prod and still facing the same issue. Is it a problem with the 'amountRequired' that I am paying back? In the docs it is said that it should be calculated with 'getAmountsIn', that is what I am doing.
What is wrong with my code? I asked on the discord channel + stackoverflow, but it seems no one there knows how to make a flash loan on unsiwap.
I have the same issue.
I too have the same issue but during flashloan swap. Did you manage to find a resolution?
seems it cuz of the requireAmount isn't proper