pyde-rust-sdk 0.3.2

Rust SDK for the Pyde blockchain — account generation, signing, RPC client, contract interaction
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
//! Transaction wire types — [`Tx`], [`TxType`], [`FeePayer`],
//! [`AccessEntry`], [`AccessType`].
//!
//! Mirrors `engine/crates/types/src/tx.rs` byte-for-byte. The wire
//! field order is **load-bearing**: Borsh serialises in declaration
//! order, and the engine's canonical hash spec assumes the order
//! laid out in [Chapter 11 §11.6][spec]. Reordering or retagging
//! any of these types is a chain-wide hard fork.
//!
//! [spec]: https://book.pyde.network/chapters/11-account-model#116-transaction-wire-format

use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};

use super::{Address, FalconSignature};

/// Gas limit type — `u64`, matches Ch 10 accounting.
pub type Gas = u64;

/// Actual gas consumed by a transaction. Same units as [`Gas`].
pub type GasUsed = u64;

/// Per-wave fee in quanta. `u128` accommodates compounding across
/// waves without overflow.
pub type FeeQuanta = u128;

/// Minimum gas accepted by ingress validation
/// (Ch 10 §10.9 — matches the cost of a plain `Transfer` handler).
pub const MIN_GAS_LIMIT: Gas = 21_000;

/// Maximum total tx size (Ch 10 §10.9). 128 KiB.
pub const MAX_TX_SIZE: usize = 128 * 1024;

/// Maximum calldata size (Ch 10 §10.9). 64 KiB — separate cap from
/// [`MAX_TX_SIZE`] so a tx can't burn the entire 128 KiB on
/// calldata and starve the access-list / envelope.
pub const MAX_CALLDATA: usize = 64 * 1024;

/// Discriminant for the 18 active + 1 reserved-vacant tx variants
/// in Ch 11 §11.8.
///
/// Tag values are **wire-load-bearing** — never reassign post-mainnet.
/// Tag `0x02` is intentionally vacant (`Batch` was prototyped pre-
/// mainnet and removed); keeping the gap means a forged
/// `tx_type = 2` fails decode rather than silently aliasing.
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    PartialEq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
    Serialize,
    Deserialize,
)]
// Borsh uses the explicit u8 discriminant; serde reads the JSON
// shape the engine emits (`"standard"`, `"deploy"`, …) per the
// canonical lowercase snake_case convention. The serde rename is
// disjoint from the borsh path — borsh is byte-tagged, not name-keyed.
#[borsh(use_discriminant = true)]
#[serde(rename_all = "snake_case")]
#[repr(u8)]
pub enum TxType {
    /// `0x00` — Value transfer or contract call. `to/value/data`
    /// carry the call target, value, and calldata.
    Standard = 0x00,
    /// `0x01` — Contract deployment. `to == Address::ZERO`; `data`
    /// holds the Borsh-encoded [`super::DeployData`] envelope
    /// (name, WASM bytes, contract type, init calldata).
    Deploy = 0x01,
    // 0x02 — reserved-as-vacant (Batch removed pre-mainnet).
    /// `0x03` — Lock `>= MIN_VALIDATOR_STAKE` (10,000 PYDE) and
    /// register as validator. `data` holds the 897-byte FALCON
    /// pubkey.
    StakeDeposit = 0x03,
    /// `0x04` — Begin 30-day unbonding.
    StakeWithdraw = 0x04,
    /// `0x05` — Submit double-sign / equivocation evidence.
    /// `data` holds the serialised evidence per `SLASHING.md`.
    Slash = 0x05,
    /// `0x06` — Claim accrued staking yield.
    ClaimReward = 0x06,
    /// `0x07` — Claim a genesis airdrop with a Merkle proof.
    /// `data` holds the proof per Ch 14.
    ClaimAirdrop = 0x07,
    /// `0x08` — Sweep unclaimed airdrop residue to treasury after
    /// the post-genesis deadline.
    SweepAirdrop = 0x08,
    /// `0x09` — Treasury spend with multisig sigs. `data` holds
    /// the (target ‖ amount ‖ multisig_sigs) envelope per Ch 15.
    MultisigTx = 0x09,
    /// `0x0A` — Rotate the treasury multisig signer set + threshold.
    /// `data` holds (new_signers ‖ new_threshold ‖ sigs).
    RotateMultisig = 0x0A,
    /// `0x0B` — Halt wave production. Multisig-signed; `data`
    /// holds sigs.
    EmergencyPause = 0x0B,
    /// `0x0C` — Resume normal processing. Multisig-signed; `data`
    /// holds sigs.
    EmergencyResume = 0x0C,
    /// `0x0D` — First-time pubkey registration for a funded-but-
    /// unregistered account. Allowed only when `balance > 0` and
    /// `auth_keys == None`; proof of pubkey ownership is the
    /// address-derivation check.
    RegisterPubkey = 0x0D,
    /// `0x0E` — Release a validator from `Jailed` back to `Active`.
    Unjail = 0x0E,
    /// `0x0F` — Rotate the FALCON-512 signing key on an already-
    /// registered validator. Signed by the OLD key; on success the
    /// handler swaps both the validator record and the account's
    /// `auth_keys` to the new key. Active validators only.
    RotateValidatorKeys = 0x0F,
    /// `0x10` — Governance dispute over a pending slash. Treasury
    /// multisig gates submission; `data` is
    /// `borsh(DisputeSlashPayload)`.
    DisputeSlash = 0x10,
    /// `0x11` — Commit-reveal private mempool, phase 1: reserve an
    /// ordered slot for a hidden transaction. `to == Address::ZERO`;
    /// `data` is `borsh(`[`CommitPayload`]`)`; `value` is the
    /// refundable reveal bond ([`crate::tx::required_bond`]). The
    /// tx's ordering position IS the reserved slot — fixed while the
    /// contents are still hidden, so no actor can read this tx and
    /// inject a reaction ahead of it.
    Commit = 0x11,
    /// `0x12` — Commit-reveal private mempool, phase 2: open a
    /// previously committed slot. `to == Address::ZERO`; `data` is
    /// `borsh(`[`RevealPayload`]`)`. The engine recomputes
    /// [`crate::tx::commitment_hash`] over `(inner_tx, nonce)` and
    /// rejects on mismatch; the inner tx then executes in COMMIT
    /// order in the resolution pass and the bond is refunded. Any
    /// account may submit the reveal — the preimage is the
    /// authorisation — so a relay can reveal on a sender's behalf.
    Reveal = 0x12,
}

/// Who pays the gas for a transaction.
///
/// Tag values per Ch 11 §11.6 and Ch 10 §10.7:
///
/// | Tag        | Variant                       |
/// |------------|-------------------------------|
/// | `0x00`     | [`FeePayer::Sender`]          |
/// | `0x01`     | [`FeePayer::GasTank`]         |
/// | `0x02`+addr | [`FeePayer::Paymaster`]       |
#[derive(
    Clone, Debug, Eq, PartialEq, Hash, BorshSerialize, BorshDeserialize, Serialize, Deserialize,
)]
#[borsh(use_discriminant = true)]
#[repr(u8)]
pub enum FeePayer {
    /// Sender's own balance pays.
    Sender = 0x00,
    /// The target contract's `gas_tank` pays.
    GasTank = 0x01,
    /// A named paymaster account pays. Subject to that paymaster's
    /// `validate_sponsorship` returning true within 100,000 gas.
    Paymaster(Address) = 0x02,
}

/// Access intent for a single `(address, slot)` entry. Drives the
/// parallel-execution scheduler (Ch 9).
#[derive(
    Clone,
    Copy,
    Debug,
    Eq,
    PartialEq,
    Hash,
    BorshSerialize,
    BorshDeserialize,
    Serialize,
    Deserialize,
)]
#[borsh(use_discriminant = true)]
#[repr(u8)]
pub enum AccessType {
    /// Slot is only read; multiple `Read` entries for the same slot
    /// can run in parallel.
    Read = 0x00,
    /// Slot may be written; conflicts with any other entry on the
    /// same slot.
    ReadWrite = 0x01,
}

/// One entry in the transaction's declared access list.
///
/// Built by `pyde_createAccessList` from a simulated execution.
/// Slots touched at execution time that aren't in the list revert
/// the tx with `ERR_ACCESS_LIST_VIOLATION`.
#[derive(
    Clone, Debug, Eq, PartialEq, Hash, BorshSerialize, BorshDeserialize, Serialize, Deserialize,
)]
pub struct AccessEntry {
    /// Account whose state is touched.
    pub address: Address,
    /// Storage slot keys touched within `address` (each is a 32-byte
    /// PIP-2 clustered key).
    pub storage_keys: Vec<[u8; 32]>,
    /// Whether these slots are read-only or read-write.
    pub access_type: AccessType,
}

/// A Pyde transaction — the wire-frozen envelope.
///
/// Field order matches Ch 11 §11.6 verbatim. **Do not reorder** —
/// Borsh serialises in declaration order and the engine's canonical
/// hash function assumes this layout.
///
/// The meaning of [`Tx::data`] depends on [`Tx::tx_type`]:
///
/// | tx_type              | `data` interpretation                                |
/// |----------------------|------------------------------------------------------|
/// | `Standard`           | calldata for the function being called               |
/// | `Deploy`             | Borsh-encoded [`DeployData`] envelope                |
/// | `StakeDeposit`       | 897-byte FALCON validator pubkey                     |
/// | `RotateValidatorKeys`| the new 897-byte FALCON pubkey                       |
/// | `Slash`              | serialised evidence per `SLASHING.md`                |
/// | `ClaimAirdrop`       | Merkle proof bytes per Ch 14                         |
/// | `MultisigTx`         | `(target ‖ amount ‖ sigs)` envelope                  |
/// | `RotateMultisig`     | `(new_signers ‖ new_threshold ‖ sigs)` envelope      |
/// | `EmergencyPause/Resume` | multisig signature bundle                         |
/// | `RegisterPubkey`     | the FALCON pubkey to register                        |
/// | `StakeWithdraw/ClaimReward/SweepAirdrop` | empty                            |
/// | `Unjail`             | empty                                                |
/// | `DisputeSlash`       | `borsh(DisputeSlashPayload)`                         |
/// | `Commit`             | `borsh(`[`CommitPayload`]`)`                         |
/// | `Reveal`             | `borsh(`[`RevealPayload`]`)`                         |
#[derive(Clone, Debug, Eq, PartialEq, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
pub struct Tx {
    /// Sender address.
    pub from: Address,
    /// Recipient. [`Address::ZERO`] for `Deploy` and envelope-style
    /// txs (Multisig*, Emergency*, Stake*, …).
    pub to: Address,
    /// Value attached to the call, in quanta.
    #[serde(deserialize_with = "crate::types::serde_hex::deserialize_u128_hex_or_int")]
    pub value: u128,
    /// Variant-specific payload — see the `data` interpretation
    /// table in the struct-level docs.
    pub data: Vec<u8>,
    /// Maximum gas the sender authorises.
    #[serde(deserialize_with = "crate::types::serde_hex::deserialize_u64_hex_or_int")]
    pub gas_limit: Gas,
    /// Sender's nonce. Must be `[base, base + 16)` per the 16-slot
    /// bitmap window (Ch 11 §11.4).
    #[serde(deserialize_with = "crate::types::serde_hex::deserialize_u64_hex_or_int")]
    pub nonce: u64,
    /// FALCON-512 signature over the tx canonical pre-image. The
    /// signature itself is NOT hashed (would be circular).
    pub signature: FalconSignature,
    /// Who pays the gas.
    pub fee_payer: FeePayer,
    /// Declared access list. Empty means "no conflicts declared" —
    /// the scheduler serialises this tx; declaring slots unlocks
    /// parallel execution.
    pub access_list: Vec<AccessEntry>,
    /// Optional inclusion deadline (wave id). After this wave, the
    /// tx is dropped from mempools and its nonce slot frees up.
    #[serde(
        default,
        deserialize_with = "crate::types::serde_hex::deserialize_opt_u64_hex_or_int"
    )]
    pub deadline: Option<u64>,
    /// Chain identifier — replay protection across chains. `1` =
    /// mainnet, `31337` = devnet (per spec; genesis-configured).
    #[serde(deserialize_with = "crate::types::serde_hex::deserialize_u64_hex_or_int")]
    pub chain_id: u64,
    /// Variant discriminant — see [`TxType`].
    pub tx_type: TxType,
}

impl Tx {
    /// Construct a transaction with an empty signature. Useful as a
    /// pre-signing scaffold — call [`crate::tx::tx_hash`] on the
    /// scaffolded tx, sign the hash, then mutate `signature` to the
    /// produced bytes.
    ///
    /// The signature is omitted from the canonical hash pre-image
    /// (otherwise signing would be circular), so signing-and-back-
    /// patching is the canonical flow.
    //
    // Many parameters by design — Tx is a wire-frozen envelope and
    // every field must be named explicitly. Prefer the
    // [`crate::tx::TxBuilder`] fluent API for the typical
    // construction path.
    #[allow(clippy::too_many_arguments)]
    #[must_use]
    pub fn unsigned(
        from: Address,
        to: Address,
        value: u128,
        data: Vec<u8>,
        gas_limit: Gas,
        nonce: u64,
        fee_payer: FeePayer,
        access_list: Vec<AccessEntry>,
        deadline: Option<u64>,
        chain_id: u64,
        tx_type: TxType,
    ) -> Self {
        Self {
            from,
            to,
            value,
            data,
            gas_limit,
            nonce,
            signature: FalconSignature::new(Vec::new()),
            fee_payer,
            access_list,
            deadline,
            chain_id,
            tx_type,
        }
    }
}

/// Borsh-encoded payload carried in `Tx::data` when
/// `tx_type == TxType::Standard` AND `tx.to` resolves to a
/// contract account (one with a non-zero `code_hash`).
///
/// Pyde dispatches contract calls by **function name** rather than
/// by 4-byte selector — the chain parses the `pyde.abi` custom
/// section at deploy time, so `name → entry point` lookup is a free
/// O(1) ABI walk. Wallets don't need to compute selectors; they
/// just send the function name + raw argument bytes.
///
/// All fields are wire-load-bearing — adding a field is a hard
/// fork of the call envelope.
#[derive(Clone, Debug, Eq, PartialEq, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
pub struct CallPayload {
    /// Name of the contract function to invoke. Looked up in the
    /// deployed contract's `ContractAbi.functions` by exact match.
    /// Missing names revert with `ERR_INVALID_FUNCTION_NAME`;
    /// constructor-attributed functions are locked out (deploy-time
    /// only).
    pub function: String,
    /// Opaque function-argument bytes. The contract's WASM reads
    /// them via `pyde::calldata_size` + `pyde::calldata_copy`;
    /// encoding is contract-defined.
    pub calldata: Vec<u8>,
}

/// Borsh-encoded payload carried in `Tx::data` when
/// `tx_type == TxType::Deploy`.
///
/// Mirrors `engine/crates/types/src/deploy.rs::DeployData`
/// byte-for-byte. The deployed contract's address is derived from
/// `name` via [`crate::types::Address::from_contract_name`] —
/// `Poseidon2("pyde-contract:" || name)` — so the name is the
/// address-derivation input. The on-chain name registry rejects
/// duplicate names at deploy time.
///
/// All fields are wire-load-bearing — adding a field is a hard
/// fork of the deploy envelope.
#[derive(Clone, Debug, Eq, PartialEq, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
pub struct DeployData {
    /// ENS-style contract name. Registered in the on-chain name
    /// registry; doubles as the address-derivation input
    /// (`Poseidon2("pyde-contract:" || name)`).
    pub name: String,
    /// The contract's WASM binary with the `pyde.abi` custom
    /// section embedded per HOST_FN_ABI §3.7.
    pub wasm_bytes: Vec<u8>,
    /// Contract-vs-parachain discriminant. Drives the host-fn
    /// import allowlist (contracts get §7 only; parachains
    /// additionally get §8).
    pub contract_type: super::abi::ContractType,
    /// Calldata passed to the constructor. Empty if the contract
    /// has no constructor or the constructor takes no arguments.
    pub init_calldata: Vec<u8>,
}

/// Borsh-encoded payload carried in `Tx::data` when
/// `tx_type == TxType::Commit`.
///
/// Phase 1 of the commit-reveal private mempool: reserves an ordered
/// slot for a hidden transaction. The Commit tx's `value` is the
/// refundable reveal bond ([`crate::tx::required_bond`]`(value_ceiling)`),
/// held in the on-chain commitment entry until the matching `Reveal`
/// lands (refund) or the reveal window expires (burned).
///
/// Mirrors `pyde_engine_tx::commit_reveal::CommitPayload` byte-for-byte.
/// Field order is wire-load-bearing — Borsh serialises positionally.
#[derive(Clone, Debug, Eq, PartialEq, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
pub struct CommitPayload {
    /// [`crate::tx::commitment_hash`] of the hidden tx:
    /// `Blake3(domain_tag || borsh(inner_tx) || nonce)`.
    pub commitment: [u8; 32],
    /// Sender-declared upper bound on the hidden tx's `value`, in
    /// quanta. The reveal is rejected if `inner_tx.value >
    /// value_ceiling`, and the bond scales with the ceiling — so it
    /// tracks the potential extraction without revealing the target
    /// or amount. Declaring `0` is valid for value-less calls.
    pub value_ceiling: u128,
}

/// Borsh-encoded payload carried in `Tx::data` when
/// `tx_type == TxType::Reveal`.
///
/// Phase 2 of the commit-reveal private mempool: opens a previously
/// committed slot. The engine recomputes [`crate::tx::commitment_hash`]
/// over `(inner_tx, nonce)` and rejects on mismatch; on success the
/// hidden tx executes in COMMIT order in the wave-commit resolution
/// pass and the bond is refunded to the original committer.
///
/// Mirrors `pyde_engine_tx::commit_reveal::RevealPayload` byte-for-byte.
/// Field order is wire-load-bearing — Borsh serialises positionally.
#[derive(Clone, Debug, Eq, PartialEq, BorshSerialize, BorshDeserialize, Serialize, Deserialize)]
pub struct RevealPayload {
    /// Which pending commitment this opens — the same 32 bytes the
    /// `Commit` posted.
    pub commitment: [u8; 32],
    /// The 32-byte salt drawn at commit time. Must be fresh CSPRNG
    /// per commit and never reused; reuse breaks hiding.
    pub nonce: [u8; 32],
    /// `borsh(Tx)` of the hidden, fully-signed inner transaction —
    /// the SAME bytes hashed into [`Self::commitment`].
    pub inner_tx: Vec<u8>,
}

// Internal test-only accessor; placed before the `#[cfg(test)] mod
// tests` block to satisfy clippy's items-after-test-module rule.
impl FeePayer {
    #[cfg(test)]
    #[allow(dead_code)]
    fn discriminant_tag(&self) -> u8 {
        match self {
            FeePayer::Sender => 0x00,
            FeePayer::GasTank => 0x01,
            FeePayer::Paymaster(_) => 0x02,
        }
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

    use super::*;
    use crate::types::FalconPubkey;

    fn minimal_tx() -> Tx {
        Tx::unsigned(
            Address::ZERO,
            Address::ZERO,
            0,
            vec![],
            21_000,
            0,
            FeePayer::Sender,
            vec![],
            None,
            1,
            TxType::Standard,
        )
    }

    #[test]
    fn tx_type_tags_match_spec() {
        assert_eq!(TxType::Standard as u8, 0x00);
        assert_eq!(TxType::Deploy as u8, 0x01);
        assert_eq!(TxType::StakeDeposit as u8, 0x03);
        assert_eq!(TxType::RegisterPubkey as u8, 0x0D);
        assert_eq!(TxType::DisputeSlash as u8, 0x10);
        assert_eq!(TxType::Commit as u8, 0x11);
        assert_eq!(TxType::Reveal as u8, 0x12);
    }

    #[test]
    fn commit_reveal_payloads_borsh_round_trip() {
        let commit = CommitPayload {
            commitment: [0xAB; 32],
            value_ceiling: 5_000_000_000,
        };
        let bytes = borsh::to_vec(&commit).unwrap();
        assert_eq!(borsh::from_slice::<CommitPayload>(&bytes).unwrap(), commit);

        let reveal = RevealPayload {
            commitment: [0xAB; 32],
            nonce: [0x5A; 32],
            inner_tx: vec![1, 2, 3, 4],
        };
        let bytes = borsh::to_vec(&reveal).unwrap();
        assert_eq!(borsh::from_slice::<RevealPayload>(&bytes).unwrap(), reveal);
    }

    #[test]
    fn fee_payer_tags_match_spec() {
        assert_eq!(FeePayer::Sender.discriminant_tag(), 0x00);
        assert_eq!(FeePayer::GasTank.discriminant_tag(), 0x01);
        let addr = Address::new([0x42; 32]);
        assert_eq!(FeePayer::Paymaster(addr).discriminant_tag(), 0x02);
    }

    #[test]
    fn access_type_tags_match_spec() {
        assert_eq!(AccessType::Read as u8, 0x00);
        assert_eq!(AccessType::ReadWrite as u8, 0x01);
    }

    #[test]
    fn tx_borsh_round_trip() {
        let tx = minimal_tx();
        let bytes = borsh::to_vec(&tx).unwrap();
        let decoded: Tx = borsh::from_slice(&bytes).unwrap();
        assert_eq!(tx, decoded);
    }

    #[test]
    fn tx_borsh_handles_full_fields() {
        let tx = Tx::unsigned(
            Address::new([0x01; 32]),
            Address::new([0x02; 32]),
            10_000,
            vec![1, 2, 3, 4],
            100_000,
            7,
            FeePayer::Paymaster(Address::new([0x03; 32])),
            vec![AccessEntry {
                address: Address::new([0x04; 32]),
                storage_keys: vec![[0u8; 32], [0xFF; 32]],
                access_type: AccessType::ReadWrite,
            }],
            Some(500),
            1,
            TxType::Standard,
        );
        let bytes = borsh::to_vec(&tx).unwrap();
        let decoded: Tx = borsh::from_slice(&bytes).unwrap();
        assert_eq!(tx, decoded);
    }

    /// Regression for the live `pyde_getTx` decode bug. Engine ships
    /// numeric fields as `0x`-prefixed lowercase hex strings (spec
    /// §17.4) and the tx-type tag as lowercase snake_case. Without the
    /// hex-string deserialisers + `TxType` serde rename, this payload
    /// fails decode with "invalid type: string `0x7a69`, expected u64"
    /// at the very first field.
    #[test]
    fn tx_json_decodes_engine_wire_shape() {
        // Engine ships numeric fields as `0x`-prefixed lowercase hex
        // strings (spec §17.4) and the tx-type tag as lowercase
        // snake_case; addresses + signature are byte arrays (the
        // archival `pyde_getTx` convention per the wire-quirks memo).
        let json = serde_json::json!({
            "from":        vec![0xAAu8; 32],
            "to":          vec![0xBBu8; 32],
            "value":       "0xf4240",
            "data":        [],
            "gas_limit":   "0x186a0",
            "nonce":       "0x4",
            "signature":   vec![0u8; 666],
            "fee_payer":   "Sender",
            "access_list": [],
            "deadline":    serde_json::Value::Null,
            "chain_id":    "0x7a69",
            "tx_type":     "standard",
        });
        let decoded: Tx = serde_json::from_value(json).expect("engine wire shape decodes");
        assert_eq!(decoded.value, 0xf_4240);
        assert_eq!(decoded.gas_limit, 0x1_86a0);
        assert_eq!(decoded.nonce, 4);
        assert_eq!(decoded.chain_id, 0x7a69);
        assert_eq!(decoded.tx_type, TxType::Standard);
        assert_eq!(decoded.deadline, None);
        assert_eq!(decoded.fee_payer, FeePayer::Sender);
    }

    #[test]
    fn deploy_tx_uses_zero_recipient() {
        let pk = FalconPubkey::new([0x55; crate::types::FALCON_PUBKEY_LEN]);
        let from = Address::from_pubkey(&pk);
        let tx = Tx::unsigned(
            from,
            Address::ZERO,
            0,
            b"wasm_bytecode_here".to_vec(),
            5_000_000,
            0,
            FeePayer::Sender,
            vec![],
            None,
            1,
            TxType::Deploy,
        );
        assert!(tx.to.is_zero());
        assert_eq!(tx.tx_type, TxType::Deploy);
    }
}