tx3-tir 0.19.0

Artifacts for the Tx3 Transaction Intermediate Representation (TIR)
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
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

pub type AssetPolicy = Vec<u8>;
pub type AssetName = Vec<u8>;

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub enum AssetClass {
    Naked,
    Named(AssetName),
    Defined(AssetPolicy, AssetName),
}

impl AssetClass {
    pub fn is_defined(&self) -> bool {
        matches!(self, AssetClass::Defined(_, _))
    }

    pub fn is_named(&self) -> bool {
        matches!(self, AssetClass::Named(_))
    }

    pub fn is_naked(&self) -> bool {
        matches!(self, AssetClass::Naked)
    }

    pub fn policy(&self) -> Option<&[u8]> {
        match self {
            AssetClass::Defined(policy, _) => Some(policy),
            _ => None,
        }
    }

    pub fn name(&self) -> Option<&[u8]> {
        match self {
            AssetClass::Defined(_, name) => Some(name),
            AssetClass::Named(name) => Some(name),
            _ => None,
        }
    }
}

impl std::fmt::Display for AssetClass {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AssetClass::Naked => write!(f, "naked")?,
            AssetClass::Named(name) => write!(f, "{}", hex::encode(name))?,
            AssetClass::Defined(policy, name) => {
                write!(f, "{}.{}", hex::encode(policy), hex::encode(name))?
            }
        }

        Ok(())
    }
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct CanonicalAssets(HashMap<AssetClass, i128>);

impl std::fmt::Display for CanonicalAssets {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "CanonicalAssets {{")?;

        for (class, amount) in self.iter() {
            write!(f, "{}:{}", class, amount)?;
        }

        write!(f, "}}")?;

        Ok(())
    }
}

impl Default for CanonicalAssets {
    fn default() -> Self {
        Self::empty()
    }
}

impl std::ops::Deref for CanonicalAssets {
    type Target = HashMap<AssetClass, i128>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl CanonicalAssets {
    pub fn empty() -> Self {
        Self(HashMap::new())
    }

    pub fn from_class_and_amount(class: AssetClass, amount: i128) -> Self {
        Self(HashMap::from([(class, amount)]))
    }

    pub fn from_naked_amount(amount: i128) -> Self {
        Self(HashMap::from([(AssetClass::Naked, amount)]))
    }

    pub fn from_named_asset(asset_name: &[u8], amount: i128) -> Self {
        if asset_name.is_empty() {
            return Self::from_naked_amount(amount);
        }

        Self(HashMap::from([(
            AssetClass::Named(asset_name.to_vec()),
            amount,
        )]))
    }

    pub fn from_defined_asset(policy: &[u8], asset_name: &[u8], amount: i128) -> Self {
        if policy.is_empty() {
            return Self::from_named_asset(asset_name, amount);
        }

        Self(HashMap::from([(
            AssetClass::Defined(policy.to_vec(), asset_name.to_vec()),
            amount,
        )]))
    }

    pub fn from_asset(policy: Option<&[u8]>, name: Option<&[u8]>, amount: i128) -> Self {
        match (policy, name) {
            (Some(policy), Some(name)) => Self::from_defined_asset(policy, name, amount),
            (Some(policy), None) => Self::from_defined_asset(policy, &[], amount),
            (None, Some(name)) => Self::from_named_asset(name, amount),
            (None, None) => Self::from_naked_amount(amount),
        }
    }

    pub fn classes(&self) -> HashSet<AssetClass> {
        self.iter().map(|(class, _)| class.clone()).collect()
    }

    pub fn naked_amount(&self) -> Option<i128> {
        self.get(&AssetClass::Naked).cloned()
    }

    pub fn asset_amount2(&self, policy: &[u8], name: &[u8]) -> Option<i128> {
        self.get(&AssetClass::Defined(policy.to_vec(), name.to_vec()))
            .cloned()
    }

    pub fn asset_amount(&self, asset: &AssetClass) -> Option<i128> {
        self.get(asset).cloned()
    }

    pub fn contains_total(&self, other: &Self) -> bool {
        for (class, other_amount) in other.iter() {
            if *other_amount == 0 {
                continue;
            }

            if *other_amount < 0 {
                return false;
            }

            let Some(self_amount) = self.get(class) else {
                return false;
            };

            if *self_amount < 0 {
                return false;
            }

            if self_amount < other_amount {
                return false;
            }
        }

        true
    }

    pub fn contains_some(&self, other: &Self) -> bool {
        if other.is_empty() {
            return true;
        }

        if self.is_empty() {
            return false;
        }

        for (class, other_amount) in other.iter() {
            if *other_amount == 0 {
                continue;
            }

            let Some(self_amount) = self.get(class) else {
                continue;
            };

            if *self_amount > 0 {
                return true;
            }
        }

        false
    }

    pub fn is_empty(&self) -> bool {
        self.iter().all(|(_, value)| *value == 0)
    }

    pub fn is_empty_or_negative(&self) -> bool {
        for (_, value) in self.iter() {
            if *value > 0 {
                return false;
            }
        }

        true
    }

    pub fn is_only_naked(&self) -> bool {
        self.iter().all(|(x, _)| x.is_naked())
    }

    pub fn as_homogenous_asset(&self) -> Option<(AssetClass, i128)> {
        if self.0.len() != 1 {
            return None;
        }

        let (class, amount) = self.0.iter().next().unwrap();
        Some((class.clone(), *amount))
    }
}

impl From<CanonicalAssets> for HashMap<AssetClass, i128> {
    fn from(assets: CanonicalAssets) -> Self {
        assets.0
    }
}

impl IntoIterator for CanonicalAssets {
    type Item = (AssetClass, i128);
    type IntoIter = std::collections::hash_map::IntoIter<AssetClass, i128>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl std::ops::Neg for CanonicalAssets {
    type Output = Self;

    fn neg(self) -> Self {
        let mut negated = self.0;

        for (_, value) in negated.iter_mut() {
            *value = -*value;
        }

        Self(negated)
    }
}

impl std::ops::Add for CanonicalAssets {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        let mut aggregated = self.0;

        for (key, value) in other.0 {
            *aggregated.entry(key).or_default() += value;
        }

        aggregated.retain(|_, &mut value| value != 0);

        Self(aggregated)
    }
}

impl std::ops::Sub for CanonicalAssets {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        let mut aggregated = self.0;

        for (key, value) in other.0 {
            *aggregated.entry(key).or_default() -= value;
        }

        aggregated.retain(|_, &mut value| value != 0);

        Self(aggregated)
    }
}

impl std::ops::Mul<i128> for CanonicalAssets {
    type Output = Self;

    /// Scale every asset quantity by a scalar factor. A factor of `0` yields the
    /// empty asset set (the `retain` drops the zeroed entries).
    fn mul(self, factor: i128) -> Self {
        let mut scaled = self.0;

        for value in scaled.values_mut() {
            *value *= factor;
        }

        scaled.retain(|_, &mut value| value != 0);

        Self(scaled)
    }
}

impl std::ops::Div<i128> for CanonicalAssets {
    type Output = Self;

    /// Divide every asset quantity by a scalar divisor (integer division,
    /// truncating toward zero). Quantities that truncate to `0` are dropped by
    /// the `retain`. The caller guarantees a non-zero divisor.
    fn div(self, divisor: i128) -> Self {
        let mut scaled = self.0;

        for value in scaled.values_mut() {
            *value /= divisor;
        }

        scaled.retain(|_, &mut value| value != 0);

        Self(scaled)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use proptest::prelude::*;

    prop_compose! {
      fn any_asset() (
        policy in any::<Vec<u8>>(),
        name in any::<Vec<u8>>(),
        amount in any::<i128>(),
      ) -> CanonicalAssets {
        CanonicalAssets::from_defined_asset(&policy, &name, amount)
      }
    }

    prop_compose! {
      fn any_positive_asset() (
        policy in any::<Vec<u8>>(),
        name in any::<Vec<u8>>(),
        amount in 1..i128::MAX,
      ) -> CanonicalAssets {
        CanonicalAssets::from_defined_asset(&policy, &name, amount)
      }
    }

    prop_compose! {
      fn any_positive_composite_asset() (
        naked_amount in 0..i128::MAX,
        defined1 in any_positive_asset(),
        defined2 in any_positive_asset(),
      ) -> CanonicalAssets {
        let naked = CanonicalAssets::from_naked_amount(naked_amount);
        let composite = naked + defined1 + defined2;
        composite
      }
    }

    proptest! {
        #[test]
        fn empty_doesnt_contain_anything(asset in any_asset()) {
            let x = CanonicalAssets::empty();
            assert!(!x.contains_total(&asset));
            assert!(!x.contains_some(&asset));
        }
    }

    proptest! {
        #[test]
        fn empty_is_contained_in_everything(asset in any_asset()) {
            let x = CanonicalAssets::empty();
            assert!(asset.contains_total(&x));
            assert!(asset.contains_some(&x));
        }
    }

    proptest! {
        #[test]
        fn add_positive_makes_it_present(asset in any_positive_asset()) {
            let x = CanonicalAssets::empty();
            let x = x + asset.clone();
            assert!(x.contains_total(&asset));
            assert!(x.contains_some(&asset));
            assert!(!x.is_empty_or_negative());
        }
    }

    proptest! {
        #[test]
        fn sub_on_empty_makes_it_negative(asset in any_positive_asset()) {
            let x = CanonicalAssets::empty();
            let x = x - asset.clone();
            assert!(!x.contains_total(&asset));
            assert!(!x.contains_some(&asset));
            assert!(x.is_empty_or_negative());
        }
    }

    proptest! {
        #[test]
        fn add_is_inverse_of_sub(original in any_asset(), subtracted in any_asset()) {
            let x = original.clone();
            let x = x - subtracted.clone();
            let x = x + subtracted.clone().clone();
            assert_eq!(x, original);
        }
    }

    proptest! {
        #[test]
        fn composite_contains_some_naked(composite in any_positive_composite_asset()) {
            assert!(composite.contains_some(&CanonicalAssets::from_naked_amount(1)));
        }
    }

    proptest! {
        #[test]
        fn composite_contains_some_composite(composite1 in any_positive_composite_asset(), composite2 in any_positive_composite_asset()) {
            assert!(composite1.contains_some(&composite2));
        }
    }
}