thruput-sdk 0.58.0

Thruput smart-contract SDK for Rust (rv32 guest runtime and native test harness)
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
use crate::xdr::*;

use crate::types::AuthTokenNode;

#[cfg(feature = "alloc")]
use crate::types::AuthTokenPayload;

/// Marker trait for types that have a pre-signing (preimage) representation.
///
/// `Preimage` is intentionally unbound — the `WriteXDR + ReadXDR` requirement
/// is deferred to the `Mintable` trait so that recursive contract_types can
/// implement `MintableType` without triggering trait-solver overflow.
pub trait MintableType: Sized + WriteXDR + for<'r> ReadXDR<'r> {
    type Preimage;
}

pub struct AuthTokenPreimage<T> {
    pub consumer: crate::types::ContractAddress,
    pub data: T,
}

// Hand-written because the `ReadXDR`/`WriteXDR` derives don't synthesize
// bounds for generic type params (`T: WriteXDR` on the impl); switch to
// derives if xdrs grows serde-style bound synthesis for them.
impl<T: WriteXDR> WriteXDR for AuthTokenPreimage<T> {
    fn write_xdr<F, W: Writer<F>>(&self, w: &mut W) -> WriteResult<()> {
        self.consumer.write_xdr(w)?;
        self.data.write_xdr(w)
    }

    unsafe fn write_xdr_unchecked<F, W: WriterUnchecked<F>>(&self, w: &mut W) {
        unsafe {
            self.consumer.write_xdr_unchecked(w);
            self.data.write_xdr_unchecked(w);
        }
    }
}

impl<'r, T: ReadXDR<'r>> ReadXDR<'r> for AuthTokenPreimage<T> {
    fn read_xdr<R: Reader<'r>>(r: &mut R) -> ReadResult<Self> {
        Ok(Self {
            consumer: crate::types::ContractAddress::read_xdr(r)?,
            data: T::read_xdr(r)?,
        })
    }
}

const AUTH_TOKEN_MAX_CHILDREN: usize =
    thruput_xdr::auth_token::kAuthTokenMaxChildNodes as usize;

pub type ChildNodeBuf = heapless::Vec<AuthTokenNode, AUTH_TOKEN_MAX_CHILDREN>;

pub trait Mintable: MintableType
where
    Self::Preimage: WriteXDR + for<'r> ReadXDR<'r>,
{
    fn mint_into_parent(
        preimage: Self::Preimage,
        children: &mut ChildNodeBuf,
    ) -> Self;
}

/// Build the [`AuthTokenNode`] tree for `preimage`: the payload is the
/// encoded `T` (nested `Signed` fields become child nodes), and the node's
/// consumer is `preimage.consumer`.
#[cfg(feature = "alloc")]
pub fn build_auth_token_node<T: Mintable>(
    preimage: AuthTokenPreimage<T::Preimage>,
) -> AuthTokenNode
where
    T::Preimage: WriteXDR + for<'r> ReadXDR<'r>,
{
    let mut children = ChildNodeBuf::new();
    let payload_value = T::mint_into_parent(preimage.data, &mut children);
    AuthTokenNode {
        consumer_address: preimage.consumer,
        payload: encode_payload(&payload_value),
        child_nodes: children_to_vecm(children),
    }
}

#[cfg(feature = "alloc")]
pub fn encode_payload<T: WriteXDR>(value: &T) -> AuthTokenPayload {
    let buf = crate::internal::encode_xdr(value).unwrap_or_else(|e| {
        crate::exn::library_throw(crate::AuthTokenError::MintEncodeFailure(
            crate::exn::FaultString::from_display(e),
        ))
    });
    let bytes: xdrs::BytesM<{ thruput_xdr::auth_token::kAuthTokenMaxLen }> =
        buf.as_slice().try_into().unwrap_or_else(|_| {
            crate::exn::library_throw(
                crate::AuthTokenError::MintEncodeFailure(
                    crate::exn::FaultString::from_display(
                        "auth token payload exceeds max length",
                    ),
                ),
            )
        });
    AuthTokenPayload::from(bytes)
}

#[cfg(feature = "alloc")]
fn children_to_vecm(
    children: ChildNodeBuf,
) -> xdrs::VecM<
    AuthTokenNode,
    { thruput_xdr::auth_token::kAuthTokenMaxChildNodes },
> {
    children.as_slice().try_into().unwrap_or_else(|_| {
        crate::exn::library_throw(crate::AuthTokenError::MintEncodeFailure(
            crate::exn::FaultString::from_display(format_args!(
                "too many auth token children (max {})",
                thruput_xdr::auth_token::kAuthTokenMaxChildNodes
            )),
        ))
    })
}

#[cfg(feature = "alloc")]
pub fn encode_auth_token_node(node: &AuthTokenNode) -> alloc::vec::Vec<u8> {
    xdrs::txs::encode(node).unwrap_or_else(|e| {
        crate::exn::library_throw(crate::AuthTokenError::MintEncodeFailure(
            crate::exn::FaultString::from_display(e),
        ))
    })
}

// ── MintableType leaf impls ──

macro_rules! impl_mintable_type_leaf {
    ($($ty:ty),+ $(,)?) => {
        $(
            impl MintableType for $ty {
                type Preimage = $ty;
            }
        )+
    };
}

impl_mintable_type_leaf!(
    u16,
    u32,
    u64,
    u128,
    i16,
    i32,
    i64,
    i128,
    bool,
    (),
    crate::types::ContractAddress,
    crate::types::SHA256Hash,
    crate::types::Ed25519PublicKey,
    crate::types::Ed25519Signature,
    crate::types::MlDsa65PublicKey,
    crate::types::MlDsa65Signature,
    crate::types::PublicKey,
    crate::types::Signature,
    crate::types::BlockHeight,
    thruput_u256::U256,
    thruput_u256::I256,
    crate::types::ContractEntrypointID,
);

impl<const MAX: u32> MintableType for BytesM<MAX> {
    type Preimage = BytesM<MAX>;
}

impl<const N: usize> MintableType for [u8; N] {
    type Preimage = [u8; N];
}

impl<const N: usize, T: MintableType> MintableType for [T; N] {
    type Preimage = [T::Preimage; N];
}

impl<T: MintableType> MintableType for Option<T> {
    type Preimage = Option<T::Preimage>;
}

impl<const MAX: usize> MintableType for heapless::String<MAX> {
    type Preimage = Self;
}

impl<const N: usize> MintableType for heapless::Vec<u8, N> {
    type Preimage = Self;
}

#[cfg(feature = "alloc")]
impl<T: MintableType + 'static, const MAX: u32> MintableType for VecM<T, MAX> {
    type Preimage = VecM<T::Preimage, MAX>;
}

#[cfg(feature = "alloc")]
impl<const MAX: u32> MintableType for StringM<MAX> {
    type Preimage = StringM<MAX>;
}

#[cfg(feature = "alloc")]
impl<T: MintableType> MintableType for alloc::vec::Vec<T> {
    type Preimage = alloc::vec::Vec<T::Preimage>;
}

#[cfg(feature = "alloc")]
impl<T: MintableType> MintableType for alloc::boxed::Box<T> {
    type Preimage = alloc::boxed::Box<T::Preimage>;
}

// ── Mintable leaf impls ──

macro_rules! impl_mintable_leaf {
    ($($ty:ty),+ $(,)?) => {
        $(
            impl Mintable for $ty {
                fn mint_into_parent(preimage: $ty, _children: &mut ChildNodeBuf) -> Self {
                    preimage
                }
            }
        )+
    };
}

impl_mintable_leaf!(
    u16,
    u32,
    u64,
    u128,
    i16,
    i32,
    i64,
    i128,
    bool,
    (),
    crate::types::ContractAddress,
    crate::types::SHA256Hash,
    crate::types::Ed25519PublicKey,
    crate::types::Ed25519Signature,
    crate::types::MlDsa65PublicKey,
    crate::types::MlDsa65Signature,
    crate::types::PublicKey,
    crate::types::Signature,
    crate::types::BlockHeight,
    thruput_u256::U256,
    thruput_u256::I256,
    crate::types::ContractEntrypointID,
);

impl<const MAX: u32> Mintable for BytesM<MAX> {
    fn mint_into_parent(
        preimage: BytesM<MAX>,
        _children: &mut ChildNodeBuf,
    ) -> Self {
        preimage
    }
}

#[cfg(feature = "alloc")]
impl<const MAX: u32> Mintable for StringM<MAX> {
    fn mint_into_parent(
        preimage: StringM<MAX>,
        _children: &mut ChildNodeBuf,
    ) -> Self {
        preimage
    }
}

impl<const MAX: usize> Mintable for heapless::String<MAX> {
    fn mint_into_parent(preimage: Self, _children: &mut ChildNodeBuf) -> Self {
        preimage
    }
}

impl<const N: usize> Mintable for heapless::Vec<u8, N> {
    fn mint_into_parent(preimage: Self, _children: &mut ChildNodeBuf) -> Self {
        preimage
    }
}

impl<const N: usize> Mintable for [u8; N] {
    fn mint_into_parent(
        preimage: [u8; N],
        _children: &mut ChildNodeBuf,
    ) -> Self {
        preimage
    }
}

impl<T: Mintable> Mintable for Option<T>
where
    T::Preimage: WriteXDR + for<'r> ReadXDR<'r>,
    Option<T::Preimage>: WriteXDR + for<'r> ReadXDR<'r>,
{
    fn mint_into_parent(
        preimage: Option<T::Preimage>,
        children: &mut ChildNodeBuf,
    ) -> Self {
        preimage.map(|inner| T::mint_into_parent(inner, children))
    }
}

#[cfg(feature = "alloc")]
impl<T: Mintable + 'static, const MAX: u32> Mintable for VecM<T, MAX>
where
    T::Preimage: WriteXDR + for<'r> ReadXDR<'r> + 'static,
    VecM<T::Preimage, MAX>: WriteXDR + for<'r> ReadXDR<'r>,
{
    fn mint_into_parent(
        preimage: VecM<T::Preimage, MAX>,
        children: &mut ChildNodeBuf,
    ) -> Self {
        let v: alloc::vec::Vec<T> = preimage
            .0
            .into_iter()
            .map(|item| T::mint_into_parent(item, children))
            .collect();
        VecM(v)
    }
}

impl<const N: usize, T: Mintable> Mintable for [T; N]
where
    T::Preimage: WriteXDR + for<'r> ReadXDR<'r>,
    [T::Preimage; N]: WriteXDR + for<'r> ReadXDR<'r>,
{
    fn mint_into_parent(
        preimage: [T::Preimage; N],
        children: &mut ChildNodeBuf,
    ) -> Self {
        preimage.map(|inner| T::mint_into_parent(inner, children))
    }
}

#[cfg(feature = "alloc")]
impl<T: Mintable> Mintable for alloc::vec::Vec<T>
where
    T::Preimage: WriteXDR + for<'r> ReadXDR<'r>,
    alloc::vec::Vec<T::Preimage>: WriteXDR + for<'r> ReadXDR<'r>,
{
    fn mint_into_parent(
        preimage: alloc::vec::Vec<T::Preimage>,
        children: &mut ChildNodeBuf,
    ) -> Self {
        preimage
            .into_iter()
            .map(|item| T::mint_into_parent(item, children))
            .collect()
    }
}

#[cfg(feature = "alloc")]
impl<T: Mintable> Mintable for alloc::boxed::Box<T>
where
    T::Preimage: Sized + WriteXDR + for<'r> ReadXDR<'r>,
    alloc::boxed::Box<T::Preimage>: WriteXDR + for<'r> ReadXDR<'r>,
{
    fn mint_into_parent(
        preimage: alloc::boxed::Box<T::Preimage>,
        children: &mut ChildNodeBuf,
    ) -> Self {
        alloc::boxed::Box::new(T::mint_into_parent(*preimage, children))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::signer::Signed;

    #[test]
    fn primitive_mintable_builds_leaf_node() {
        let node = build_auth_token_node::<u64>(AuthTokenPreimage {
            consumer: crate::types::ContractAddress::default(),
            data: 42u64,
        });
        assert!(node.child_nodes.is_empty());
    }

    #[test]
    fn build_node_sets_consumer_from_preimage() {
        let consumer = crate::types::ContractAddress::from([0xAB; 32]);
        let node = build_auth_token_node::<u64>(AuthTokenPreimage {
            consumer,
            data: 42u64,
        });
        assert_eq!(node.consumer_address, consumer);
    }

    #[test]
    fn primitive_mint_into_parent_no_children() {
        let mut children = ChildNodeBuf::new();
        let val = u64::mint_into_parent(42u64, &mut children);
        assert_eq!(val, 42);
        assert!(children.is_empty());
    }

    #[test]
    fn signed_mint_into_parent_pushes_child() {
        let mut children = ChildNodeBuf::new();
        let consumer = crate::types::ContractAddress::default();
        let val = <Signed<u64>>::mint_into_parent(
            AuthTokenPreimage {
                consumer,
                data: 42u64,
            },
            &mut children,
        );
        assert_eq!(val.handle(), u32::MAX);
        assert_eq!(children.len(), 1);
    }

    #[test]
    fn option_none_no_children() {
        let mut children = ChildNodeBuf::new();
        let val = <Option<Signed<u64>>>::mint_into_parent(None, &mut children);
        assert!(val.is_none());
        assert!(children.is_empty());
    }

    #[test]
    fn option_some_signed_pushes_child() {
        let mut children = ChildNodeBuf::new();
        let consumer = crate::types::ContractAddress::default();
        let val = <Option<Signed<u64>>>::mint_into_parent(
            Some(AuthTokenPreimage {
                consumer,
                data: 42u64,
            }),
            &mut children,
        );
        assert!(val.is_some());
        assert_eq!(children.len(), 1);
    }
}