低延迟链上交易执行引擎,支持 MEV 保护、交易排序优化与高频策略执行
┌─────────────────────────────────────────────────────────────┐ │ Trading Strategy Layer │ ├─────────────────────────────────────────────────────────────┤ │ Order │ Risk │ Position │ PnL │ │ Manager │ Controller │ Manager │ Calculator │ ├─────────────────────────────────────────────────────────────┤ │ Transaction Execution Engine │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Gas Optimizer│ │ Nonce Manager│ │ TX Simulator │ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ MEV Protection Layer │ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ │ Flashbots │ │ MEV Blocker │ │Private Mempool│ │ │ └──────────────┘ └──────────────┘ └──────────────┘ │ ├─────────────────────────────────────────────────────────────┤ │ Mempool Monitor │ Block Builder │ WebSocket Feed │ └─────────────────────────────────────────────────────────────┘
1// FlashbotsClient Flashbots 私有交易提交2type FlashbotsClient struct {3 relayURL string4 authSigner *ecdsa.PrivateKey5 httpClient *http.Client6}7 8// SendBundle 提交交易 Bundle9func (f *FlashbotsClient) SendBundle(10 ctx context.Context,11 bundle *Bundle,12) (*BundleResponse, error) {13 // 1. 构建 Bundle 请求14 params := map[string]interface{}{15 "txs": bundle.SignedTransactions,16 "blockNumber": fmt.Sprintf("0x%x", bundle.TargetBlock),17 }18 19 if bundle.MinTimestamp > 0 {20 params["minTimestamp"] = bundle.MinTimestamp21 }22 if bundle.MaxTimestamp > 0 {23 params["maxTimestamp"] = bundle.MaxTimestamp24 }25 26 // 2. 签名请求27 payload, _ := json.Marshal(map[string]interface{}{28 "jsonrpc": "2.0",29 "id": 1,30 "method": "eth_sendBundle",31 "params": []interface{}{params},32 })33 34 signature, err := f.signPayload(payload)35 if err != nil {36 return nil, fmt.Errorf("sign payload: %w", err)37 }38 39 // 3. 发送请求40 req, _ := http.NewRequestWithContext(41 ctx, "POST", f.relayURL, bytes.NewReader(payload),42 )43 req.Header.Set("Content-Type", "application/json")44 req.Header.Set("X-Flashbots-Signature", signature)45 46 resp, err := f.httpClient.Do(req)47 if err != nil {48 return nil, fmt.Errorf("send request: %w", err)49 }50 defer resp.Body.Close()51 52 var result BundleResponse53 json.NewDecoder(resp.Body).Decode(&result)54 55 return &result, nil56}57 58// SimulateBundle 模拟 Bundle 执行59func (f *FlashbotsClient) SimulateBundle(60 ctx context.Context,61 bundle *Bundle,62) (*SimulationResult, error) {63 // 调用 eth_callBundle 模拟执行64 params := map[string]interface{}{65 "txs": bundle.SignedTransactions,66 "blockNumber": fmt.Sprintf("0x%x", bundle.TargetBlock),67 "stateBlockNumber": "latest",68 }69 70 // ... 发送模拟请求 ...71 72 return &SimulationResult{73 Success: true,74 GasUsed: gasUsed,75 CoinbaseDiff: coinbaseDiff,76 }, nil77}1// NonceManager 高并发 Nonce 管理器2type NonceManager struct {3 mu sync.Mutex4 client *ethclient.Client5 pending map[common.Address]uint646 inFlight map[common.Address]map[uint64]time.Time7}8 9// AcquireNonce 获取下一个可用 Nonce10func (m *NonceManager) AcquireNonce(11 ctx context.Context,12 wallet common.Address,13) (uint64, func(success bool), error) {14 m.mu.Lock()15 defer m.mu.Unlock()16 17 // 初始化或同步 pending nonce18 if _, ok := m.pending[wallet]; !ok {19 nonce, err := m.client.PendingNonceAt(ctx, wallet)20 if err != nil {21 return 0, nil, err22 }23 m.pending[wallet] = nonce24 m.inFlight[wallet] = make(map[uint64]time.Time)25 }26 27 // 分配 nonce28 nonce := m.pending[wallet]29 m.pending[wallet]++30 m.inFlight[wallet][nonce] = time.Now()31 32 // 返回释放函数33 release := func(success bool) {34 m.mu.Lock()35 defer m.mu.Unlock()36 37 delete(m.inFlight[wallet], nonce)38 39 if !success {40 // 交易失败,可能需要重置 nonce41 // 检查是否有更低的 nonce 失败42 minInFlight := uint64(math.MaxUint64)43 for n := range m.inFlight[wallet] {44 if n < minInFlight {45 minInFlight = n46 }47 }48 if nonce < m.pending[wallet] && 49 (len(m.inFlight[wallet]) == 0 || nonce < minInFlight) {50 m.pending[wallet] = nonce51 }52 }53 }54 55 return nonce, release, nil56}