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
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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
//! Transaction construction, canonical encoding, and `tx_hash`.
//!
//! This module owns:
//!
//! - [`tx_hash`] — the canonical Poseidon2 tx hash per Ch 11 §11.6,
//!   byte-identical to `engine/crates/tx/src/hashing.rs::tx_hash`.
//! - [`encode`] / [`decode`] — Borsh codec for the full [`Tx`]
//!   envelope, what `pyde_sendRawTransaction` expects on the wire.
//! - [`TxBuilder`] — fluent builder for the common construction
//!   patterns (transfer, contract call, deploy).
//!
//! The signing flow is:
//!
//! 1. Build an unsigned [`Tx`] (signature field is empty).
//! 2. Compute [`tx_hash`] over the canonical pre-image (the
//!    signature is **not** in the pre-image — including it would
//!    be circular).
//! 3. FALCON-sign the hash bytes.
//! 4. Patch the produced [`FalconSignature`] into `tx.signature`.
//! 5. [`encode`] the now-signed [`Tx`] and submit via
//!    `pyde_sendRawTransaction`.
//!
//! Step 4-5 are handled by [`crate::signer::Signer::sign_tx`].

use borsh::BorshDeserialize;
use pyde_crypto::poseidon2::poseidon2_hash;

use crate::error::SdkError;
use crate::types::{
    AccessEntry, Address, CommitPayload, FalconSignature, FeePayer, Gas, RevealPayload, Tx, TxHash,
    TxType,
};

// ── Commit-reveal private mempool ──────────────────────────────

/// Domain-separation tag for [`commitment_hash`]. Baked into every
/// commitment so a commit-reveal preimage can never collide with any
/// other Blake3 use in the protocol. Wire-frozen — mirrors
/// `engine/crates/types/src/tx.rs::COMMITMENT_DOMAIN_TAG`.
pub const COMMITMENT_DOMAIN_TAG: &[u8] = b"pyde-commit-reveal-v1";

/// Reveal window in waves (~60 s at 500 ms waves). A commit's matching
/// reveal must land in wave `W'` with `commit_wave < W' <= commit_wave
/// + COMMIT_REVEAL_WINDOW_WAVES`, else the slot expires and the bond is
/// forfeit. This is a liveness/censorship cushion, not the happy path —
/// honest wallets auto-reveal the moment the commit finalises (~1-2 s).
/// Mirrors the engine's `COMMIT_REVEAL_WINDOW_WAVES`.
pub const COMMIT_REVEAL_WINDOW_WAVES: u64 = 120;

/// Flat bond floor in quanta (1 PYDE = 10⁹ quanta). Prices commit-spam:
/// reserving a slot and never revealing forfeits at least this much.
/// Mirrors the engine's `MIN_COMMIT_BOND`.
pub const MIN_COMMIT_BOND: u128 = 1_000_000_000;

/// Bond scaling in basis points of the declared `value_ceiling`
/// (100 bps = 1%). Mirrors the engine's `COMMIT_BOND_BPS`.
pub const COMMIT_BOND_BPS: u128 = 100;

/// Canonical commit-reveal commitment:
/// `Blake3(COMMITMENT_DOMAIN_TAG || inner_tx_bytes || nonce)`.
///
/// `inner_tx_bytes` is the Borsh encoding of the hidden [`Tx`] — the
/// SAME bytes you place in [`RevealPayload::inner_tx`]. Encode the
/// signed inner tx exactly once and reuse those bytes for both the
/// hash and the reveal payload; re-encoding risks a byte drift that
/// makes the reveal's recomputed hash mismatch and get rejected.
///
/// `nonce` is 32 bytes of sender-chosen randomness — the salt that
/// makes the commitment hiding. It MUST come from a CSPRNG and MUST
/// NOT be reused across commitments.
///
/// Byte-identical to `engine/crates/types/src/tx.rs::commitment_hash`.
#[must_use]
pub fn commitment_hash(inner_tx_bytes: &[u8], nonce: &[u8; 32]) -> [u8; 32] {
    let mut hasher = blake3::Hasher::new();
    hasher.update(COMMITMENT_DOMAIN_TAG);
    hasher.update(inner_tx_bytes);
    hasher.update(nonce);
    *hasher.finalize().as_bytes()
}

/// Minimum bond a `Commit` must post for a declared value ceiling:
/// `max(MIN_COMMIT_BOND, value_ceiling × COMMIT_BOND_BPS / 10_000)`.
///
/// The Commit tx sets `tx.value = required_bond(value_ceiling)`. The
/// bond is refunded when the matching Reveal is accepted, and burned
/// if the commit is never revealed inside the window. Byte-identical
/// to `engine/crates/tx/src/commit_reveal.rs::required_bond`.
#[must_use]
pub fn required_bond(value_ceiling: u128) -> u128 {
    let scaled = value_ceiling
        .saturating_mul(COMMIT_BOND_BPS)
        .saturating_div(10_000);
    scaled.max(MIN_COMMIT_BOND)
}

// ── Canonical hash ─────────────────────────────────────────────

/// Compute the canonical transaction hash.
///
/// The hash is `Poseidon2` over a fixed-order pre-image:
///
/// ```text
/// tx_hash = Poseidon2(
///     chain_id (u64 LE)
///     || from (32 B)
///     || to (32 B)
///     || value (u128 LE)
///     || Poseidon2(data) (32 B)
///     || gas_limit (u64 LE)
///     || nonce (u64 LE)
///     || fee_payer_tag (1 B or 1 + 32 B)
///     || Poseidon2(access_list_borsh) (32 B)
///     || deadline_tag (1 B or 1 + 8 B)
///     || tx_type_tag (u8)
/// )
/// ```
///
/// `data` and `access_list` are pre-hashed to keep the outer
/// Poseidon2 permutation at a bounded cost regardless of input
/// size (~11 field elements vs unbounded otherwise).
///
/// The [`FalconSignature`] is the only field excluded from the
/// pre-image — otherwise signing would be circular.
///
/// Byte-identical to `engine/crates/tx/src/hashing.rs::tx_hash`.
#[must_use]
pub fn tx_hash(tx: &Tx) -> TxHash {
    let data_digest: [u8; 32] = poseidon2_hash(&tx.data).into();
    let access_list_digest = hash_access_list(&tx.access_list);
    let fee_payer_bytes = encode_fee_payer_tag(&tx.fee_payer);
    let deadline_bytes = encode_deadline_tag(tx.deadline);

    let mut preimage = Vec::with_capacity(
        8                          // chain_id
        + 32                       // from
        + 32                       // to
        + 16                       // value
        + 32                       // Poseidon2(data)
        + 8                        // gas_limit
        + 8                        // nonce
        + fee_payer_bytes.len()    // fee_payer tag
        + 32                       // Poseidon2(access_list)
        + deadline_bytes.len()     // deadline tag
        + 1, // tx_type tag
    );
    preimage.extend_from_slice(&tx.chain_id.to_le_bytes());
    preimage.extend_from_slice(tx.from.as_bytes());
    preimage.extend_from_slice(tx.to.as_bytes());
    preimage.extend_from_slice(&tx.value.to_le_bytes());
    preimage.extend_from_slice(&data_digest);
    preimage.extend_from_slice(&tx.gas_limit.to_le_bytes());
    preimage.extend_from_slice(&tx.nonce.to_le_bytes());
    preimage.extend_from_slice(&fee_payer_bytes);
    preimage.extend_from_slice(&access_list_digest);
    preimage.extend_from_slice(&deadline_bytes);
    preimage.push(tx_type_tag(&tx.tx_type));

    let digest: [u8; 32] = poseidon2_hash(&preimage).into();
    TxHash::new(digest)
}

/// `Poseidon2(borsh_canonical(access_list))`.
///
/// `AccessEntry` has a fixed Borsh schema (address 32 B + storage
/// keys length-prefixed Vec + access_type tag), and the access list
/// is itself a length-prefixed `Vec<AccessEntry>`. Encoding the
/// full slice via Borsh is canonical.
fn hash_access_list(list: &[AccessEntry]) -> [u8; 32] {
    let encoded = borsh::to_vec(list).unwrap_or_default();
    poseidon2_hash(&encoded).into()
}

/// Canonical-hash byte encoding of [`FeePayer`].
///
/// `Sender → [0x00]`, `GasTank → [0x01]`, `Paymaster(addr) →
/// [0x02, addr[..32]]`. This matches Borsh's discriminant
/// encoding for the frozen enum but is spelt out explicitly so the
/// canonical hash never drifts if a future Borsh upgrade changes
/// its representation.
fn encode_fee_payer_tag(payer: &FeePayer) -> Vec<u8> {
    match payer {
        FeePayer::Sender => vec![0x00],
        FeePayer::GasTank => vec![0x01],
        FeePayer::Paymaster(addr) => {
            let mut out = Vec::with_capacity(1 + 32);
            out.push(0x02);
            out.extend_from_slice(addr.as_bytes());
            out
        }
    }
}

/// Canonical-hash byte encoding of `Option<deadline>`.
///
/// `None → [0x00]`, `Some(d) → [0x01, d.to_le_bytes()]`. Matches
/// Borsh `Option` encoding; spelt out for the same wire-stability
/// reason as [`encode_fee_payer_tag`].
fn encode_deadline_tag(deadline: Option<u64>) -> Vec<u8> {
    match deadline {
        None => vec![0x00],
        Some(d) => {
            let mut out = Vec::with_capacity(1 + 8);
            out.push(0x01);
            out.extend_from_slice(&d.to_le_bytes());
            out
        }
    }
}

/// One-byte tag for [`TxType`] used in the canonical hash.
///
/// Uses Borsh's `use_discriminant` so the value matches the
/// `#[repr(u8)]` discriminant on the enum. Spelt out here so wire
/// stability is decoupled from `borsh-derive` output.
fn tx_type_tag(t: &TxType) -> u8 {
    match t {
        TxType::Standard => 0x00,
        TxType::Deploy => 0x01,
        TxType::StakeDeposit => 0x03,
        TxType::StakeWithdraw => 0x04,
        TxType::Slash => 0x05,
        TxType::ClaimReward => 0x06,
        TxType::ClaimAirdrop => 0x07,
        TxType::SweepAirdrop => 0x08,
        TxType::MultisigTx => 0x09,
        TxType::RotateMultisig => 0x0A,
        TxType::EmergencyPause => 0x0B,
        TxType::EmergencyResume => 0x0C,
        TxType::RegisterPubkey => 0x0D,
        TxType::Unjail => 0x0E,
        TxType::RotateValidatorKeys => 0x0F,
        TxType::DisputeSlash => 0x10,
        TxType::Commit => 0x11,
        TxType::Reveal => 0x12,
        // 0x02 — Batch was removed pre-mainnet; tag intentionally vacant.
    }
}

// ── Wire codec ──────────────────────────────────────────────────

/// Borsh-encode a [`Tx`] into the bytes accepted by
/// `pyde_sendRawTransaction`.
///
/// Field order is fixed in [`Tx`]'s declaration; Borsh serialises
/// in declaration order, so this output is byte-identical to what
/// the engine produces.
///
/// # Errors
/// Returns [`SdkError::Other`] only if Borsh serialisation itself
/// fails (effectively unreachable for the shapes here).
pub fn encode(tx: &Tx) -> Result<Vec<u8>, SdkError> {
    borsh::to_vec(tx).map_err(|e| SdkError::Other(format!("borsh encode: {e}")))
}

/// Borsh-decode bytes into a [`Tx`].
///
/// # Errors
/// Returns [`SdkError::InvalidArgument`] if the bytes don't conform
/// to the canonical Borsh schema.
pub fn decode(bytes: &[u8]) -> Result<Tx, SdkError> {
    Tx::try_from_slice(bytes).map_err(|e| SdkError::InvalidArgument(format!("borsh decode: {e}")))
}

// ── Builder ────────────────────────────────────────────────────

/// Fluent builder for the common tx-construction patterns.
///
/// Modelled on alloy's `TransactionRequest`. The builder collects
/// fields and produces an unsigned [`Tx`] on [`TxBuilder::build`].
/// The unsigned tx is then handed to a [`crate::signer::Signer`]
/// to populate `signature` and ready it for submission.
///
/// Sensible defaults:
///
/// - `to` = [`Address::ZERO`] (set explicitly via [`Self::to`])
/// - `value` = `0`
/// - `data` = empty
/// - `gas_limit` = [`crate::types::MIN_GAS_LIMIT`]
/// - `nonce` = `0` (will usually be overwritten by a nonce filler)
/// - `fee_payer` = [`FeePayer::Sender`]
/// - `access_list` = empty
/// - `deadline` = `None`
/// - `chain_id` = `1` (mainnet)
/// - `tx_type` = [`TxType::Standard`]
#[derive(Clone, Debug)]
pub struct TxBuilder {
    from: Option<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,
}

impl Default for TxBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl TxBuilder {
    /// Start a new builder with sensible defaults.
    #[must_use]
    pub fn new() -> Self {
        Self {
            from: None,
            to: Address::ZERO,
            value: 0,
            data: Vec::new(),
            gas_limit: crate::types::MIN_GAS_LIMIT,
            nonce: 0,
            fee_payer: FeePayer::Sender,
            access_list: Vec::new(),
            deadline: None,
            chain_id: 1,
            tx_type: TxType::Standard,
        }
    }

    /// Set the sender.
    #[must_use]
    pub fn from(mut self, addr: Address) -> Self {
        self.from = Some(addr);
        self
    }

    /// Set the recipient.
    #[must_use]
    pub fn to(mut self, addr: Address) -> Self {
        self.to = addr;
        self
    }

    /// Set the attached value, in quanta.
    #[must_use]
    pub fn value(mut self, quanta: u128) -> Self {
        self.value = quanta;
        self
    }

    /// Set the calldata / payload bytes.
    #[must_use]
    pub fn data(mut self, bytes: Vec<u8>) -> Self {
        self.data = bytes;
        self
    }

    /// Set the gas limit.
    #[must_use]
    pub fn gas_limit(mut self, gas: Gas) -> Self {
        self.gas_limit = gas;
        self
    }

    /// Set the nonce.
    #[must_use]
    pub fn nonce(mut self, nonce: u64) -> Self {
        self.nonce = nonce;
        self
    }

    /// Set who pays the gas.
    #[must_use]
    pub fn fee_payer(mut self, payer: FeePayer) -> Self {
        self.fee_payer = payer;
        self
    }

    /// Set the declared access list.
    #[must_use]
    pub fn access_list(mut self, list: Vec<AccessEntry>) -> Self {
        self.access_list = list;
        self
    }

    /// Set the optional inclusion deadline (wave id).
    #[must_use]
    pub fn deadline(mut self, wave: u64) -> Self {
        self.deadline = Some(wave);
        self
    }

    /// Clear any previously-set deadline.
    #[must_use]
    pub fn clear_deadline(mut self) -> Self {
        self.deadline = None;
        self
    }

    /// Set the chain id.
    #[must_use]
    pub fn chain_id(mut self, id: u64) -> Self {
        self.chain_id = id;
        self
    }

    /// Set the tx-type discriminant.
    #[must_use]
    pub fn tx_type(mut self, ty: TxType) -> Self {
        self.tx_type = ty;
        self
    }

    /// Configure this builder as a plain value transfer.
    ///
    /// Equivalent to `.tx_type(Standard).to(addr).value(quanta)`.
    #[must_use]
    pub fn transfer(self, to: Address, quanta: u128) -> Self {
        self.tx_type(TxType::Standard).to(to).value(quanta)
    }

    /// Configure this builder as a contract deployment.
    ///
    /// Sets `tx_type = Deploy`, `to = Address::ZERO`, and `data` to
    /// the Borsh encoding of [`crate::types::DeployData`] (name,
    /// WASM bytes, contract type, constructor calldata). The
    /// deployed contract's address is derived deterministically as
    /// `Address::from_contract_name(name)`.
    ///
    /// # Errors
    /// Returns [`SdkError::Other`] if Borsh encoding fails — which
    /// in practice requires malformed input.
    pub fn deploy(
        self,
        name: impl Into<String>,
        wasm_bytes: Vec<u8>,
        contract_type: crate::types::ContractType,
        init_calldata: Vec<u8>,
    ) -> Result<Self, SdkError> {
        let data = borsh::to_vec(&crate::types::DeployData {
            name: name.into(),
            wasm_bytes,
            contract_type,
            init_calldata,
        })
        .map_err(|e| SdkError::Other(format!("borsh encode DeployData: {e}")))?;
        Ok(self.tx_type(TxType::Deploy).to(Address::ZERO).data(data))
    }

    /// Configure this builder as a contract call.
    ///
    /// Sets `tx_type = Standard`, `to = contract`, and `data =
    /// calldata` (typically `selector || encoded_args`).
    #[must_use]
    pub fn call(self, contract: Address, calldata: Vec<u8>) -> Self {
        self.tx_type(TxType::Standard).to(contract).data(calldata)
    }

    /// Configure this builder as a treasury multisig spend.
    ///
    /// Sets `tx_type = MultisigTx`, `to = Address::ZERO` (envelope-
    /// style), and `data` to the Borsh encoding of
    /// [`crate::multisig::MultisigTxPayload`]. The bundle must
    /// contain `>= MultisigState::threshold` valid signatures over
    /// [`crate::multisig::canonical_msg`] for the on-chain treasury
    /// nonce; the chain verifies + bumps the nonce on commit.
    ///
    /// Treasury txs are NOT signed at the tx level — the bundle is
    /// the authorisation. After `.build()`, submit the tx unsigned.
    ///
    /// # Errors
    /// Returns [`SdkError::Other`] if Borsh encoding fails (not
    /// reachable for fixed-size inputs + a well-formed bundle).
    pub fn multisig_treasury_spend(
        self,
        target: Address,
        amount: u128,
        bundle: crate::multisig::SigBundle,
    ) -> Result<Self, SdkError> {
        let payload = crate::multisig::MultisigTxPayload {
            target,
            amount,
            bundle,
        };
        let data = borsh::to_vec(&payload)
            .map_err(|e| SdkError::Other(format!("borsh encode MultisigTxPayload: {e}")))?;
        Ok(self
            .tx_type(TxType::MultisigTx)
            .to(Address::ZERO)
            .data(data))
    }

    /// Configure this builder as a commit-reveal **Commit** (phase 1).
    ///
    /// Sets `tx_type = Commit`, `to = Address::ZERO`, `value =`
    /// [`required_bond`]`(value_ceiling)`, and `data = borsh(`[`CommitPayload`]`)`.
    /// The `commitment` is [`commitment_hash`]`(borsh(inner_tx), nonce)`.
    ///
    /// For the one-call flow that builds, submits, and auto-reveals,
    /// prefer [`crate::RootProvider::send_private`]. Use this builder
    /// directly only when splitting the two phases (e.g. a relay that
    /// reveals on someone else's behalf).
    ///
    /// # Errors
    /// Returns [`SdkError::Other`] if Borsh encoding fails.
    pub fn commit(self, commitment: [u8; 32], value_ceiling: u128) -> Result<Self, SdkError> {
        let data = borsh::to_vec(&CommitPayload {
            commitment,
            value_ceiling,
        })
        .map_err(|e| SdkError::Other(format!("borsh encode CommitPayload: {e}")))?;
        Ok(self
            .tx_type(TxType::Commit)
            .to(Address::ZERO)
            .value(required_bond(value_ceiling))
            .data(data))
    }

    /// Configure this builder as a commit-reveal **Reveal** (phase 2).
    ///
    /// Sets `tx_type = Reveal`, `to = Address::ZERO`, `value = 0`, and
    /// `data = borsh(`[`RevealPayload`]`)`. `inner_tx_bytes` MUST be the
    /// exact `borsh(inner_tx)` bytes that were hashed into `commitment`
    /// — re-encoding risks a byte drift that makes the engine's
    /// recomputed hash mismatch and reject the reveal.
    ///
    /// Any account may submit the reveal (the preimage is the
    /// authorisation), so this is relay-friendly.
    ///
    /// # Errors
    /// Returns [`SdkError::Other`] if Borsh encoding fails.
    pub fn reveal(
        self,
        commitment: [u8; 32],
        nonce: [u8; 32],
        inner_tx_bytes: Vec<u8>,
    ) -> Result<Self, SdkError> {
        let data = borsh::to_vec(&RevealPayload {
            commitment,
            nonce,
            inner_tx: inner_tx_bytes,
        })
        .map_err(|e| SdkError::Other(format!("borsh encode RevealPayload: {e}")))?;
        Ok(self
            .tx_type(TxType::Reveal)
            .to(Address::ZERO)
            .value(0)
            .data(data))
    }

    /// Build an unsigned [`Tx`].
    ///
    /// # Errors
    /// Returns [`SdkError::InvalidArgument`] if `from` wasn't set —
    /// the signing flow needs to know the sender address to derive
    /// the nonce-window slot and assert the FALCON pubkey matches.
    pub fn build(self) -> Result<Tx, SdkError> {
        let from = self.from.ok_or_else(|| {
            SdkError::InvalidArgument("from address must be set on TxBuilder".into())
        })?;
        Ok(Tx {
            from,
            to: self.to,
            value: self.value,
            data: self.data,
            gas_limit: self.gas_limit,
            nonce: self.nonce,
            signature: FalconSignature::new(Vec::new()),
            fee_payer: self.fee_payer,
            access_list: self.access_list,
            deadline: self.deadline,
            chain_id: self.chain_id,
            tx_type: self.tx_type,
        })
    }
}

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

    use super::*;
    use crate::types::{AccessType, FalconPubkey, FALCON_PUBKEY_LEN};

    fn minimal_tx() -> Tx {
        Tx {
            from: Address::ZERO,
            to: Address::ZERO,
            value: 0,
            data: Vec::new(),
            gas_limit: 0,
            nonce: 0,
            signature: FalconSignature::new(vec![0u8; 32]),
            fee_payer: FeePayer::Sender,
            access_list: Vec::new(),
            deadline: None,
            chain_id: 0,
            tx_type: TxType::Standard,
        }
    }

    // ── tx_hash determinism + signature exclusion ───────────────

    #[test]
    fn same_input_yields_same_hash() {
        let tx = minimal_tx();
        assert_eq!(tx_hash(&tx), tx_hash(&tx));
    }

    #[test]
    fn signature_not_included_in_hash() {
        let mut a = minimal_tx();
        let mut b = minimal_tx();
        a.signature = FalconSignature::new(vec![0xAA; 666]);
        b.signature = FalconSignature::new(vec![0xBB; 666]);
        assert_eq!(tx_hash(&a), tx_hash(&b));
    }

    // ── per-field sensitivity ───────────────────────────────────

    macro_rules! sensitivity_test {
        ($name:ident, $mutator_a:expr, $mutator_b:expr) => {
            #[test]
            fn $name() {
                let mut a = minimal_tx();
                let mut b = minimal_tx();
                $mutator_a(&mut a);
                $mutator_b(&mut b);
                assert_ne!(tx_hash(&a), tx_hash(&b), "field must affect hash");
            }
        };
    }

    sensitivity_test!(
        chain_id_change_changes_hash,
        |t: &mut Tx| t.chain_id = 1,
        |t: &mut Tx| t.chain_id = 31337
    );
    sensitivity_test!(
        from_change_changes_hash,
        |t: &mut Tx| t.from = Address::new([0x01; 32]),
        |t: &mut Tx| t.from = Address::new([0x02; 32])
    );
    sensitivity_test!(
        to_change_changes_hash,
        |t: &mut Tx| t.to = Address::new([0x01; 32]),
        |t: &mut Tx| t.to = Address::new([0x02; 32])
    );
    sensitivity_test!(
        value_change_changes_hash,
        |t: &mut Tx| t.value = 1,
        |t: &mut Tx| t.value = 2
    );
    sensitivity_test!(
        data_change_changes_hash,
        |t: &mut Tx| t.data = vec![0x01],
        |t: &mut Tx| t.data = vec![0x02]
    );
    sensitivity_test!(
        gas_limit_change_changes_hash,
        |t: &mut Tx| t.gas_limit = 21_000,
        |t: &mut Tx| t.gas_limit = 21_001
    );
    sensitivity_test!(
        nonce_change_changes_hash,
        |t: &mut Tx| t.nonce = 0,
        |t: &mut Tx| t.nonce = 1
    );
    sensitivity_test!(
        deadline_presence_changes_hash,
        |t: &mut Tx| t.deadline = None,
        |t: &mut Tx| t.deadline = Some(0)
    );
    sensitivity_test!(
        deadline_value_changes_hash,
        |t: &mut Tx| t.deadline = Some(100),
        |t: &mut Tx| t.deadline = Some(101)
    );
    sensitivity_test!(
        tx_type_change_changes_hash,
        |t: &mut Tx| t.tx_type = TxType::Standard,
        |t: &mut Tx| t.tx_type = TxType::Deploy
    );

    // ── fee_payer / access_list ────────────────────────────────

    #[test]
    fn fee_payer_variant_change_changes_hash() {
        let mut a = minimal_tx();
        let mut b = minimal_tx();
        let mut c = minimal_tx();
        a.fee_payer = FeePayer::Sender;
        b.fee_payer = FeePayer::GasTank;
        c.fee_payer = FeePayer::Paymaster(Address::new([0x42; 32]));
        let ha = tx_hash(&a);
        let hb = tx_hash(&b);
        let hc = tx_hash(&c);
        assert_ne!(ha, hb);
        assert_ne!(hb, hc);
        assert_ne!(ha, hc);
    }

    #[test]
    fn paymaster_addr_change_changes_hash() {
        let mut a = minimal_tx();
        let mut b = minimal_tx();
        a.fee_payer = FeePayer::Paymaster(Address::new([0x01; 32]));
        b.fee_payer = FeePayer::Paymaster(Address::new([0x02; 32]));
        assert_ne!(tx_hash(&a), tx_hash(&b));
    }

    #[test]
    fn access_list_ordering_changes_hash() {
        let a_entry = AccessEntry {
            address: Address::new([0x01; 32]),
            storage_keys: vec![[0u8; 32]],
            access_type: AccessType::Read,
        };
        let b_entry = AccessEntry {
            address: Address::new([0x02; 32]),
            storage_keys: vec![[0u8; 32]],
            access_type: AccessType::Read,
        };
        let mut a = minimal_tx();
        let mut b = minimal_tx();
        a.access_list = vec![a_entry.clone(), b_entry.clone()];
        b.access_list = vec![b_entry, a_entry];
        assert_ne!(tx_hash(&a), tx_hash(&b));
    }

    #[test]
    fn empty_access_list_uses_canonical_borsh_encoding() {
        // Empty Vec serialises to its 4-byte LE length prefix (0)
        // under Borsh; hashing that through Poseidon2 must yield
        // a stable digest different from "Poseidon2(empty)".
        let empty_digest = hash_access_list(&[]);
        let raw_empty: [u8; 32] = poseidon2_hash(&[]).into();
        assert_ne!(empty_digest, raw_empty);
    }

    #[test]
    fn known_vector_hash_is_stable() {
        // Minimal-tx hash must be deterministic and non-zero.
        let tx = minimal_tx();
        let h1 = tx_hash(&tx);
        let h2 = tx_hash(&tx);
        assert_eq!(h1, h2);
        assert_ne!(h1, TxHash::zero());
    }

    #[test]
    fn every_tx_type_yields_distinct_hash_when_otherwise_identical() {
        use TxType::*;
        let variants = [
            Standard,
            Deploy,
            StakeDeposit,
            StakeWithdraw,
            Slash,
            ClaimReward,
            ClaimAirdrop,
            SweepAirdrop,
            MultisigTx,
            RotateMultisig,
            EmergencyPause,
            EmergencyResume,
            RegisterPubkey,
            Unjail,
            RotateValidatorKeys,
            DisputeSlash,
            Commit,
            Reveal,
        ];
        let mut seen = std::collections::HashSet::new();
        for ty in variants {
            let mut tx = minimal_tx();
            tx.tx_type = ty;
            let h = tx_hash(&tx);
            assert!(seen.insert(h), "collision at TxType::{ty:?}");
        }
        assert_eq!(seen.len(), 18);
    }

    // ── codec round-trip ────────────────────────────────────────

    #[test]
    fn encode_decode_round_trip() {
        let tx = minimal_tx();
        let bytes = encode(&tx).unwrap();
        let decoded = decode(&bytes).unwrap();
        assert_eq!(tx, decoded);
    }

    // ── builder ────────────────────────────────────────────────

    #[test]
    fn builder_defaults() {
        let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
        let from = Address::from_pubkey(&pk);
        let tx = TxBuilder::new().from(from).build().unwrap();
        assert_eq!(tx.from, from);
        assert_eq!(tx.to, Address::ZERO);
        assert_eq!(tx.value, 0);
        assert_eq!(tx.gas_limit, crate::types::MIN_GAS_LIMIT);
        assert_eq!(tx.chain_id, 1);
        assert_eq!(tx.tx_type, TxType::Standard);
        assert!(tx.signature.is_empty());
    }

    #[test]
    fn builder_requires_from() {
        assert!(TxBuilder::new().build().is_err());
    }

    #[test]
    fn builder_transfer_helper() {
        let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
        let from = Address::from_pubkey(&pk);
        let to = Address::new([0x55; 32]);
        let tx = TxBuilder::new()
            .from(from)
            .transfer(to, 1_500_000_000)
            .build()
            .unwrap();
        assert_eq!(tx.tx_type, TxType::Standard);
        assert_eq!(tx.to, to);
        assert_eq!(tx.value, 1_500_000_000);
    }

    #[test]
    fn builder_deploy_helper() {
        let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
        let from = Address::from_pubkey(&pk);
        let wasm = b"\0asm\x01\0\0\0".to_vec();
        let tx = TxBuilder::new()
            .from(from)
            .deploy(
                "my-contract",
                wasm.clone(),
                crate::types::ContractType::Contract,
                Vec::new(),
            )
            .unwrap()
            .gas_limit(5_000_000)
            .build()
            .unwrap();
        assert_eq!(tx.tx_type, TxType::Deploy);
        assert!(tx.to.is_zero());
        // tx.data is the Borsh encoding of DeployData; decode to confirm.
        let decoded: crate::types::DeployData = borsh::from_slice(&tx.data).unwrap();
        assert_eq!(decoded.name, "my-contract");
        assert_eq!(decoded.wasm_bytes, wasm);
        assert_eq!(decoded.contract_type, crate::types::ContractType::Contract);
        assert!(decoded.init_calldata.is_empty());
    }

    #[test]
    fn builder_call_helper() {
        let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
        let from = Address::from_pubkey(&pk);
        let contract = Address::from_contract_name("counter");
        let calldata = vec![0xDE, 0xAD, 0xBE, 0xEF];
        let tx = TxBuilder::new()
            .from(from)
            .call(contract, calldata.clone())
            .build()
            .unwrap();
        assert_eq!(tx.tx_type, TxType::Standard);
        assert_eq!(tx.to, contract);
        assert_eq!(tx.data, calldata);
    }

    // ── commit-reveal ──────────────────────────────────────────

    #[test]
    fn commitment_hash_is_salted_and_deterministic() {
        let inner = b"borsh-inner-tx-bytes";
        let nonce_a = [0x11u8; 32];
        let nonce_b = [0x22u8; 32];
        // Deterministic for the same (bytes, nonce).
        assert_eq!(
            commitment_hash(inner, &nonce_a),
            commitment_hash(inner, &nonce_a)
        );
        // Salt changes the commitment.
        assert_ne!(
            commitment_hash(inner, &nonce_a),
            commitment_hash(inner, &nonce_b)
        );
        // Different inner bytes change the commitment.
        assert_ne!(
            commitment_hash(b"other", &nonce_a),
            commitment_hash(inner, &nonce_a)
        );
    }

    #[test]
    fn required_bond_floors_and_scales() {
        assert_eq!(required_bond(0), MIN_COMMIT_BOND);
        assert_eq!(required_bond(1_000), MIN_COMMIT_BOND);
        let crossover = MIN_COMMIT_BOND * 10_000 / COMMIT_BOND_BPS;
        assert_eq!(required_bond(crossover), MIN_COMMIT_BOND);
        assert_eq!(required_bond(crossover * 10), MIN_COMMIT_BOND * 10);
        // Saturates rather than overflowing on pathological input.
        let _ = required_bond(u128::MAX);
    }

    #[test]
    fn builder_commit_helper() {
        let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
        let from = Address::from_pubkey(&pk);
        let commitment = [0xCC; 32];
        let ceiling = 5_000_000_000u128;
        let tx = TxBuilder::new()
            .from(from)
            .commit(commitment, ceiling)
            .unwrap()
            .gas_limit(200_000)
            .build()
            .unwrap();
        assert_eq!(tx.tx_type, TxType::Commit);
        assert!(tx.to.is_zero());
        assert_eq!(tx.value, required_bond(ceiling));
        let decoded: crate::types::CommitPayload = borsh::from_slice(&tx.data).unwrap();
        assert_eq!(decoded.commitment, commitment);
        assert_eq!(decoded.value_ceiling, ceiling);
    }

    #[test]
    fn builder_reveal_helper() {
        let pk = FalconPubkey::new([0xAB; FALCON_PUBKEY_LEN]);
        let from = Address::from_pubkey(&pk);
        let commitment = [0xCC; 32];
        let nonce = [0x5A; 32];
        let inner_bytes = vec![1, 2, 3, 4, 5];
        let tx = TxBuilder::new()
            .from(from)
            .reveal(commitment, nonce, inner_bytes.clone())
            .unwrap()
            .gas_limit(5_000_000)
            .build()
            .unwrap();
        assert_eq!(tx.tx_type, TxType::Reveal);
        assert!(tx.to.is_zero());
        assert_eq!(tx.value, 0);
        let decoded: crate::types::RevealPayload = borsh::from_slice(&tx.data).unwrap();
        assert_eq!(decoded.commitment, commitment);
        assert_eq!(decoded.nonce, nonce);
        assert_eq!(decoded.inner_tx, inner_bytes);
    }
}