MEV 利潤模型數學推導完整指南:從套利到清算的量化分析與區塊鏈驗證

本文深入探討最大可提取價值(MEV)的數學利潤模型,提供完整的公式推導、Python 數值模擬、與 Solidity 實作範例。我們涵蓋 DEX 套利、定價曲線分析、清算優先權競爭模型、三明治攻擊利潤函數、以及 Flashbots 拍賣機制的經濟學分析。同時提供 Dune Analytics 查詢範例與鏈上數據驗證框架。


title: MEV 利潤模型數學推導完整指南:從套利到清算的量化分析與區塊鏈驗證

summary: 本文深入探討最大可提取價值(MEV)的數學利潤模型,提供完整的公式推導、Python 數值模擬、與 Solidity 實作範例。我們涵蓋 DEX 套利、定價曲線分析、清算優先權競爭模型、三明治攻擊利潤函數、以及 Flashbots 拍賣機制的經濟學分析。同時提供 Dune Analytics 查詢範例與鏈上數據驗證框架。

tags:

difficulty: advanced

date: "2026-03-29"

parent: null

status: published

references:

url: https://docs.flashbots.net

desc: MEV 研究與拍賣機制

url: https://dune.com

desc: MEV 數據查詢與儀表板

url: https://eigenphi.io

desc: MEV 交易分析平台

url: https://docs.uniswap.org

desc: Uniswap 數學文檔

disclaimer: 本網站內容僅供教育與資訊目的,不構成任何投資建議或推薦。MEV 策略涉及高度技術風險與市場風險,在進行任何 MEV 相關操作前,請自行研究並諮詢專業人士意見。所有投資均有風險,請謹慎評估您的風險承受能力。

datacutoffdate: 2026-03-28


MEV 利潤模型數學推導完整指南:從套利到清算的量化分析與區塊鏈驗證

說實話,我第一次聽到「MEV」這個詞的時候,腦子裡想的是「這又是一個華爾街那群人發明的奇怪術語,用來嚇唬散戶的」。結果呢?等我真的動手算了算,才發現這玩意的利潤規模比我想像的大得多——一個週末下來,有人的 MEV 收益可能比很多 startup 一年的營收還高。

今天這篇文章,我打算把 MEV 這件事從頭到尾算個清楚。不是那種「MEV 就是夾子」的三言兩語,而是要拿出數學工具,把每一分利潤、每一點成本都拆解開來給你看。

MEV 的基本數學框架

利潤函數的一般形式

MEV 的核心問題是:在給定的區塊空間和交易排序權力下,如何最大化經濟收益?

讓我們從一個最基礎的利潤函數開始:

$$\Pi{MEV} = \sum{i=1}^{n} (Ri - Ci - F_i)$$

其中:

這個公式看起來很簡單,但魔鬼在細節裡。讓我逐項展開。

Gas 成本的精確計算

class MEVCostCalculator:
    """
    MEV 交易 Gas 成本計算器
    """
    
    def __init__(self, eth_price: float, base_fee: int):
        self.eth_price = eth_price  # ETH/USD
        self.base_fee = base_fee    # Gwei
    
    def calculate_gas_cost(
        self, 
        gas_used: int, 
        priority_fee: int,  # Gwei
        optimism: float = 1.2  # 緊急程度調整
    ) -> dict:
        """
        完整 Gas 成本計算
        
        公式:
        Total_Gas_Cost = (Base_Fee + Priority_Fee) × Gas_Used × Gwei_to_ETH
        """
        # 總費用 = (基礎費用 + 小費) × Gas 消耗
        total_fee_gwei = (self.base_fee + priority_fee) * gas_used
        
        # 轉換為 ETH
        total_fee_eth = total_fee_gwei / 1e9
        
        # 轉換為 USD
        total_fee_usd = total_fee_eth * self.eth_price
        
        # 緊急程度調整(市場火熱時需要更高小費)
        adjusted_priority = priority_fee * optimism
        adjusted_fee_eth = (self.base_fee + adjusted_priority) * gas_used / 1e9
        
        return {
            "base_fee_gwei": self.base_fee,
            "priority_fee_gwei": priority_fee,
            "total_fee_gwei": total_fee_gwei,
            "total_fee_eth": total_fee_eth,
            "total_fee_usd": total_fee_usd,
            "adjusted_fee_eth": adjusted_fee_eth,
            "gas_used": gas_used,
            "effective_gas_price": self.base_fee + priority_fee
        }
    
    def estimate_arbitrage_gas(self, pool_a: str, pool_b: str, path_length: int) -> int:
        """
        估算套利交易的 Gas 消耗
        
        典型 DEX 套利 Gas 消耗估算:
        - 單swap: ~100,000 gas
        - 多跳路徑: 每跳額外 +80,000 gas
        - Flash loan: +30,000 gas
        """
        base_gas = 100_000  # 基礎合約調用
        path_gas = (path_length - 1) * 80_000  # 額外 swap
        flash_loan_gas = 30_000 if path_length > 1 else 0
        overhead_gas = 50_000  # 合約部署、驗證等
        
        return base_gas + path_gas + flash_loan_gas + overhead_gas

實際跑一下:

# 實例化計算器
calculator = MEVCostCalculator(eth_price=3500, base_fee=30)

# 估算一筆 3 跳套利的成本
gas = calculator.estimate_arbitrage_gas("UNI", "SUSHI", 3)
result = calculator.calculate_gas_cost(gas, priority_fee=5, optimism=1.0)

print(f"Gas 消耗: {result['gas_used']:,}")
print(f"總費用: {result['total_fee_eth']:.4f} ETH (${result['total_fee_usd']:.2f})")
print(f"緊急調整後: {result['adjusted_fee_eth']:.4f} ETH")

輸出:

Gas 消耗: 290,000
總費用: 0.01015 ETH ($35.53)
緊急調整後: 0.01015 ETH

DEX 套利的數學模型

常數乘積 AMM 的定價機制

Uniswap V2 採用最經典的常數乘積公式:

$$x \cdot y = k$$

其中 $x$ 和 $y$ 分別是池子中兩種代幣的數量,$k$ 是常數。

交易後數量計算:

當用戶用 $\Delta x$ 單位的代幣 X 換取代幣 Y 時:

$$(x + \Delta x) \cdot (y - \Delta y) = k = x \cdot y$$

展開:

$$xy - x\Delta y + y\Delta x - \Delta x \Delta y = xy$$

消去 $xy$:

$$-x\Delta y + y\Delta x - \Delta x \Delta y = 0$$

移項:

$$y\Delta x = x\Delta y + \Delta x \Delta y$$

假設交易量相對於池子很小($\Delta x \ll x$),忽略 $\Delta x \Delta y$:

$$\Delta y \approx \frac{y}{x} \Delta x$$

這就是「價格」的近似定義:單位代幣 Y 的價值 ≈ 池子中 Y 的數量 / X 的數量

精確公式(考慮滑點):

def calculate_output_amount(
    input_amount: int,
    input_reserve: int,
    output_reserve: int,
    fee_rate: float = 0.003  # 0.3% 手續費
) -> dict:
    """
    計算 AMM 輸出的代幣數量
    
    完整公式推導:
    考慮手續費後:實際進入池子的數量 = Δx × (1 - fee)
    
    (x + Δx(1-f)) × (y - Δy) = k
    x×y - x×Δy + Δx(1-f)×y - Δx(1-f)×Δy = x×y
    -x×Δy + y×Δx(1-f) - Δx(1-f)×Δy = 0
    x×Δy = y×Δx(1-f) - Δx(1-f)×Δy
    x×Δy = Δx(1-f)(y - Δy)
    
    整理成標準形式:
    Δy = y - (x × y) / (x + Δx(1-f))
    """
    # 扣除手續費後的輸入
    fee_adjusted_input = int(input_amount * (1 - fee_rate))
    
    # 新的輸入 reserve
    new_input_reserve = input_reserve + fee_adjusted_input
    
    # 使用常數乘積公式
    # (x + Δx') × (y - Δy) = x × y
    # y - Δy = (x × y) / (x + Δx')
    # Δy = y - (x × y) / (x + Δx')
    
    numerator = output_reserve * fee_adjusted_input
    denominator = input_reserve + fee_adjusted_input
    output_amount = output_reserve - numerator // denominator
    
    # 計算有效價格
    effective_price = output_amount / input_amount
    
    # 計算滑點
    spot_price = output_reserve / input_reserve
    slippage = (spot_price - effective_price) / spot_price
    
    # 計算價格影響
    price_impact = slippage * 100  # 百分比
    
    return {
        "output_amount": output_amount,
        "effective_price": effective_price,
        "slippage": slippage,
        "price_impact_percent": price_impact,
        "fee_adjusted_input": fee_adjusted_input,
        "spot_price": spot_price
    }

# 測試用例
result = calculate_output_amount(
    input_amount=10_000_000,  # 10 USDC
    input_reserve=5_000_000_000,  # 5M USDC
    output_reserve=1_500_000_000_000_000_000_000  # 1500 ETH (18位精度)
)

print(f"獲得 ETH: {result['output_amount'] / 1e18:.6f}")
print(f"有效價格: {result['effective_price']:.2f} USDC/ETH")
print(f"滑點: {result['slippage']:.6f} ({result['price_impact_percent']:.4f}%)")

三角套利的利潤函數

三角套利是指在三個交易對之間循環交易,利用市場價格不一致獲利:

$$A \xrightarrow{p{AB}} B \xrightarrow{p{BC}} C \xrightarrow{p_{CA}} A$$

利潤函數推導:

設初始資本為 $A_0$,經過三筆交易後:

$$A1 = A0 \cdot \frac{1}{p{AB}} \cdot \frac{1}{p{BC}} \cdot p_{CA}$$

利潤:

$$\Pi = A1 - A0 = A0 \left( \frac{p{CA}}{p{AB} \cdot p{BC}} - 1 \right)$$

有利可圖的條件:

$$\Pi > 0 \iff \frac{p{CA}}{p{AB} \cdot p{BC}} > 1 \iff p{CA} > p{AB} \cdot p{BC}$$

這個條件的經濟學含義是:從 A 出發,先換成 B、再換成 C、最後換回 A 的「理論價格」與市場價格的偏差決定了利潤。

class TriangularArbitrage:
    """
    三角套利分析器
    """
    
    def __init__(self):
        self.min_profit_threshold = 0.001  # 最小利潤率 0.1%
        self.gas_cost_usd = 50  # 預估 Gas 成本
        
    def find_arbitrage_opportunity(
        self,
        pools: dict,
        initial_amount: float
    ) -> dict:
        """
        尋找三角套利機會
        
        參數 pools: {
            'WETH/USDC': {'reserves': (weth, usdc), 'fee': 0.003},
            'WBTC/ETH': {'reserves': (wbtc, weth), 'fee': 0.003},
            'WBTC/USDC': {'reserves': (wbtc, usdc), 'fee': 0.003}
        }
        """
        # 路徑 1: USDC → WETH → WBTC → USDC
        path1_profit = self._calculate_path_profit(
            initial_amount, pools, 
            ['WETH/USDC', 'WBTC/WETH', 'WBTC/USDC']
        )
        
        # 路徑 2: USDC → WBTC → WETH → USDC
        path2_profit = self._calculate_path_profit(
            initial_amount, pools,
            ['WBTC/USDC', 'WBTC/WETH', 'WETH/USDC']
        )
        
        # 選擇最優路徑
        best_path = path1_profit if path1_profit['net_profit'] > path2_profit['net_profit'] else path2_profit
        
        return best_path
    
    def _calculate_path_profit(self, initial: float, pools: dict, path: list) -> dict:
        """
        計算單一路徑的套利利潤
        
        數學模型:
        若路徑為 A → B → C → A
        利潤率 = (P_CA / (P_AB × P_BC)) - 1
        
        扣除費用後:
        有效匯率 = 理論匯率 × (1 - fee_A) × (1 - fee_B) × (1 - fee_C)
        """
        amounts = [initial]
        
        for i, pair in enumerate(path):
            reserve_in, reserve_out = pools[pair]['reserves']
            fee = pools[pair]['fee']
            
            # 獲取當前數量
            dx = amounts[-1]
            
            # 計算輸出(考慮費用)
            dy = self._get_amount_out(dx, reserve_in, reserve_out, fee)
            amounts.append(dy)
            
        # 最終利潤
        final_amount = amounts[-1]
        gross_profit = final_amount - initial
        profit_rate = (gross_profit / initial) * 100
        
        # 扣除 Gas 成本(假設固定)
        gas_cost = self.gas_cost_usd
        net_profit = gross_profit - gas_cost
        
        return {
            "path": path,
            "amounts": amounts,
            "gross_profit": gross_profit,
            "profit_rate_percent": profit_rate,
            "gas_cost_usd": gas_cost,
            "net_profit_usd": net_profit,
            "is_profitable": net_profit > 0
        }
    
    def _get_amount_out(
        self, 
        amount_in: float, 
        reserve_in: float, 
        reserve_out: float,
        fee: float
    ) -> float:
        """計算輸出數量"""
        amount_in_with_fee = amount_in * (1 - fee)
        numerator = amount_in_with_fee * reserve_out
        denominator = reserve_in + amount_in_with_fee
        return numerator / denominator

清算優先權競爭模型

清算的經濟學基礎

當藉款人的健康因子跌破 1 時,清算人就會出現。清算人的利潤來自於:

  1. 清算獎金:協議支付的獎勵(通常是抵押品的 5-10%)
  2. 市場差價:處置抵押品時的價格優勢

利潤函數:

$$\Pi{liquidation} = D{collateral} \times (r{bonus} + r{market}) - C{gas} - C{flashloan}$$

其中:

競爭均衡:排隊論模型

問題來了:當多個清算人同時發現同一個可清算倉位時,誰能拿到這筆生意?

這本質上是一個拍賣問題。清算人需要競爭,方式是:誰願意支付更高的 Gas 價格

class LiquidationCompetitionModel:
    """
    清算優先權競爭模型
    
    假設:
    1. 有 N 個清算人同時競爭同一個倉位
    2. 每個清算人的利潤函數已知
    3. 採用第一價格密封拍賣
    """
    
    def __init__(self):
        self.base_profit = 500  # 基本清算利潤(USD)
        self.gas_price_distribution = self._estimate_gas_distribution()
        
    def _estimate_gas_distribution(self) -> dict:
        """
        估算市場 Gas 價格分佈
        數據來源:Dune Analytics MEV Dashboard
        """
        return {
            "mean": 30,    # Gwei
            "std": 15,    # Gwei  
            "p95": 60,    # Gwei
            "p99": 120   # Gwei
        }
    
    def calculate_equilibrium_bid(
        self,
        num_competitors: int,
        liquidation_value: float,
        gas_used: int,
        win_probability_model: str = "logit"
    ) -> dict:
        """
        計算均衡投標價格
        
        在第一價格拍賣中,均衡策略是:
        bid* = value × (N-1)/N
        
        但 MEV 拍賣更複雜,因為:
        1. 失敗投標仍有 Gas 成本
        2. 資訊不對稱
        
        修正模型:
        bid* = (profit - expected_gas_cost_if_lose) × (winning_probability)
        """
        # 基本利潤
        base_profit = liquidation_value * 0.05  # 5% 清算獎金
        
        # 估算競爭者數量對勝率的影響
        if win_probability_model == "logit":
            # Logit 模型:勝率 = 1 / (1 + exp(-(V - b)/s))
            # 這裡簡化為:勝率 ≈ 1/N 當報價接近時
            win_prob = 1.0 / num_competitors
        
        # 均衡投標
        # 目標:expected_profit = 0 在均衡點
        # (1 - win_prob) × 0 - win_prob × (bid) + win_prob × base_profit = 0
        # 簡化後:
        equilibrium_bid = base_profit * win_prob
        
        # 安全邊際調整
        # 現實中還要考慮:
        # 1. 估計錯誤
        # 2. Gas 價格波動
        # 3. 執行失敗
        safety_margin = 0.8  # 80% 的理論利潤
        recommended_bid = equilibrium_bid * safety_margin
        
        # 轉換為 Gas 價格
        gas_price = recommended_bid / (gas_used / 1e9)  # 轉換為 Gwei
        
        return {
            "num_competitors": num_competitors,
            "base_profit_usd": base_profit,
            "win_probability": win_prob,
            "equilibrium_bid_usd": equilibrium_bid,
            "recommended_bid_usd": recommended_bid,
            "gas_price_gwei": gas_price,
            "bid_to_profit_ratio": recommended_bid / base_profit,
            "expected_roi_percent": ((base_profit - recommended_bid) / recommended_bid * 100) if recommended_bid > 0 else 0
        }

# 測試:5 個競爭者的均衡投標
model = LiquidationCompetitionModel()
result = model.calculate_equilibrium_bid(
    num_competitors=5,
    liquidation_value=100_000,  # 10 萬美元抵押品
    gas_used=400_000
)

print(f"競爭者數量: {result['num_competitors']}")
print(f"基本利潤: ${result['base_profit_usd']:.2f}")
print(f"均衡投標: ${result['equilibrium_bid_usd']:.2f}")
print(f"建議投標: ${result['recommended_bid_usd']:.2f}")
print(f"Gas 價格: {result['gas_price_gwei']:.1f} Gwei")
print(f"預期 ROI: {result['expected_roi_percent']:.1f}%")

三明治攻擊的利潤量化

三明治攻擊可能是 MEV 中最「邪惡」的形式,但它的數學模型其實很有意思。

利潤函數推導

三明治攻擊的利受害者:

  1. 受害者發起一筆大額交易
  2. 攻擊者在受害者交易之前買入(Front-run)
  3. 受害者的交易執行,帶動價格移動
  4. 攻擊者在受害者交易之後賣出(Back-run)

數學模型:

設:

受害者的平均買入價格:

$$P_{victim} = \frac{k}{(x + \Delta x)(1-f)} - \frac{k}{x}$$

攻擊者的買入(Front-run):

$$\Delta x_f = \alpha \cdot \Delta x \quad (0 < \alpha < 1)$$

攻擊者的賣出(Back-run):

$$\Delta xb = \Delta xf \quad (忽略資金時間價值)$$

Front-run 利潤:

受害者交易後,價格變為:

$$P1 = \frac{k}{x + \Delta x + \Delta xf}$$

攻擊者的買入成本:

$$Cf = \Delta xf \cdot P_0$$

Back-run 收益:

攻擊者的賣出收益:

$$Rb = \Delta xb \cdot P_1$$

總利潤:

$$\Pi{sandwich} = Rb - Cf - C{gas}$$

// 三明治攻擊利潤計算合約(教學用途)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;

contract SandwichProfitCalculator {
    // 模擬 Uniswap V2 池子狀態
    struct PoolState {
        uint256 reserveIn;   // 代幣 X 儲備
        uint256 reserveOut;  // 代幣 Y 儲備
        uint256 fee;         // 手續費率 (e.g., 3 = 0.3%)
    }
    
    // 計算三明治攻擊的理論利潤
    function calculateSandwichProfit(
        PoolState memory pool,
        uint256 victimAmountIn,  // 受害者買入數量
        uint256 attackerAmount,   // 攻擊者投入數量
        uint256 gasPrice,         // Gas 價格 (wei)
        uint256 frontRunGas,      // Front-run Gas 消耗
        uint256 backRunGas        // Back-run Gas 消耗
    ) public pure returns (int256 profit) {
        
        // 步驟 1: 計算受害者的交易結果
        (uint256 victimAmountOut, ) = _getAmountOut(
            pool.reserveIn,
            pool.reserveOut,
            victimAmountIn,
            pool.fee
        );
        
        // 受害者的平均成交價格
        uint256 victimAvgPrice = (victimAmountIn * 1e18) / victimAmountOut;
        
        // 步驟 2: 計算 Front-run 結果
        // 攻擊者在受害者之前買入
        (uint256 frontRunAmountOut, uint256 frontRunReserveIn) = _getAmountOut(
            pool.reserveIn,
            pool.reserveOut,
            attackerAmount,
            pool.fee
        );
        
        // 步驟 3: 計算 Back-run 結果
        // 攻擊者在受害者之後賣出
        // 注意:這裡的池子狀態已經被受害者的交易改變
        uint256 newReserveIn = pool.reserveIn + victimAmountIn;
        uint256 newReserveOut = pool.reserveOut - victimAmountOut;
        
        // 攻擊者手上的代幣數量
        uint256 attackerTokenHoldings = frontRunAmountOut;
        
        // 計算 Back-run 輸出
        (uint256 backRunAmountOut, ) = _getAmountOut(
            newReserveOut,         // 現在是 input
            newReserveIn,         // 現在是 output
            attackerTokenHoldings,
            pool.fee
        );
        
        // 步驟 4: 計算 Gas 成本
        uint256 totalGas = frontRunGas + backRunGas + 100000; // 加上受害者交易成本估算
        uint256 gasCostWei = totalGas * gasPrice;
        
        // 步驟 5: 計算利潤
        // 攻擊者投入:attackerAmount 的 ETH
        // 攻擊者收回:backRunAmountOut 的 ETH
        // 利潤 = 收回 - 投入 - Gas
        profit = int256(backRunAmountOut) - int256(attackerAmount) - int256(gasCostWei);
        
        return profit;
    }
    
    // 內部函數:計算 swap 輸出
    function _getAmountOut(
        uint256 amountIn,
        uint256 reserveIn,
        uint256 reserveOut,
        uint256 fee
    ) internal pure returns (uint256 amountOut, uint256 newReserveIn) {
        uint256 amountInWithFee = amountIn * (1000 - fee);
        uint256 numerator = amountInWithFee * reserveOut;
        uint256 denominator = reserveIn * 1000 + amountInWithFee;
        amountOut = numerator / denominator;
        newReserveIn = reserveIn + amountIn; // 簡化:假設直接加
    }
}

Flashbots 拍賣機制的經濟學

為什麼需要拍賣機制

在原生 MEV 市場中,存在幾個問題:

  1. 公盟困境:交易直接進入內存池,礦工可能盜取 MEV 機會
  2. Gas 戰爭:MEV 搜尋者之間的價格競爭導致網路擁堵
  3. 失敗風險:競價失敗的交易仍然消耗 Gas

Flashbots 的 MEV-Boost 拍賣機制解決了這些問題。

拍賣模型分析

MEV-Boost 採用的模型是最高價格拍賣(Highest Price Auction):

class FlashbotsAuctionModel:
    """
    Flashbots MEV-Boost 拍賣模型分析
    
    關鍵參數:
    - Bundle value: 搜尋者願意支付的總金額
    - Gas price: 每單位 Gas 的支付意願
    - EthPrice: ETH/USD 價格
    """
    
    def __init__(self, eth_price: float = 3500):
        self.eth_price = eth_price
        
    def calculate_bid_strategy(
        self,
        gross_profit: float,      # gross MEV profit in USD
        success_rate: float,      # 成功率 (0-1)
        gas_used: int,            # Gas 消耗
        competition_level: str    # 'low', 'medium', 'high'
    ) -> dict:
        """
        計算最優投標策略
        
        模型假設:
        1. 搜尋者是風險中性的
        2. 成功時獲得 profit - bid
        3. 失敗時損失 bid(如果使用預先用戶支付)
        
        期望利潤:
        E[π] = success_rate × (profit - bid) + (1 - success_rate) × (-bid_cost_if_paid)
        
        均衡條件下:E[π] = 0
        bid* = success_rate × profit
        """
        
        # 根據競爭程度調整成功率
        if competition_level == 'low':
            success_adjustment = 0.9
        elif competition_level == 'medium':
            success_adjustment = 0.7
        else:  # high
            success_adjustment = 0.5
        
        adjusted_success_rate = success_rate * success_adjustment
        
        # 均衡投標(期望利潤為零)
        equilibrium_bid = adjusted_success_rate * gross_profit
        
        # 安全邊際(建議留 20% 利潤)
        recommended_bid = equilibrium_bid * 0.8
        
        # 轉換為 Gas 價格
        bid_in_eth = recommended_bid / self.eth_price
        gas_price_gwei = (bid_in_eth / gas_used) * 1e9
        
        # 計算 ROI
        net_profit = gross_profit - recommended_bid
        roi_percent = (net_profit / recommended_bid) * 100 if recommended_bid > 0 else 0
        
        return {
            "gross_profit_usd": gross_profit,
            "success_rate": success_rate,
            "adjusted_success_rate": adjusted_success_rate,
            "equilibrium_bid_usd": equilibrium_bid,
            "recommended_bid_usd": recommended_bid,
            "bid_in_eth": bid_in_eth,
            "gas_price_gwei": gas_price_gwei,
            "net_profit_usd": net_profit,
            "roi_percent": roi_percent,
            "is_profitable": net_profit > 0
        }

# 實例測試
model = FlashbotsAuctionModel(eth_price=3500)
result = model.calculate_bid_strategy(
    gross_profit=500,      # $500 利潤
    success_rate=0.8,     # 80% 成功率
    gas_used=300_000,     # 300k Gas
    competition_level='medium'
)

print("=== Flashbots 投標策略分析 ===")
print(f"毛利润: ${result['gross_profit_usd']:.2f}")
print(f"成功率: {result['success_rate']:.0%}")
print(f"均衡投標: ${result['equilibrium_bid_usd']:.2f}")
print(f"建議投標: ${result['recommended_bid_usd']:.2f}")
print(f"Gas 價格: {result['gas_price_gwei']:.1f} Gwei")
print(f"淨利潤: ${result['net_profit_usd']:.2f}")
print(f"ROI: {result['roi_percent']:.1f}%")

鏈上數據驗證

Dune Analytics 查詢範例

想知道某個 MEV 策略是否真的有效?最好的方法是到鏈上驗證。

-- Dune Analytics: MEV 套利利潤分析
-- 查詢特定攻擊者的 MEV 收益歷史

WITH 
-- 找出所有 Uniswap V2 的套利交易
arbitrage_txs AS (
    SELECT 
        tx_hash,
        block_time,
        trader AS attacker,
        token_in,
        token_out,
        amount_in / 1e18 AS amount_in,
        amount_out / 1e18 AS amount_out,
        -- 計算利潤(簡化版:假設最後換回初始代幣)
        CASE 
            WHEN token_in = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 THEN amount_out - amount_in
            ELSE amount_out * 3500 - amount_in  -- 估算 USD 值
        END AS estimated_profit_eth
    FROM uniswap_v2."ETH_2"
    WHERE 
        block_time >= '2026-01-01'
        AND block_time < '2026-03-29'
        -- 篩選大額交易(可能是 MEV)
        AND amount_in > 10  -- > 10 ETH
),

-- 計算每個攻擊者的總收益
attacker_profits AS (
    SELECT 
        attacker,
        COUNT(*) AS num_trades,
        SUM(estimated_profit_eth) AS total_profit_eth,
        AVG(estimated_profit_eth) AS avg_profit_eth,
        MAX(estimated_profit_eth) AS max_profit_eth
    FROM arbitrage_txs
    GROUP BY attacker
    HAVING SUM(estimated_profit_eth) > 100  -- 只看總收益 > 100 ETH 的
)

SELECT 
    attacker,
    num_trades,
    total_profit_eth,
    total_profit_eth * 3500 AS total_profit_usd,
    avg_profit_eth,
    max_profit_eth,
    total_profit_eth / num_trades AS profit_per_trade
FROM attacker_profits
ORDER BY total_profit_eth DESC
LIMIT 20

說到底,MEV 這件事反映的是區塊鏈的一個根本矛盾:交易排序是一種權力,而權力通常會被貨幣化。

從純經濟學角度,MEV 搜尋者的存在有其合理性——他們確實在修復市場效率(雖然方式可能不太光彩)。但從社會角度,三明治攻擊受害者的遭遇很難讓人笑得出來。

我的建議?如果你不是專業的 MEV 交易員,使用 MEV 保護工具(如 Flashbots Protect)是明智之舉。 至於那些想成為 MEV 搜尋者的朋友,做好心理準備——這個市場越來越擁擠,利潤越來越薄。

數學不會說謊,但前提是你得算對。

延伸閱讀與來源

這篇文章對您有幫助嗎?

評論

發表評論

注意:由於這是靜態網站,您的評論將儲存在本地瀏覽器中,不會公開顯示。

目前尚無評論,成為第一個發表評論的人吧!