Skip to main content

pyde_rust_sdk/contract/
codec.rs

1//! Calldata + return-value codec — encode runtime values into the
2//! Borsh-shaped bytes a Pyde contract reads back through
3//! `pyde::calldata_*`, and decode return data the same way.
4//!
5//! The wire format for each [`ParamType`] matches Borsh's canonical
6//! encoding so contracts written in any wasm32-target language
7//! (Rust, Go, Zig, …) can `borsh::from_slice` the args directly.
8
9use std::collections::BTreeMap;
10
11use borsh::{BorshDeserialize, BorshSerialize};
12
13use crate::error::SdkError;
14use crate::types::{Address, ParamAbi, ParamType};
15
16/// A runtime value tagged by its [`ParamType`].
17///
18/// Mirrors the [`ParamType`] variant set 1-to-1. Used as the
19/// untyped argument / return type on the dynamic [`super::Contract`]
20/// surface; typed wrappers generated by the `pyde_abi!` macro
21/// translate to/from concrete Rust types.
22#[derive(Clone, Debug, PartialEq)]
23pub enum Value {
24    /// `u8` value.
25    U8(u8),
26    /// `u16` value.
27    U16(u16),
28    /// `u32` value.
29    U32(u32),
30    /// `u64` value.
31    U64(u64),
32    /// `u128` value.
33    U128(u128),
34    /// `i8` value.
35    I8(i8),
36    /// `i16` value.
37    I16(i16),
38    /// `i32` value.
39    I32(i32),
40    /// `i64` value.
41    I64(i64),
42    /// `i128` value.
43    I128(i128),
44    /// Boolean.
45    Bool(bool),
46    /// 32-byte Pyde address.
47    Address(Address),
48    /// Variable-length opaque bytes.
49    Bytes(Vec<u8>),
50    /// UTF-8 string.
51    String(String),
52    /// Fixed-size byte array.
53    FixedBytes(Vec<u8>),
54    /// Homogeneous list of values.
55    Vec(Vec<Value>),
56    /// Key-value pairs (in deterministic order — see [`Value::map`]).
57    Map(Vec<(Value, Value)>),
58    /// Optional value.
59    Option(Option<Box<Value>>),
60    /// Opaque Borsh bytes for a [`ParamType::Custom`]-tagged value.
61    /// The SDK doesn't decode custom types; the bytes are produced
62    /// (and consumed) by the caller's typed wrapper.
63    Custom(Vec<u8>),
64}
65
66impl Value {
67    /// Build a [`Value::Map`] from a [`BTreeMap`], preserving the
68    /// deterministic key order Borsh expects.
69    #[must_use]
70    pub fn map(entries: BTreeMap<Value, Value>) -> Self {
71        Self::Map(entries.into_iter().collect())
72    }
73}
74
75// `Eq` + `Hash` + `Ord` for `BTreeMap` keys — provided by deriving
76// `PartialEq` plus a manual `Eq` impl. The actual ordering only
77// matters when the user wants to insert into a `BTreeMap` of
78// `Value` keys (rare in v1).
79impl Eq for Value {}
80
81impl PartialOrd for Value {
82    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
83        Some(self.cmp(other))
84    }
85}
86
87impl Ord for Value {
88    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
89        // Order by canonical Borsh-encoded bytes — gives a stable,
90        // wire-consistent ordering without re-implementing per-
91        // variant `Ord`. Cheap enough for the rare `BTreeMap<Value, _>`
92        // case; not on any hot path.
93        let a = borsh_encode(self).unwrap_or_default();
94        let b = borsh_encode(other).unwrap_or_default();
95        a.cmp(&b)
96    }
97}
98
99// ── Encoding ───────────────────────────────────────────────────
100
101/// Encode a single value into its canonical Borsh wire bytes.
102///
103/// Returns the encoded bytes — no length prefix, no type tag.
104/// Concatenate multiple encoded values to build calldata for a
105/// multi-arg call.
106///
107/// # Errors
108/// Returns [`SdkError::InvalidArgument`] if `value` doesn't match
109/// the variant tag of `param_type` (e.g. encoding a `Value::U32`
110/// under [`ParamType::U64`]).
111pub fn encode_value(param_type: &ParamType, value: &Value) -> Result<Vec<u8>, SdkError> {
112    let mut buf = Vec::new();
113    write_value(param_type, value, &mut buf)?;
114    Ok(buf)
115}
116
117/// Encode calldata for a function call.
118///
119/// Each argument is Borsh-encoded against its declared
120/// [`ParamType`] and the results are concatenated in declaration
121/// order. This matches the convention contracts use to decode
122/// their inputs via `pyde::calldata_copy` + `borsh::from_slice`.
123///
124/// # Errors
125/// - [`SdkError::InvalidArgument`] if `args.len() != params.len()`.
126/// - Any error from [`encode_value`].
127pub fn encode_calldata(params: &[ParamAbi], args: &[Value]) -> Result<Vec<u8>, SdkError> {
128    if args.len() != params.len() {
129        return Err(SdkError::InvalidArgument(format!(
130            "expected {} args, got {}",
131            params.len(),
132            args.len()
133        )));
134    }
135    let mut buf = Vec::new();
136    for (param, arg) in params.iter().zip(args.iter()) {
137        write_value(&param.ty, arg, &mut buf)?;
138    }
139    Ok(buf)
140}
141
142fn write_value(ty: &ParamType, value: &Value, out: &mut Vec<u8>) -> Result<(), SdkError> {
143    use ParamType as P;
144    use Value as V;
145    match (ty, value) {
146        (P::U8, V::U8(v)) => borsh_write(v, out),
147        (P::U16, V::U16(v)) => borsh_write(v, out),
148        (P::U32, V::U32(v)) => borsh_write(v, out),
149        (P::U64, V::U64(v)) => borsh_write(v, out),
150        (P::U128, V::U128(v)) => borsh_write(v, out),
151        (P::I8, V::I8(v)) => borsh_write(v, out),
152        (P::I16, V::I16(v)) => borsh_write(v, out),
153        (P::I32, V::I32(v)) => borsh_write(v, out),
154        (P::I64, V::I64(v)) => borsh_write(v, out),
155        (P::I128, V::I128(v)) => borsh_write(v, out),
156        (P::Bool, V::Bool(v)) => borsh_write(v, out),
157        (P::Address, V::Address(addr)) => {
158            out.extend_from_slice(addr.as_bytes());
159            Ok(())
160        }
161        (P::Bytes, V::Bytes(b)) => borsh_write(b, out),
162        (P::String, V::String(s)) => borsh_write(s, out),
163        (P::FixedBytes(len), V::FixedBytes(b)) => {
164            if b.len() as u32 != *len {
165                return Err(SdkError::InvalidArgument(format!(
166                    "FixedBytes({len}) length mismatch: got {} bytes",
167                    b.len()
168                )));
169            }
170            out.extend_from_slice(b);
171            Ok(())
172        }
173        (P::Vec(inner), V::Vec(items)) => {
174            // Length-prefixed Borsh Vec: u32_le count then each
175            // element in declaration order.
176            borsh_write(&(items.len() as u32), out)?;
177            for item in items {
178                write_value(inner, item, out)?;
179            }
180            Ok(())
181        }
182        (P::Map { key, value: vt }, V::Map(pairs)) => {
183            // Same shape as Borsh's `HashMap` / `BTreeMap`:
184            // u32_le count + (k, v) pairs.
185            borsh_write(&(pairs.len() as u32), out)?;
186            for (k, v) in pairs {
187                write_value(key, k, out)?;
188                write_value(vt, v, out)?;
189            }
190            Ok(())
191        }
192        (P::Option(inner), V::Option(opt)) => match opt {
193            None => {
194                out.push(0x00);
195                Ok(())
196            }
197            Some(v) => {
198                out.push(0x01);
199                write_value(inner, v, out)
200            }
201        },
202        (P::Custom(_), V::Custom(bytes)) => {
203            // Opaque; caller-supplied bytes go straight through.
204            out.extend_from_slice(bytes);
205            Ok(())
206        }
207        (ty, value) => Err(SdkError::InvalidArgument(format!(
208            "type mismatch: {ty:?} cannot encode {value:?}"
209        ))),
210    }
211}
212
213fn borsh_write<T: BorshSerialize>(v: &T, out: &mut Vec<u8>) -> Result<(), SdkError> {
214    v.serialize(out)
215        .map_err(|e| SdkError::InvalidArgument(format!("borsh encode: {e}")))
216}
217
218/// Convenience: encode a [`Value::Bool`] / numeric / address / …
219/// to a standalone Borsh blob.
220fn borsh_encode(v: &Value) -> Result<Vec<u8>, SdkError> {
221    fn b<T: BorshSerialize>(x: &T) -> Result<Vec<u8>, SdkError> {
222        borsh::to_vec(x).map_err(|e| SdkError::Other(format!("borsh encode: {e}")))
223    }
224    match v {
225        Value::U8(x) => b(x),
226        Value::U16(x) => b(x),
227        Value::U32(x) => b(x),
228        Value::U64(x) => b(x),
229        Value::U128(x) => b(x),
230        Value::I8(x) => b(x),
231        Value::I16(x) => b(x),
232        Value::I32(x) => b(x),
233        Value::I64(x) => b(x),
234        Value::I128(x) => b(x),
235        Value::Bool(x) => b(x),
236        Value::Address(a) => Ok(a.as_bytes().to_vec()),
237        Value::Bytes(b) | Value::FixedBytes(b) | Value::Custom(b) => Ok(b.clone()),
238        Value::String(s) => b(s),
239        Value::Vec(items) => {
240            let mut out = b(&(items.len() as u32))?;
241            for item in items {
242                out.extend_from_slice(&borsh_encode(item)?);
243            }
244            Ok(out)
245        }
246        Value::Map(pairs) => {
247            let mut out = b(&(pairs.len() as u32))?;
248            for (k, v) in pairs {
249                out.extend_from_slice(&borsh_encode(k)?);
250                out.extend_from_slice(&borsh_encode(v)?);
251            }
252            Ok(out)
253        }
254        Value::Option(opt) => match opt {
255            None => Ok(vec![0]),
256            Some(v) => {
257                let mut out = vec![1];
258                out.extend_from_slice(&borsh_encode(v)?);
259                Ok(out)
260            }
261        },
262    }
263}
264
265// ── Decoding ───────────────────────────────────────────────────
266
267/// Decode bytes into a typed [`Value`].
268///
269/// Used for return-data decoding and for fully-typed event-data
270/// decoding. The byte slice is expected to be exactly the Borsh
271/// encoding of one value of the given type; trailing bytes cause
272/// an error.
273///
274/// # Errors
275/// - [`SdkError::InvalidResponse`] if Borsh decoding fails.
276/// - [`SdkError::InvalidResponse`] if trailing bytes remain after
277///   decoding (the encoder produced more than one value).
278pub fn decode_value(param_type: &ParamType, bytes: &[u8]) -> Result<Value, SdkError> {
279    let mut slice = bytes;
280    let v = read_value(param_type, &mut slice)?;
281    if !slice.is_empty() {
282        return Err(SdkError::InvalidResponse(format!(
283            "trailing {} bytes after decoding {param_type:?}",
284            slice.len()
285        )));
286    }
287    Ok(v)
288}
289
290/// Decode one value from a byte slice, advancing the slice past
291/// the consumed bytes. Used for multi-value decoding (e.g. event
292/// data with multiple non-indexed parameters).
293///
294/// # Errors
295/// Returns [`SdkError::InvalidResponse`] on Borsh decoding failure.
296pub fn decode_value_inplace(param_type: &ParamType, slice: &mut &[u8]) -> Result<Value, SdkError> {
297    read_value(param_type, slice)
298}
299
300/// Decode a function's return data into an `Option<Value>`. `None`
301/// when the function's `returns` is `None` and the buffer is empty.
302///
303/// # Errors
304/// Returns [`SdkError::InvalidResponse`] on type mismatch / decode
305/// failure.
306pub fn decode_return(returns: &Option<ParamType>, bytes: &[u8]) -> Result<Option<Value>, SdkError> {
307    match returns {
308        None => {
309            if !bytes.is_empty() {
310                return Err(SdkError::InvalidResponse(format!(
311                    "function returns (), but got {} bytes of return data",
312                    bytes.len()
313                )));
314            }
315            Ok(None)
316        }
317        Some(ty) => decode_value(ty, bytes).map(Some),
318    }
319}
320
321fn read_value(ty: &ParamType, slice: &mut &[u8]) -> Result<Value, SdkError> {
322    use ParamType as P;
323    Ok(match ty {
324        P::U8 => Value::U8(read_borsh::<u8>(slice)?),
325        P::U16 => Value::U16(read_borsh::<u16>(slice)?),
326        P::U32 => Value::U32(read_borsh::<u32>(slice)?),
327        P::U64 => Value::U64(read_borsh::<u64>(slice)?),
328        P::U128 => Value::U128(read_borsh::<u128>(slice)?),
329        P::I8 => Value::I8(read_borsh::<i8>(slice)?),
330        P::I16 => Value::I16(read_borsh::<i16>(slice)?),
331        P::I32 => Value::I32(read_borsh::<i32>(slice)?),
332        P::I64 => Value::I64(read_borsh::<i64>(slice)?),
333        P::I128 => Value::I128(read_borsh::<i128>(slice)?),
334        P::Bool => Value::Bool(read_borsh::<bool>(slice)?),
335        P::Address => {
336            if slice.len() < 32 {
337                return Err(short_read(32, slice.len(), "Address"));
338            }
339            let mut arr = [0u8; 32];
340            arr.copy_from_slice(&slice[..32]);
341            *slice = &slice[32..];
342            Value::Address(Address(arr))
343        }
344        P::Bytes => Value::Bytes(read_borsh::<Vec<u8>>(slice)?),
345        P::String => Value::String(read_borsh::<String>(slice)?),
346        P::FixedBytes(len) => {
347            let len = *len as usize;
348            if slice.len() < len {
349                return Err(short_read(len, slice.len(), "FixedBytes"));
350            }
351            let bytes = slice[..len].to_vec();
352            *slice = &slice[len..];
353            Value::FixedBytes(bytes)
354        }
355        P::Vec(inner) => {
356            let count = decode_count(slice, "Vec")?;
357            let mut items = Vec::with_capacity(count);
358            for _ in 0..count {
359                items.push(read_value(inner, slice)?);
360            }
361            Value::Vec(items)
362        }
363        P::Map { key, value } => {
364            let count = decode_count(slice, "Map")?;
365            let mut pairs = Vec::with_capacity(count);
366            for _ in 0..count {
367                let k = read_value(key, slice)?;
368                let v = read_value(value, slice)?;
369                pairs.push((k, v));
370            }
371            Value::Map(pairs)
372        }
373        P::Option(inner) => {
374            let tag = read_borsh::<u8>(slice)?;
375            match tag {
376                0 => Value::Option(None),
377                1 => Value::Option(Some(Box::new(read_value(inner, slice)?))),
378                other => {
379                    return Err(SdkError::InvalidResponse(format!(
380                        "Option tag must be 0 or 1; got {other}"
381                    )))
382                }
383            }
384        }
385        P::Custom(_) => {
386            // Opaque: hand the caller everything remaining. Custom-
387            // typed values are typically the only thing in their
388            // wire region (one custom return value), so consuming
389            // the rest of the slice is the right default.
390            let bytes = slice.to_vec();
391            *slice = &slice[slice.len()..];
392            Value::Custom(bytes)
393        }
394    })
395}
396
397/// Hard cap on the element count any single length-prefixed Vec or
398/// Map decoder will materialise.
399///
400/// `u32::MAX` is the theoretical Borsh ceiling, but a malicious
401/// upstream can ship a `[0xff, 0xff, 0xff, 0xff, …]` prefix and force
402/// the SDK to `Vec::with_capacity(4 billion)` — instant OOM. 1M
403/// elements is well above any plausible legitimate response (the
404/// engine's tx-size cap is 128 KiB so a single `Vec<u8>` field can
405/// hold at most that many bytes, and other field types are larger
406/// per element) while keeping the allocation bounded.
407pub const MAX_DECODE_ELEMENTS: usize = 1_000_000;
408
409/// Read a `u32` length prefix and reject any count larger than
410/// [`MAX_DECODE_ELEMENTS`]. Used by every variable-length decoder
411/// path; the bound is the SDK's first line of defence against a
412/// malicious server (or corrupt contract return).
413fn decode_count(slice: &mut &[u8], label: &str) -> Result<usize, SdkError> {
414    let raw = read_borsh::<u32>(slice)? as usize;
415    if raw > MAX_DECODE_ELEMENTS {
416        return Err(SdkError::InvalidResponse(format!(
417            "{label}: declared length {raw} exceeds MAX_DECODE_ELEMENTS \
418             ({MAX_DECODE_ELEMENTS}) — refusing to allocate"
419        )));
420    }
421    Ok(raw)
422}
423
424fn read_borsh<T: BorshDeserialize>(slice: &mut &[u8]) -> Result<T, SdkError> {
425    T::deserialize(slice).map_err(|e| SdkError::InvalidResponse(format!("borsh decode: {e}")))
426}
427
428fn short_read(want: usize, got: usize, label: &str) -> SdkError {
429    SdkError::InvalidResponse(format!("{label}: need {want} bytes, have {got}"))
430}
431
432#[cfg(test)]
433mod tests {
434    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
435
436    use super::*;
437
438    fn round_trip(ty: ParamType, value: Value) {
439        let bytes = encode_value(&ty, &value).unwrap();
440        let decoded = decode_value(&ty, &bytes).unwrap();
441        assert_eq!(decoded, value, "round-trip mismatch for {ty:?}");
442    }
443
444    #[test]
445    fn round_trip_primitives() {
446        round_trip(ParamType::U8, Value::U8(42));
447        round_trip(ParamType::U128, Value::U128(u128::MAX));
448        round_trip(ParamType::I64, Value::I64(-1));
449        round_trip(ParamType::Bool, Value::Bool(true));
450        round_trip(ParamType::Bool, Value::Bool(false));
451    }
452
453    #[test]
454    fn round_trip_address() {
455        round_trip(ParamType::Address, Value::Address(Address([0xAB; 32])));
456    }
457
458    #[test]
459    fn round_trip_bytes_and_string() {
460        round_trip(ParamType::Bytes, Value::Bytes(vec![1, 2, 3, 4]));
461        round_trip(ParamType::String, Value::String("hello".into()));
462    }
463
464    #[test]
465    fn round_trip_fixed_bytes() {
466        round_trip(
467            ParamType::FixedBytes(8),
468            Value::FixedBytes(vec![1, 2, 3, 4, 5, 6, 7, 8]),
469        );
470    }
471
472    #[test]
473    fn fixed_bytes_length_validated() {
474        let err =
475            encode_value(&ParamType::FixedBytes(8), &Value::FixedBytes(vec![1, 2])).unwrap_err();
476        assert!(matches!(err, SdkError::InvalidArgument(_)));
477    }
478
479    #[test]
480    fn round_trip_vec_and_map() {
481        round_trip(
482            ParamType::Vec(Box::new(ParamType::U32)),
483            Value::Vec(vec![Value::U32(1), Value::U32(2), Value::U32(3)]),
484        );
485        round_trip(
486            ParamType::Map {
487                key: Box::new(ParamType::String),
488                value: Box::new(ParamType::U64),
489            },
490            Value::Map(vec![
491                (Value::String("a".into()), Value::U64(1)),
492                (Value::String("b".into()), Value::U64(2)),
493            ]),
494        );
495    }
496
497    #[test]
498    fn round_trip_option() {
499        round_trip(
500            ParamType::Option(Box::new(ParamType::U128)),
501            Value::Option(Some(Box::new(Value::U128(42)))),
502        );
503        round_trip(
504            ParamType::Option(Box::new(ParamType::Bool)),
505            Value::Option(None),
506        );
507    }
508
509    #[test]
510    fn calldata_concatenates_args() {
511        let params = vec![
512            ParamAbi {
513                name: "a".into(),
514                ty: ParamType::U64,
515            },
516            ParamAbi {
517                name: "b".into(),
518                ty: ParamType::String,
519            },
520        ];
521        let args = vec![Value::U64(7), Value::String("ok".into())];
522        let bytes = encode_calldata(&params, &args).unwrap();
523        // Should equal encode(U64) ++ encode(String).
524        let expected = {
525            let mut v = encode_value(&params[0].ty, &args[0]).unwrap();
526            v.extend(encode_value(&params[1].ty, &args[1]).unwrap());
527            v
528        };
529        assert_eq!(bytes, expected);
530    }
531
532    #[test]
533    fn calldata_arity_mismatch() {
534        let params = vec![ParamAbi {
535            name: "x".into(),
536            ty: ParamType::U64,
537        }];
538        let err = encode_calldata(&params, &[]).unwrap_err();
539        assert!(matches!(err, SdkError::InvalidArgument(_)));
540    }
541
542    #[test]
543    fn type_mismatch_rejected() {
544        let err = encode_value(&ParamType::U32, &Value::U64(7)).unwrap_err();
545        assert!(matches!(err, SdkError::InvalidArgument(_)));
546    }
547
548    #[test]
549    fn decode_return_empty_for_unit_return() {
550        let v = decode_return(&None, &[]).unwrap();
551        assert!(v.is_none());
552    }
553
554    #[test]
555    fn decode_return_rejects_trailing_bytes() {
556        let err = decode_return(&None, &[1, 2, 3]).unwrap_err();
557        assert!(matches!(err, SdkError::InvalidResponse(_)));
558    }
559
560    #[test]
561    fn decode_return_typed() {
562        let bytes = encode_value(&ParamType::U64, &Value::U64(123)).unwrap();
563        let v = decode_return(&Some(ParamType::U64), &bytes).unwrap();
564        assert_eq!(v, Some(Value::U64(123)));
565    }
566}