I'm creating a smart contract that can both make flash loans and swap tokens via 0x. I can call the flash loan and token swap functions just fine, but when I try to call the token swap within the flash loan callback, I get the error: execution reverted: SafeERC20: low-level call failed
.
If I understand this error correctly, I believe this means I'm not approving the tokens properly. Here's the gist of what my code looks like:
/// Make a flash loan.
function makeFlashLoan(...) {
IERC20(borrowedTokenAddress).approve(zrxSpender, uint256(-1));
lendingPool.flashLoan(...);
}
/// Callback for flash loan.
function executeOperation(...) {
IERC20(borrowedTokenAddress).approve(lendingPoolAddress, uint256(-1));
swapOnZrx(...);
}
/// Swap a token on 0x.
function swapOnZrx(...) {
IERC20(fromToken).approve(zrxSpender, uint256(-1));
...
(bool success,) = _swapTarget.call(_swapCallData);
...
}
If I make a transaction to just call swapOnZrx
, the transaction succeeds. Similarly, if I make a transaction to just call makeFlashLoan
with swapOnZrx
commented out, the transaction also succeeds. However, When I call makeFlashLoan
with the call to swapOnZrx
, I keep getting the SafeERC20 error.
Any help would be greatly appreciated as I've been struggling with this error for almost an entire day :(