MEV 供應鏈數學建模完整指南:區塊建構者利潤最大化與拍賣機制的貝葉斯均衡分析

本文使用經濟學和博弈論工具建模 MEV 供應鏈的數學結構。涵蓋搜尋者利潤最大化模型、區塊建構者利潤最大化的一階條件、PBS 拍賣機制的貝葉斯Nash均衡分析,以及完整的 Python/TypeScript 實現程式碼。

MEV 供應鏈數學建模完整指南:區塊建構者利潤最大化與拍賣機制的貝葉斯均衡分析

前言

說到 MEV(Maximal Extractable Value,最大可提取價值),大家第一反應往往是「三明治攻擊」和「吸血鬼套利」。

但實際上,MEV 的世界比你想像的要複雜得多。

今天我想用經濟學和博弈論的工具,來建模 MEV 供應鏈的數學結構。我會推導區塊建構者利潤最大化的一階條件,會分析拍賣機制的貝葉斯均衡,還會用 Python 程式碼把這些模型實際跑一遍。

如果你對 MEV 的認知還停留在「搶先交易」層面,這篇文章會給你一個全新的視角。

第一章:MEV 供應鏈概述

1.1 MEV 供應鏈的參與者

MEV 供應鏈是一個多層級的經濟系統,主要參與者包括:

┌─────────────────────────────────────────────────────────────┐
│                    MEV 供應鏈結構                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  原始交易來源                                               │
│      │                                                     │
│      ├── 普通用戶的交易(Uniswap swap, lending, ...)     │
│      ├── 機器人交易(套利機器人、-liquidation bots)       │
│      └── 閃電貸交易(Flash loan attacks)                  │
│                                                             │
│  搜尋者(Searcher)                                        │
│      │                                                     │
│      ├── 識別利潤機會                                      │
│      ├── 構造 bundle(交易捆綁)                           │
│      └── 向建構者提交交易                                  │
│                                                             │
│  建構者(Builder)                                         │
│      │                                                     │
│      ├── 接收多個 bundle                                   │
│      ├── 排序和選擇交易                                    │
│      ├── 構造完整區塊                                      │
│      └── 向提議者提交區塊投標                              │
│                                                             │
│  提議者(Proposer/Validator)                               │
│      │                                                     │
│      └── 選擇最高價值的區塊                                 │
│                                                             │
└─────────────────────────────────────────────────────────────┘

1.2 MEV 的利潤來源

MEV 的本質是:區塊空間的優先權可以被貨幣化

讓我列出具體的利潤來源:

MEV 利潤來源分類:

1. 套利利潤(Arbitrage)
   - DEX 價格差異
   - 穩定幣脫錨
   - 跨市場價差

2. 清算利潤(Liquidation)
   - Aave/MakerDAO 清算
   - 健康因子跌破閾值
   - 清算獎勵分割

3.  sandwich 攻擊利潤
   - 前端交易
   -受害者交易
   - 後端交易
   - 扣除滑點

4. JIT 流動性攻擊
   - 在大宗交易前提供流動性
   - 交易後立即移除流動性

第二章:搜尋者模型

2.1 搜尋者的最優化問題

每個搜尋者都面臨這樣的決策:要不要提交這筆交易?

假設搜尋者發現了一個套利機會:

期望利潤

$$

E[\pi] = (1-p) \cdot \pi - p \cdot c

$$

搜尋者應該提交交易的條件是:

$$

E[\pi] > 0

$$

或者更嚴格地說:

$$

(1-p) \cdot \pi > p \cdot c

$$

即:

$$

\pi > \frac{p}{1-p} \cdot c

$$

2.2 競爭對搜尋者利潤的影響

在現實世界中,搜尋者之間的競爭會壓縮利潤空間。

讓我們建模這個競爭:

假設有 $n$ 個搜尋者同時發現了同一個套利機會。他們同時提交交易,但只有第一個被包含的交易才能獲得利潤。

博弈論模型

每個搜尋者面臨的決策是:是否提交交易?

收益矩陣(兩個搜尋者的情況):

                    提交                  不提交
    提交        (0, 0)              (π - fee, 0)
    不提交      (0, π - fee)        (0, 0)

π = 套利利潤(扣除 Gas)
fee = 區塊建構者費用

這個博弈有多個均衡,取決於具體的參數。

2.3 搜尋者利潤的 Python 模擬

import numpy as np
import matplotlib.pyplot as plt
from dataclasses import dataclass
from typing import List
import random

@dataclass
class Searcher:
    """搜尋者模型"""
    name: str
    capital: float  # 初始資金
    gas_cost: float  # Gas 成本(ETH)
    success_probability: float  # 單次成功率
    
    def expected_profit(self, opportunity_value: float, 
                        num_competitors: int) -> float:
        """
        計算期望利潤
        
        假設每個搜尋者獨立地嘗試機會,
        第一個成功的搜尋者獲得全部利潤
        """
        # 在 n 個競爭者中第一個成功的機率
        prob_first = self.success_probability
        for _ in range(num_competitors):
            prob_first *= (1 - self.success_probability)
        prob_first *= num_competitors
        
        # 期望利潤 = 第一名的機率 × 利潤 - Gas 成本
        expected = prob_first * opportunity_value - self.gas_cost
        return expected
    
    def should_submit(self, opportunity_value: float,
                     num_competitors: int,
                     threshold: float = 0) -> bool:
        """決定是否提交交易"""
        return self.expected_profit(opportunity_value, num_competitors) > threshold


def simulate_searcher_competition(
    num_searchers: int,
    opportunity_value: float,
    success_prob: float,
    gas_cost: float,
    num_simulations: int = 10000
) -> dict:
    """
    模擬搜尋者之間的競爭
    """
    profits = []
    
    for _ in range(num_simulations):
        # 每個搜尋者獨立地嘗試
        outcomes = [
            random.random() < success_prob 
            for _ in range(num_searchers)
        ]
        
        if any(outcomes):
            # 有人成功了,利潤歸第一個成功的搜尋者
            winner = outcomes.index(True)
            profit = opportunity_value - gas_cost
            profits.append(profit)
        else:
            # 沒人成功,所有人損失 Gas
            profits.append(-gas_cost)
    
    return {
        'mean_profit': np.mean(profits),
        'std_profit': np.std(profits),
        'success_rate': sum(1 for p in profits if p > 0) / len(profits),
        'profits': profits
    }


# 測試:模擬不同數量搜尋者的競爭
searcher_count_range = range(1, 20)
opportunity_value = 10.0  # ETH
gas_cost = 0.01  # ETH
success_prob = 0.3

results = []
for n in searcher_count_range:
    result = simulate_searcher_competition(
        num_searchers=n,
        opportunity_value=opportunity_value,
        success_prob=success_prob,
        gas_cost=gas_cost
    )
    results.append(result)
    print(f"搜尋者數量: {n:2d} | 平均利潤: {result['mean_profit']:7.4f} | "
          f"成功率: {result['success_rate']:.2%}")

# 繪圖
plt.figure(figsize=(12, 6))
means = [r['mean_profit'] for r in results]
stds = [r['std_profit'] for r in results]

plt.errorbar(list(searcher_count_range), means, yerr=stds, 
             fmt='o-', capsize=3, label='平均利潤 ± 標準差')
plt.axhline(y=0, color='r', linestyle='--', label='盈虧平衡線')
plt.xlabel('搜尋者數量')
plt.ylabel('利潤 (ETH)')
plt.title(f'MEV 套利機會利潤 vs 競爭者數量\n'
          f'(機會價值={opportunity_value} ETH, 成功率={success_prob})')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('searcher_competition_simulation.png', dpi=150)
plt.close()

2.4 競爭對利潤的影響——數學分析

讓我們嚴格地分析這個模型。

假設有 $n$ 個風險中性的搜尋者,競爭一個價值為 $V$ 的 MEV 機會。成功提取 MEV 的總成本是 $c$(主要是 Gas)。

每個搜尋者獨立地以機率 $p$ 成功執行交易(或者被包含到區塊中)。

單個搜尋者的期望利潤

$$

E[\pi_i] = P(\text{第 i 個搜尋者成功}) \cdot V - c

$$

其中:

$$

P(\text{第 i 個搜尋者成功}) = p \cdot (1-p)^{i-1}

$$

這個公式的意思是:搜尋者 $i$ 必須成功,而且前面 $i-1$ 個搜尋者都失敗了。

競爭均衡的特徵

在均衡中,搜尋者會持續進入,直到:

$$

p \cdot V \leq c

$$

為什麼?因為如果 $p \cdot V > c$,總是有搜尋者願意嘗試,這會導致更多的搜尋者進入,最終壓縮利潤到 $p \cdot V = c$。

關鍵結論

競爭會把搜尋者利潤壓縮到零附近(扣除 Gas 後)
這就是為什麼我們看到的 MEV 套利利潤往往很快消失

第三章:區塊建構者模型

3.1 建構者的利潤最大化問題

區塊建構者(Builder)的目標是最大化區塊利潤

一個區塊的價值可以分解為:

區塊總價值 = MEV 收入 - 建構成本 - 投標支付

其中:
- MEV 收入:區塊內交易的 MEV 總和
- 建構成本:計算、儲存、網路成本
- 投標支付:向提議者支付的費用

數學上,建構者的利潤函數是:

$$

\PiB = \sum{i \in \text{txs}} MEV_i - C(q) - \text{bid}

$$

其中 $C(q)$ 是建構成本,$q$ 是區塊大小(以 Gas 計算)。

3.2 建構成本函數

建構成本可以分為固定成本和變動成本:

$$

C(q) = C0 + cv \cdot q

$$

其中:

3.3 利潤最大化的一階條件

假設建構者面臨一個確定的 MEV 收入函數 $MEV(q)$。我們要找到最優的區塊大小 $q^*$。

最大化問題:

$$

\maxq \quad \Pi(q) = MEV(q) - C0 - c_v \cdot q - \text{bid}(q)

$$

一階條件(FOC):

$$

\frac{d\Pi}{dq} = \frac{dMEV}{dq} - c_v - \frac{d(\text{bid})}{dq} = 0

$$

即:

$$

\frac{dMEV}{dq} = c_v + \frac{d(\text{bid})}{dq}

$$

經濟解釋

邊際 MEV 收入 = 邊際建構成本 + 邊際投標支付

這個條件告訴我們:建構者應該擴展區塊,直到增加最後一單位交易所帶來的 MEV 收入,恰好被額外的成本和投標支付抵消。

3.4 實際的 MEV 收入函數

在現實中,MEV 收入並不是簡單的線性函數。讓我構造一個更現實的模型:

class BlockBuilder:
    """區塊建構者模型"""
    
    def __init__(self, gas_limit: int = 30_000_000):
        self.gas_limit = gas_limit
        self.base_cost = 0.1  # 固定成本(ETH)
        self.marginal_cost = 1e-9  # 變動成本(ETH per gas)
        
    def mev_revenue(self, gas_used: int, 
                   bundle_submissions: List[dict]) -> float:
        """
        計算區塊的 MEV 收入
        
        收入來自:
        1. 可提取的 MEV(套利、清算等)
        2. 用戶願意支付的 Gas
        """
        # 基礎 MEV:與 gas 使用量大致成正比
        base_mev = 0.001 * (gas_used / 1_000_000)  # 簡化模型
        
        # Bundle 帶來的額外 MEV
        bundle_mev = sum(b.get('value', 0) for b in bundle_submissions)
        
        return base_mev + bundle_mev
    
    def construction_cost(self, gas_used: int) -> float:
        """計算建構成本"""
        return self.base_cost + self.marginal_cost * gas_used
    
    def optimal_block_size(self, 
                          potential_bundles: List[dict],
                          current_gas: int = 0) -> tuple:
        """
        找到最優的區塊大小
        
        Returns:
            (最優 gas 使用量, 預期利潤)
        """
        best_gas = current_gas
        best_profit = float('-inf')
        
        # 枚舉不同的 bundle 組合
        # 這裡用貪心方法簡化
        sorted_bundles = sorted(
            potential_bundles, 
            key=lambda x: x.get('value', 0) / max(x.get('gas', 1), 1),
            reverse=True
        )
        
        remaining_gas = self.gas_limit
        included_bundles = []
        
        for bundle in sorted_bundles:
            bundle_gas = bundle.get('gas', 21000)
            if bundle_gas <= remaining_gas:
                included_bundles.append(bundle)
                remaining_gas -= bundle_gas
        
        final_gas = self.gas_limit - remaining_gas
        
        # 計算利潤
        revenue = self.mev_revenue(final_gas, included_bundles)
        cost = self.construction_cost(final_gas)
        bid = 0.9 * revenue  # 投標 90% 的收入
        
        profit = revenue - cost - bid
        
        return final_gas, profit, included_bundles


# 測試建構者模型
builder = BlockBuilder()

# 模擬潛在的 bundle 提交
np.random.seed(42)
test_bundles = [
    {'id': f'bundle_{i}', 
     'value': np.random.exponential(0.5),  # 隨機 MEV 價值
     'gas': np.random.randint(50000, 500000),  # 隨機 Gas 需求
     'priority_fee': np.random.uniform(10, 100)}  # 優先費用
    for i in range(50)
]

optimal_gas, profit, included = builder.optimal_block_size(test_bundles)

print(f"最優區塊大小:{optimal_gas:,} Gas")
print(f"包含的 bundle 數量:{len(included)}")
print(f"預期利潤:{profit:.4f} ETH")

3.5 邊際 MEV 分析

讓我們更仔細地分析邊際 MEV。

假設區塊內的交易服從以下規律:

那麼總 MEV 是:

$$

MEV{total} = \sum{i=1}^{n} MEV_i

$$

其中 $n$ 是區塊內的交易數量,取決於總 Gas 使用量。

邊際 MEV 的遞減

實際數據顯示,MEV 有明顯的邊際遞減效應。讓我用真實數據來擬合:

def fit_mev_function(gas_used: np.ndarray, 
                     mev_revenue: np.ndarray) -> tuple:
    """
    用實際數據擬合 MEV 收入函數
    
    假設服從對數函數:
    MEV(gas) = a * log(1 + b * gas)
    """
    from scipy.optimize import curve_fit
    
    def mev_model(x, a, b):
        return a * np.log(1 + b * x)
    
    params, covariance = curve_fit(
        mev_model, gas_used, mev_revenue,
        p0=[1.0, 1e-7],
        bounds=([0, 0], [np.inf, np.inf])
    )
    
    return params

# 模擬數據(實際應用中應該用真實數據)
gas_range = np.linspace(0, 30_000_000, 100)
# 假設 MEV 服從對數函數
true_mev = 0.5 * np.log(1 + 1e-7 * gas_range)
# 添加噪聲
mev_with_noise = true_mev + np.random.normal(0, 0.02, 100)

# 擬合
a, b = fit_mev_function(gas_range, mev_with_noise)
print(f"擬合的 MEV 函數參數:a = {a:.4f}, b = {b:.2e}")
print(f"MEV({gas_range[-1]:,.0f}) = {a * np.log(1 + b * gas_range[-1]):.4f} ETH")

# 繪圖
plt.figure(figsize=(12, 6))
plt.scatter(gas_range / 1e6, mev_with_noise, alpha=0.5, label='數據點')
plt.plot(gas_range / 1e6, a * np.log(1 + b * gas_range), 'r-', 
         linewidth=2, label='擬合曲線')
plt.xlabel('Gas 使用量 (M)')
plt.ylabel('MEV 收入 (ETH)')
plt.title('MEV 收入函數擬合')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('mev_revenue_function.png', dpi=150)
plt.close()

第四章:拍賣機制分析

4.1 PBS(Proposer-Builder Separation)拍賣機制

在 Ethereum 的 PBS(提議者-建構者分離)機制中:

  1. 建構者構造區塊並投標
  2. 提議者選擇最高投標的區塊
  3. 勝出的建構者支付投標金額
  4. 提議者獲得區塊獎勵 + 投標金額

這是一個密封拍賣(Sealed-bid Auction)的變體。

4.2 拍賣的博弈論分析

假設:

建構者的利潤

如果建構者 $i$ 以投標 $b_i$ 勝出:

投標策略

在這種拍賣中,建構者面臨一個經典的「贏家詛咒」(Winner's Curse)問題。

如果建構者 $i$ 勝出,說明 $b_i$ 是所有投標中最高的。這意味著:

4.3 貝葉斯Nash均衡

讓我們建模貝葉斯博弈:

貝葉斯拍賣模型:

- 建構者 i 的類型:θᵢ ~ 均勻分佈[0, 1]
- 類型 θᵢ 代表建構者的「效率」或「MEV 提取能力」
- 類型是私有資訊

建構者 i 的利潤:
πᵢ = (vᵢ - b) · 1{ b > bⱼ for all j ≠ i }

其中 vᵢ 是建構者 i 的估值(與 θᵢ 正相關)

直接揭示機制(Direct Revelation Mechanism):

在這種機制下,建構者直接報告自己的類型。

讓我們求解這個博弈的貝葉斯Nash均衡。

4.4 拍賣均衡的 Python 模擬

class PBSAuctionSimulator:
    """PBS 拍賣模擬器"""
    
    def __init__(self, num_builders: int = 10):
        self.num_builders = num_builders
        
    def simulate_auction(self, 
                         mev_capabilities: List[float],
                         num_rounds: int = 10000) -> dict:
        """
        模擬 PBS 拍賣
        
        Args:
            mev_capabilities: 每個建構者的 MEV 能力
            num_rounds: 模擬回合數
        
        Returns:
            模擬結果統計
        """
        revenues = []
        winner_profits = []
        second_bids = []
        
        for _ in range(num_rounds):
            # 每個建構者根據自己的能力選擇投標策略
            bids = []
            for capability in mev_capabilities:
                # 投標策略:投到能力的一定比例(留有一定的空間)
                # 這是一個簡化的策略
                bid = capability * np.random.uniform(0.7, 0.95)
                bids.append(bid)
            
            # 找出贏家
            winner_idx = np.argmax(bids)
            winner_bid = bids[winner_idx]
            winner_profit = mev_capabilities[winner_idx] - winner_bid
            
            # 第二高價
            sorted_bids = sorted(bids, reverse=True)
            second_bid = sorted_bids[1] if len(sorted_bids) > 1 else 0
            
            revenues.append(winner_bid)
            winner_profits.append(winner_profit)
            second_bids.append(second_bid)
        
        return {
            'mean_revenue': np.mean(revenues),
            'std_revenue': np.std(revenues),
            'mean_winner_profit': np.mean(winner_profits),
            'mean_second_bid': np.mean(second_bids),
            'revenue_ratio': np.mean(revenues) / np.mean(mev_capabilities)
        }
    
    def analyze_equilibrium(self, num_types: int = 100) -> dict:
        """
        分析拍賣的均衡
        
        假設建構者的類型服從均勻分佈 [0, 1]
        在 First-Price Sealed-Bid Auction 中,
        對稱均衡的投標策略是:
        b(θ) = θ - ∫₀^θ t / θ dt = θ / 2
        """
        types = np.linspace(0, 1, num_types)
        
        # 理論均衡投標
        theoretical_bids = types / 2  # 一階逼近
        
        # 模擬計算
        simulated_bids = []
        for theta in types:
            # 投標 = theta - 風險調整
            # 這裡用 Monte Carlo 模擬
            bids = []
            for _ in range(1000):
                other_type = np.random.uniform(0, theta)
                bid = theta - 0.5 * (theta - other_type)
                bids.append(bid)
            simulated_bids.append(np.mean(bids))
        
        return {
            'types': types,
            'theoretical_bids': theoretical_bids,
            'simulated_bids': simulated_bids
        }


# 測試拍賣模擬
simulator = PBSAuctionSimulator(num_builders=10)

# 假設建構者的 MEV 能力
np.random.seed(42)
mev_caps = np.random.uniform(0.1, 2.0, 10)

results = simulator.simulate_auction(mev_caps)
print("PBS 拍賣模擬結果:")
print(f"  平均收入(給提議者): {results['mean_revenue']:.4f} ETH")
print(f"  收入標準差: {results['std_revenue']:.4f} ETH")
print(f"  贏家平均利潤: {results['mean_winner_profit']:.4f} ETH")
print(f"  收入/MEV 比率: {results['revenue_ratio']:.2%}")

# 分析均衡
equilibrium = simulator.analyze_equilibrium()

plt.figure(figsize=(12, 6))
plt.plot(equilibrium['types'], equilibrium['theoretical_bids'], 
         'r-', linewidth=2, label='理論均衡投標')
plt.plot(equilibrium['types'], equilibrium['simulated_bids'], 
         'b--', linewidth=2, label='模擬均衡投標')
plt.plot([0, 1], [0, 1], 'g:', alpha=0.5, label='完整資訊線')
plt.xlabel('建構者類型 (θ)')
plt.ylabel('投標金額 (b)')
plt.title('First-Price Sealed-Bid Auction 均衡投標函數')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('auction_equilibrium.png', dpi=150)
plt.close()

4.5 拍賣效率分析

PBS 拍賣是否有效率?這是一個重要的問題。

拍賣效率的評估標準:

1. 社會福利最大化
   - 最高效的建構者應該勝出
   - 但這要求對建構者的能力有完整資訊

2. 激勵相容性
   - 建構者應該有動機如實報告自己的能力
   - 防止策略性投標

3. 個人理性
   - 參與拍賣不應該讓建構者受損
   - 防止惡意競爭

在 PBS 機制中:

優點:
- 建構者有動機提高效率(因為要與其他建構者競爭)
- 提議者獲得最大化的收入

缺點:
- 可能導致建構者利潤過低(競爭激烈時)
- 區塊生產的集中化風險
- MEV 的外部性問題(用戶被剝削)

第五章:MEV 供應鏈的整體均衡

5.1 市場均衡模型

讓我們把搜尋者、建構者和提議者整合到一個統一模型中。

市場結構:

1. 上游:搜尋者發現 MEV 機會
   - 搜尋者數量:n_s
   - 每個搜尋者的成功機率:p
   - 搜尋者的期望利潤:E[π_s]

2. 中游:建構者整合 MEV
   - 建構者數量:n_b
   - 建構成本:C(q)
   - 建構者的期望利潤:E[π_b]

3. 下游:提議者選擇區塊
   - 提議者數量:n_p
   - 區塊獎勵:R
   - 提議者的期望利潤:E[π_p]

均衡條件

在長期均衡中,以下條件必須同時成立:

  1. 搜尋者均衡:$E[\pi_s] = 0$(如果 $>0$,會有新搜尋者進入)
  2. 建構者均衡:$E[\pi_b] = 0$(如果 $>0$,會有新建構者進入)
  3. 提議者均衡:$E[\pi_p] \geq R$(否則提議者沒有動機參與)

5.2 均衡穩定性分析

class MEVSupplyChainEquilibrium:
    """MEV 供應鏈整體均衡模型"""
    
    def __init__(self):
        self.base_mev = 100.0  # 基礎 MEV 機會(ETH/區塊)
        self.searcher_cost = 0.01  # 搜尋者每次嘗試成本
        self.builder_fixed_cost = 1.0  # 建構者固定成本
        self.builder_marginal_cost = 0.001  # 建構者邊際成本
        self.block_reward = 0.05  # 區塊獎勵
        
    def equilibrium_searchers(self, mev_opportunity: float) -> float:
        """
        計算搜尋者的均衡數量
        
        均衡條件:期望利潤 = 0
        E[π] = p * mev_opportunity - cost = 0
        n = 當利潤趨近於零時的搜尋者數量
        """
        # 簡化:每個搜尋者獨立,成功機率隨數量增加而降低
        n = 0
        profit = 1.0
        p_base = 0.5
        
        while profit > 0 and n < 1000:
            # 成功機率遞減
            success_prob = p_base / (1 + 0.1 * n)
            profit = success_prob * mev_opportunity - self.searcher_cost
            n += 1
        
        return n, profit
    
    def equilibrium_builders(self, total_mev: float, 
                            num_searchers: int) -> tuple:
        """
        計算建構者的均衡數量
        
        均衡條件:建構者利潤 = 0
        """
        # 簡化:每個建構者獲得的份額與數量成反比
        n = 1
        profit = 1.0
        
        while profit > 0 and n < 20:
            share = total_mev / n
            revenue = share * 0.9  # 90% 作為投標
            cost = self.builder_fixed_cost + self.builder_marginal_cost * 15_000_000
            profit = revenue - cost
            n += 1
        
        return n - 1, profit
    
    def simulate_equilibrium_dynamics(
        self, 
        initial_searchers: int = 10,
        initial_builders: int = 5,
        num_periods: int = 100
    ) -> dict:
        """
        模擬均衡的動態調整過程
        """
        searchers = [initial_searchers]
        builders = [initial_builders]
        searcher_profits = []
        builder_profits = []
        
        current_searchers = initial_searchers
        current_builders = initial_builders
        
        for _ in range(num_periods):
            # 計算當前的 MEV 收入
            base_mev = self.base_mev * (1 + np.random.normal(0, 0.1))
            
            # 搜尋者利潤
            if current_searchers > 0:
                success_prob = 0.5 / (1 + 0.1 * current_searchers)
                searcher_profit = success_prob * base_mev - self.searcher_cost
            else:
                searcher_profit = base_mev * 0.5
            
            searcher_profits.append(searcher_profit)
            
            # 建構者利潤
            if current_builders > 0:
                mev_share = base_mev / current_builders
                revenue = mev_share * 0.9
                cost = self.builder_fixed_cost + 0.001 * 15
                builder_profit = revenue - cost
            else:
                builder_profit = base_mev * 0.9
            
            builder_profits.append(builder_profit)
            
            # 調整搜尋者數量
            if searcher_profit > 0.01:
                current_searchers = min(100, int(current_searchers * 1.1))
            elif searcher_profit < -0.01:
                current_searchers = max(1, int(current_searchers * 0.9))
            
            # 調整建構者數量
            if builder_profit > 0.1:
                current_builders = min(20, current_builders + 1)
            elif builder_profit < -0.1:
                current_builders = max(1, current_builders - 1)
            
            searchers.append(current_searchers)
            builders.append(current_builders)
        
        return {
            'searchers': searchers,
            'builders': builders,
            'searcher_profits': searcher_profits,
            'builder_profits': builder_profits
        }


# 模擬均衡動態
model = MEVSupplyChainEquilibrium()
dynamics = model.simulate_equilibrium_dynamics()

# 繪圖
fig, axes = plt.subplots(2, 2, figsize=(14, 10))

# 搜尋者數量
axes[0, 0].plot(dynamics['searchers'])
axes[0, 0].set_title('搜尋者數量動態')
axes[0, 0].set_xlabel('時期')
axes[0, 0].set_ylabel('搜尋者數量')

# 建構者數量
axes[0, 1].plot(dynamics['builders'])
axes[0, 1].set_title('建構者數量動態')
axes[0, 1].set_xlabel('時期')
axes[0, 1].set_ylabel('建構者數量')

# 搜尋者利潤
axes[1, 0].plot(dynamics['searcher_profits'])
axes[1, 0].axhline(y=0, color='r', linestyle='--')
axes[1, 0].set_title('搜尋者利潤動態')
axes[1, 0].set_xlabel('時期')
axes[1, 0].set_ylabel('利潤 (ETH)')

# 建構者利潤
axes[1, 1].plot(dynamics['builder_profits'])
axes[1, 1].axhline(y=0, color='r', linestyle='--')
axes[1, 1].set_title('建構者利潤動態')
axes[1, 1].set_xlabel('時期')
axes[1, 1].set_ylabel('利潤 (ETH)')

plt.tight_layout()
plt.savefig('mev_equilibrium_dynamics.png', dpi=150)
plt.close()

print("均衡分析結果:")
print(f"搜尋者數量收斂到: {dynamics['searchers'][-1]}")
print(f"建構者數量收斂到: {dynamics['builders'][-1]}")
print(f"搜尋者最終利潤: {dynamics['searcher_profits'][-1]:.4f} ETH")
print(f"建構者最終利潤: {dynamics['builder_profits'][-1]:.4f} ETH")

5.3 均衡的福利分析

讓我們分析這個市場的福利分配:

MEV 供應鏈的福利分配:

假設總 MEV = 100 ETH

分配:
┌────────────────────────────────────────────┐
│                                            │
│  用戶損失:~70%                            │
│  (滑點、套利損失、效率損失)               │
│                                            │
│  搜尋者獲得:~10%                          │
│  (套利利潤、活動利潤)                     │
│                                            │
│  建構者獲得:~10%                          │
│  (基礎設施報酬)                           │
│                                            │
│  提議者獲得:~10%                          │
│  (區塊獎勵 + MEV 拍賣收入)               │
│                                            │
└────────────────────────────────────────────┘

這只是一個粗略的估計,
實際數字會因為市場條件而大幅波動

第六章:MEV 市場的實證分析

6.1 數據來源

要進行實證分析,我們需要:

MEV 數據來源:

1. Flashbots MEV-Boost
   - 中繼數據
   - 建構者投標記錄
   - https://boost.flashbots.net/

2. Dune Analytics
   - MEV 拍賣數據儀表板
   - 建構者份額分析
   - https://dune.com/flashbots/mev

3. Etherscan
   - 區塊內交易排序
   - Gas 使用情況
   - https://etherscan.io/

4. 區塊瀏覽器 API
   - 實際提取的 MEV
   - 時間序列數據

6.2 建構者市場份額分析

def analyze_builder市场份额():
    """
    分析建構者市場份額
    
    數據來自 Flashbots MEV-Boost 中繼
    """
    # 模擬數據(實際應用中應該用真實 API)
    np.random.seed(42)
    
    builders = ['beaverbuild', 'rsync', 'lightning', 
                'bloXroute', 'manifold', '其他']
    
    # 模擬市場份額(真實數據顯示頭部效應很明顯)
    true_shares = [0.35, 0.20, 0.15, 0.12, 0.08, 0.10]
    
    # 添加一些隨機變化
    num_blocks = 10000
    observations = np.random.choice(
        builders, 
        size=num_blocks, 
        p=true_shares
    )
    
    # 計算觀察到的份額
    observed_shares = [
        np.sum(observations == b) / num_blocks 
        for b in builders
    ]
    
    # Herfindahl 指數(衡量市場集中度)
    hhi = sum(s**2 for s in observed_shares)
    
    print("建構者市場份額分析:")
    for b, s in zip(builders, observed_shares):
        print(f"  {b:12s}: {s:.2%}")
    print(f"\nHHI 指數: {hhi:.4f}")
    print(f"市場集中度: {'極高' if hhi > 0.25 else '中等' if hhi > 0.15 else '競爭性'}")
    
    return dict(zip(builders, observed_shares))


def estimate_mev_extraction_rate():
    """
    估算 MEV 提取率
    
    定義:提取的 MEV / 可提取的總 MEV
    """
    # 這個估算需要仔細建模
    # 這裡用一個簡化的方法
    
    # 假設:
    # - 每個區塊有 50 個 MEV 機會
    # - 每個搜尋者能捕獲其中 1 個
    # - 搜尋者之間均勻競爭
    # - 建構者捕獲搜尋者利潤的 50%
    
    mev_opportunities = 50
    searcher_capture_rate = 1 / mev_opportunities  # 1/50
    builder_capture_rate = 0.5  # 從搜尋者捕獲 50%
    
    extraction_rate = searcher_capture_rate * builder_capture_rate
    
    print(f"\nMEV 提取率估算:")
    print(f"  搜尋者捕獲率: {searcher_capture_rate:.2%}")
    print(f"  建構者捕獲率: {builder_capture_rate:.2%}")
    print(f"  總提取率: {extraction_rate:.2%}")
    
    return extraction_rate


# 運行分析
shares = analyze_builder市场份额()
rate = estimate_mev_extraction_rate()

結論

MEV 供應鏈的數學建模揭示了這個市場的幾個關鍵特徵:

  1. 競爭會壓縮利潤:搜尋者和建構者之間的激烈競爭,最終把利潤壓到接近零(扣除成本後)
  1. 頭部效應明顯:建構者市場呈現明顯的頭部效應,少數大型建構者佔據大部分市場份額
  1. 激勵扭曲:現有的 MEV 機制可能不是社會最優的,存在各種外部性問題
  1. 拍賣機制的效率:PBS 拍賣機制在理論上是激勵相容的,但在實踐中仍有改进空间

這些模型雖然是簡化的,但它們捕捉到了 MEV 市場的核心經濟邏輯。如果你對這個領域有興趣,我建議:

  1. 先把基礎的博弈論和拍賣理論搞清楚
  2. 實際跑一下模擬程式,感受一下均衡是如何形成的
  3. 關注 Flashbots 和以太坊社群對 MEV 機制的最新改進提案

MEV 這個領域變化很快,但底層的經濟學原理是相對穩定的。掌握這些數學工具,能幫你更好地理解這個複雜的市場。


程式碼說明

本文中的所有 Python 程式碼都可以直接運行。所需的依賴包括:

numpy
matplotlib
scipy

這些模型是簡化的,實際的 MEV 市場要複雜得多。建議讀者在理解這些基礎模型後,再深入研究更複雜的機制設計問題。

延伸閱讀與來源

這篇文章對您有幫助嗎?

評論

發表評論

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

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