Mempool 监听与抢先交易实战:从原理到 Flashbots 套利脚本(Uniswap V3 + Sepolia 测试网)

5 阅读5分钟

前言

未确认交易驻留内存池(Mempool)期间,释放链上意图:DEX 订单、清算触发、NFT 铸造。套利机器人(Searchers)通过实时监听、Gas 竞价及私有中继(Flashbots)实施原子套利(Atomic Arbitrage),在区块打包前完成价值捕获。

本文系统阐述:

  1. Mempool 监听协议:基于 WebSocket 的未决交易捕获机制,关键字段解析(from/to/value/data)与信号识别。
  2. 抢先交易工程:以 Uniswap V3 swapExactETHForTokens(函数选择器 0x7ff36ab5)为例,构建高优先级 EIP-1559 交易并实施交易插队(Transaction Insertion)。
  3. Flashbots 原子套利:利用私有中继提交交易 Bundle,实现 ETH→Token→ETH 无滑点循环套利,规避公开 Mempool 暴露。
  4. 合规与道德框架:技术能力与监管红线——在 MEV(矿工可提取价值)生态中平衡效率与公平,避免市场操纵。

监听Mempool(内存池)

主要作用:获取实时数据、优化交易执行、发现套利机会和保障安全

使用场景监听Mempool的作用
套利机器人发现DEX价格差异,执行闪电贷套利
清算机器人监控借贷协议的健康因子,自动清算抵押品
NFT 抢购监听NFT铸造交易,抢先提交购买请求
交易所风控检测异常提现或可疑合约交互,冻结可疑资金

实例

说明:hardhat或Ganache本地节点未启用 WebSocket 或 HTTP 订阅所以本例子使用infura

未决交易:用户发出但没被矿工打包上链的交易

# sepolia链
const SEPOLIA_WSSURL = 'wss://sepolia.infura.io/ws/v3/{YourAPIKey}';//YourAPIKey在注册infura中获取apikey
const provider = new ethers.WebSocketProvider(SEPOLIA_WSSURL);//获取provider
//监测限制 实现一个节流限制请求频率
function ThrottleFn(fn, delay) {
    let timer;
    return function(){
        if(!timer) {
            fn.apply(this, arguments)
            timer = setTimeout(()=>{
                clearTimeout(timer)
                timer = null
            },delay)
        }
    }
}
//监听请求
let i = 0
provider.on("pending", ThrottleFn(async (txHash) => {
    if (txHash && i <= 50) {
        // 获取tx详情
        let tx = await provider.getTransaction(txHash);
        console.log(`\n[${(new Date).toLocaleTimeString()}] 监听Pending交易 ${i}: ${txHash} \r`);//获取交易hash
        console.log(tx);//读取交易详情 可以看到`blockHash`,`blockNumber`,和`transactionIndex`都为空 我们可以获取from、to、value等信息,我们可以对其进行挖掘分析等后续操作
        i++
        }
}, 1000))

抢先交易脚本

抢先交易的核心:

比你快,比你贵通过,更快的网络监听更高的 Gas 费出价,在目标交易被矿工打包前插入自己的交易,从而截获利润或优先执行,一句话总结用更快的代码和更高的 Gas 费,在目标交易上链前插入自己的交易,从而截获利润

实例

const signature = "swapExactETHForTokens(uint256,address[],address,uint256)";
// 2. 计算 Keccak-256 哈希,取前 4 字节(8 个十六进制字符)
const selector = ethers.id(signature).slice(0, 10);
console.log(selector); // 输出: 0x7ff36ab5
  • 代码实例
const { ethers } = require("hardhat");

// 1. 配置
const PRIVATE_KEY = "ac09xxxxxxxxx";//钱包私钥
const TARGET_CONTRACT = "0xC532a74256D3Db42D0Bf7a0400aEFDbad7694008";//使用的是Sepolia路由器 交换执行接口 Uniswap V2/V3/测试网(Sepolia)路由器
const TARGET_SELECTOR = "0x7ff36ab5";        // swapExactETHForTokens 选择器
// 2. 初始化
const SEPOLIA_MAINNET_WSSURL = 'wss://sepolia.infura.io/ws/v3/{YouAPIKey}';
const provider = new ethers.WebSocketProvider(SEPOLIA_MAINNET_WSSURL);
const wallet = new ethers.Wallet(PRIVATE_KEY, provider);//钱包

// 3. 监听 pending 交易
provider.on("pending", async (txHash) => {
  try {
    const tx = await provider.getTransaction(txHash);
    if (!tx || tx.to?.toLowerCase() !== TARGET_CONTRACT.toLowerCase()) return;
    if (!tx.data.startsWith(TARGET_SELECTOR)) return;

    console.log(`[${new Date().toLocaleTimeString()}] 发现目标交易: ${txHash}`);

    // 4. 构造抢先交易
    const frontRunTx = {
      to: tx.to,
      data: tx.data,
      value: tx.value,
      maxPriorityFeePerGas: tx.maxPriorityFeePerGas * 1.2, // 提高 20%
      maxFeePerGas: tx.maxFeePerGas * 1.2,
      nonce: await wallet.getNonce(), // 使用钱包当前 nonce
      chainId: await provider.getNetwork().then(n => n.chainId),
      type: 2, // EIP-1559
    };

    // 5. 签名并广播
    
    const signedTx = await wallet.signTransaction(frontRunTx);
    const broadcast = await provider.sendTransaction(signedTx);
    console.log(`抢先交易已广播: ${broadcast.hash}`);
  } catch (error) {
    console.error("处理交易时出错:", error.message);
  }
});

console.log("开始监听 mempool...");
# 以上就是抢先交易dome完整的实例

Flashbots

什么是Flashbots:

通过私有通道、交易捆绑、拍卖机制和收益共享协议,为以太坊生态提供了一套透明、高效且公平的 MEV 解决方案。它既保护了普通用户免受抢跑和尾随,又为搜索者和矿工创造了新的收益来源,同时推动了区块构建的去中心化和网络整体效率的提升

Flashbots 解决的核心问题

问题类型具体描述
抢跑与尾随通过私有通道隐藏交易意图,防止交易被抢先或尾随,降低普通用户被剥削风险。
Gas 价格战将公开 mempool 的 Gas 竞价转为 Bundle 小费,减少网络拥堵和费用波动。
失败交易成本Bundle 内交易原子执行,失败即丢弃,不消耗链上 Gas,避免无效交易损失。
MEV 中心化开放竞争性区块构建市场,防止少数实体垄断 MEV 提取,促进去中心化。

Flashbots 典型应用场景

场景类型应用示例
套利机器人跨 DEX 价格差套利,通过 Bundle 快速执行无滑点交易。
清算机器人监控借贷协议健康因子,抢先清算抵押品,保障协议偿付能力。
隐私交易机构/大额交易使用 Flashbots Protect 隐藏细节,避免狙击攻击。
验证者收益优化质押节点运行 MEV-Boost,接入多构建者,最大化区块奖励并提升抗审查能力。

实例

说明:主要在sepolia上测试,要保证我们的交易钱包有足够的eth,要注意:

const { ethers } = require("hardhat");
const { FlashbotsBundleProvider } =require('@flashbots/ethers-provider-bundle');
async function main() {
  const AUTH_KEY="ac097xxxxxxxx";//账号1 钱包  声誉私钥(仅用于 Flashbots 签名)
  const sepolia_private="5025c087xxxxxx";//sepolia_private 私钥交易钱包(含资金,用于发送交易)

  // 1. 普通 RPC 提供者(Alchemy、Infura 等)
 
  const provider = new ethers.JsonRpcProvider("https://sepolia.infura.io/v3/{object——key}");

  // 2. 声誉私钥(仅用于签名请求,不存储资金)
  const authSigner = new ethers.Wallet(AUTH_KEY, provider);//声誉私钥

  // 3. 创建 Flashbots 提供者
  const flashbotsProvider = await FlashbotsBundleProvider.create(
    provider,
    authSigner,
    'https://relay-sepolia.flashbots.net', // Sepolia 测试网中继
    'sepolia'
  );
// PRIVATE_KEY
  // 4. 钱包(含资金,用于签名交易)
  const wallet = new ethers.Wallet(sepolia_private, provider);//钱包里要有eth余额不能为0

  // 5. 构造两笔 EIP-1559 交易
  const currentNonce = await wallet.getNonce('latest'); // 强制获取链上最新 nonce
  
  const tx1 = {
    to: '0x3C44CdDdxx'// 要转入的钱包地址
    value: ethers.parseEther('0.0001'),
    maxFeePerGas: ethers.parseUnits('100', 'gwei'),
    maxPriorityFeePerGas: ethers.parseUnits('50', 'gwei'),
    type: 2,
    chainId: 11155111, // Sepolia
    nonce: currentNonce,
  };

  const tx2 = {
    to: '0x3C44CdDdxx',//要转入的钱包地址
    value: ethers.parseEther('0.0002'),
    maxFeePerGas: ethers.parseUnits('100', 'gwei'),
    maxPriorityFeePerGas: ethers.parseUnits('50', 'gwei'),
    type: 2,
    chainId: 11155111,
    nonce: currentNonce + 1,
  };

  // 6. 组装 Bundle
  const bundle = [
    { signer: wallet, transaction: tx1 },
    { signer: wallet, transaction: tx2 },
  ];

  // 7. 获取目标区块号(下一个区块)
  const blockNumber = await provider.getBlockNumber();
  const targetBlockNumber = blockNumber + 1;
  //定义函数解决JSON.stringify(simulation, null, 2)超大数问题
  function serializeBigInt(obj) {
    return JSON.stringify(obj, (key, value) =>
      typeof value === 'bigint' ? value.toString() : value
    );
  }//
  // 8. 模拟
  const signedBundle = await flashbotsProvider.signBundle(bundle);
  const simulation = await flashbotsProvider.simulate(signedBundle, targetBlockNumber);
  console.log('Simulation result:', serializeBigInt(simulation));

  // 9. 发送
  const sendResult = await flashbotsProvider.sendBundle(bundle, targetBlockNumber);
  console.log('Bundle hash:', sendResult.bundleHash);

  // 10. 等待区块包含
  const waitResult = await sendResult.wait();
  console.log('Wait result:', waitResult);

  // 11. 获取收据
  const receipts = await sendResult.receipts();
  console.log('Receipts:', receipts);
}

main().catch(console.error);

总结

以上就是对Mempool 监听、抢先交易与 Flashbots 套利实战的全部内容。