Skip to main content

alloy_signer_ledger/
utils.rs

1// Helper to encode a big-endian varint (no leading zeroes)
2// Nonce limit is 2**64 - 1 https://eips.ethereum.org/EIPS/eip-2681
3#[cfg(feature = "eip7702")]
4pub(crate) fn be_varint(n: u64) -> Vec<u8> {
5    let mut buf = n.to_be_bytes().to_vec();
6    while buf.first() == Some(&0) && buf.len() > 1 {
7        buf.remove(0);
8    }
9    buf
10}
11
12// Tlv encoding for the 7702 authorization list
13#[cfg(feature = "eip7702")]
14pub(crate) fn make_eip7702_tlv(
15    chain_id: alloy_primitives::U256,
16    delegate: &[u8; 20],
17    nonce: u64,
18) -> Vec<u8> {
19    let mut tlv = Vec::with_capacity(9 + 20);
20
21    // STRUCT_VERSION tag=0x00, one-byte version=1
22    tlv.push(0x00);
23    tlv.push(1);
24    tlv.push(1);
25
26    // DELEGATE_ADDR tag=0x01
27    tlv.push(0x01);
28    tlv.push(20);
29    tlv.extend_from_slice(delegate);
30
31    // CHAIN_ID tag=0x02
32    let ci = be_varint(chain_id.to::<u64>());
33    tlv.push(0x02);
34    tlv.push(ci.len() as u8);
35    tlv.extend_from_slice(&ci);
36
37    // NONCE tag=0x03
38    let nn = be_varint(nonce);
39    tlv.push(0x03);
40    tlv.push(nn.len() as u8);
41    tlv.extend_from_slice(&nn);
42
43    tlv
44}