I am building a smart contract for flash loan swap, however, whenever I call my "flash" function I get "execution reverted: Dai/insufficient-balance". I read through your discussions but nothing solved it. can someone please guide me, I am kind of learning also.
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
interface IERC20 {
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
interface IUniswap {
function swapExactTokensForTokens(uint256, uint256, address[] calldata, address, uint256) external returns (uint256[] memory);
function swapExactETHForTokens(uint256, address[] calldata, address, uint256) external payable returns (uint256[] memory);
function WETH() external pure returns (address);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
}
contract FlashBot is Ownable {
using SafeMath for uint256;
uint256 public constant MAX_SLIPPAGE_RATIO = 5; // 5%
uint256 public constant MIN_PROFIT = 0.05 ether;
uint256 public constant MIN_TOKEN_BALANCE = 0.1 ether;
uint256 public constant TRADE_INTERVAL = 60; // 1 minute
uint256 public nextTradeTime;
address public uniswapV2Router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public WETH = IUniswap(uniswapV2Router).WETH();
event FlashLoanExecuted(address indexed user, address indexed token, uint256 flashLoanAmount, uint256 expectedAmount, uint256 profit);
function flash(address token, uint256 flashLoanAmount) public onlyOwner {
IERC20 tokenContract = IERC20(token);
IERC20 wethContract = IERC20(WETH);
require(tokenContract.approve(uniswapV2Router, flashLoanAmount), "Approval failed");
require(wethContract.approve(uniswapV2Router, flashLoanAmount), "WETH approval failed");
require(tokenContract.transferFrom(msg.sender, address(this), flashLoanAmount), "Token transfer failed");
// Add this code to approve the contract to spend tokens from the user's account
require(tokenContract.approve(address(this), 100000000000000), "Approval failed");
// Calculate the gas cost of the transaction
uint256 gasCost = gasleft() * tx.gasprice;
// Calculate the flash loan amount needed to cover the gas cost
uint256 flashLoanAmountWithGas = flashLoanAmount.add(gasCost);
// Execute the flash loan trade
address[] memory path = new address[](2);
path[0] = token;
path[1] = WETH;
// Swap the tokens for WETH
uint256[] memory amounts = IUniswap(uniswapV2Router).swapExactTokensForTokens(
flashLoanAmountWithGas,
0,
path,
address(this),
block.timestamp + 60
);