Part-1: Intro to MEV(Maximal Extractable value) Attack

Part-1: Intro to MEV(Maximal Extractable value) Attack

posted 3 min read
  • MEV attacks happen when someone (usually a miner, validator, or bot) manipulates the order of pending transactions in Ethereum (EVM chains) to make extra money
  • This attaclk is done by front-running, back-running, sandwich or liquidation attacks

  • mempool -> this is a public memory pool, where all TNX are visible

  • bots and attackers scans mempool for higher and profitable trades

Note: This is just an intro for MEV attack with minimal code example. Part-2 will contain the code example for each attack type in MEV

How this attacks work?

  • valid user submits TNX for some operation -> attacker/bots scan the mempool for profitable opportunities or for high trades
  • before user submit and completes TNX -> attacker/bots manipulates the block/price/protocol to earn more profit

Core concepts of MEV

  • it is easier to take advantage of MEV opportunities on ethereum than bitcoin
  • Due to Ethereum account model as compared to Bitcoin UTXO model

  • arbitrage trading

  • liquidation
  • sandwiching

Types of MEV Attacks

  1. Front-running attack:
  • An attacker/bot scans mempool for higher trading price and sees user TNX waiting to be processed and quickly submits their own -> just ahead of yours
// protocol will submit TNX to select a winner ->  attacker/bot sees TNX in mempool -> realizes they are not winner
// before protocol completes TNX and select a winner  ->   attacker refunds all token from protocol
// winner ends up getting lower winning price  -> attacker/bot gets their token
function selectWinner() external;
function refund(uint256 amount) external;
  • user submit TNX -> attacker/bot scans TNX in mempool -> attacker submit their own TNX before user can submit their TNX
  1. Sandwich attack:
  • An attacker places one transaction just before user and another just after user -> sandwiching your trade.
// attacker/bot TNX  ->>>  user TNX  ->>>   attacker/bot TNX
// user takes flashloan to buy token  ->  attacker/bot buys token before user  ->  increases the token price
// user buys token at higher price ->  after users TNX  ->  attacker/bot sells token at higher price
function flashloan(to, token, amount) external;
function Tswap(token, amount) external;
  • Attacker buys before you and sells after you ->>> earning profit and users ends up paying higher price
  1. Arbitrage MEV Attack:
  • An attacker exploits price differences for a token across different DEX's at the same time
// tokenA costs -> 100 USDC on uniswap
// tokenA costs -> 150 USDC on sushi at same time
// attacker/bots continuously scans mempool for higher trades and price changes
function tokenA_pool_uni(amount) external;
function tokenA_pool_sushi(amount) external;
  • attacker/bot always looks for higher and profitable trades in mempool to gain profit
  1. Liquidation MEV Attack:
  • On DeFi lending protocols, if someone’s loan goes under-collateralize (not enough assets to back the loan, e.g., in a price drop), anyone can repay their debt and claim their collateral—with a profit bonus.
  • MEV bots race to be first and claim the extra bonus
// A loan on Aave or Compound is about to be liquidated. 
// Bots spot the chance, quickly repay the debt, seize the collateral (often at a discount), 
// and resell it for a reward
  1. JIT (Just-In-Time) MEV Attack:

Simple contract example for MEV Attack

  • the contract is vulnerable to MEV attack
  • attacker/bot can scan mempool for TNX and password ->>> withdraws funds before user could
  • To run the code on remix checkout the below link(Thanks to CyfrinUpdraft):
    Run code on remix
contract FrontRan {
    error BadWithdraw();

    bytes32 public s_secretHash;

    event success();
    event fail();

    constructor(bytes32 secretHash) payable {
        s_secretHash = secretHash;
    }

    // userA -> call withdraw() with valid password to withdraw 100ETH
    // userB -> user MEV Bot frontrun the TNX, uses the valid password from userA's TNX and calls the withdraw()
    // userB -> withdraws 100ETH before userA withdraws funds
    function withdraw(string memory password) external payable {
        if (keccak256(abi.encodePacked(password)) == s_secretHash) {
            (bool sent,) = msg.sender.call{value: address(this).balance}("");
            if (!sent) {
                revert BadWithdraw();
            }
            emit success();
        } else {
            emit fail();
        }
    }
    function balance() external view returns (uint256) {
        return address(this).balance;
    }
}

Mitigation

  • Proper slippage protection
  • use of private RPC url and Private transactions (Flashbots, MEV-resistant chains).
  • And, base on protocol implement the protection

Resources

If you read this far, tweet to the author to show them you care. Tweet a Thanks
0 votes

More Posts

Advance EVM - Opcodes, low-level calls and instructions

abiEncode - Jul 3

Private variables are not really private on EVM

abiEncode - Jul 8

Introduction to solidity smart contracts storage layout -- What are risks in manipulating storage???

abiEncode - Jun 30

Blockchain File Storage---What is IPFS and Types of web3 Storage

abiEncode - Jul 14

What are Price Oracle Manipulation Attacks in Blockchain contracts and EVM???

abiEncode - Jul 5
chevron_left