miden-base-sys 0.14.0-rc.1

Miden rollup Rust bingings and MASM library
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
948
949
950
951
952
953
954
955
956
957
958
extern crate alloc;

use miden_field_repr::FromFeltRepr;
use miden_stdlib_sys::{Felt, Word, felt};

/// Packs a scalar felt into the leading limb of a protocol word.
pub fn padded_word_from_felt(value: Felt) -> Word {
    Word::new([value, felt!(0), felt!(0), felt!(0)])
}

/// Extracts a scalar felt from a protocol word with zero-padded trailing limbs.
pub fn felt_from_padded_word(value: Word) -> Result<Felt, &'static str> {
    if value[1] != felt!(0) || value[2] != felt!(0) || value[3] != felt!(0) {
        return Err("expected zero padding in the trailing three felts");
    }

    Ok(value[0])
}

/// Unique identifier for a Miden account, composed of two field elements.
#[derive(Copy, Clone, Debug, PartialEq, Eq, FromFeltRepr)]
pub struct AccountId {
    pub prefix: Felt,
    pub suffix: Felt,
}

impl AccountId {
    /// Creates a new AccountId from prefix and suffix Felt values.
    pub fn new(prefix: Felt, suffix: Felt) -> Self {
        Self { prefix, suffix }
    }
}

/// Raw protocol return layout for account identifiers.
/// The protocol MASM procedures are returning [suffix, prefix]
#[derive(Copy, Clone)]
#[repr(C)]
pub(crate) struct RawAccountId {
    pub suffix: Felt,
    pub prefix: Felt,
}

impl RawAccountId {
    /// Converts the protocol return layout into the Rust [`AccountId`] layout.
    pub(crate) fn into_account_id(self) -> AccountId {
        AccountId::new(self.prefix, self.suffix)
    }
}

impl From<AccountId> for Word {
    #[inline]
    fn from(value: AccountId) -> Self {
        Word::from([felt!(0), felt!(0), value.suffix, value.prefix])
    }
}

impl TryFrom<Word> for AccountId {
    type Error = &'static str;

    #[inline]
    fn try_from(value: Word) -> Result<Self, Self::Error> {
        if value[0] != felt!(0) || value[1] != felt!(0) {
            return Err("expected zero padding in the upper two felts");
        }

        Ok(Self {
            prefix: value[3],
            suffix: value[2],
        })
    }
}

/// A fungible or non-fungible asset encoded as separate vault key and value words.
///
/// The `key` identifies the asset in the account vault and the `value` stores the corresponding
/// asset contents. This matches the v0.14 protocol/base ABI.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct Asset {
    /// The asset's vault key.
    pub key: Word,
    /// The asset's vault value.
    pub value: Word,
}

impl Asset {
    /// Creates a new [`Asset`] from its key and value words.
    pub fn new(key: impl Into<Word>, value: impl Into<Word>) -> Self {
        Self {
            key: key.into(),
            value: value.into(),
        }
    }

    /// Returns this asset's fungible amount.
    ///
    /// Intended for kernel-encoded assets (e.g. the ones returned by the `get_assets`
    /// bindings), whose encoding invariants make the composition bit sufficient to discriminate
    /// fungibility.
    ///
    /// # Panics
    ///
    /// Panics if the asset is not fungible or its amount exceeds [`AssetAmount::MAX_U64`].
    pub fn amount(&self) -> AssetAmount {
        assert!(self.is_fungible(), "asset is not fungible");
        let amount = self.value[0];
        assert!(
            amount <= AssetAmount::max_inner(),
            "asset amount exceeds the maximum allowed amount"
        );
        AssetAmount { inner: amount }
    }

    /// Returns `true` if this asset is fungible.
    ///
    /// Intended for kernel-encoded assets (e.g. the ones returned by the `get_assets`
    /// bindings), whose encoding invariants make the composition bit sufficient to discriminate
    /// fungibility.
    #[inline]
    pub fn is_fungible(&self) -> bool {
        // The composition field occupies the lowest bits of the vault-key metadata byte (the
        // low byte of the faucet-id suffix limb, mirroring
        // `miden_protocol::asset::AssetVaultKey`), and `Fungible = 0b01` is the only odd
        // composition, so the limb's parity discriminates fungible assets.
        self.key[2].as_canonical_u64() & 1 == 1
    }
}

impl From<Asset> for (Word, Word) {
    fn from(val: Asset) -> Self {
        (val.key, val.value)
    }
}

/// An error produced while constructing an [`AssetAmount`] from an out-of-range value.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum AssetAmountError {
    /// The amount exceeds [`AssetAmount::MAX_U64`].
    AmountTooBig(u64),
}

impl core::fmt::Display for AssetAmountError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::AmountTooBig(amount) => {
                write!(f, "asset amount {amount} exceeds the maximum {}", AssetAmount::MAX_U64)
            }
        }
    }
}

impl core::error::Error for AssetAmountError {}

/// A validated fungible asset amount.
///
/// Values created through this type's constructors, conversions, and arithmetic operations wrap
/// a [`Felt`] whose canonical value is at most [`AssetAmount::MAX_U64`]. The API mirrors
/// `miden_protocol::asset::AssetAmount` so that on-chain and off-chain code handle amounts the
/// same way, while the felt representation avoids integer/felt conversions around the
/// transaction kernel procedures.
///
/// Unlike a raw [`Felt`], an amount only offers integer semantics: addition and subtraction
/// panic on overflow and underflow instead of wrapping, and comparison follows the canonical
/// integer value. Finite field arithmetic (wrapping at the field modulus, division via the
/// multiplicative inverse) is intentionally unavailable; convert with [`AssetAmount::as_u64`]
/// when full integer functionality is needed.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct AssetAmount {
    /// The raw field representation.
    ///
    /// Assigning this field directly bypasses amount validation; the checked arithmetic rejects
    /// out-of-range operands. It is public only because component-model bindings construct WIT
    /// records by field — use the checked constructors and accessors instead.
    #[doc(hidden)]
    pub inner: Felt,
}

impl AssetAmount {
    /// The maximum value an asset amount can represent, equal to `2^63 - 2^31`.
    ///
    /// Matches `miden_protocol::asset::AssetAmount::MAX`, which is chosen so that an amount fits
    /// in a field element as both a positive and a negative value.
    // Felt constants on the Miden target are limited to 32-bit values, so the maximum amount
    // cannot be an associated `AssetAmount` constant; see `Self::max`.
    pub const MAX_U64: u64 = (1u64 << 63) - (1u64 << 31);
    /// The zero amount.
    pub const ZERO: Self = Self { inner: Felt::ZERO };

    /// Returns the maximum representable asset amount, equal to [`Self::MAX_U64`].
    #[inline]
    pub fn max() -> Self {
        Self {
            inner: Self::max_inner(),
        }
    }

    /// Returns a new asset amount if `amount` does not exceed [`Self::MAX_U64`].
    ///
    /// # Errors
    ///
    /// Returns an error if `amount` is greater than [`Self::MAX_U64`].
    pub fn new(amount: u64) -> Result<Self, AssetAmountError> {
        if amount > Self::MAX_U64 {
            return Err(AssetAmountError::AmountTooBig(amount));
        }
        // The bound check above also guarantees the value is below the field modulus.
        Ok(Self {
            inner: Felt::new_unchecked(amount),
        })
    }

    /// Returns the amount as a `u64` value.
    #[inline]
    pub fn as_u64(&self) -> u64 {
        self.inner.as_canonical_u64()
    }

    /// Returns the amount as a raw [`Felt`] for advanced use.
    #[inline]
    pub fn as_felt(&self) -> Felt {
        self.inner
    }

    /// Returns the maximum amount as a raw felt.
    #[inline(always)]
    fn max_inner() -> Felt {
        // MAX_U64 is below the field modulus, so no reduction occurs.
        Felt::new_unchecked(Self::MAX_U64)
    }

    /// Builds the out-of-range error for the provided felt.
    #[inline]
    fn amount_too_big(value: Felt) -> AssetAmountError {
        // The felt-to-integer conversion only runs on error paths.
        AssetAmountError::AmountTooBig(value.as_canonical_u64())
    }
}

// Two maximal amounts must sum to exactly the field modulus minus one; the checked arithmetic
// below relies on this to rule out field wrap-around for validated operands.
const _: () = assert!(AssetAmount::MAX_U64 * 2 == Felt::ORDER - 1);

impl core::ops::Add for AssetAmount {
    type Output = Self;

    /// Adds two asset amounts, staying in the field domain.
    ///
    /// # Panics
    ///
    /// Panics if either operand or the sum exceeds [`AssetAmount::MAX_U64`].
    fn add(self, other: Self) -> Self {
        let max = Self::max_inner();
        // Reject an out-of-range operand (possible via direct `inner` assignment) before
        // relying on its value.
        assert!(self.inner <= max, "asset amount exceeds the maximum allowed amount");
        // `self` is in range, so this felt subtraction is exact and the headroom is at most
        // MAX_U64. One comparison then proves both that `other` is in range
        // (other <= headroom <= MAX_U64) and that the sum stays in range
        // (self + other <= MAX_U64), so the felt addition below cannot wrap around.
        let headroom = max - self.inner;
        assert!(other.inner <= headroom, "asset amount addition overflow");
        Self {
            inner: self.inner + other.inner,
        }
    }
}

impl core::ops::Sub for AssetAmount {
    type Output = Self;

    /// Subtracts `other` from `self`, staying in the field domain.
    ///
    /// # Panics
    ///
    /// Panics if either operand exceeds [`AssetAmount::MAX_U64`] or if `other` is greater than
    /// `self`.
    fn sub(self, other: Self) -> Self {
        let max = Self::max_inner();
        // An out-of-range minuend (possible via direct `inner` assignment) could otherwise
        // produce an out-of-range result.
        assert!(self.inner <= max, "asset amount exceeds the maximum allowed amount");
        // When this check passes, other <= self <= MAX_U64, so `other` is in range, the felt
        // subtraction cannot wrap around, and the result needs no validation.
        assert!(other.inner <= self.inner, "asset amount subtraction underflow");
        Self {
            inner: self.inner - other.inner,
        }
    }
}

impl Default for AssetAmount {
    fn default() -> Self {
        Self::ZERO
    }
}

impl From<u8> for AssetAmount {
    fn from(value: u8) -> Self {
        Self {
            inner: Felt::from(value),
        }
    }
}

impl From<u16> for AssetAmount {
    fn from(value: u16) -> Self {
        Self {
            inner: Felt::from(value),
        }
    }
}

impl From<u32> for AssetAmount {
    fn from(value: u32) -> Self {
        // Any u32 value is below the maximum amount.
        Self {
            inner: Felt::from_u32(value),
        }
    }
}

impl TryFrom<u64> for AssetAmount {
    type Error = AssetAmountError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl TryFrom<Felt> for AssetAmount {
    type Error = AssetAmountError;

    fn try_from(value: Felt) -> Result<Self, Self::Error> {
        if value > Self::max_inner() {
            return Err(Self::amount_too_big(value));
        }
        Ok(Self { inner: value })
    }
}

impl From<AssetAmount> for u64 {
    fn from(amount: AssetAmount) -> Self {
        amount.as_u64()
    }
}

impl From<AssetAmount> for Felt {
    fn from(amount: AssetAmount) -> Self {
        amount.inner
    }
}

impl core::fmt::Display for AssetAmount {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.as_u64())
    }
}

/// A note recipient digest.
#[derive(Clone, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct Recipient {
    pub inner: Word,
}

/// The note metadata returned by `*_note::get_metadata` procedures.
///
/// In the Miden protocol, metadata retrieval returns a single metadata header word. Note
/// attachments are retrieved separately via the `*_note::get_attachments_commitment`,
/// `find_attachment`, and `write_attachment_*` procedures.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct NoteMetadata {
    /// The metadata header of the note.
    pub header: Word,
}

impl NoteMetadata {
    /// Creates a new [`NoteMetadata`] from the metadata header word.
    pub fn new(header: Word) -> Self {
        Self { header }
    }
}

/// Raw protocol return layout for attachment lookups.
#[derive(Copy, Clone)]
#[repr(C)]
pub(crate) struct RawAttachmentLocation {
    /// Non-zero when the attachment scheme was found.
    pub is_found: Felt,
    /// The matching attachment index, valid only when `is_found` is non-zero.
    pub index: Felt,
}

impl RawAttachmentLocation {
    /// Converts the protocol return layout into the found attachment index, if any.
    pub(crate) fn into_attachment_index(self) -> Option<u32> {
        if self.is_found == Felt::ZERO {
            return None;
        }
        // The transaction kernel guarantees attachment indexes fit in a u32.
        Some(self.index.as_canonical_u64() as u32)
    }
}

impl From<[Felt; 4]> for Recipient {
    fn from(value: [Felt; 4]) -> Self {
        Recipient {
            inner: Word::from(value),
        }
    }
}

impl From<Word> for Recipient {
    fn from(value: Word) -> Self {
        Recipient { inner: value }
    }
}

impl From<Recipient> for Word {
    #[inline]
    fn from(value: Recipient) -> Self {
        value.inner
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct Tag {
    pub inner: Felt,
}

impl From<Felt> for Tag {
    fn from(value: Felt) -> Self {
        Tag { inner: value }
    }
}

impl From<Tag> for Word {
    #[inline]
    fn from(value: Tag) -> Self {
        padded_word_from_felt(value.inner)
    }
}

impl TryFrom<Word> for Tag {
    type Error = &'static str;

    #[inline]
    fn try_from(value: Word) -> Result<Self, Self::Error> {
        Ok(Tag {
            inner: felt_from_padded_word(value)?,
        })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct NoteIdx {
    pub inner: Felt,
}

impl From<NoteIdx> for Word {
    #[inline]
    fn from(value: NoteIdx) -> Self {
        padded_word_from_felt(value.inner)
    }
}

impl TryFrom<Word> for NoteIdx {
    type Error = &'static str;

    #[inline]
    fn try_from(value: Word) -> Result<Self, Self::Error> {
        Ok(NoteIdx {
            inner: felt_from_padded_word(value)?,
        })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct NoteType {
    pub inner: Felt,
}

impl From<Felt> for NoteType {
    fn from(value: Felt) -> Self {
        NoteType { inner: value }
    }
}

impl From<NoteType> for Word {
    #[inline]
    fn from(value: NoteType) -> Self {
        padded_word_from_felt(value.inner)
    }
}

impl TryFrom<Word> for NoteType {
    type Error = &'static str;

    #[inline]
    fn try_from(value: Word) -> Result<Self, Self::Error> {
        Ok(NoteType {
            inner: felt_from_padded_word(value)?,
        })
    }
}

/// An account nonce: a counter the transaction kernel increments once per state-changing
/// transaction.
///
/// Nonces compare as integers; they are produced by the account bindings and carry no
/// arithmetic of their own.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Nonce {
    /// The raw field representation. Public only because component-model bindings construct
    /// WIT records by field.
    #[doc(hidden)]
    pub inner: Felt,
}

impl Nonce {
    /// Returns the nonce as a `u64` value.
    #[inline]
    pub fn as_u64(&self) -> u64 {
        self.inner.as_canonical_u64()
    }

    /// Returns the nonce as a raw [`Felt`] for advanced use.
    #[inline]
    pub fn as_felt(&self) -> Felt {
        self.inner
    }
}

impl From<Nonce> for Felt {
    #[inline]
    fn from(value: Nonce) -> Self {
        value.inner
    }
}

/// A block height in the chain.
///
/// Block numbers compare as integers and are bounded to `u32` by the protocol. Kernel-returned
/// heights are trusted; raw felts (e.g. read from note storage) convert via the validated
/// [`TryFrom<Felt>`] implementation.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct BlockNumber {
    /// The raw field representation. Public only because component-model bindings construct
    /// WIT records by field.
    #[doc(hidden)]
    pub inner: Felt,
}

impl BlockNumber {
    /// Returns the block number as a `u32` value.
    ///
    /// # Panics
    ///
    /// Panics if the wrapped felt exceeds the maximum block height (possible only for values
    /// that bypassed validation, e.g. a WIT record lifted from a raw felt).
    #[inline]
    pub fn as_u32(&self) -> u32 {
        // Compared in the felt domain: felt comparisons lower to VM intrinsics, which is much
        // cheaper than u64 comparison libcalls.
        assert!(
            self.inner <= Felt::from_u32(u32::MAX),
            "block number exceeds the maximum block height"
        );
        self.inner.as_canonical_u64() as u32
    }

    /// Returns the block number as a raw [`Felt`] for advanced use.
    #[inline]
    pub fn as_felt(&self) -> Felt {
        self.inner
    }
}

impl From<u32> for BlockNumber {
    fn from(value: u32) -> Self {
        Self {
            inner: Felt::from_u32(value),
        }
    }
}

impl TryFrom<Felt> for BlockNumber {
    type Error = &'static str;

    fn try_from(value: Felt) -> Result<Self, Self::Error> {
        if value.as_canonical_u64() > u32::MAX as u64 {
            return Err("block number exceeds the maximum block height");
        }
        Ok(Self { inner: value })
    }
}

impl From<BlockNumber> for Felt {
    #[inline]
    fn from(value: BlockNumber) -> Self {
        value.inner
    }
}

/// The partial hash of a storage slot name.
///
/// A slot id consists of two field elements: a `prefix` and a `suffix`.
///
/// Slot ids uniquely identify slots in account storage and are used by the host functions exposed
/// via `miden::protocol::*`.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct StorageSlotId {
    suffix: Felt,
    prefix: Felt,
}

impl StorageSlotId {
    /// Creates a new [`StorageSlotId`] from the provided felts.
    ///
    /// Note: this constructor takes `(suffix, prefix)` to match the values returned by
    /// `miden_protocol::account::StorageSlotId::{suffix,prefix}`.
    pub fn new(suffix: Felt, prefix: Felt) -> Self {
        Self { suffix, prefix }
    }

    /// Creates a new [`StorageSlotId`] from the provided felts in host-call order.
    ///
    /// Host functions take the `prefix` first and then the `suffix`.
    pub fn from_prefix_suffix(prefix: Felt, suffix: Felt) -> Self {
        Self { suffix, prefix }
    }

    /// Returns the `(prefix, suffix)` pair in host-call order.
    pub fn to_prefix_suffix(&self) -> (Felt, Felt) {
        (self.prefix, self.suffix)
    }

    /// Returns the `(suffix, prefix)` pair in storage-slot order.
    pub fn to_suffix_prefix(&self) -> (Felt, Felt) {
        (self.suffix, self.prefix)
    }

    /// Returns the suffix of the [`StorageSlotId`].
    pub fn suffix(&self) -> Felt {
        self.suffix
    }

    /// Returns the prefix of the [`StorageSlotId`].
    pub fn prefix(&self) -> Felt {
        self.prefix
    }
}

#[cfg(test)]
mod tests {
    use miden_stdlib_sys::{Felt, Word, felt};

    use super::{
        Asset, AssetAmount, AssetAmountError, BlockNumber, felt_from_padded_word,
        padded_word_from_felt,
    };

    /// Ensures `padded_word_from_felt` zero-pads the trailing three limbs.
    #[test]
    fn padded_word_from_felt_zero_pads_trailing_limbs() {
        assert_eq!(
            padded_word_from_felt(felt!(7)),
            Word::new([felt!(7), felt!(0), felt!(0), felt!(0)])
        );
    }

    /// Ensures `felt_from_padded_word` rejects words with non-zero trailing padding.
    #[test]
    fn felt_from_padded_word_rejects_non_zero_padding() {
        let err =
            felt_from_padded_word(Word::new([felt!(7), felt!(1), felt!(0), felt!(0)])).unwrap_err();

        assert_eq!(err, "expected zero padding in the trailing three felts");
    }

    /// Ensures the felt-padding helpers form a lossless roundtrip for scalar values.
    #[test]
    fn felt_padding_helpers_roundtrip() {
        let value = felt!(42);

        assert_eq!(felt_from_padded_word(padded_word_from_felt(value)), Ok(value));
    }

    /// Ensures amounts within the bound construct successfully and convert back losslessly.
    #[test]
    fn asset_amount_valid_amounts() {
        assert_eq!(AssetAmount::new(0).unwrap().as_u64(), 0);
        assert_eq!(AssetAmount::new(1000).unwrap().as_u64(), 1000);
        assert_eq!(AssetAmount::new(AssetAmount::MAX_U64).unwrap(), AssetAmount::max());
    }

    /// Ensures amounts above the bound are rejected with the offending value.
    #[test]
    fn asset_amount_exceeds_max() {
        assert_eq!(
            AssetAmount::new(AssetAmount::MAX_U64 + 1),
            Err(AssetAmountError::AmountTooBig(AssetAmount::MAX_U64 + 1))
        );
        assert_eq!(AssetAmount::new(u64::MAX), Err(AssetAmountError::AmountTooBig(u64::MAX)));
    }

    /// Ensures the maximum amount constant matches its documented value.
    #[test]
    fn asset_amount_max_value() {
        assert_eq!(AssetAmount::MAX_U64, 2u64.pow(63) - 2u64.pow(31));
        assert_eq!(AssetAmount::max().as_u64(), AssetAmount::MAX_U64);
    }

    /// Ensures the infallible conversions from small integer types.
    #[test]
    fn asset_amount_from_small_types() {
        assert_eq!(AssetAmount::from(42u8).as_u64(), 42);
        assert_eq!(AssetAmount::from(1000u16).as_u64(), 1000);
        assert_eq!(AssetAmount::from(u32::MAX).as_u64(), u32::MAX as u64);
    }

    /// Ensures the fallible conversions from `u64` and `Felt` enforce the bound.
    #[test]
    fn asset_amount_try_from() {
        assert!(AssetAmount::try_from(AssetAmount::MAX_U64).is_ok());
        assert!(AssetAmount::try_from(AssetAmount::MAX_U64 + 1).is_err());
        assert!(AssetAmount::try_from(Felt::new(AssetAmount::MAX_U64).unwrap()).is_ok());
        assert!(AssetAmount::try_from(Felt::new(AssetAmount::MAX_U64 + 1).unwrap()).is_err());
        // The largest canonical felt is far above the bound and must be rejected.
        assert_eq!(
            AssetAmount::try_from(Felt::new(Felt::ORDER - 1).unwrap()),
            Err(AssetAmountError::AmountTooBig(Felt::ORDER - 1))
        );
    }

    /// Ensures addition computes exact integer sums for in-range amounts.
    #[test]
    fn asset_amount_add() {
        let a = AssetAmount::new(100).unwrap();
        let b = AssetAmount::new(200).unwrap();

        assert_eq!((a + b).as_u64(), 300);
        assert_eq!(AssetAmount::ZERO + AssetAmount::ZERO, AssetAmount::ZERO);
        assert_eq!(AssetAmount::max() + AssetAmount::ZERO, AssetAmount::max());
    }

    /// Ensures addition panics when the sum exceeds the maximum amount.
    #[test]
    #[should_panic(expected = "asset amount addition overflow")]
    fn asset_amount_add_panics_on_overflow() {
        let _ = AssetAmount::max() + AssetAmount::new(1).unwrap();
    }

    /// Ensures addition rejects an out-of-range left operand built via direct field assignment
    /// instead of laundering it into a valid-looking sum; this operand would wrap the field to
    /// zero if it were not rejected.
    #[test]
    #[should_panic(expected = "asset amount exceeds the maximum allowed amount")]
    fn asset_amount_add_panics_on_forged_lhs() {
        let wrapping = AssetAmount {
            inner: Felt::new(Felt::ORDER - 1).unwrap(),
        };

        let _ = wrapping + AssetAmount::new(1).unwrap();
    }

    /// Ensures addition rejects an out-of-range right operand built via direct field
    /// assignment (reported as an overflowing sum).
    #[test]
    #[should_panic(expected = "asset amount addition overflow")]
    fn asset_amount_add_panics_on_forged_rhs() {
        let forged = AssetAmount {
            inner: Felt::new(AssetAmount::MAX_U64 + 1).unwrap(),
        };

        let _ = AssetAmount::new(1).unwrap() + forged;
    }

    /// Ensures subtraction computes exact integer differences for in-range amounts.
    #[test]
    fn asset_amount_sub() {
        let a = AssetAmount::new(300).unwrap();
        let b = AssetAmount::new(100).unwrap();

        assert_eq!((a - b).as_u64(), 200);
        assert_eq!(AssetAmount::ZERO - AssetAmount::ZERO, AssetAmount::ZERO);
        assert_eq!(AssetAmount::max() - AssetAmount::max(), AssetAmount::ZERO);
    }

    /// Ensures subtraction panics when the subtrahend exceeds the minuend.
    #[test]
    #[should_panic(expected = "asset amount subtraction underflow")]
    fn asset_amount_sub_panics_on_underflow() {
        let _ = AssetAmount::ZERO - AssetAmount::new(1).unwrap();
    }

    /// Ensures subtraction rejects an out-of-range minuend built via direct field assignment,
    /// which could otherwise produce an out-of-range result.
    #[test]
    #[should_panic(expected = "asset amount exceeds the maximum allowed amount")]
    fn asset_amount_sub_panics_on_forged_minuend() {
        let forged = AssetAmount {
            inner: Felt::new(AssetAmount::MAX_U64 + 1).unwrap(),
        };

        let _ = forged - AssetAmount::new(1).unwrap();
    }

    /// Ensures the SDK amount arithmetic agrees with the off-chain protocol implementation
    /// whenever the protocol operation succeeds (the SDK panics where the protocol errors).
    #[test]
    fn asset_amount_differential_vs_protocol() {
        use miden_protocol::asset::AssetAmount as ProtocolAmount;

        let values = [
            0u64,
            1,
            2,
            31,
            u32::MAX as u64,
            1 << 40,
            AssetAmount::MAX_U64 / 2,
            AssetAmount::MAX_U64 - 1,
            AssetAmount::MAX_U64,
        ];
        for &a in &values {
            for &b in &values {
                let ours = (AssetAmount::new(a).unwrap(), AssetAmount::new(b).unwrap());
                let theirs = (ProtocolAmount::new(a).unwrap(), ProtocolAmount::new(b).unwrap());

                if let Ok(sum) = theirs.0 + theirs.1 {
                    assert_eq!(
                        (ours.0 + ours.1).as_u64(),
                        sum.as_u64(),
                        "sum mismatch for {a} + {b}"
                    );
                }

                if let Ok(difference) = theirs.0 - theirs.1 {
                    assert_eq!(
                        (ours.0 - ours.1).as_u64(),
                        difference.as_u64(),
                        "difference mismatch for {a} - {b}"
                    );
                }
            }
        }
    }

    /// Ensures comparison follows canonical integer ordering.
    #[test]
    fn asset_amount_ordering() {
        assert!(AssetAmount::new(1).unwrap() < AssetAmount::new(2).unwrap());
        assert!(AssetAmount::max() > AssetAmount::ZERO);
        assert_eq!(AssetAmount::default(), AssetAmount::ZERO);
    }

    /// Ensures the amount displays as a decimal integer.
    #[test]
    fn asset_amount_display() {
        extern crate alloc;
        use alloc::string::ToString;

        assert_eq!(AssetAmount::new(12345).unwrap().to_string(), "12345");
    }

    /// Ensures the felt accessor and conversions roundtrip the underlying value.
    #[test]
    fn asset_amount_felt_roundtrip() {
        let amount = AssetAmount::new(500).unwrap();

        assert_eq!(amount.as_felt(), felt!(500));
        assert_eq!(Felt::from(amount), felt!(500));
        assert_eq!(u64::from(amount), 500);
    }

    /// Creates a raw fungible asset encoding (composition bits `0b01` in the key metadata byte)
    /// for amount tests.
    fn fungible_asset(amount: Felt) -> Asset {
        Asset::new(
            Word::new([felt!(0), felt!(0), felt!(1), felt!(0)]),
            Word::new([amount, felt!(0), felt!(0), felt!(0)]),
        )
    }

    /// Ensures the fungibility check discriminates by the composition parity.
    #[test]
    fn asset_is_fungible() {
        let non_fungible = Asset::new(
            Word::new([felt!(0), felt!(0), felt!(2), felt!(0)]),
            Word::new([felt!(42), felt!(0), felt!(0), felt!(0)]),
        );

        assert!(fungible_asset(felt!(42)).is_fungible());
        assert!(!non_fungible.is_fungible());
    }

    /// Ensures fungible asset amounts are decoded from valid key/value encodings.
    #[test]
    fn asset_amount_decodes_valid_fungible_assets() {
        let asset = fungible_asset(felt!(42));
        // Metadata byte 0b101: fungible composition with the callback flag set.
        let callback_asset =
            Asset::new(Word::new([felt!(0), felt!(0), felt!(5), felt!(0)]), asset.value);

        assert_eq!(asset.amount(), AssetAmount::new(42).unwrap());
        assert_eq!(callback_asset.amount(), AssetAmount::new(42).unwrap());
    }

    /// Ensures the amount accessor panics for non-fungible assets (even composition bits).
    #[test]
    #[should_panic(expected = "asset is not fungible")]
    fn asset_amount_panics_on_non_fungible() {
        let non_fungible = Asset::new(
            Word::new([felt!(1), felt!(0), felt!(0), felt!(0)]),
            Word::new([felt!(42), felt!(0), felt!(0), felt!(0)]),
        );

        let _ = non_fungible.amount();
    }

    /// Ensures the amount accessor panics when the amount exceeds the maximum.
    #[test]
    #[should_panic(expected = "asset amount exceeds the maximum allowed amount")]
    fn asset_amount_panics_on_excessive_amount() {
        let excessive_amount = fungible_asset(Felt::new(AssetAmount::MAX_U64 + 1).unwrap());

        let _ = excessive_amount.amount();
    }

    /// Ensures block-number felts validate against the `u32` protocol bound.
    #[test]
    fn block_number_try_from_felt_bounds() {
        let max = Felt::new(u32::MAX as u64).unwrap();

        assert_eq!(BlockNumber::try_from(max).unwrap().as_u32(), u32::MAX);
        assert!(BlockNumber::try_from(Felt::new(u32::MAX as u64 + 1).unwrap()).is_err());
    }

    /// Ensures `as_u32` refuses to truncate an out-of-range felt smuggled in through the public
    /// WIT-record field.
    #[test]
    #[should_panic(expected = "block number exceeds the maximum block height")]
    fn block_number_as_u32_panics_on_out_of_range_felt() {
        let forged = BlockNumber {
            inner: Felt::new(u32::MAX as u64 + 1).unwrap(),
        };

        let _ = forged.as_u32();
    }
}