xenith-layerzero 0.1.0

LayerZero v2 transport implementation for xenith
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use bytes::Bytes;
use k256::ecdsa::{RecoveryId, Signature, SigningKey};
use serde::{Deserialize, Serialize};
use xenith_core::{
    ChainId, KeyMetadata, MessageId, MessageStatus, MessagingTransport, Result as XResult,
    SendOptions, StateKey, StateValue, TransactionSigner, XenithError,
};

use crate::options::encode_executor_lz_receive_option;

/// LayerZero v2 endpoint address on Ethereum mainnet.
const LZ_ENDPOINT_V2: [u8; 20] = [
    0x1a, 0x44, 0x07, 0x60, 0x50, 0x12, 0x58, 0x25, 0x90, 0x0e, 0x73, 0x6c, 0x50, 0x1f, 0x85, 0x9c,
    0x50, 0xfe, 0x72, 0x8c,
];

// ── JSON-RPC types ────────────────────────────────────────────────────────────

#[derive(Serialize)]
struct RpcRequest<'a> {
    jsonrpc: &'a str,
    method: &'a str,
    params: serde_json::Value,
    id: u64,
}

#[derive(Deserialize)]
struct RpcResponse {
    result: Option<String>,
    error: Option<RpcError>,
}

#[derive(Deserialize)]
struct RpcError {
    message: String,
}

#[derive(Deserialize)]
struct ScanResponse {
    data: Option<Vec<ScanMessage>>,
}

#[derive(Deserialize)]
struct LogEntry {
    topics: Vec<String>,
    data: String,
    #[serde(rename = "blockNumber")]
    block_number: String,
}

#[derive(Deserialize)]
struct LogsRpcResponse {
    result: Option<Vec<LogEntry>>,
    error: Option<RpcError>,
}

#[derive(Deserialize)]
struct ScanMessage {
    status: String,
    #[serde(rename = "statusDetail")]
    status_detail: Option<String>,
}

// ── K256Signer ────────────────────────────────────────────────────────────────

/// A secp256k1 ECDSA signer backed by a 32-byte private key held in memory.
///
/// Produces EIP-155 signed transactions. Suitable for single-key bot operators.
///
/// # Example
///
/// ```rust,no_run
/// use xenith_core::TransactionSigner;
/// use xenith_layerzero::K256Signer;
/// let signer = K256Signer::from_hex(
///     "4c0883a69102937d6231471b5dbb6e538eba2ef8ac6b36a75cf9de4bca4a4e3a",
/// ).unwrap();
/// println!("address: {:?}", signer.address());
/// ```
pub struct K256Signer {
    key: SigningKey,
    address: [u8; 20],
}

impl K256Signer {
    /// Construct from a 64-character lowercase hex private key (no `0x` prefix).
    pub fn from_hex(hex: &str) -> Result<Self, XenithError> {
        let bytes = alloy_primitives::hex::decode(hex)
            .map_err(|e| XenithError::Serialization(format!("invalid private key hex: {e}")))?;
        if bytes.len() != 32 {
            return Err(XenithError::Serialization(format!(
                "private key must be 32 bytes, got {}",
                bytes.len()
            )));
        }
        let mut buf = [0u8; 32];
        buf.copy_from_slice(&bytes);
        Self::from_bytes(&buf)
    }

    /// Construct from a 32-byte private key.
    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self, XenithError> {
        let key = SigningKey::try_from(bytes.as_ref())
            .map_err(|e| XenithError::Serialization(format!("invalid secp256k1 key: {e}")))?;
        let address = derive_address(&key);
        Ok(Self { key, address })
    }
}

#[async_trait]
impl TransactionSigner for K256Signer {
    fn address(&self) -> [u8; 20] {
        self.address
    }

    /// Sign a transaction with EIP-155 encoding and return the raw signed bytes.
    ///
    /// Uses `options.nonce` (default 0) and `options.max_fee_per_gas` as gas
    /// price. Callers are responsible for nonce management.
    ///
    /// TODO v0.2: auto-fetch nonce from RPC when `options.nonce` is `None`.
    async fn sign_transaction(
        &self,
        to: [u8; 20],
        calldata: Bytes,
        options: &SendOptions,
        chain_id: ChainId,
    ) -> Result<Bytes, XenithError> {
        sign_eip155(&self.key, to, &calldata, options, chain_id.0)
    }
}

// ── LayerZeroLiveTransport ────────────────────────────────────────────────────

/// LayerZero v2 transport that submits real on-chain transactions.
///
/// Requires the `live` feature flag. Uses a [`TransactionSigner`] for signing
/// and a JSON-RPC node for broadcast. Fee estimation goes through the endpoint's
/// `quote()` view function; message delivery status is checked via the LayerZero
/// scan API.
///
/// # Example
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use xenith_core::ChainId;
/// use xenith_layerzero::{K256Signer, LayerZeroLiveTransport};
///
/// let signer = Arc::new(K256Signer::from_hex(
///     "4c0883a69102937d6231471b5dbb6e538eba2ef8ac6b36a75cf9de4bca4a4e3a",
/// ).unwrap());
///
/// let transport = LayerZeroLiveTransport::new(
///     signer,
///     ChainId::from(1),
///     "https://eth-mainnet.example.com".into(),
///     vec![(ChainId::from(42161), 30110)],
/// );
/// ```
pub struct LayerZeroLiveTransport {
    signer: Arc<dyn TransactionSigner>,
    endpoint_address: [u8; 20],
    chain_id: ChainId,
    supported_chains: HashMap<ChainId, u32>,
    rpc_url: String,
    http_client: reqwest::Client,
    /// Maps MessageId → tx hash for scan API lookups.
    tx_hashes: Arc<Mutex<HashMap<MessageId, String>>>,
    /// Cursor for poll_incoming — next block to query from.
    last_seen_block: Arc<AtomicU64>,
}

impl LayerZeroLiveTransport {
    /// Create a live transport.
    ///
    /// `chain_id` is the source chain this transport submits from.
    /// `chain_mappings` maps destination [`ChainId`]s to LayerZero endpoint IDs.
    pub fn new(
        signer: Arc<dyn TransactionSigner>,
        chain_id: ChainId,
        rpc_url: String,
        chain_mappings: Vec<(ChainId, u32)>,
    ) -> Self {
        Self {
            signer,
            endpoint_address: LZ_ENDPOINT_V2,
            chain_id,
            supported_chains: chain_mappings.into_iter().collect(),
            rpc_url,
            http_client: reqwest::Client::new(),
            tx_hashes: Arc::new(Mutex::new(HashMap::new())),
            last_seen_block: Arc::new(AtomicU64::new(0)),
        }
    }

    async fn eth_call_endpoint(&self, calldata: &[u8]) -> Result<Vec<u8>, XenithError> {
        let data = format!("0x{}", alloy_primitives::hex::encode(calldata));
        let to = format!("0x{}", alloy_primitives::hex::encode(self.endpoint_address));
        let req = RpcRequest {
            jsonrpc: "2.0",
            method: "eth_call",
            params: serde_json::json!([{"to": to, "data": data}, "latest"]),
            id: 1,
        };
        let resp: RpcResponse = self
            .http_client
            .post(&self.rpc_url)
            .json(&req)
            .send()
            .await
            .map_err(|e| XenithError::Transport {
                chain: self.chain_id,
                message: e.to_string(),
            })?
            .json()
            .await
            .map_err(|e| XenithError::Transport {
                chain: self.chain_id,
                message: format!("JSON-RPC parse error: {e}"),
            })?;

        if let Some(err) = resp.error {
            return Err(XenithError::Transport {
                chain: self.chain_id,
                message: format!("eth_call error: {}", err.message),
            });
        }
        let hex_str = resp.result.ok_or_else(|| XenithError::Transport {
            chain: self.chain_id,
            message: "eth_call returned null result".into(),
        })?;
        alloy_primitives::hex::decode(hex_str.strip_prefix("0x").unwrap_or(&hex_str)).map_err(|e| {
            XenithError::Transport {
                chain: self.chain_id,
                message: format!("eth_call hex decode: {e}"),
            }
        })
    }

    async fn eth_send_raw(&self, raw_tx: &[u8]) -> Result<String, XenithError> {
        let hex_tx = format!("0x{}", alloy_primitives::hex::encode(raw_tx));
        let req = RpcRequest {
            jsonrpc: "2.0",
            method: "eth_sendRawTransaction",
            params: serde_json::json!([hex_tx]),
            id: 1,
        };
        let resp: RpcResponse = self
            .http_client
            .post(&self.rpc_url)
            .json(&req)
            .send()
            .await
            .map_err(|e| XenithError::Transport {
                chain: self.chain_id,
                message: e.to_string(),
            })?
            .json()
            .await
            .map_err(|e| XenithError::Transport {
                chain: self.chain_id,
                message: format!("JSON-RPC parse error: {e}"),
            })?;

        if let Some(err) = resp.error {
            return Err(XenithError::Transport {
                chain: self.chain_id,
                message: format!("eth_sendRawTransaction error: {}", err.message),
            });
        }
        resp.result.ok_or_else(|| XenithError::Transport {
            chain: self.chain_id,
            message: "eth_sendRawTransaction returned null".into(),
        })
    }

    async fn fetch_scan_status(&self, tx_hash: &str) -> Result<MessageStatus, XenithError> {
        let url = format!("https://scan.layerzero-api.com/v1/messages/tx/{tx_hash}");
        let resp: ScanResponse = self
            .http_client
            .get(&url)
            .send()
            .await
            .map_err(|e| XenithError::Transport {
                chain: self.chain_id,
                message: format!("scan API error: {e}"),
            })?
            .json()
            .await
            .map_err(|e| XenithError::Transport {
                chain: self.chain_id,
                message: format!("scan API parse error: {e}"),
            })?;

        Ok(match resp.data.and_then(|msgs| msgs.into_iter().next()) {
            Some(msg) => match msg.status.as_str() {
                "INFLIGHT" => MessageStatus::InFlight,
                "DELIVERED" => MessageStatus::Delivered,
                "FAILED" => MessageStatus::Failed {
                    reason: msg.status_detail.unwrap_or_else(|| "unknown".into()),
                },
                _ => MessageStatus::Pending,
            },
            None => MessageStatus::Pending,
        })
    }

    async fn eth_get_logs(
        &self,
        from_block: u64,
        topic0: &str,
    ) -> Result<Vec<LogEntry>, XenithError> {
        let from_hex = format!("0x{from_block:x}");
        let to_addr = format!("0x{}", alloy_primitives::hex::encode(self.endpoint_address));
        let req = RpcRequest {
            jsonrpc: "2.0",
            method: "eth_getLogs",
            params: serde_json::json!([{
                "fromBlock": from_hex,
                "toBlock": "latest",
                "address": to_addr,
                "topics": [topic0]
            }]),
            id: 1,
        };
        let resp: LogsRpcResponse = self
            .http_client
            .post(&self.rpc_url)
            .json(&req)
            .send()
            .await
            .map_err(|e| XenithError::Transport {
                chain: self.chain_id,
                message: e.to_string(),
            })?
            .json()
            .await
            .map_err(|e| XenithError::Transport {
                chain: self.chain_id,
                message: format!("JSON-RPC parse error: {e}"),
            })?;

        if let Some(err) = resp.error {
            return Err(XenithError::Transport {
                chain: self.chain_id,
                message: format!("eth_getLogs error: {}", err.message),
            });
        }
        Ok(resp.result.unwrap_or_default())
    }
}

#[async_trait]
impl MessagingTransport for LayerZeroLiveTransport {
    async fn send_message(
        &self,
        destination: ChainId,
        payload: Bytes,
        options: SendOptions,
    ) -> XResult<MessageId> {
        let &dst_eid = self
            .supported_chains
            .get(&destination)
            .ok_or(XenithError::UnsupportedChain(destination))?;

        let receiver = {
            let addr = self.signer.address();
            let mut buf = [0u8; 32];
            buf[12..32].copy_from_slice(&addr);
            buf
        };
        let lz_opts = encode_executor_lz_receive_option(options.gas_limit.unwrap_or(200_000));
        let refund = options
            .refund_address
            .unwrap_or_else(|| self.signer.address());

        let calldata = Bytes::from(build_send_calldata(
            dst_eid, receiver, &payload, &lz_opts, refund,
        ));

        // Estimate fee so we can attach it as tx value.
        let fee = self.estimate_fee(destination, payload.clone()).await?;

        let tx_opts = SendOptions {
            value: Some(fee),
            ..options
        };

        let signed_tx = self
            .signer
            .sign_transaction(self.endpoint_address, calldata, &tx_opts, self.chain_id)
            .await?;

        let tx_hash = self.eth_send_raw(&signed_tx).await?;

        // TODO: canonical MessageId should come from the PacketSent event nonce;
        // for now use the first 8 bytes of the tx hash as a deterministic proxy.
        let id = tx_hash_to_message_id(&tx_hash)?;

        self.tx_hashes
            .lock()
            .map_err(|_| XenithError::Transport {
                chain: self.chain_id,
                message: "tx_hashes mutex poisoned".into(),
            })?
            .insert(id, tx_hash);

        Ok(id)
    }

    async fn estimate_fee(&self, destination: ChainId, payload: Bytes) -> XResult<u128> {
        let &dst_eid = self
            .supported_chains
            .get(&destination)
            .ok_or(XenithError::UnsupportedChain(destination))?;

        let receiver = {
            let addr = self.signer.address();
            let mut buf = [0u8; 32];
            buf[12..32].copy_from_slice(&addr);
            buf
        };
        let lz_opts = encode_executor_lz_receive_option(200_000);
        let sender = self.signer.address();

        let calldata = build_quote_calldata(dst_eid, receiver, &payload, &lz_opts, sender);
        let result = self.eth_call_endpoint(&calldata).await?;

        // Return value: (nativeFee: uint256, lzTokenFee: uint256) — each 32 bytes.
        if result.len() < 32 {
            return Err(XenithError::Transport {
                chain: self.chain_id,
                message: format!("quote() returned {} bytes, expected ≥ 32", result.len()),
            });
        }
        // Parse nativeFee from the first 32 bytes (big-endian u256, we take low 16 bytes).
        let native_fee =
            u128::from_be_bytes(
                result[16..32]
                    .try_into()
                    .map_err(|_| XenithError::Transport {
                        chain: self.chain_id,
                        message: "quote() fee slice conversion failed".into(),
                    })?,
            );
        Ok(native_fee)
    }

    async fn message_status(&self, id: MessageId) -> XResult<MessageStatus> {
        let tx_hash = self
            .tx_hashes
            .lock()
            .map_err(|_| XenithError::Transport {
                chain: self.chain_id,
                message: "tx_hashes mutex poisoned".into(),
            })?
            .get(&id)
            .cloned()
            .ok_or_else(|| XenithError::Transport {
                chain: self.chain_id,
                message: format!("unknown message ID: {:?}", id),
            })?;

        self.fetch_scan_status(&tx_hash).await
    }

    fn sender_address(&self) -> Option<[u8; 20]> {
        Some(self.signer.address())
    }

    async fn poll_incoming(&self) -> XResult<Vec<(StateKey, StateValue, Option<KeyMetadata>)>> {
        // topic0 = keccak256("PacketReceived(bytes,bytes,bytes32)")
        let topic0 = {
            let hash = alloy_primitives::keccak256(b"PacketReceived(bytes,bytes,bytes32)");
            format!("0x{}", alloy_primitives::hex::encode(hash.as_slice()))
        };

        let from_block = self.last_seen_block.load(Ordering::Relaxed);
        let logs = match self.eth_get_logs(from_block, &topic0).await {
            Ok(logs) => logs,
            // Silently return empty on network errors — subscribe() will retry next poll.
            Err(_) => return Ok(vec![]),
        };

        let mut results = Vec::new();
        let mut max_block = from_block;

        for log in &logs {
            // Verify topic0 matches (eth_getLogs filter should guarantee this, but be safe).
            if log.topics.first().map(|t| t.as_str()) != Some(&topic0) {
                continue;
            }

            // Update cursor.
            let block_num = u64::from_str_radix(
                log.block_number
                    .strip_prefix("0x")
                    .unwrap_or(&log.block_number),
                16,
            )
            .unwrap_or(0);
            if block_num > max_block {
                max_block = block_num;
            }

            // Decode hex log data.
            let data_hex = log.data.strip_prefix("0x").unwrap_or(&log.data);
            let data = match alloy_primitives::hex::decode(data_hex) {
                Ok(d) => d,
                Err(_) => continue,
            };

            // Extract the payload field (second `bytes` arg) from the ABI-encoded event data.
            if let Some(payload) = decode_packet_received_payload(&data) {
                // Attempt to decode as a xenith wire message; skip non-xenith payloads silently.
                if let Ok((key, value, meta)) = xenith_core::wire::decode(&payload) {
                    results.push((key, value, meta));
                }
            }
        }

        // Advance cursor past the last seen block so the next call doesn't re-process.
        if !logs.is_empty() {
            self.last_seen_block.store(max_block + 1, Ordering::Relaxed);
        }

        Ok(results)
    }
}

// ── Calldata builders (pub(crate) so tests can verify selectors) ──────────────

/// Build `quote((uint32,bytes32,bytes,bytes,bool),address)` calldata.
pub(crate) fn build_quote_calldata(
    dst_eid: u32,
    receiver: [u8; 32],
    message: &[u8],
    options: &[u8],
    sender: [u8; 20],
) -> Vec<u8> {
    let selector = fn_selector(b"quote((uint32,bytes32,bytes,bytes,bool),address)");
    abi_encode_call(selector, dst_eid, receiver, message, options, false, sender)
}

/// Build `send((uint32,bytes32,bytes,bytes,bool),address)` calldata.
pub(crate) fn build_send_calldata(
    dst_eid: u32,
    receiver: [u8; 32],
    message: &[u8],
    options: &[u8],
    refund: [u8; 20],
) -> Vec<u8> {
    let selector = fn_selector(b"send((uint32,bytes32,bytes,bytes,bool),address)");
    abi_encode_call(selector, dst_eid, receiver, message, options, false, refund)
}

// ── Internal helpers ──────────────────────────────────────────────────────────

fn fn_selector(sig: &[u8]) -> [u8; 4] {
    let hash = alloy_primitives::keccak256(sig);
    [hash[0], hash[1], hash[2], hash[3]]
}

/// ABI-encode a call with `(MessagingParams, address)` arguments.
///
/// MessagingParams = (dstEid: uint32, receiver: bytes32, message: bytes,
///                    options: bytes, payInLzToken: bool)
///
/// MessagingParams is a dynamic tuple (contains two `bytes` fields), so it is
/// encoded as a dynamic argument at the function level.
fn abi_encode_call(
    selector: [u8; 4],
    dst_eid: u32,
    receiver: [u8; 32],
    message: &[u8],
    options: &[u8],
    pay_in_lz_token: bool,
    addr: [u8; 20],
) -> Vec<u8> {
    let mut out = Vec::with_capacity(4 + 64 + 256);
    out.extend_from_slice(&selector);

    // Function-level head (2 arguments):
    //   arg0 (struct, dynamic) → offset = 64 (2 words × 32 bytes)
    //   arg1 (address, static) → inline
    out.extend_from_slice(&pad_u64_to_32(64));
    out.extend_from_slice(&pad_addr_to_32(addr));

    // Struct body head (5 fields):
    //   [0] dstEid   → static 32 bytes
    //   [1] receiver → static 32 bytes
    //   [2] message  → dynamic, offset relative to struct body start
    //   [3] options  → dynamic, offset relative to struct body start
    //   [4] payLz    → static 32 bytes
    let msg_padded = pad_to_32_multiple(message.len());
    let msg_offset: u64 = 5 * 32; // after 5 head words
    let opts_offset: u64 = msg_offset + 32 + msg_padded as u64;

    out.extend_from_slice(&pad_u32_to_32(dst_eid));
    out.extend_from_slice(&receiver);
    out.extend_from_slice(&pad_u64_to_32(msg_offset));
    out.extend_from_slice(&pad_u64_to_32(opts_offset));
    out.extend_from_slice(&pad_bool_to_32(pay_in_lz_token));

    // Struct body tail — message data:
    out.extend_from_slice(&pad_u64_to_32(message.len() as u64));
    out.extend_from_slice(message);
    out.resize(out.len() + msg_padded - message.len(), 0);

    // Struct body tail — options data:
    let opts_padded = pad_to_32_multiple(options.len());
    out.extend_from_slice(&pad_u64_to_32(options.len() as u64));
    out.extend_from_slice(options);
    out.resize(out.len() + opts_padded - options.len(), 0);

    out
}

fn pad_to_32_multiple(n: usize) -> usize {
    if n == 0 {
        0
    } else {
        n.div_ceil(32) * 32
    }
}

fn pad_u32_to_32(v: u32) -> [u8; 32] {
    let mut buf = [0u8; 32];
    buf[28..32].copy_from_slice(&v.to_be_bytes());
    buf
}

fn pad_u64_to_32(v: u64) -> [u8; 32] {
    let mut buf = [0u8; 32];
    buf[24..32].copy_from_slice(&v.to_be_bytes());
    buf
}

fn pad_addr_to_32(a: [u8; 20]) -> [u8; 32] {
    let mut buf = [0u8; 32];
    buf[12..32].copy_from_slice(&a);
    buf
}

fn pad_bool_to_32(b: bool) -> [u8; 32] {
    let mut buf = [0u8; 32];
    if b {
        buf[31] = 1;
    }
    buf
}

/// Parse a 0x-prefixed tx hash string into a deterministic [`MessageId`].
///
/// The u64 is derived from the first 8 bytes of the tx hash (big-endian).
/// TODO: replace with the `nonce` field from the PacketSent event once the
/// tx is mined and the event is available.
pub(crate) fn tx_hash_to_message_id(hash_hex: &str) -> Result<MessageId, XenithError> {
    let hex = hash_hex.strip_prefix("0x").unwrap_or(hash_hex);
    let bytes = alloy_primitives::hex::decode(hex).map_err(|e| XenithError::Transport {
        chain: ChainId(0),
        message: format!("invalid tx hash hex: {e}"),
    })?;
    let id_bytes: [u8; 8] = bytes
        .get(0..8)
        .ok_or_else(|| XenithError::Transport {
            chain: ChainId(0),
            message: format!("tx hash too short: {} bytes", bytes.len()),
        })?
        .try_into()
        .map_err(|_| XenithError::Transport {
            chain: ChainId(0),
            message: "tx hash slice error".into(),
        })?;
    Ok(MessageId::from(u64::from_be_bytes(id_bytes)))
}

// ── Signing helpers ───────────────────────────────────────────────────────────

fn derive_address(key: &SigningKey) -> [u8; 20] {
    let encoded = key.verifying_key().to_encoded_point(false); // uncompressed
    let pub_bytes = &encoded.as_bytes()[1..]; // skip 0x04 prefix → 64 bytes
    let hash = alloy_primitives::keccak256(pub_bytes);
    let mut addr = [0u8; 20];
    addr.copy_from_slice(&hash.as_slice()[12..]);
    addr
}

/// Sign a legacy EIP-155 transaction and return the raw RLP-encoded bytes.
fn sign_eip155(
    key: &SigningKey,
    to: [u8; 20],
    data: &[u8],
    options: &SendOptions,
    chain_id: u64,
) -> Result<Bytes, XenithError> {
    let nonce = options.nonce.unwrap_or(0);
    let gas_price = options.max_fee_per_gas.unwrap_or(0);
    let gas_limit = options.gas_limit.unwrap_or(200_000);
    let value = options.value.unwrap_or(0);

    // Step 1: RLP-encode unsigned tx (EIP-155: append chainId, 0, 0).
    let mut s = rlp::RlpStream::new_list(9);
    s.append(&nonce);
    rlp_append_u128(&mut s, gas_price);
    s.append(&gas_limit);
    s.append(&to.to_vec());
    rlp_append_u128(&mut s, value);
    s.append(&data.to_vec());
    s.append(&chain_id);
    s.append(&0u64);
    s.append(&0u64);
    let unsigned_rlp = s.out();

    // Step 2: keccak256 hash the unsigned tx.
    let hash = alloy_primitives::keccak256(&unsigned_rlp[..]);

    // Step 3: sign with secp256k1 (recoverable signature).
    let (sig, rec_id): (Signature, RecoveryId) = key
        .sign_prehash_recoverable(hash.as_ref())
        .map_err(|e| XenithError::Serialization(format!("signing failed: {e}")))?;

    // Step 4: extract r, s, compute EIP-155 v.
    let r = sig.r().to_bytes();
    let s_bytes = sig.s().to_bytes();
    let v: u64 = rec_id.to_byte() as u64 + 35 + chain_id * 2;

    // Step 5: RLP-encode the signed tx.
    let mut stream = rlp::RlpStream::new_list(9);
    stream.append(&nonce);
    rlp_append_u128(&mut stream, gas_price);
    stream.append(&gas_limit);
    stream.append(&to.to_vec());
    rlp_append_u128(&mut stream, value);
    stream.append(&data.to_vec());
    stream.append(&v);
    rlp_append_be_bytes(&mut stream, r.as_ref());
    rlp_append_be_bytes(&mut stream, s_bytes.as_ref());

    Ok(Bytes::from(stream.out().to_vec()))
}

fn rlp_append_u128(s: &mut rlp::RlpStream, v: u128) {
    let bytes = v.to_be_bytes();
    let skip = bytes.iter().position(|&b| b != 0).unwrap_or(16);
    s.append(&bytes[skip..].to_vec());
}

/// Append big-endian bytes with leading zeros stripped (for r/s sig components).
fn rlp_append_be_bytes(s: &mut rlp::RlpStream, bytes: &[u8]) {
    let skip = bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len());
    s.append(&bytes[skip..].to_vec());
}

/// Extract the `payload` field (second `bytes` arg) from ABI-encoded
/// `PacketReceived(bytes header, bytes payload, bytes32 reason)` event data.
///
/// ABI layout for (bytes, bytes, bytes32) with no indexed parameters:
/// ```text
/// [0..32]   offset0  → header start (uint256)
/// [32..64]  offset1  → payload start (uint256)
/// [64..96]  reason   → inline bytes32
/// [offset0] header length (uint256) + data (padded)
/// [offset1] payload length (uint256) + data (padded)
/// ```
fn decode_packet_received_payload(data: &[u8]) -> Option<bytes::Bytes> {
    if data.len() < 96 {
        return None;
    }
    // Read offset1 from the second 32-byte word; take the last 8 bytes as u64.
    let offset1 = u64::from_be_bytes(data[56..64].try_into().ok()?) as usize;
    if data.len() < offset1 + 32 {
        return None;
    }
    // Read payload length from last 8 bytes of the length word at offset1.
    let payload_len =
        u64::from_be_bytes(data[offset1 + 24..offset1 + 32].try_into().ok()?) as usize;
    if data.len() < offset1 + 32 + payload_len {
        return None;
    }
    Some(bytes::Bytes::copy_from_slice(
        &data[offset1 + 32..offset1 + 32 + payload_len],
    ))
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use xenith_core::SendOptions;

    #[test]
    fn test_fee_estimation_calldata() {
        let calldata = build_quote_calldata(30110, [0u8; 32], &[], &[], [0u8; 20]);
        let expected_selector = fn_selector(b"quote((uint32,bytes32,bytes,bytes,bool),address)");
        assert_eq!(
            &calldata[0..4],
            &expected_selector,
            "quote() calldata must start with the correct 4-byte selector"
        );
    }

    #[test]
    fn test_send_message_calldata() {
        let calldata = build_send_calldata(30110, [0u8; 32], &[], &[], [0u8; 20]);
        let expected_selector = fn_selector(b"send((uint32,bytes32,bytes,bytes,bool),address)");
        assert_eq!(
            &calldata[0..4],
            &expected_selector,
            "send() calldata must start with the correct 4-byte selector"
        );
    }

    #[test]
    fn test_message_id_derivation() {
        let hash = "0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";
        let id = tx_hash_to_message_id(hash).unwrap();
        // First 8 bytes big-endian: 0x0102030405060708
        assert_eq!(id, MessageId::from(0x0102030405060708u64));
    }

    #[tokio::test]
    async fn test_sign_eip155_known_vector() {
        // EIP-155 test vector from the specification.
        // Private key: 0x4646...4646
        // nonce=9, gasPrice=20Gwei, gasLimit=21000, to=0x3535..., value=1ETH, data=""
        let signer = K256Signer::from_hex(
            "4646464646464646464646464646464646464646464646464646464646464646",
        )
        .unwrap();

        let to = [0x35u8; 20];
        let opts = SendOptions {
            nonce: Some(9),
            max_fee_per_gas: Some(20_000_000_000),
            gas_limit: Some(21_000),
            value: Some(1_000_000_000_000_000_000),
            ..Default::default()
        };

        let signed = signer
            .sign_transaction(to, Bytes::new(), &opts, ChainId(1))
            .await
            .unwrap();

        // Expected signed transaction from EIP-155:
        let expected_hex = concat!(
            "f86c",
            "09",
            "8504a817c800",
            "825208",
            "943535353535353535353535353535353535353535",
            "880de0b6b3a7640000",
            "80",
            "25",
            "a028ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa636276",
            "a067cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d83"
        );
        let expected = alloy_primitives::hex::decode(expected_hex).unwrap();
        assert_eq!(
            signed.as_ref(),
            expected.as_slice(),
            "signed tx must match EIP-155 test vector"
        );
    }
}