Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
5.1 kB
5
Indexable
Never
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@aave/protocol-v2/contracts/interfaces/ILendingPool.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

contract MEVFlashbotArbitrage is Ownable, ReentrancyGuard {
    using SafeMath for uint256;

    ILendingPool public lendingPool;
    IUniswapV2Router02 public uniswapRouter;
    AggregatorV3Interface public priceOracle; // Chainlink price oracle for more accurate prices

    address public tokenA;
    address public tokenB;

    uint256 public slippageTolerance = 1; // Default 1% slippage tolerance
    uint256 public tradeDeadline = 600; // Default 10-minute deadline
    uint256 public minTradeSize = 100; // Minimum trade size to execute

    event ArbitrageExecuted(address indexed executor, uint256 profit);

    constructor(
        address _lendingPoolAddress,
        address _uniswapRouterAddress,
        address _tokenA,
        address _tokenB,
        address _priceOracle
    ) {
        lendingPool = ILendingPool(_lendingPoolAddress);
        uniswapRouter = IUniswapV2Router02(_uniswapRouterAddress);
        priceOracle = AggregatorV3Interface(_priceOracle);
        tokenA = _tokenA;
        tokenB = _tokenB;

        // Approve Aave lending pool to use the tokens
        IERC20(tokenA).approve(_lendingPoolAddress, type(uint256).max);

        // Approve Uniswap router to spend tokenA
        IERC20(tokenA).approve(_uniswapRouterAddress, type(uint256).max);

        // Approve Uniswap router to spend tokenB
        IERC20(tokenB).approve(_uniswapRouterAddress, type(uint256).max);
    }

    modifier validTradeSize(uint256 amount) {
        require(amount >= minTradeSize, "Trade size below minimum");
        _;
    }

    function executeArbitrage(uint256 amount) external onlyOwner nonReentrant {
        require(IERC20(tokenA).balanceOf(address(this)) >= amount, "Insufficient balance for flash loan");
        lendingPool.flashLoan(address(this), tokenA, amount, abi.encode(tokenA, tokenB, amount));
    }

    function executeOperation(
        address sender,
        address underlying,
        uint256 amount,
        uint256,
        bytes calldata params
    ) external nonReentrant {
        (address tokenA, address tokenB, uint256 originalAmount) =
            abi.decode(params, (address, address, uint256));
        require(msg.sender == address(lendingPool), "Invalid sender");

        _executeArbitrageTrade(tokenA, tokenB, originalAmount);
        IERC20(underlying).approve(address(lendingPool), amount.add(2));
        lendingPool.repay(underlying, amount.add(2), 2, address(this));

        uint256 profit = calculateProfit();
        IERC20(tokenA).transfer(owner(), profit);

        emit ArbitrageExecuted(owner(), profit);
    }

    function _executeArbitrageTrade(
        address tokenA,
        address tokenB,
        uint256 amount
    ) internal validTradeSize(amount) {
        uint256 tokenBPrice = _getLatestTokenBPrice();
        address[] memory path = new address[](2);
        path[0] = tokenA;
        path[1] = tokenB;

        uint256[] memory amounts = uniswapRouter.swapExactTokensForTokens(
            amount,
            tokenBPrice.mul(slippageTolerance).div(100),
            path,
            address(this),
            block.timestamp + tradeDeadline
        );

        require(amounts[1] > 0, "Uniswap trade failed");
    }

    function calculateProfit() internal view returns (uint256) {
        uint256 balanceTokenBAfter = IERC20(tokenB).balanceOf(address(this));
        uint256 profit = balanceTokenBAfter.sub(IERC20(tokenB).balanceOf(owner()));

        uint256 slippage = balanceTokenBAfter.mul(slippageTolerance).div(100);
        return (profit > slippage) ? profit.sub(slippage) : 0;
    }

    function withdrawTokens(address token, uint256 amount) external onlyOwner {
        IERC20(token).transfer(owner(), amount);
    }

    function withdrawETH(uint256 amount) external onlyOwner {
        payable(owner()).transfer(amount);
    }

    function setUniswapRouter(address _uniswapRouterAddress) external onlyOwner {
        uniswapRouter = IUniswapV2Router02(_uniswapRouterAddress);
    }

    function setSlippageTolerance(uint256 _slippageTolerance) external onlyOwner {
        slippageTolerance = _slippageTolerance;
    }

    function setTradeDeadline(uint256 _tradeDeadline) external onlyOwner {
        tradeDeadline = _tradeDeadline;
    }

    function setMinTradeSize(uint256 _minTradeSize) external onlyOwner {
        minTradeSize = _minTradeSize;
    }

    function _getLatestTokenBPrice() internal view returns (uint256) {
        (, int256 price, , , ) = priceOracle.latestRoundData();
        require(price > 0, "Invalid Chainlink price");
        return uint256(price);
    }
}
Leave a Comment