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
//! Calldata + return-value codec — encode runtime values into the
//! Borsh-shaped bytes a Pyde contract reads back through
//! `pyde::calldata_*`, and decode return data the same way.
//!
//! The wire format for each [`ParamType`] matches Borsh's canonical
//! encoding so contracts written in any wasm32-target language
//! (Rust, Go, Zig, …) can `borsh::from_slice` the args directly.

use std::collections::BTreeMap;

use borsh::{BorshDeserialize, BorshSerialize};

use crate::error::SdkError;
use crate::types::{Address, ParamAbi, ParamType};

/// A runtime value tagged by its [`ParamType`].
///
/// Mirrors the [`ParamType`] variant set 1-to-1. Used as the
/// untyped argument / return type on the dynamic [`super::Contract`]
/// surface; typed wrappers generated by the `pyde_abi!` macro
/// translate to/from concrete Rust types.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    /// `u8` value.
    U8(u8),
    /// `u16` value.
    U16(u16),
    /// `u32` value.
    U32(u32),
    /// `u64` value.
    U64(u64),
    /// `u128` value.
    U128(u128),
    /// `i8` value.
    I8(i8),
    /// `i16` value.
    I16(i16),
    /// `i32` value.
    I32(i32),
    /// `i64` value.
    I64(i64),
    /// `i128` value.
    I128(i128),
    /// Boolean.
    Bool(bool),
    /// 32-byte Pyde address.
    Address(Address),
    /// Variable-length opaque bytes.
    Bytes(Vec<u8>),
    /// UTF-8 string.
    String(String),
    /// Fixed-size byte array.
    FixedBytes(Vec<u8>),
    /// Homogeneous list of values.
    Vec(Vec<Value>),
    /// Key-value pairs (in deterministic order — see [`Value::map`]).
    Map(Vec<(Value, Value)>),
    /// Optional value.
    Option(Option<Box<Value>>),
    /// Opaque Borsh bytes for a [`ParamType::Custom`]-tagged value.
    /// The SDK doesn't decode custom types; the bytes are produced
    /// (and consumed) by the caller's typed wrapper.
    Custom(Vec<u8>),
}

impl Value {
    /// Build a [`Value::Map`] from a [`BTreeMap`], preserving the
    /// deterministic key order Borsh expects.
    #[must_use]
    pub fn map(entries: BTreeMap<Value, Value>) -> Self {
        Self::Map(entries.into_iter().collect())
    }
}

// `Eq` + `Hash` + `Ord` for `BTreeMap` keys — provided by deriving
// `PartialEq` plus a manual `Eq` impl. The actual ordering only
// matters when the user wants to insert into a `BTreeMap` of
// `Value` keys (rare in v1).
impl Eq for Value {}

impl PartialOrd for Value {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Value {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Order by canonical Borsh-encoded bytes — gives a stable,
        // wire-consistent ordering without re-implementing per-
        // variant `Ord`. Cheap enough for the rare `BTreeMap<Value, _>`
        // case; not on any hot path.
        let a = borsh_encode(self).unwrap_or_default();
        let b = borsh_encode(other).unwrap_or_default();
        a.cmp(&b)
    }
}

// ── Encoding ───────────────────────────────────────────────────

/// Encode a single value into its canonical Borsh wire bytes.
///
/// Returns the encoded bytes — no length prefix, no type tag.
/// Concatenate multiple encoded values to build calldata for a
/// multi-arg call.
///
/// # Errors
/// Returns [`SdkError::InvalidArgument`] if `value` doesn't match
/// the variant tag of `param_type` (e.g. encoding a `Value::U32`
/// under [`ParamType::U64`]).
pub fn encode_value(param_type: &ParamType, value: &Value) -> Result<Vec<u8>, SdkError> {
    let mut buf = Vec::new();
    write_value(param_type, value, &mut buf)?;
    Ok(buf)
}

/// Encode calldata for a function call.
///
/// Each argument is Borsh-encoded against its declared
/// [`ParamType`] and the results are concatenated in declaration
/// order. This matches the convention contracts use to decode
/// their inputs via `pyde::calldata_copy` + `borsh::from_slice`.
///
/// # Errors
/// - [`SdkError::InvalidArgument`] if `args.len() != params.len()`.
/// - Any error from [`encode_value`].
pub fn encode_calldata(params: &[ParamAbi], args: &[Value]) -> Result<Vec<u8>, SdkError> {
    if args.len() != params.len() {
        return Err(SdkError::InvalidArgument(format!(
            "expected {} args, got {}",
            params.len(),
            args.len()
        )));
    }
    let mut buf = Vec::new();
    for (param, arg) in params.iter().zip(args.iter()) {
        write_value(&param.ty, arg, &mut buf)?;
    }
    Ok(buf)
}

fn write_value(ty: &ParamType, value: &Value, out: &mut Vec<u8>) -> Result<(), SdkError> {
    use ParamType as P;
    use Value as V;
    match (ty, value) {
        (P::U8, V::U8(v)) => borsh_write(v, out),
        (P::U16, V::U16(v)) => borsh_write(v, out),
        (P::U32, V::U32(v)) => borsh_write(v, out),
        (P::U64, V::U64(v)) => borsh_write(v, out),
        (P::U128, V::U128(v)) => borsh_write(v, out),
        (P::I8, V::I8(v)) => borsh_write(v, out),
        (P::I16, V::I16(v)) => borsh_write(v, out),
        (P::I32, V::I32(v)) => borsh_write(v, out),
        (P::I64, V::I64(v)) => borsh_write(v, out),
        (P::I128, V::I128(v)) => borsh_write(v, out),
        (P::Bool, V::Bool(v)) => borsh_write(v, out),
        (P::Address, V::Address(addr)) => {
            out.extend_from_slice(addr.as_bytes());
            Ok(())
        }
        (P::Bytes, V::Bytes(b)) => borsh_write(b, out),
        (P::String, V::String(s)) => borsh_write(s, out),
        (P::FixedBytes(len), V::FixedBytes(b)) => {
            if b.len() as u32 != *len {
                return Err(SdkError::InvalidArgument(format!(
                    "FixedBytes({len}) length mismatch: got {} bytes",
                    b.len()
                )));
            }
            out.extend_from_slice(b);
            Ok(())
        }
        (P::Vec(inner), V::Vec(items)) => {
            // Length-prefixed Borsh Vec: u32_le count then each
            // element in declaration order.
            borsh_write(&(items.len() as u32), out)?;
            for item in items {
                write_value(inner, item, out)?;
            }
            Ok(())
        }
        (P::Map { key, value: vt }, V::Map(pairs)) => {
            // Same shape as Borsh's `HashMap` / `BTreeMap`:
            // u32_le count + (k, v) pairs.
            borsh_write(&(pairs.len() as u32), out)?;
            for (k, v) in pairs {
                write_value(key, k, out)?;
                write_value(vt, v, out)?;
            }
            Ok(())
        }
        (P::Option(inner), V::Option(opt)) => match opt {
            None => {
                out.push(0x00);
                Ok(())
            }
            Some(v) => {
                out.push(0x01);
                write_value(inner, v, out)
            }
        },
        (P::Custom(_), V::Custom(bytes)) => {
            // Opaque; caller-supplied bytes go straight through.
            out.extend_from_slice(bytes);
            Ok(())
        }
        (ty, value) => Err(SdkError::InvalidArgument(format!(
            "type mismatch: {ty:?} cannot encode {value:?}"
        ))),
    }
}

fn borsh_write<T: BorshSerialize>(v: &T, out: &mut Vec<u8>) -> Result<(), SdkError> {
    v.serialize(out)
        .map_err(|e| SdkError::InvalidArgument(format!("borsh encode: {e}")))
}

/// Convenience: encode a [`Value::Bool`] / numeric / address / …
/// to a standalone Borsh blob.
fn borsh_encode(v: &Value) -> Result<Vec<u8>, SdkError> {
    fn b<T: BorshSerialize>(x: &T) -> Result<Vec<u8>, SdkError> {
        borsh::to_vec(x).map_err(|e| SdkError::Other(format!("borsh encode: {e}")))
    }
    match v {
        Value::U8(x) => b(x),
        Value::U16(x) => b(x),
        Value::U32(x) => b(x),
        Value::U64(x) => b(x),
        Value::U128(x) => b(x),
        Value::I8(x) => b(x),
        Value::I16(x) => b(x),
        Value::I32(x) => b(x),
        Value::I64(x) => b(x),
        Value::I128(x) => b(x),
        Value::Bool(x) => b(x),
        Value::Address(a) => Ok(a.as_bytes().to_vec()),
        Value::Bytes(b) | Value::FixedBytes(b) | Value::Custom(b) => Ok(b.clone()),
        Value::String(s) => b(s),
        Value::Vec(items) => {
            let mut out = b(&(items.len() as u32))?;
            for item in items {
                out.extend_from_slice(&borsh_encode(item)?);
            }
            Ok(out)
        }
        Value::Map(pairs) => {
            let mut out = b(&(pairs.len() as u32))?;
            for (k, v) in pairs {
                out.extend_from_slice(&borsh_encode(k)?);
                out.extend_from_slice(&borsh_encode(v)?);
            }
            Ok(out)
        }
        Value::Option(opt) => match opt {
            None => Ok(vec![0]),
            Some(v) => {
                let mut out = vec![1];
                out.extend_from_slice(&borsh_encode(v)?);
                Ok(out)
            }
        },
    }
}

// ── Decoding ───────────────────────────────────────────────────

/// Decode bytes into a typed [`Value`].
///
/// Used for return-data decoding and for fully-typed event-data
/// decoding. The byte slice is expected to be exactly the Borsh
/// encoding of one value of the given type; trailing bytes cause
/// an error.
///
/// # Errors
/// - [`SdkError::InvalidResponse`] if Borsh decoding fails.
/// - [`SdkError::InvalidResponse`] if trailing bytes remain after
///   decoding (the encoder produced more than one value).
pub fn decode_value(param_type: &ParamType, bytes: &[u8]) -> Result<Value, SdkError> {
    let mut slice = bytes;
    let v = read_value(param_type, &mut slice)?;
    if !slice.is_empty() {
        return Err(SdkError::InvalidResponse(format!(
            "trailing {} bytes after decoding {param_type:?}",
            slice.len()
        )));
    }
    Ok(v)
}

/// Decode one value from a byte slice, advancing the slice past
/// the consumed bytes. Used for multi-value decoding (e.g. event
/// data with multiple non-indexed parameters).
///
/// # Errors
/// Returns [`SdkError::InvalidResponse`] on Borsh decoding failure.
pub fn decode_value_inplace(param_type: &ParamType, slice: &mut &[u8]) -> Result<Value, SdkError> {
    read_value(param_type, slice)
}

/// Decode a function's return data into an `Option<Value>`. `None`
/// when the function's `returns` is `None` and the buffer is empty.
///
/// # Errors
/// Returns [`SdkError::InvalidResponse`] on type mismatch / decode
/// failure.
pub fn decode_return(returns: &Option<ParamType>, bytes: &[u8]) -> Result<Option<Value>, SdkError> {
    match returns {
        None => {
            if !bytes.is_empty() {
                return Err(SdkError::InvalidResponse(format!(
                    "function returns (), but got {} bytes of return data",
                    bytes.len()
                )));
            }
            Ok(None)
        }
        Some(ty) => decode_value(ty, bytes).map(Some),
    }
}

fn read_value(ty: &ParamType, slice: &mut &[u8]) -> Result<Value, SdkError> {
    use ParamType as P;
    Ok(match ty {
        P::U8 => Value::U8(read_borsh::<u8>(slice)?),
        P::U16 => Value::U16(read_borsh::<u16>(slice)?),
        P::U32 => Value::U32(read_borsh::<u32>(slice)?),
        P::U64 => Value::U64(read_borsh::<u64>(slice)?),
        P::U128 => Value::U128(read_borsh::<u128>(slice)?),
        P::I8 => Value::I8(read_borsh::<i8>(slice)?),
        P::I16 => Value::I16(read_borsh::<i16>(slice)?),
        P::I32 => Value::I32(read_borsh::<i32>(slice)?),
        P::I64 => Value::I64(read_borsh::<i64>(slice)?),
        P::I128 => Value::I128(read_borsh::<i128>(slice)?),
        P::Bool => Value::Bool(read_borsh::<bool>(slice)?),
        P::Address => {
            if slice.len() < 32 {
                return Err(short_read(32, slice.len(), "Address"));
            }
            let mut arr = [0u8; 32];
            arr.copy_from_slice(&slice[..32]);
            *slice = &slice[32..];
            Value::Address(Address(arr))
        }
        P::Bytes => Value::Bytes(read_borsh::<Vec<u8>>(slice)?),
        P::String => Value::String(read_borsh::<String>(slice)?),
        P::FixedBytes(len) => {
            let len = *len as usize;
            if slice.len() < len {
                return Err(short_read(len, slice.len(), "FixedBytes"));
            }
            let bytes = slice[..len].to_vec();
            *slice = &slice[len..];
            Value::FixedBytes(bytes)
        }
        P::Vec(inner) => {
            let count = decode_count(slice, "Vec")?;
            let mut items = Vec::with_capacity(count);
            for _ in 0..count {
                items.push(read_value(inner, slice)?);
            }
            Value::Vec(items)
        }
        P::Map { key, value } => {
            let count = decode_count(slice, "Map")?;
            let mut pairs = Vec::with_capacity(count);
            for _ in 0..count {
                let k = read_value(key, slice)?;
                let v = read_value(value, slice)?;
                pairs.push((k, v));
            }
            Value::Map(pairs)
        }
        P::Option(inner) => {
            let tag = read_borsh::<u8>(slice)?;
            match tag {
                0 => Value::Option(None),
                1 => Value::Option(Some(Box::new(read_value(inner, slice)?))),
                other => {
                    return Err(SdkError::InvalidResponse(format!(
                        "Option tag must be 0 or 1; got {other}"
                    )))
                }
            }
        }
        P::Custom(_) => {
            // Opaque: hand the caller everything remaining. Custom-
            // typed values are typically the only thing in their
            // wire region (one custom return value), so consuming
            // the rest of the slice is the right default.
            let bytes = slice.to_vec();
            *slice = &slice[slice.len()..];
            Value::Custom(bytes)
        }
    })
}

/// Hard cap on the element count any single length-prefixed Vec or
/// Map decoder will materialise.
///
/// `u32::MAX` is the theoretical Borsh ceiling, but a malicious
/// upstream can ship a `[0xff, 0xff, 0xff, 0xff, …]` prefix and force
/// the SDK to `Vec::with_capacity(4 billion)` — instant OOM. 1M
/// elements is well above any plausible legitimate response (the
/// engine's tx-size cap is 128 KiB so a single `Vec<u8>` field can
/// hold at most that many bytes, and other field types are larger
/// per element) while keeping the allocation bounded.
pub const MAX_DECODE_ELEMENTS: usize = 1_000_000;

/// Read a `u32` length prefix and reject any count larger than
/// [`MAX_DECODE_ELEMENTS`]. Used by every variable-length decoder
/// path; the bound is the SDK's first line of defence against a
/// malicious server (or corrupt contract return).
fn decode_count(slice: &mut &[u8], label: &str) -> Result<usize, SdkError> {
    let raw = read_borsh::<u32>(slice)? as usize;
    if raw > MAX_DECODE_ELEMENTS {
        return Err(SdkError::InvalidResponse(format!(
            "{label}: declared length {raw} exceeds MAX_DECODE_ELEMENTS \
             ({MAX_DECODE_ELEMENTS}) — refusing to allocate"
        )));
    }
    Ok(raw)
}

fn read_borsh<T: BorshDeserialize>(slice: &mut &[u8]) -> Result<T, SdkError> {
    T::deserialize(slice).map_err(|e| SdkError::InvalidResponse(format!("borsh decode: {e}")))
}

fn short_read(want: usize, got: usize, label: &str) -> SdkError {
    SdkError::InvalidResponse(format!("{label}: need {want} bytes, have {got}"))
}

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

    use super::*;

    fn round_trip(ty: ParamType, value: Value) {
        let bytes = encode_value(&ty, &value).unwrap();
        let decoded = decode_value(&ty, &bytes).unwrap();
        assert_eq!(decoded, value, "round-trip mismatch for {ty:?}");
    }

    #[test]
    fn round_trip_primitives() {
        round_trip(ParamType::U8, Value::U8(42));
        round_trip(ParamType::U128, Value::U128(u128::MAX));
        round_trip(ParamType::I64, Value::I64(-1));
        round_trip(ParamType::Bool, Value::Bool(true));
        round_trip(ParamType::Bool, Value::Bool(false));
    }

    #[test]
    fn round_trip_address() {
        round_trip(ParamType::Address, Value::Address(Address([0xAB; 32])));
    }

    #[test]
    fn round_trip_bytes_and_string() {
        round_trip(ParamType::Bytes, Value::Bytes(vec![1, 2, 3, 4]));
        round_trip(ParamType::String, Value::String("hello".into()));
    }

    #[test]
    fn round_trip_fixed_bytes() {
        round_trip(
            ParamType::FixedBytes(8),
            Value::FixedBytes(vec![1, 2, 3, 4, 5, 6, 7, 8]),
        );
    }

    #[test]
    fn fixed_bytes_length_validated() {
        let err =
            encode_value(&ParamType::FixedBytes(8), &Value::FixedBytes(vec![1, 2])).unwrap_err();
        assert!(matches!(err, SdkError::InvalidArgument(_)));
    }

    #[test]
    fn round_trip_vec_and_map() {
        round_trip(
            ParamType::Vec(Box::new(ParamType::U32)),
            Value::Vec(vec![Value::U32(1), Value::U32(2), Value::U32(3)]),
        );
        round_trip(
            ParamType::Map {
                key: Box::new(ParamType::String),
                value: Box::new(ParamType::U64),
            },
            Value::Map(vec![
                (Value::String("a".into()), Value::U64(1)),
                (Value::String("b".into()), Value::U64(2)),
            ]),
        );
    }

    #[test]
    fn round_trip_option() {
        round_trip(
            ParamType::Option(Box::new(ParamType::U128)),
            Value::Option(Some(Box::new(Value::U128(42)))),
        );
        round_trip(
            ParamType::Option(Box::new(ParamType::Bool)),
            Value::Option(None),
        );
    }

    #[test]
    fn calldata_concatenates_args() {
        let params = vec![
            ParamAbi {
                name: "a".into(),
                ty: ParamType::U64,
            },
            ParamAbi {
                name: "b".into(),
                ty: ParamType::String,
            },
        ];
        let args = vec![Value::U64(7), Value::String("ok".into())];
        let bytes = encode_calldata(&params, &args).unwrap();
        // Should equal encode(U64) ++ encode(String).
        let expected = {
            let mut v = encode_value(&params[0].ty, &args[0]).unwrap();
            v.extend(encode_value(&params[1].ty, &args[1]).unwrap());
            v
        };
        assert_eq!(bytes, expected);
    }

    #[test]
    fn calldata_arity_mismatch() {
        let params = vec![ParamAbi {
            name: "x".into(),
            ty: ParamType::U64,
        }];
        let err = encode_calldata(&params, &[]).unwrap_err();
        assert!(matches!(err, SdkError::InvalidArgument(_)));
    }

    #[test]
    fn type_mismatch_rejected() {
        let err = encode_value(&ParamType::U32, &Value::U64(7)).unwrap_err();
        assert!(matches!(err, SdkError::InvalidArgument(_)));
    }

    #[test]
    fn decode_return_empty_for_unit_return() {
        let v = decode_return(&None, &[]).unwrap();
        assert!(v.is_none());
    }

    #[test]
    fn decode_return_rejects_trailing_bytes() {
        let err = decode_return(&None, &[1, 2, 3]).unwrap_err();
        assert!(matches!(err, SdkError::InvalidResponse(_)));
    }

    #[test]
    fn decode_return_typed() {
        let bytes = encode_value(&ParamType::U64, &Value::U64(123)).unwrap();
        let v = decode_return(&Some(ParamType::U64), &bytes).unwrap();
        assert_eq!(v, Some(Value::U64(123)));
    }
}