Skip to main content

moonproof_wallet/
types.rs

1//! Public value types shared across the wallet crate.
2//!
3//! ## `Amount` — 256-bit signed integer
4//!
5//! On-chain `Coin::value` is `u128` (`moonproof_ledger::coin_structure::coin::Coin.value`,
6//! range `0..=2^128 − 1`). The wallet's balancer works in *imbalances*
7//! — `inputs − outputs` — so the type has to be signed AND has to fit
8//! a sum-of-many-u128-coins minus a sum-of-many-u128-coins without
9//! overflow. `i128` cannot do that: its positive range is exactly half
10//! of `u128`, so a single coin with `value > 2^127` already overflows
11//! when cast.
12//!
13//! [`Amount`] is therefore a newtype over `ethnum::I256`:
14//!
15//! - 256 bits is **2× the source-bit width**, so any single u128 lifts
16//!   cleanly and any sum/difference of u128 values fits without
17//!   overflow given realistic transaction sizes (worst-case ≈ 2^130
18//!   for tens of thousands of u128-max coins, well below 2^255).
19//! - Stack-allocated, `Copy`, no heap allocation per arithmetic op —
20//!   stays primitive-int-fast on the balancer hot path. Per-op cost is
21//!   roughly 2-3× `i128` (4-6 instructions vs 2-3 on `x86_64`), still
22//!   sub-microsecond.
23//! - Lifts to/from `i128` and `u128` via `From` / `TryFrom`. Display
24//!   and `FromStr` are decimal so it round-trips through FFI as a
25//!   string at no precision loss (`UniFFI` does not support 128-bit
26//!   integers, let alone 256-bit, regardless of declaration mode).
27//!
28//! ### Why not `num_bigint::BigInt`?
29//! The TS reference uses `bigint` because JavaScript has no
30//! fixed-width 256-bit integer type. `BigInt` is heap-allocated and
31//! pays 10-100× the per-op cost of a stack integer. The balancer
32//! processes hundreds of arithmetic ops per transaction and is on
33//! every wallet user's hot path — primitive-int speed matters.
34//! `I256`'s headroom over realistic u128 sums is so large that `BigInt`
35//! gives no extra correctness in practice.
36//!
37//! ### Why not `i128` with `checked_*` everywhere?
38//! Because `i128` cannot represent the full positive range of `u128`.
39//! `checked_add` only flags overflows that already happened; the type
40//! itself is too small to hold a single legal on-chain value above
41//! `2^127`. That's a soundness gap, not an arithmetic-discipline gap.
42
43use std::fmt;
44use std::iter::Sum;
45use std::num::ParseIntError;
46use std::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};
47use std::str::FromStr;
48
49use ethnum::I256;
50use serde::{Deserialize, Serialize};
51
52use crate::error::{Result, WalletError};
53
54/// A token type identifier. On-chain these are hex-encoded bytes; we keep
55/// them as `String` so the balancer can key on them with `IndexMap` and
56/// consumers can round-trip schema values without parsing.
57#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
58#[serde(transparent)]
59pub struct TokenType(pub String);
60
61impl TokenType {
62    #[inline]
63    #[must_use]
64    pub fn new(s: impl Into<String>) -> Self {
65        Self(s.into())
66    }
67
68    #[inline]
69    #[must_use]
70    pub fn as_str(&self) -> &str {
71        &self.0
72    }
73}
74
75impl fmt::Display for TokenType {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        f.write_str(&self.0)
78    }
79}
80
81impl From<String> for TokenType {
82    #[inline]
83    fn from(s: String) -> Self {
84        Self(s)
85    }
86}
87
88impl From<&str> for TokenType {
89    #[inline]
90    fn from(s: &str) -> Self {
91        Self(s.to_owned())
92    }
93}
94
95// =============================================================================
96// Amount — newtype over ethnum::I256.
97// =============================================================================
98
99/// Signed amount of a token (NIGHT / DUST / etc.). Positive = credit to
100/// the tx's local side; negative = debit.
101///
102/// See the module docs for why this is a 256-bit type. Use
103/// [`Amount::from_u128`] / [`Amount::from_i128`] for the common lifts;
104/// arithmetic is just `+` / `-` / `*`. The arithmetic operators panic
105/// on overflow in debug builds and wrap in release — same behavior as
106/// stdlib integers. For boundary inputs (parsing untrusted strings,
107/// summing arbitrary user-supplied chains) prefer the
108/// [`Amount::checked_add`] / [`Amount::checked_sub`] / etc. variants
109/// that return `Option`.
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
111pub struct Amount(I256);
112
113impl Amount {
114    /// `0`.
115    pub const ZERO: Self = Self(I256::ZERO);
116    /// `1`.
117    pub const ONE: Self = Self(I256::ONE);
118    /// `-1`.
119    pub const NEG_ONE: Self = Self(I256::MINUS_ONE);
120    /// Largest representable value (`2^255 − 1`).
121    pub const MAX: Self = Self(I256::MAX);
122    /// Smallest representable value (`-2^255`).
123    pub const MIN: Self = Self(I256::MIN);
124
125    /// Lift a `u128` (the on-chain `Coin::value` shape). Infallible —
126    /// any `u128` fits in `I256` without sign issues since the high
127    /// 128 bits stay zero.
128    #[inline]
129    #[must_use]
130    pub fn from_u128(value: u128) -> Self {
131        Self(I256::from(value))
132    }
133
134    /// Lift an `i128`. Infallible — the sign extends into the upper
135    /// 128 bits of `I256`.
136    #[inline]
137    #[must_use]
138    pub fn from_i128(value: i128) -> Self {
139        Self(I256::from(value))
140    }
141
142    /// Convert back to `u128`. Returns `None` if the amount is negative
143    /// or doesn't fit in `u128` (exceeds `2^128 − 1`).
144    #[inline]
145    pub fn try_to_u128(self) -> Option<u128> {
146        if self.0 < I256::ZERO {
147            return None;
148        }
149        let (hi, lo) = self.0.into_words();
150        if hi != 0 {
151            return None;
152        }
153        // `lo` is i128 in ethnum's `into_words` for I256 — reinterpret as u128.
154        // Since the high word is zero and the value is non-negative, the low
155        // word's bit pattern is the u128 value.
156        Some(u128::from_ne_bytes(lo.to_ne_bytes()))
157    }
158
159    /// Convert back to `i128`. Returns `None` if the amount doesn't
160    /// fit in `i128` (`< -2^127` or `> 2^127 − 1`).
161    #[inline]
162    pub fn try_to_i128(self) -> Option<i128> {
163        let min = I256::from(i128::MIN);
164        let max = I256::from(i128::MAX);
165        if self.0 < min || self.0 > max {
166            return None;
167        }
168        let (_hi, lo) = self.0.into_words();
169        Some(lo)
170    }
171
172    /// `true` if this amount is greater than zero. Convenience for
173    /// imbalance-direction checks.
174    #[inline]
175    #[must_use]
176    pub fn is_positive(self) -> bool {
177        self.0 > I256::ZERO
178    }
179
180    /// `true` if this amount is less than zero.
181    #[inline]
182    #[must_use]
183    pub fn is_negative(self) -> bool {
184        self.0 < I256::ZERO
185    }
186
187    /// `true` if this amount is exactly zero.
188    #[inline]
189    #[must_use]
190    pub fn is_zero(self) -> bool {
191        self.0 == I256::ZERO
192    }
193
194    /// Absolute value. Saturates at [`Amount::MAX`] when called on
195    /// [`Amount::MIN`] (since `-MIN > MAX`).
196    #[inline]
197    #[must_use]
198    pub fn abs(self) -> Self {
199        Self(self.0.checked_abs().unwrap_or(I256::MAX))
200    }
201
202    /// Checked addition. Returns `None` on overflow.
203    #[inline]
204    #[must_use]
205    pub fn checked_add(self, rhs: Self) -> Option<Self> {
206        self.0.checked_add(rhs.0).map(Self)
207    }
208
209    /// Checked subtraction. Returns `None` on overflow.
210    #[inline]
211    #[must_use]
212    pub fn checked_sub(self, rhs: Self) -> Option<Self> {
213        self.0.checked_sub(rhs.0).map(Self)
214    }
215
216    /// Checked multiplication. Returns `None` on overflow.
217    #[inline]
218    #[must_use]
219    pub fn checked_mul(self, rhs: Self) -> Option<Self> {
220        self.0.checked_mul(rhs.0).map(Self)
221    }
222
223    /// Checked negation. Returns `None` only for [`Amount::MIN`]
224    /// (whose `-` doesn't fit).
225    #[inline]
226    #[must_use]
227    pub fn checked_neg(self) -> Option<Self> {
228        self.0.checked_neg().map(Self)
229    }
230
231    /// Borrow the inner `I256`. Useful in tight loops where the wrapper
232    /// overhead matters.
233    #[inline]
234    #[must_use]
235    pub const fn as_i256(self) -> I256 {
236        self.0
237    }
238}
239
240// ---- Arithmetic operators (delegate to I256). -------------------------------
241
242impl Add for Amount {
243    type Output = Self;
244    #[inline]
245    fn add(self, rhs: Self) -> Self {
246        Self(self.0 + rhs.0)
247    }
248}
249
250impl Sub for Amount {
251    type Output = Self;
252    #[inline]
253    fn sub(self, rhs: Self) -> Self {
254        Self(self.0 - rhs.0)
255    }
256}
257
258impl Mul for Amount {
259    type Output = Self;
260    #[inline]
261    fn mul(self, rhs: Self) -> Self {
262        Self(self.0 * rhs.0)
263    }
264}
265
266impl Neg for Amount {
267    type Output = Self;
268    #[inline]
269    fn neg(self) -> Self {
270        Self(-self.0)
271    }
272}
273
274impl AddAssign for Amount {
275    #[inline]
276    fn add_assign(&mut self, rhs: Self) {
277        self.0 += rhs.0;
278    }
279}
280
281impl SubAssign for Amount {
282    #[inline]
283    fn sub_assign(&mut self, rhs: Self) {
284        self.0 -= rhs.0;
285    }
286}
287
288impl MulAssign for Amount {
289    #[inline]
290    fn mul_assign(&mut self, rhs: Self) {
291        self.0 *= rhs.0;
292    }
293}
294
295impl Sum for Amount {
296    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
297        iter.fold(Self::ZERO, Add::add)
298    }
299}
300
301impl<'a> Sum<&'a Amount> for Amount {
302    fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
303        iter.copied().fold(Self::ZERO, Add::add)
304    }
305}
306
307// ---- Conversions in. --------------------------------------------------------
308
309impl From<i128> for Amount {
310    #[inline]
311    fn from(v: i128) -> Self {
312        Self::from_i128(v)
313    }
314}
315
316impl From<u128> for Amount {
317    #[inline]
318    fn from(v: u128) -> Self {
319        Self::from_u128(v)
320    }
321}
322
323impl From<i64> for Amount {
324    #[inline]
325    fn from(v: i64) -> Self {
326        Self(I256::from(v))
327    }
328}
329
330impl From<u64> for Amount {
331    #[inline]
332    fn from(v: u64) -> Self {
333        Self(I256::from(v))
334    }
335}
336
337impl From<i32> for Amount {
338    #[inline]
339    fn from(v: i32) -> Self {
340        Self(I256::from(v))
341    }
342}
343
344impl From<u32> for Amount {
345    #[inline]
346    fn from(v: u32) -> Self {
347        Self(I256::from(v))
348    }
349}
350
351impl From<i16> for Amount {
352    #[inline]
353    fn from(v: i16) -> Self {
354        Self(I256::from(v))
355    }
356}
357
358impl From<u16> for Amount {
359    #[inline]
360    fn from(v: u16) -> Self {
361        Self(I256::from(v))
362    }
363}
364
365impl From<i8> for Amount {
366    #[inline]
367    fn from(v: i8) -> Self {
368        Self(I256::from(v))
369    }
370}
371
372impl From<u8> for Amount {
373    #[inline]
374    fn from(v: u8) -> Self {
375        Self(I256::from(v))
376    }
377}
378
379// ---- Conversions out — fail when the value won't fit. ---------------------
380
381impl TryFrom<Amount> for u128 {
382    type Error = WalletError;
383
384    fn try_from(value: Amount) -> std::result::Result<Self, Self::Error> {
385        value
386            .try_to_u128()
387            .ok_or_else(|| WalletError::InvalidAmount(format!("{value} does not fit in u128")))
388    }
389}
390
391impl TryFrom<Amount> for i128 {
392    type Error = WalletError;
393
394    fn try_from(value: Amount) -> std::result::Result<Self, Self::Error> {
395        value
396            .try_to_i128()
397            .ok_or_else(|| WalletError::InvalidAmount(format!("{value} does not fit in i128")))
398    }
399}
400
401// ---- Display / FromStr — decimal, FFI-friendly. -----------------------------
402
403impl fmt::Display for Amount {
404    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
405        fmt::Display::fmt(&self.0, f)
406    }
407}
408
409impl FromStr for Amount {
410    type Err = WalletError;
411
412    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
413        I256::from_str_prefixed(s)
414            .map(Self)
415            .map_err(|e| WalletError::InvalidAmount(format!("'{s}': {e}")))
416    }
417}
418
419// ---- Serde — string form, matches the FFI wire shape. -----------------------
420//
421// Using string serialization rather than I256's default JSON form keeps
422// downstream consumers (the FFI `value: String` field, JSON-RPC clients,
423// scenario fixtures) from depending on `ethnum`'s representation choice.
424
425impl Serialize for Amount {
426    fn serialize<S: serde::Serializer>(
427        &self,
428        serializer: S,
429    ) -> std::result::Result<S::Ok, S::Error> {
430        serializer.collect_str(&self.0)
431    }
432}
433
434impl<'de> Deserialize<'de> for Amount {
435    fn deserialize<D: serde::Deserializer<'de>>(
436        deserializer: D,
437    ) -> std::result::Result<Self, D::Error> {
438        let s = String::deserialize(deserializer)?;
439        Self::from_str(&s).map_err(serde::de::Error::custom)
440    }
441}
442
443// ---- Public re-exports + helpers used by the rest of the wallet crate. ------
444
445/// `parse::<i128>` doesn't compose with our `WalletError`, so wallet
446/// code that needs to parse a decimal-string amount uses
447/// `Amount::from_str` and gets a `WalletError::InvalidAmount` for free.
448pub fn parse_amount(s: &str) -> Result<Amount> {
449    Amount::from_str(s)
450}
451
452// =============================================================================
453// CoinRecipe + SimpleCoin — the balancer's input shape.
454// =============================================================================
455
456/// A coin / UTXO abstraction consumed by the balancer.
457pub trait CoinRecipe {
458    fn token_type(&self) -> &TokenType;
459    fn value(&self) -> Amount;
460}
461
462/// Simple concrete `CoinRecipe` useful for tests and consumers that
463/// don't need extra bookkeeping beyond (type, value).
464#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
465pub struct SimpleCoin {
466    pub token_type: TokenType,
467    pub value: Amount,
468}
469
470impl SimpleCoin {
471    /// Build a coin. Both arguments accept any `Into<TokenType>` /
472    /// `Into<Amount>` so test fixtures and config-loaders can pass
473    /// plain integer / string literals.
474    #[inline]
475    #[must_use]
476    pub fn new(token_type: impl Into<TokenType>, value: impl Into<Amount>) -> Self {
477        Self {
478            token_type: token_type.into(),
479            value: value.into(),
480        }
481    }
482}
483
484impl CoinRecipe for SimpleCoin {
485    #[inline]
486    fn token_type(&self) -> &TokenType {
487        &self.token_type
488    }
489
490    #[inline]
491    fn value(&self) -> Amount {
492        self.value
493    }
494}
495
496// =============================================================================
497// TransactionCostModel — per-tx fee overhead model.
498// =============================================================================
499
500/// Per-transaction fee model. Fees are paid in the *native* token (DUST
501/// on Midnight mainnet). Each input and each output consumes a flat
502/// overhead that the balancer deducts from the native-token imbalance
503/// as it runs.
504#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
505pub struct TransactionCostModel {
506    pub input_fee_overhead: Amount,
507    pub output_fee_overhead: Amount,
508}
509
510impl TransactionCostModel {
511    /// Build a model. Both overhead arguments accept anything that
512    /// converts to `Amount` (`u128` / `i128` / `i32` / etc.) so test
513    /// fixtures and config-loaders can pass plain integer literals.
514    #[inline]
515    #[must_use]
516    pub fn new(
517        input_fee_overhead: impl Into<Amount>,
518        output_fee_overhead: impl Into<Amount>,
519    ) -> Self {
520        Self {
521            input_fee_overhead: input_fee_overhead.into(),
522            output_fee_overhead: output_fee_overhead.into(),
523        }
524    }
525
526    /// Zero-cost model — useful in tests where fees aren't the focus.
527    pub const ZERO: Self = Self {
528        input_fee_overhead: Amount::ZERO,
529        output_fee_overhead: Amount::ZERO,
530    };
531}
532
533// =============================================================================
534// Conversion away from `ParseIntError` so callers can use `?` cleanly.
535// =============================================================================
536
537impl From<ParseIntError> for WalletError {
538    fn from(e: ParseIntError) -> Self {
539        WalletError::InvalidAmount(e.to_string())
540    }
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546
547    #[test]
548    fn lifts_full_u128_range_without_overflow() {
549        let max_u128 = u128::MAX;
550        let amt = Amount::from_u128(max_u128);
551        assert!(amt.is_positive());
552        assert_eq!(amt.try_to_u128(), Some(max_u128));
553    }
554
555    #[test]
556    fn sum_of_two_max_u128_does_not_overflow() {
557        // The exact case that would overflow `i128`: two coins of u128::MAX.
558        let a = Amount::from_u128(u128::MAX);
559        let b = Amount::from_u128(u128::MAX);
560        let sum = a + b;
561        // No panic, and the sum is back-convertible through Display.
562        let s = sum.to_string();
563        // Sanity: the sum is exactly `2 * (2^128 - 1)` = `2^129 - 2`.
564        let expected: I256 = (I256::ONE << 129u8) - I256::from(2u32);
565        assert_eq!(sum.as_i256(), expected, "got {s}");
566    }
567
568    #[test]
569    fn negative_imbalance_round_trips() {
570        let inputs = Amount::from_u128(100);
571        let outputs = Amount::from_u128(150);
572        let imbalance = inputs - outputs;
573        assert!(imbalance.is_negative());
574        assert_eq!(imbalance, -Amount::from_u128(50));
575    }
576
577    #[test]
578    fn checked_add_returns_none_on_overflow() {
579        // Can't overflow with u128 inputs but we can with MAX + 1.
580        assert_eq!(Amount::MAX.checked_add(Amount::ONE), None);
581    }
582
583    #[test]
584    fn try_to_u128_rejects_negative() {
585        assert_eq!(Amount::from_i128(-1).try_to_u128(), None);
586    }
587
588    #[test]
589    fn try_to_u128_rejects_above_u128_max() {
590        let big = Amount::from_u128(u128::MAX) + Amount::ONE;
591        assert_eq!(big.try_to_u128(), None);
592    }
593
594    #[test]
595    fn try_to_i128_rejects_above_i128_max() {
596        let big = Amount::from_i128(i128::MAX) + Amount::ONE;
597        assert_eq!(big.try_to_i128(), None);
598    }
599
600    #[test]
601    fn try_to_i128_allows_full_i128_range() {
602        assert_eq!(Amount::from_i128(i128::MAX).try_to_i128(), Some(i128::MAX));
603        assert_eq!(Amount::from_i128(i128::MIN).try_to_i128(), Some(i128::MIN));
604    }
605
606    #[test]
607    fn display_round_trip() {
608        let a = Amount::from_u128(123_456_789_012_345_678_901_234_567_890_u128);
609        let s = a.to_string();
610        let b: Amount = s.parse().unwrap();
611        assert_eq!(a, b);
612    }
613
614    #[test]
615    fn negative_display_round_trip() {
616        let a = -Amount::from_u128(42);
617        let s = a.to_string();
618        assert_eq!(s, "-42");
619        let b: Amount = s.parse().unwrap();
620        assert_eq!(a, b);
621    }
622
623    #[test]
624    fn serde_uses_string_form() {
625        let a = Amount::from_u128(u128::MAX);
626        let json = serde_json::to_string(&a).unwrap();
627        // String-encoded so it survives the JSON Number precision limit.
628        assert!(json.starts_with('"'));
629        let back: Amount = serde_json::from_str(&json).unwrap();
630        assert_eq!(a, back);
631    }
632
633    #[test]
634    fn sum_iterator() {
635        let coins = [
636            Amount::from_u128(10),
637            Amount::from_u128(20),
638            Amount::from_u128(30),
639        ];
640        let total: Amount = coins.iter().sum();
641        assert_eq!(total, Amount::from_u128(60));
642    }
643}