1use std::collections::BTreeMap;
10
11use borsh::{BorshDeserialize, BorshSerialize};
12
13use crate::error::SdkError;
14use crate::types::{Address, ParamAbi, ParamType};
15
16#[derive(Clone, Debug, PartialEq)]
23pub enum Value {
24 U8(u8),
26 U16(u16),
28 U32(u32),
30 U64(u64),
32 U128(u128),
34 I8(i8),
36 I16(i16),
38 I32(i32),
40 I64(i64),
42 I128(i128),
44 Bool(bool),
46 Address(Address),
48 Bytes(Vec<u8>),
50 String(String),
52 FixedBytes(Vec<u8>),
54 Vec(Vec<Value>),
56 Map(Vec<(Value, Value)>),
58 Option(Option<Box<Value>>),
60 Custom(Vec<u8>),
64}
65
66impl Value {
67 #[must_use]
70 pub fn map(entries: BTreeMap<Value, Value>) -> Self {
71 Self::Map(entries.into_iter().collect())
72 }
73}
74
75impl 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 let a = borsh_encode(self).unwrap_or_default();
94 let b = borsh_encode(other).unwrap_or_default();
95 a.cmp(&b)
96 }
97}
98
99pub 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
117pub 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(¶m.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 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 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 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
218fn 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
265pub 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
290pub fn decode_value_inplace(param_type: &ParamType, slice: &mut &[u8]) -> Result<Value, SdkError> {
297 read_value(param_type, slice)
298}
299
300pub 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 let bytes = slice.to_vec();
391 *slice = &slice[slice.len()..];
392 Value::Custom(bytes)
393 }
394 })
395}
396
397pub const MAX_DECODE_ELEMENTS: usize = 1_000_000;
408
409fn 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(¶ms, &args).unwrap();
523 let expected = {
525 let mut v = encode_value(¶ms[0].ty, &args[0]).unwrap();
526 v.extend(encode_value(¶ms[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(¶ms, &[]).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}