// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@aave/protocol-v2/contracts/flashloan/base/FlashLoanReceiverBase.sol";
import "@aave/protocol-v2/contracts/interfaces/ILendingPool.sol";
// DEX Interfaces
interface IUniswapV2Router02 {
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
}
interface IOneInchRouter {
function swap(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 minReturnAmount,
uint256 flags,
bytes calldata data
) external returns (uint256 returnAmount);
}
contract ArbitrageBot is ReentrancyGuard, Ownable, FlashLoanReceiverBase {
using SafeERC20 for IERC20;
// DEX router addresses
address public uniswapRouter;
address public sushiswapRouter;
address public oneInchRouter;
// Constants
uint256 public constant MAX_SLIPPAGE = 200; // 2% slippage tolerance (basis points)
// Events
event ArbitrageExecuted(
address indexed tokenA,
address indexed tokenB,
uint256 amountIn,
uint256 amountOut,
uint256 profit
);
event FlashLoanExecuted(
address indexed token,
uint256 amount,
uint256 fee
);
event TradeExecuted(
address indexed dex,
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
event LiquidityCheckFailed(
address indexed dex,
address indexed tokenIn,
address indexed tokenOut,
uint256 requestedAmount
);
/**
* @dev Constructor to initialize DEX router addresses and lending pool
* @param _uniswapRouter Address of Uniswap V2 Router
* @param _sushiswapRouter Address of SushiSwap Router
* @param _oneInchRouter Address of 1inch Router
* @param _lendingPoolAddressesProvider Address of Aave lending pool provider
*/
constructor(
address _uniswapRouter,
address _sushiswapRouter,
address _oneInchRouter,
address _lendingPoolAddressesProvider
) FlashLoanReceiverBase(_lendingPoolAddressesProvider) {
uniswapRouter = _uniswapRouter;
sushiswapRouter = _sushiswapRouter;
oneInchRouter = _oneInchRouter;
}
/**
* @dev Execute arbitrage between DEXs
* @param _tokenA The first token in the trade path
* @param _tokenB The second token in the trade path
* @param _amount The amount of _tokenA to borrow for arbitrage
*/
function executeArbitrage(
address _tokenA,
address _tokenB,
uint256 _amount
) external onlyOwner nonReentrant {
// Check if arbitrage is profitable before proceeding
require(isProfitable(_tokenA, _tokenB, _amount), "Arbitrage not profitable");
// Request flash loan from Aave
address[] memory assets = new address[](1);
assets[0] = _tokenA;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _amount;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
// Store arbitrage data to be used in executeOperation
bytes memory params = abi.encode(_tokenA, _tokenB);
LENDING_POOL.flashLoan(
address(this),
assets,
amounts,
modes,
address(this),
params,
0
);
}
/**
* @dev Callback function called by Aave after flash loan
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
// Ensure callback is from the lending pool
require(msg.sender == address(LENDING_POOL), "Callback not from lending pool");
require(initiator == address(this), "Initiator not this contract");
// Decode params
(address tokenA, address tokenB) = abi.decode(params, (address, address));
uint256 amountBorrowed = amounts[0];
uint256 fee = premiums[0];
uint256 totalDebt = amountBorrowed + fee;
// Execute arbitrage strategy
uint256 profit = executeArbitrageStrategy(tokenA, tokenB, amountBorrowed);
// Ensure we have enough to repay the loan plus fees
require(IERC20(assets[0]).balanceOf(address(this)) >= totalDebt, "Not enough funds to repay flash loan");
// Approve the LendingPool to pull the owed amount + fee
IERC20(assets[0]).safeApprove(address(LENDING_POOL), totalDebt);
emit FlashLoanExecuted(assets[0], amountBorrowed, fee);
return true;
}
/**
* @dev Check if an arbitrage opportunity is profitable
*/
function isProfitable(
address _tokenA,
address _tokenB,
uint256 _amount
) public view returns (bool) {
// Check liquidity first
if (checkLiquidity(_tokenA, _tokenB, _amount) == false) {
return false;
}
// Get the best rate from DEX 1
uint256 bestRateOutDex1 = getBestRateFromDex(_tokenA, _tokenB, _amount);
// Get the best rate from DEX 2 for the reverse trade
uint256 bestRateOutDex2 = getBestRateFromDex(_tokenB, _tokenA, bestRateOutDex1);
// Calculate the flash loan fee
uint256 flashLoanFee = (_amount * 9) / 10000; // Aave charges 0.09%
// Add a buffer for gas costs
uint256 gasCostInToken = (_amount * 5) / 10000; // Estimated 0.05% for gas
// Check if the final amount is greater than the initial amount plus fees
return bestRateOutDex2 > (_amount + flashLoanFee + gasCostInToken);
}
/**
* @dev Check if there's enough liquidity for the trade
*/
function checkLiquidity(
address _tokenA,
address _tokenB,
uint256 _amount
) public view returns (bool) {
// Check Uniswap liquidity
bool uniswapLiquidity = getUniswapRate(_tokenA, _tokenB, _amount) > 0;
// Check SushiSwap liquidity
bool sushiswapLiquidity = getSushiswapRate(_tokenA, _tokenB, _amount) > 0;
return uniswapLiquidity || sushiswapLiquidity;
}
/**
* @dev Get the best rate from available DEXs
*/
function getBestRateFromDex(
address _tokenIn,
address _tokenOut,
uint256 _amountIn
) public view returns (uint256) {
// Check Uniswap rate
uint256 uniswapRate = getUniswapRate(_tokenIn, _tokenOut, _amountIn);
// Check Sushiswap rate
uint256 sushiswapRate = getSushiswapRate(_tokenIn, _tokenOut, _amountIn);
// Return the best rate
return uniswapRate > sushiswapRate ? uniswapRate : sushiswapRate;
}
/**
* @dev Get estimated output amount from Uniswap
*/
function getUniswapRate(
address _tokenIn,
address _tokenOut,
uint256 _amountIn
) public view returns (uint256) {
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
try IUniswapV2Router02(uniswapRouter).getAmountsOut(_amountIn, path) returns (uint[] memory amounts) {
return amounts[1];
} catch {
return 0;
}
}
/**
* @dev Get estimated output amount from Sushiswap
*/
function getSushiswapRate(
address _tokenIn,
address _tokenOut,
uint256 _amountIn
) public view returns (uint256) {
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
try IUniswapV2Router02(sushiswapRouter).getAmountsOut(_amountIn, path) returns (uint[] memory amounts) {
return amounts[1];
} catch {
return 0;
}
}
/**
* @dev Execute the arbitrage strategy
*/
function executeArbitrageStrategy(
address _tokenA,
address _tokenB,
uint256 _amount
) internal returns (uint256) {
// Check initial balance
uint256 initialBalanceA = IERC20(_tokenA).balanceOf(address(this));
// Determine best DEX for first trade (_tokenA -> _tokenB)
uint256 uniswapRateAB = getUniswapRate(_tokenA, _tokenB, _amount);
uint256 sushiswapRateAB = getSushiswapRate(_tokenA, _tokenB, _amount);
uint256 amountB;
// Execute first trade on the DEX with better rate
if (uniswapRateAB > sushiswapRateAB) {
amountB = executeUniswapTrade(_tokenA, _tokenB, _amount);
} else {
amountB = executeSushiswapTrade(_tokenA, _tokenB, _amount);
}
// Check liquidity
require(amountB > 0, "Insufficient liquidity for first trade");
// Determine best DEX for second trade (_tokenB -> _tokenA)
uint256 uniswapRateBA = getUniswapRate(_tokenB, _tokenA, amountB);
uint256 sushiswapRateBA = getSushiswapRate(_tokenB, _tokenA, amountB);
uint256 finalAmountA;
// Execute second trade on the DEX with better rate
if (uniswapRateBA > sushiswapRateBA) {
finalAmountA = executeUniswapTrade(_tokenB, _tokenA, amountB);
} else {
finalAmountA = executeSushiswapTrade(_tokenB, _tokenA, amountB);
}
// Check final balance and calculate profit
uint256 finalBalanceA = IERC20(_tokenA).balanceOf(address(this));
uint256 profit = finalBalanceA - initialBalanceA;
emit ArbitrageExecuted(_tokenA, _tokenB, _amount, finalAmountA, profit);
return profit;
}
/**
* @dev Execute trade on Uniswap
*/
function executeUniswapTrade(
address _tokenIn,
address _tokenOut,
uint256 _amountIn
) internal returns (uint256) {
// Approve router to spend token
IERC20(_tokenIn).safeApprove(uniswapRouter, _amountIn);
// Setup path
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
// Calculate minimum output amount with slippage protection
uint256 expectedOutput = getUniswapRate(_tokenIn, _tokenOut, _amountIn);
uint256 minAmountOut = (expectedOutput * (10000 - MAX_SLIPPAGE)) / 10000;
// Execute swap
try IUniswapV2Router02(uniswapRouter).swapExactTokensForTokens(
_amountIn,
minAmountOut,
path,
address(this),
block.timestamp + 300 // 5 minutes deadline
) returns (uint[] memory amounts) {
emit TradeExecuted(uniswapRouter, _tokenIn, _tokenOut, _amountIn, amounts[1]);
return amounts[1];
} catch {
emit LiquidityCheckFailed(uniswapRouter, _tokenIn, _tokenOut, _amountIn);
return 0;
}
}
/**
* @dev Execute trade on Sushiswap
*/
function executeSushiswapTrade(
address _tokenIn,
address _tokenOut,
uint256 _amountIn
) internal returns (uint256) {
// Approve router to spend token
IERC20(_tokenIn).safeApprove(sushiswapRouter, _amountIn);
// Setup path
address[] memory path = new address[](2);
path[0] = _tokenIn;
path[1] = _tokenOut;
// Calculate minimum output amount with slippage protection
uint256 expectedOutput = getSushiswapRate(_tokenIn, _tokenOut, _amountIn);
uint256 minAmountOut = (expectedOutput * (10000 - MAX_SLIPPAGE)) / 10000;
// Execute swap
try IUniswapV2Router02(sushiswapRouter).swapExactTokensForTokens(
_amountIn,
minAmountOut,
path,
address(this),
block.timestamp + 300 // 5 minutes deadline
) returns (uint[] memory amounts) {
emit TradeExecuted(sushiswapRouter, _tokenIn, _tokenOut, _amountIn, amounts[1]);
return amounts[1];
} catch {
emit LiquidityCheckFailed(sushiswapRouter, _tokenIn, _tokenOut, _amountIn);
return 0;
}
}
/**
* @dev Execute trade on 1inch
*/
function executeOneInchTrade(
address _tokenIn,
address _tokenOut,
uint256 _amountIn,
bytes calldata _data
) internal returns (uint256) {
// Approve router to spend token
IERC20(_tokenIn).safeApprove(oneInchRouter, _amountIn);
// Calculate minimum output amount with slippage protection
uint256 expectedOutput = getBestRateFromDex(_tokenIn, _tokenOut, _amountIn);
uint256 minAmountOut = (expectedOutput * (10000 - MAX_SLIPPAGE)) / 10000;
// Execute swap
try IOneInchRouter(oneInchRouter).swap(
_tokenIn,
_tokenOut,
_amountIn,
minAmountOut,
0, // flags
_data
) returns (uint256 returnAmount) {
emit TradeExecuted(oneInchRouter, _tokenIn, _tokenOut, _amountIn, returnAmount);
return returnAmount;
} catch {
emit LiquidityCheckFailed(oneInchRouter, _tokenIn, _tokenOut, _amountIn);
return 0;
}
}
/**
* @dev Withdraw tokens from the contract (emergency function)
*/
function withdrawToken(address _token, uint256 _amount) external onlyOwner {
IERC20(_token).safeTransfer(owner(), _amount);
}
/**
* @dev Withdraw ETH from the contract (emergency function)
*/
function withdrawETH(uint256 _amount) external onlyOwner {
payable(owner()).transfer(_amount);
}
// Fallback function to receive ETH
receive() external payable {}
}
Would you like me to explain or break down the code?