Skip to main content

tycho_types/abi/value/
mod.rs

1use std::collections::BTreeMap;
2use std::num::NonZeroU8;
3use std::sync::Arc;
4
5use anyhow::Result;
6use bytes::Bytes;
7use num_bigint::{BigInt, BigUint};
8use num_traits::ToPrimitive;
9use serde::Deserialize;
10use serde::de::DeserializeSeed;
11use serde::ser::{SerializeMap, SerializeSeq};
12
13use super::ty::*;
14use super::{IntoAbi, IntoPlainAbi, WithAbiType, WithPlainAbiType, WithoutName};
15use crate::abi::error::AbiError;
16use crate::boc::Boc;
17use crate::cell::{Cell, CellFamily};
18use crate::models::{AnyAddr, ExtAddr, IntAddr, StdAddr, StdAddrFormat};
19use crate::num::Tokens;
20use crate::util::BigIntExt;
21
22mod de;
23pub(crate) mod ser;
24
25/// ABI value with name.
26#[derive(Debug, Clone, Eq, PartialEq)]
27pub struct NamedAbiValue {
28    /// Item name.
29    pub name: Arc<str>,
30    /// ABI value.
31    pub value: AbiValue,
32}
33
34impl NamedAbiValue {
35    /// Ensures that all values satisfy the provided types.
36    pub fn check_types(items: &[Self], types: &[NamedAbiType]) -> Result<()> {
37        anyhow::ensure!(Self::have_types(items, types), AbiError::TypeMismatch {
38            expected: DisplayTupleType(types).to_string().into(),
39            ty: DisplayTupleValueType(items).to_string().into(),
40        });
41        Ok(())
42    }
43
44    /// Returns whether all values satisfy the provided types.
45    pub fn have_types(items: &[Self], types: &[NamedAbiType]) -> bool {
46        items.len() == types.len()
47            && items
48                .iter()
49                .zip(types.iter())
50                .all(|(item, t)| item.value.has_type(&t.ty))
51    }
52
53    /// Creates a named ABI value with an index name (e.g. `value123`).
54    pub fn from_index(index: usize, value: AbiValue) -> Self {
55        Self {
56            name: format!("value{index}").into(),
57            value,
58        }
59    }
60
61    /// Ensures that value satisfies the type.
62    pub fn check_type<T: AsRef<AbiType>>(&self, ty: T) -> Result<()> {
63        fn type_mismatch(this: &NamedAbiValue, expected: &AbiType) -> AbiError {
64            AbiError::TypeMismatch {
65                expected: expected.to_string().into(),
66                ty: this.value.display_type().to_string().into(),
67            }
68        }
69        let ty = ty.as_ref();
70        anyhow::ensure!(self.value.has_type(ty), type_mismatch(self, ty));
71        Ok(())
72    }
73
74    /// Parses a tuple of [`NamedAbiValue`] from JSON using the provided [`NamedAbiType`]s.
75    pub fn tuple_from_json_str(
76        s: &str,
77        types: &[NamedAbiType],
78    ) -> Result<Vec<Self>, serde_path_to_error::Error<serde_json::Error>> {
79        let jd = &mut serde_json::Deserializer::from_str(s);
80        let mut track = serde_path_to_error::Track::new();
81        match (DeserializeAbiValues { types })
82            .deserialize(serde_path_to_error::Deserializer::new(&mut *jd, &mut track))
83        {
84            Ok(values) => {
85                if let Err(e) = jd.end() {
86                    return Err(serde_path_to_error::Error::new(track.path(), e));
87                }
88
89                debug_assert_eq!(values.len(), types.len());
90                Ok(values)
91            }
92            Err(e) => Err(serde_path_to_error::Error::new(track.path(), e)),
93        }
94    }
95}
96
97impl From<(String, AbiValue)> for NamedAbiValue {
98    #[inline]
99    fn from((name, value): (String, AbiValue)) -> Self {
100        Self {
101            name: name.into(),
102            value,
103        }
104    }
105}
106
107impl<'a> From<(&'a str, AbiValue)> for NamedAbiValue {
108    #[inline]
109    fn from((name, value): (&'a str, AbiValue)) -> Self {
110        Self {
111            name: Arc::from(name),
112            value,
113        }
114    }
115}
116
117impl From<(usize, AbiValue)> for NamedAbiValue {
118    #[inline]
119    fn from((index, value): (usize, AbiValue)) -> Self {
120        Self::from_index(index, value)
121    }
122}
123
124impl NamedAbiType {
125    /// Returns a default value corresponding to the this type.
126    pub fn make_default_value(&self) -> NamedAbiValue {
127        NamedAbiValue {
128            name: self.name.clone(),
129            value: self.ty.make_default_value(),
130        }
131    }
132}
133
134impl PartialEq for WithoutName<NamedAbiValue> {
135    #[inline]
136    fn eq(&self, other: &Self) -> bool {
137        WithoutName::wrap(&self.0.value).eq(WithoutName::wrap(&other.0.value))
138    }
139}
140
141impl std::borrow::Borrow<WithoutName<AbiValue>> for WithoutName<NamedAbiValue> {
142    fn borrow(&self) -> &WithoutName<AbiValue> {
143        WithoutName::wrap(&self.0.value)
144    }
145}
146
147/// ABI encoded value.
148#[derive(Debug, Clone, Eq, PartialEq)]
149pub enum AbiValue {
150    /// Unsigned integer of n bits.
151    Uint(u16, BigUint),
152    /// Signed integer of n bits.
153    Int(u16, BigInt),
154    /// Variable-length unsigned integer of maximum n bytes.
155    VarUint(NonZeroU8, BigUint),
156    /// Variable-length signed integer of maximum n bytes.
157    VarInt(NonZeroU8, BigInt),
158    /// Boolean.
159    Bool(bool),
160    /// Tree of cells ([`Cell`]).
161    ///
162    /// [`Cell`]: crate::cell::Cell
163    Cell(Cell),
164    /// Any address ([`AnyAddr`]).
165    ///
166    /// [`AnyAddr`]: crate::models::message::AnyAddr
167    Address(Box<AnyAddr>),
168    /// Standard internal address ([`StdAddr`])
169    /// [`StdAddr`]: crate::models::message::StdAddr
170    AddressStd(Option<Box<StdAddr>>),
171    /// Byte array.
172    Bytes(Bytes),
173    /// Byte array of fixed length.
174    FixedBytes(Bytes),
175    /// Utf8-encoded string.
176    String(String),
177    /// Variable length 120-bit integer ([`Tokens`]).
178    ///
179    /// [`Tokens`]: crate::num::Tokens
180    Token(Tokens),
181    /// Product type.
182    Tuple(Vec<NamedAbiValue>),
183    /// Array of ABI values.
184    Array(Arc<AbiType>, Vec<Self>),
185    /// Fixed-length array of ABI values.
186    FixedArray(Arc<AbiType>, Vec<Self>),
187    /// Sorted dictionary of ABI values.
188    Map(
189        PlainAbiType,
190        Arc<AbiType>,
191        BTreeMap<PlainAbiValue, AbiValue>,
192    ),
193    /// Optional value.
194    Optional(Arc<AbiType>, Option<Box<Self>>),
195    /// Value stored in a new cell.
196    Ref(Box<Self>),
197}
198
199impl AbiValue {
200    /// Returns a named ABI value.
201    pub fn named<T: Into<String>>(self, name: T) -> NamedAbiValue {
202        NamedAbiValue {
203            name: Arc::from(name.into()),
204            value: self,
205        }
206    }
207
208    /// Ensures that value satisfies the type.
209    pub fn check_type<T: AsRef<AbiType>>(&self, ty: T) -> Result<()> {
210        fn type_mismatch(value: &AbiValue, expected: &AbiType) -> AbiError {
211            AbiError::TypeMismatch {
212                expected: expected.to_string().into(),
213                ty: value.display_type().to_string().into(),
214            }
215        }
216        let ty = ty.as_ref();
217        anyhow::ensure!(self.has_type(ty), type_mismatch(self, ty));
218        Ok(())
219    }
220
221    /// Returns whether this value has the same type as the provided one.
222    pub fn has_type(&self, ty: &AbiType) -> bool {
223        match (self, ty) {
224            (Self::Uint(n, _), AbiType::Uint(t)) => n == t,
225            (Self::Int(n, _), AbiType::Int(t)) => n == t,
226            (Self::VarUint(n, _), AbiType::VarUint(t)) => n == t,
227            (Self::VarInt(n, _), AbiType::VarInt(t)) => n == t,
228            (Self::FixedBytes(bytes), AbiType::FixedBytes(len)) => bytes.len() == *len,
229            (Self::Tuple(items), AbiType::Tuple(types)) => NamedAbiValue::have_types(items, types),
230            (Self::Array(ty, _), AbiType::Array(t)) => ty == t,
231            (Self::FixedArray(ty, items), AbiType::FixedArray(t, len)) => {
232                items.len() == *len && ty == t
233            }
234            (Self::Map(key_ty, value_ty, _), AbiType::Map(k, v)) => key_ty == k && value_ty == v,
235            (Self::Optional(ty, _), AbiType::Optional(t)) => ty == t,
236            (Self::Ref(value), AbiType::Ref(t)) => value.has_type(t),
237            (Self::Bool(_), AbiType::Bool)
238            | (Self::Cell(_), AbiType::Cell)
239            | (Self::Address(_), AbiType::Address)
240            | (Self::AddressStd(_), AbiType::AddressStd)
241            | (Self::Bytes(_), AbiType::Bytes)
242            | (Self::String(_), AbiType::String)
243            | (Self::Token(_), AbiType::Token) => true,
244            _ => false,
245        }
246    }
247
248    /// Returns an ABI type of the value.
249    pub fn get_type(&self) -> AbiType {
250        match self {
251            AbiValue::Uint(n, _) => AbiType::Uint(*n),
252            AbiValue::Int(n, _) => AbiType::Int(*n),
253            AbiValue::VarUint(n, _) => AbiType::VarUint(*n),
254            AbiValue::VarInt(n, _) => AbiType::VarInt(*n),
255            AbiValue::Bool(_) => AbiType::Bool,
256            AbiValue::Cell(_) => AbiType::Cell,
257            AbiValue::Address(_) => AbiType::Address,
258            AbiValue::AddressStd(_) => AbiType::AddressStd,
259            AbiValue::Bytes(_) => AbiType::Bytes,
260            AbiValue::FixedBytes(bytes) => AbiType::FixedBytes(bytes.len()),
261            AbiValue::String(_) => AbiType::String,
262            AbiValue::Token(_) => AbiType::Token,
263            AbiValue::Tuple(items) => AbiType::Tuple(
264                items
265                    .iter()
266                    .map(|item| NamedAbiType::new(item.name.clone(), item.value.get_type()))
267                    .collect(),
268            ),
269            AbiValue::Array(ty, _) => AbiType::Array(ty.clone()),
270            AbiValue::FixedArray(ty, items) => AbiType::FixedArray(ty.clone(), items.len()),
271            AbiValue::Map(key_ty, value_ty, _) => AbiType::Map(*key_ty, value_ty.clone()),
272            AbiValue::Optional(ty, _) => AbiType::Optional(ty.clone()),
273            AbiValue::Ref(value) => AbiType::Ref(Arc::new(value.get_type())),
274        }
275    }
276
277    /// Returns a printable object which will display a value type signature.
278    #[inline]
279    pub fn display_type(&self) -> impl std::fmt::Display + '_ {
280        DisplayValueType(self)
281    }
282
283    /// Simple `uintN` constructor.
284    #[inline]
285    pub fn uint<T>(bits: u16, value: T) -> Self
286    where
287        BigUint: From<T>,
288    {
289        Self::Uint(bits, BigUint::from(value))
290    }
291
292    /// Simple `intN` constructor.
293    #[inline]
294    pub fn int<T>(bits: u16, value: T) -> Self
295    where
296        BigInt: From<T>,
297    {
298        Self::Int(bits, BigInt::from(value))
299    }
300
301    /// Simple `varuintN` constructor.
302    #[inline]
303    pub fn varuint<T>(size: u8, value: T) -> Self
304    where
305        BigUint: From<T>,
306    {
307        Self::VarUint(NonZeroU8::new(size).unwrap(), BigUint::from(value))
308    }
309
310    /// Simple `varintN` constructor.
311    #[inline]
312    pub fn varint<T>(size: u8, value: T) -> Self
313    where
314        BigInt: From<T>,
315    {
316        Self::VarInt(NonZeroU8::new(size).unwrap(), BigInt::from(value))
317    }
318
319    /// Simple `address` constructor.
320    #[inline]
321    pub fn address<T>(value: T) -> Self
322    where
323        AnyAddr: From<T>,
324    {
325        Self::Address(Box::new(AnyAddr::from(value)))
326    }
327
328    /// Simple `address_std` constructor.
329    #[inline]
330    pub fn address_std<T>(value: T) -> Self
331    where
332        StdAddr: From<T>,
333    {
334        // TODO: Use `castaway` to specialize on `Box<StdAddr>`.
335        Self::AddressStd(Some(Box::new(StdAddr::from(value))))
336    }
337
338    /// Simple `bytes` constructor.
339    #[inline]
340    pub fn bytes<T>(value: T) -> Self
341    where
342        Bytes: From<T>,
343    {
344        Self::Bytes(Bytes::from(value))
345    }
346
347    /// Simple `bytes` constructor.
348    #[inline]
349    pub fn fixedbytes<T>(value: T) -> Self
350    where
351        Bytes: From<T>,
352    {
353        Self::FixedBytes(Bytes::from(value))
354    }
355
356    /// Simple `tuple` constructor.
357    #[inline]
358    pub fn tuple<I, T>(values: I) -> Self
359    where
360        I: IntoIterator<Item = T>,
361        NamedAbiValue: From<T>,
362    {
363        Self::Tuple(values.into_iter().map(NamedAbiValue::from).collect())
364    }
365
366    /// Simple `tuple` constructor.
367    #[inline]
368    pub fn unnamed_tuple<I>(values: I) -> Self
369    where
370        I: IntoIterator<Item = AbiValue>,
371    {
372        Self::Tuple(
373            values
374                .into_iter()
375                .enumerate()
376                .map(|(i, value)| NamedAbiValue::from_index(i, value))
377                .collect(),
378        )
379    }
380
381    /// Simple `array` constructor.
382    #[inline]
383    pub fn array<T, I>(values: I) -> Self
384    where
385        T: WithAbiType + IntoAbi,
386        I: IntoIterator<Item = T>,
387    {
388        Self::Array(
389            Arc::new(T::abi_type()),
390            values.into_iter().map(IntoAbi::into_abi).collect(),
391        )
392    }
393
394    /// Simple `fixedarray` constructor.
395    #[inline]
396    pub fn fixedarray<T, I>(values: I) -> Self
397    where
398        T: WithAbiType + IntoAbi,
399        I: IntoIterator<Item = T>,
400    {
401        Self::FixedArray(
402            Arc::new(T::abi_type()),
403            values.into_iter().map(IntoAbi::into_abi).collect(),
404        )
405    }
406
407    /// Simple `map` constructor.
408    #[inline]
409    pub fn map<K, V, I>(entries: I) -> Self
410    where
411        K: WithPlainAbiType + IntoPlainAbi,
412        V: WithAbiType + IntoAbi,
413        I: IntoIterator<Item = (K, V)>,
414    {
415        Self::Map(
416            K::plain_abi_type(),
417            Arc::new(V::abi_type()),
418            entries
419                .into_iter()
420                .map(|(key, value)| (key.into_plain_abi(), value.into_abi()))
421                .collect(),
422        )
423    }
424
425    /// Simple `optional` constructor.
426    #[inline]
427    pub fn optional<T>(value: Option<T>) -> Self
428    where
429        T: WithAbiType + IntoAbi,
430    {
431        Self::Optional(
432            Arc::new(T::abi_type()),
433            value.map(T::into_abi).map(Box::new),
434        )
435    }
436
437    /// Simple `optional` constructor.
438    #[inline]
439    pub fn reference<T>(value: T) -> Self
440    where
441        T: IntoAbi,
442    {
443        Self::Ref(Box::new(value.into_abi()))
444    }
445
446    /// Parses [`AbiValue`] from JSON using the provided [`AbiType`].
447    pub fn from_json_str(
448        s: &str,
449        ty: &AbiType,
450    ) -> Result<Self, serde_path_to_error::Error<serde_json::Error>> {
451        let jd = &mut serde_json::Deserializer::from_str(s);
452        let mut track = serde_path_to_error::Track::new();
453        match (DeserializeAbiValue { ty })
454            .deserialize(serde_path_to_error::Deserializer::new(&mut *jd, &mut track))
455        {
456            Ok(value) => {
457                if let Err(e) = jd.end() {
458                    return Err(serde_path_to_error::Error::new(track.path(), e));
459                }
460
461                Ok(value)
462            }
463            Err(e) => Err(serde_path_to_error::Error::new(track.path(), e)),
464        }
465    }
466}
467
468impl AbiType {
469    /// Returns a default value corresponding to the this type.
470    pub fn make_default_value(&self) -> AbiValue {
471        match self {
472            AbiType::Uint(bits) => AbiValue::Uint(*bits, BigUint::default()),
473            AbiType::Int(bits) => AbiValue::Int(*bits, BigInt::default()),
474            AbiType::VarUint(size) => AbiValue::VarUint(*size, BigUint::default()),
475            AbiType::VarInt(size) => AbiValue::VarInt(*size, BigInt::default()),
476            AbiType::Bool => AbiValue::Bool(false),
477            AbiType::Cell => AbiValue::Cell(Cell::empty_cell()),
478            AbiType::Address => AbiValue::Address(Box::default()),
479            AbiType::AddressStd => AbiValue::AddressStd(None),
480            AbiType::Bytes => AbiValue::Bytes(Bytes::default()),
481            AbiType::FixedBytes(len) => AbiValue::FixedBytes(Bytes::from(vec![0u8; *len])),
482            AbiType::String => AbiValue::String(String::default()),
483            AbiType::Token => AbiValue::Token(Tokens::ZERO),
484            AbiType::Tuple(items) => {
485                let mut tuple = Vec::with_capacity(items.len());
486                for item in items.as_ref() {
487                    tuple.push(item.make_default_value());
488                }
489                AbiValue::Tuple(tuple)
490            }
491            AbiType::Array(ty) => AbiValue::Array(ty.clone(), Vec::new()),
492            AbiType::FixedArray(ty, items) => {
493                AbiValue::FixedArray(ty.clone(), vec![ty.make_default_value(); *items])
494            }
495            AbiType::Map(key_ty, value_ty) => {
496                AbiValue::Map(*key_ty, value_ty.clone(), BTreeMap::default())
497            }
498            AbiType::Optional(ty) => AbiValue::Optional(ty.clone(), None),
499            AbiType::Ref(ty) => AbiValue::Ref(Box::new(ty.make_default_value())),
500        }
501    }
502}
503
504impl PartialEq for WithoutName<AbiValue> {
505    fn eq(&self, other: &Self) -> bool {
506        match (&self.0, &other.0) {
507            (AbiValue::Uint(an, a), AbiValue::Uint(bn, b)) => an.eq(bn) && a.eq(b),
508            (AbiValue::Int(an, a), AbiValue::Int(bn, b)) => an.eq(bn) && a.eq(b),
509            (AbiValue::VarUint(an, a), AbiValue::VarUint(bn, b)) => an.eq(bn) && a.eq(b),
510            (AbiValue::VarInt(an, a), AbiValue::VarInt(bn, b)) => an.eq(bn) && a.eq(b),
511            (AbiValue::Bool(a), AbiValue::Bool(b)) => a.eq(b),
512            (AbiValue::Cell(a), AbiValue::Cell(b)) => a.eq(b),
513            (AbiValue::Address(a), AbiValue::Address(b)) => a.eq(b),
514            (AbiValue::AddressStd(a), AbiValue::AddressStd(b)) => a.eq(b),
515            (AbiValue::Bytes(a), AbiValue::Bytes(b)) => a.eq(b),
516            (AbiValue::FixedBytes(a), AbiValue::FixedBytes(b)) => a.eq(b),
517            (AbiValue::String(a), AbiValue::String(b)) => a.eq(b),
518            (AbiValue::Token(a), AbiValue::Token(b)) => a.eq(b),
519            (AbiValue::Tuple(a), AbiValue::Tuple(b)) => {
520                WithoutName::wrap_slice(a.as_slice()).eq(WithoutName::wrap_slice(b.as_slice()))
521            }
522            (AbiValue::Array(at, av), AbiValue::Array(bt, bv))
523            | (AbiValue::FixedArray(at, av), AbiValue::FixedArray(bt, bv)) => {
524                WithoutName::wrap(at.as_ref()).eq(WithoutName::wrap(bt.as_ref()))
525                    && WithoutName::wrap_slice(av.as_slice())
526                        .eq(WithoutName::wrap_slice(bv.as_slice()))
527            }
528            (AbiValue::Map(akt, avt, a), AbiValue::Map(bkt, bvt, b)) => {
529                akt.eq(bkt)
530                    && WithoutName::wrap(avt.as_ref()).eq(WithoutName::wrap(bvt.as_ref()))
531                    && WithoutName::wrap(a).eq(WithoutName::wrap(b))
532            }
533            (AbiValue::Optional(at, a), AbiValue::Optional(bt, b)) => {
534                WithoutName::wrap(at.as_ref()).eq(WithoutName::wrap(bt.as_ref()))
535                    && a.as_deref()
536                        .map(WithoutName::wrap)
537                        .eq(&b.as_deref().map(WithoutName::wrap))
538            }
539            (AbiValue::Ref(a), AbiValue::Ref(b)) => {
540                WithoutName::wrap(a.as_ref()).eq(WithoutName::wrap(b.as_ref()))
541            }
542            _unused => false,
543        }
544    }
545}
546
547/// ABI value which has a fixed bits representation
548/// and therefore can be used as a map key.
549#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
550pub enum PlainAbiValue {
551    /// Unsigned integer of n bits.
552    Uint(u16, BigUint),
553    /// Signed integer of n bits.
554    Int(u16, BigInt),
555    /// Boolean.
556    Bool(bool),
557    /// Internal address ([`IntAddr`]).
558    ///
559    /// [`IntAddr`]: crate::models::message::IntAddr
560    Address(Box<IntAddr>),
561    /// Std address ([`StdAddr`]).
562    ///
563    /// [`StdAddr`]: crate::models::message::StdAddr
564    AddressStd(Box<StdAddr>),
565    /// Byte array of fixed length.
566    FixedBytes(Bytes),
567}
568
569impl PlainAbiValue {
570    /// Returns whether this value has the same type as the provided one.
571    pub fn has_type(&self, ty: &PlainAbiType) -> bool {
572        match (self, ty) {
573            (Self::Uint(n, _), PlainAbiType::Uint(t)) => n == t,
574            (Self::Int(n, _), PlainAbiType::Int(t)) => n == t,
575            (Self::Bool(_), PlainAbiType::Bool)
576            | (Self::Address(_), PlainAbiType::Address)
577            | (Self::AddressStd(_), PlainAbiType::AddressStd) => true,
578            (Self::FixedBytes(bytes), PlainAbiType::FixedBytes(n)) => bytes.len() == *n,
579            _ => false,
580        }
581    }
582
583    /// Returns a printable object which will display a value type signature.
584    #[inline]
585    pub fn display_type(&self) -> impl std::fmt::Display + '_ {
586        DisplayPlainValueType(self)
587    }
588}
589
590impl From<PlainAbiValue> for AbiValue {
591    fn from(value: PlainAbiValue) -> Self {
592        match value {
593            PlainAbiValue::Uint(n, value) => Self::Uint(n, value),
594            PlainAbiValue::Int(n, value) => Self::Int(n, value),
595            PlainAbiValue::Bool(value) => Self::Bool(value),
596            PlainAbiValue::Address(value) => {
597                let addr = match value.as_ref() {
598                    IntAddr::Std(addr) => AnyAddr::Std(addr.clone()),
599                    IntAddr::Var(addr) => AnyAddr::Var(addr.clone()),
600                };
601                AbiValue::Address(Box::new(addr))
602            }
603            PlainAbiValue::AddressStd(value) => AbiValue::AddressStd(Some(value)),
604            PlainAbiValue::FixedBytes(bytes) => AbiValue::FixedBytes(bytes),
605        }
606    }
607}
608
609/// Contract header value.
610#[derive(Debug, Clone, Eq, PartialEq)]
611pub enum AbiHeader {
612    /// `time` header.
613    Time(u64),
614    /// `expire` header.
615    Expire(u32),
616    /// `pubkey` header.
617    PublicKey(Option<Box<ed25519_dalek::VerifyingKey>>),
618}
619
620impl AbiHeader {
621    /// Returns whether this value has the same type as the provided one.
622    pub fn has_type(&self, ty: &AbiHeaderType) -> bool {
623        matches!(
624            (self, ty),
625            (Self::Time(_), AbiHeaderType::Time)
626                | (Self::Expire(_), AbiHeaderType::Expire)
627                | (Self::PublicKey(_), AbiHeaderType::PublicKey)
628        )
629    }
630
631    /// Returns a printable object which will display a header type signature.
632    #[inline]
633    pub fn display_type(&self) -> impl std::fmt::Display + '_ {
634        DisplayHeaderType(self)
635    }
636}
637
638struct DisplayHeaderType<'a>(&'a AbiHeader);
639
640impl std::fmt::Display for DisplayHeaderType<'_> {
641    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
642        f.write_str(match self.0 {
643            AbiHeader::Time(_) => "time",
644            AbiHeader::Expire(_) => "expire",
645            AbiHeader::PublicKey(_) => "pubkey",
646        })
647    }
648}
649
650struct DisplayPlainValueType<'a>(&'a PlainAbiValue);
651
652impl std::fmt::Display for DisplayPlainValueType<'_> {
653    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
654        f.write_str(match self.0 {
655            PlainAbiValue::Uint(n, _) => return write!(f, "uint{n}"),
656            PlainAbiValue::Int(n, _) => return write!(f, "int{n}"),
657            PlainAbiValue::Bool(_) => "bool",
658            PlainAbiValue::Address(_) => "address",
659            PlainAbiValue::AddressStd(_) => "address_std",
660            PlainAbiValue::FixedBytes(bytes) => return write!(f, "fixedbytes{}", bytes.len()),
661        })
662    }
663}
664
665struct DisplayValueType<'a>(&'a AbiValue);
666
667impl std::fmt::Display for DisplayValueType<'_> {
668    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
669        let s = match self.0 {
670            AbiValue::Uint(n, _) => return write!(f, "uint{n}"),
671            AbiValue::Int(n, _) => return write!(f, "int{n}"),
672            AbiValue::VarUint(n, _) => return write!(f, "varuint{n}"),
673            AbiValue::VarInt(n, _) => return write!(f, "varint{n}"),
674            AbiValue::Bool(_) => "bool",
675            AbiValue::Cell(_) => "cell",
676            AbiValue::Address(_) => "address",
677            AbiValue::AddressStd(_) => "address_std",
678            AbiValue::Bytes(_) => "bytes",
679            AbiValue::FixedBytes(bytes) => return write!(f, "fixedbytes{}", bytes.len()),
680            AbiValue::String(_) => "string",
681            AbiValue::Token(_) => "gram",
682            AbiValue::Tuple(items) => {
683                return std::fmt::Display::fmt(&DisplayTupleValueType(items), f);
684            }
685            AbiValue::Array(ty, _) => return write!(f, "{ty}[]"),
686            AbiValue::FixedArray(ty, items) => return write!(f, "{ty}[{}]", items.len()),
687            AbiValue::Map(key_ty, value_ty, _) => return write!(f, "map({key_ty},{value_ty})"),
688            AbiValue::Optional(ty, _) => return write!(f, "optional({ty})"),
689            AbiValue::Ref(val) => return write!(f, "ref({})", val.display_type()),
690        };
691        f.write_str(s)
692    }
693}
694
695struct DisplayTupleValueType<'a>(&'a [NamedAbiValue]);
696
697impl std::fmt::Display for DisplayTupleValueType<'_> {
698    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
699        let s = if self.0.is_empty() {
700            "()"
701        } else {
702            let mut first = true;
703            ok!(f.write_str("("));
704            for item in self.0 {
705                if !std::mem::take(&mut first) {
706                    ok!(f.write_str(","));
707                }
708                ok!(write!(f, "{}", item.value.display_type()));
709            }
710            ")"
711        };
712        f.write_str(s)
713    }
714}
715
716struct DisplayTupleType<'a>(&'a [NamedAbiType]);
717
718impl std::fmt::Display for DisplayTupleType<'_> {
719    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
720        let s = if self.0.is_empty() {
721            "()"
722        } else {
723            let mut first = true;
724            ok!(f.write_str("("));
725            for item in self.0 {
726                if !std::mem::take(&mut first) {
727                    ok!(f.write_str(","));
728                }
729                ok!(write!(f, "{}", item.ty));
730            }
731            ")"
732        };
733        f.write_str(s)
734    }
735}
736
737/// Serialization params for [`AbiValue`].
738#[derive(Debug, Default, Clone, Copy)]
739pub struct SerializeAbiValueParams {
740    /// Integer **types** with bit width greater than 128
741    /// will be serialized as hex (with `0x` prefix).
742    ///
743    /// Default: `false`.
744    ///
745    /// See [`SerializeAbiValueParams::NUMBERS_AS_HEX_THRESHOLD`].
746    pub big_numbers_as_hex: bool,
747    /// Integer **values** with bit len not greater than 53
748    /// will be serialized as is (e.g. as JSON numbers).
749    ///
750    /// Default: `false`.
751    ///
752    /// See [`SerializeAbiValueParams::NUMBERS_AS_IS_THRESHOLD`].
753    pub small_numbers_as_is: bool,
754}
755
756impl SerializeAbiValueParams {
757    /// Number of bits after which the number will
758    /// be serialized as hex.
759    pub const NUMBERS_AS_HEX_THRESHOLD: u16 = 128;
760
761    /// Number of bits before which the number will
762    /// be serialized as is (e.g. as JSON number).
763    ///
764    /// See [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER].
765    pub const NUMBERS_AS_IS_THRESHOLD: u16 = 53;
766
767    const _ASSERT: () = const {
768        assert!(SerializeAbiValueParams::NUMBERS_AS_IS_THRESHOLD <= 64);
769    };
770
771    fn serialize_uint<S: serde::Serializer>(
772        &self,
773        value: &BigUint,
774        type_bits: u16,
775        s: S,
776    ) -> Result<S::Ok, S::Error> {
777        if self.big_numbers_as_hex && type_bits > Self::NUMBERS_AS_HEX_THRESHOLD {
778            let hex_len = type_bits.div_ceil(4) as usize;
779            s.collect_str(&format_args!("0x{value:0hex_len$x}"))
780        } else if self.small_numbers_as_is
781            && value.bits() <= Self::NUMBERS_AS_IS_THRESHOLD as u64
782            && let Some(value) = value.to_u64()
783        {
784            s.serialize_u64(value)
785        } else {
786            s.collect_str(value)
787        }
788    }
789
790    fn serialize_int<S: serde::Serializer>(
791        &self,
792        value: &BigInt,
793        type_bits: u16,
794        s: S,
795    ) -> Result<S::Ok, S::Error> {
796        if self.big_numbers_as_hex && type_bits > Self::NUMBERS_AS_HEX_THRESHOLD {
797            let hex_len = type_bits.div_ceil(4) as usize;
798            let uint = value.magnitude();
799            let sign = if value.sign() == num_bigint::Sign::Minus {
800                "-"
801            } else {
802                ""
803            };
804            s.collect_str(&format_args!("{sign}0x{uint:0hex_len$x}"))
805        } else if self.small_numbers_as_is
806            && value.bits() <= Self::NUMBERS_AS_IS_THRESHOLD as u64
807            && let Some(value) = value.to_i64()
808        {
809            s.serialize_i64(value)
810        } else {
811            s.collect_str(value)
812        }
813    }
814
815    fn serialize_tokens<S: serde::Serializer>(
816        &self,
817        value: &Tokens,
818        s: S,
819    ) -> Result<S::Ok, S::Error> {
820        if self.small_numbers_as_is {
821            let inner = 128 - value.into_inner().leading_zeros();
822            if inner <= Self::NUMBERS_AS_IS_THRESHOLD as u32 {
823                return s.serialize_u64(value.into_inner() as u64);
824            }
825        }
826
827        s.collect_str(value)
828    }
829}
830
831/// A [`serde::Serialize`] for a tuple of [`NamedAbiValue`].
832pub struct SerializeAbiValues<'a> {
833    /// A tuple of values.
834    pub values: &'a [NamedAbiValue],
835    /// Serialization params.
836    pub params: SerializeAbiValueParams,
837}
838
839impl<'a> SerializeAbiValues<'a> {
840    /// Creates a serializer.
841    #[inline]
842    pub fn with_params(values: &'a [NamedAbiValue], params: SerializeAbiValueParams) -> Self {
843        Self { values, params }
844    }
845}
846
847impl serde::Serialize for SerializeAbiValues<'_> {
848    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
849        let mut map = s.serialize_map(Some(self.values.len()))?;
850        for item in self.values {
851            map.serialize_entry(item.name.as_ref(), &SerializeAbiValue {
852                value: &item.value,
853                params: self.params,
854            })?;
855        }
856        map.end()
857    }
858}
859
860/// A [`serde::Serialize`] for [`AbiValue`].
861pub struct SerializeAbiValue<'a> {
862    /// Value to serialize.
863    pub value: &'a AbiValue,
864    /// Serialization params.
865    pub params: SerializeAbiValueParams,
866}
867
868impl<'a> SerializeAbiValue<'a> {
869    /// Creates a serializer.
870    #[inline]
871    pub fn with_params(value: &'a AbiValue, params: SerializeAbiValueParams) -> Self {
872        Self { value, params }
873    }
874}
875
876impl serde::Serialize for SerializeAbiValue<'_> {
877    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
878        use base64::prelude::{BASE64_STANDARD, Engine as _};
879
880        struct SerdeBytes<'a> {
881            bytes: &'a [u8],
882            fixed: bool,
883        }
884
885        impl serde::Serialize for SerdeBytes<'_> {
886            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
887                if s.is_human_readable() {
888                    let string = if self.fixed {
889                        hex::encode(self.bytes)
890                    } else {
891                        BASE64_STANDARD.encode(self.bytes)
892                    };
893                    s.serialize_str(&string)
894                } else {
895                    s.serialize_bytes(self.bytes)
896                }
897            }
898        }
899
900        struct SerdeMapKey<'a> {
901            key: &'a PlainAbiValue,
902            big_numbers_as_hex: bool,
903        }
904
905        impl serde::Serialize for SerdeMapKey<'_> {
906            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
907                let params = SerializeAbiValueParams {
908                    big_numbers_as_hex: self.big_numbers_as_hex,
909                    ..Default::default()
910                };
911
912                match self.key {
913                    PlainAbiValue::Uint(bits, value) => params.serialize_uint(value, *bits, s),
914                    PlainAbiValue::Int(bits, value) => params.serialize_int(value, *bits, s),
915                    PlainAbiValue::Bool(value) => s.collect_str(value),
916                    PlainAbiValue::Address(value) => s.collect_str(value),
917                    PlainAbiValue::AddressStd(value) => s.collect_str(value),
918                    PlainAbiValue::FixedBytes(bytes) => s.serialize_str(&hex::encode(bytes)),
919                }
920            }
921        }
922
923        match self.value {
924            AbiValue::Uint(bits, value) => self.params.serialize_uint(value, *bits, s),
925            AbiValue::Int(bits, value) => self.params.serialize_int(value, *bits, s),
926            AbiValue::VarUint(bytes, value) => {
927                self.params.serialize_uint(value, bytes.get() as u16 * 8, s)
928            }
929            AbiValue::VarInt(bytes, value) => {
930                self.params.serialize_int(value, bytes.get() as u16 * 8, s)
931            }
932            AbiValue::Bool(value) => s.serialize_bool(*value),
933            AbiValue::Cell(cell) => Boc::serialize(cell, s),
934            AbiValue::Address(addr) => match addr.as_ref() {
935                AnyAddr::None => s.serialize_str(""),
936                AnyAddr::Std(addr) => s.collect_str(addr),
937                AnyAddr::Ext(addr) => s.collect_str(addr),
938                AnyAddr::Var(_) => s.serialize_str("varaddr"), // TODO: add proper support
939            },
940            AbiValue::AddressStd(addr) => match addr {
941                None => s.serialize_str(""),
942                Some(addr) => s.collect_str(addr),
943            },
944            AbiValue::Bytes(bytes) => SerdeBytes {
945                bytes,
946                fixed: false,
947            }
948            .serialize(s),
949            AbiValue::FixedBytes(bytes) => SerdeBytes { bytes, fixed: true }.serialize(s),
950            AbiValue::String(value) => s.serialize_str(value),
951            AbiValue::Token(tokens) => self.params.serialize_tokens(tokens, s),
952            AbiValue::Tuple(values) => SerializeAbiValues {
953                values,
954                params: self.params,
955            }
956            .serialize(s),
957            AbiValue::Array(_, values) | AbiValue::FixedArray(_, values) => {
958                let mut seq = s.serialize_seq(Some(values.len()))?;
959                for value in values {
960                    seq.serialize_element(&SerializeAbiValue {
961                        value,
962                        params: self.params,
963                    })?;
964                }
965                seq.end()
966            }
967            AbiValue::Map(_, _, items) => {
968                let mut map = s.serialize_map(Some(items.len()))?;
969                for (key, value) in items {
970                    map.serialize_entry(
971                        &SerdeMapKey {
972                            key,
973                            big_numbers_as_hex: self.params.big_numbers_as_hex,
974                        },
975                        &SerializeAbiValue {
976                            value,
977                            params: self.params,
978                        },
979                    )?;
980                }
981                map.end()
982            }
983            AbiValue::Optional(_, value) => value
984                .as_ref()
985                .map(|value| SerializeAbiValue {
986                    value,
987                    params: self.params,
988                })
989                .serialize(s),
990            AbiValue::Ref(value) => SerializeAbiValue {
991                value,
992                params: self.params,
993            }
994            .serialize(s),
995        }
996    }
997}
998
999/// A [`DeserializeSeed`] for a tuple of [`NamedAbiValue`].
1000pub struct DeserializeAbiValues<'a> {
1001    /// Types of tuple items.
1002    pub types: &'a [NamedAbiType],
1003}
1004
1005impl<'de> serde::de::DeserializeSeed<'de> for DeserializeAbiValues<'_> {
1006    type Value = Vec<NamedAbiValue>;
1007
1008    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
1009        use serde::de::{Error, Visitor};
1010
1011        struct TupleVisitor<'a>(&'a [NamedAbiType]);
1012
1013        impl<'de> Visitor<'de> for TupleVisitor<'_> {
1014            type Value = Vec<NamedAbiValue>;
1015
1016            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1017                write!(f, "a tuple with named fields")
1018            }
1019
1020            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1021            where
1022                A: serde::de::MapAccess<'de>,
1023            {
1024                let mut items =
1025                    ahash::HashMap::with_capacity_and_hasher(self.0.len(), Default::default());
1026                for ty in self.0 {
1027                    items.insert(ty.name.as_ref(), (&ty.ty, None));
1028                }
1029
1030                while let Some(key) = map.next_key::<String>()? {
1031                    let Some((ty, value)) = items.get_mut(key.as_str()) else {
1032                        return Err(Error::custom(format_args!(
1033                            "unknown field `{key}` in tuple"
1034                        )));
1035                    };
1036
1037                    *value = Some(map.next_value_seed(DeserializeAbiValue { ty })?);
1038                }
1039
1040                let mut result = Vec::with_capacity(self.0.len());
1041                for item in self.0 {
1042                    if let Some((_, value)) = items.get_mut(item.name.as_ref())
1043                        && let Some(value) = value.take()
1044                    {
1045                        result.push(NamedAbiValue {
1046                            name: item.name.clone(),
1047                            value,
1048                        });
1049                    } else {
1050                        return Err(Error::custom(format_args!(
1051                            "missing field `{}` in tuple",
1052                            item.name.as_ref()
1053                        )));
1054                    }
1055                }
1056
1057                Ok(result)
1058            }
1059        }
1060
1061        d.deserialize_map(TupleVisitor(self.types))
1062    }
1063}
1064
1065/// A [`DeserializeSeed`] for [`AbiValue`].
1066///
1067/// Example:
1068/// ```
1069/// # use serde::de::DeserializeSeed;
1070/// # use tycho_types::abi::{AbiType, AbiValue, DeserializeAbiValue};
1071/// let abi_type = AbiType::int(32);
1072/// let json = "123";
1073/// let value: AbiValue = DeserializeAbiValue { ty: &abi_type }
1074///     .deserialize(&mut serde_json::Deserializer::from_str(json))
1075///     .unwrap();
1076/// assert_eq!(value, AbiValue::int(32, 123));
1077/// ```
1078#[repr(transparent)]
1079pub struct DeserializeAbiValue<'a> {
1080    /// Value type description.
1081    pub ty: &'a AbiType,
1082}
1083
1084impl<'de> serde::de::DeserializeSeed<'de> for DeserializeAbiValue<'_> {
1085    type Value = AbiValue;
1086
1087    fn deserialize<D: serde::Deserializer<'de>>(self, d: D) -> Result<Self::Value, D::Error> {
1088        use std::str::FromStr;
1089
1090        use base64::prelude::{BASE64_STANDARD, Engine as _};
1091        use num_traits::Num;
1092        use serde::de::{Error, Visitor};
1093
1094        fn ensure_fits<V: BigIntExt, T: std::fmt::Display, E: Error>(
1095            v: &V,
1096            ty: T,
1097            bits: u16,
1098            signed: bool,
1099        ) -> Result<(), E> {
1100            let value_bits = v.bitsize(signed);
1101            if value_bits <= bits {
1102                Ok(())
1103            } else {
1104                Err(Error::custom(format_args!(
1105                    "parsed integer doesn't fit into `{ty}`"
1106                )))
1107            }
1108        }
1109
1110        fn parse_common<T: std::fmt::Display, E: Error>(v: &str, ty: T) -> Result<BigUint, E> {
1111            let (v, radix) = if let Some(v) = v.strip_prefix("0x") {
1112                (v, 16)
1113            } else if let Some(v) = v.strip_prefix("0b") {
1114                (v, 2)
1115            } else {
1116                (v, 10)
1117            };
1118
1119            BigUint::from_str_radix(v, radix)
1120                .map_err(|e| E::custom(format_args!("invalid {ty}: {e}")))
1121        }
1122
1123        fn parse_uint<T: std::fmt::Display, E: Error>(
1124            v: &str,
1125            ty: T,
1126            bits: u16,
1127        ) -> Result<BigUint, E> {
1128            if v.starts_with('-') {
1129                return Err(Error::custom(format_args!("expected an unsigned integer")));
1130            }
1131            let value = parse_common(v, &ty)?;
1132            ensure_fits(&value, ty, bits, false)?;
1133            Ok(value)
1134        }
1135
1136        fn parse_int<T: std::fmt::Display, E: Error>(
1137            v: &str,
1138            ty: T,
1139            bits: u16,
1140        ) -> Result<BigInt, E> {
1141            let (v, sign) = if let Some(v) = v.strip_prefix('-') {
1142                (v, num_bigint::Sign::Minus)
1143            } else {
1144                (v, num_bigint::Sign::Plus)
1145            };
1146
1147            let value = BigInt::from_biguint(sign, parse_common(v, &ty)?);
1148            ensure_fits(&value, ty, bits, true)?;
1149            Ok(value)
1150        }
1151
1152        struct PlainAbiValueSeed(PlainAbiType);
1153
1154        impl<'de> serde::de::DeserializeSeed<'de> for PlainAbiValueSeed {
1155            type Value = PlainAbiValue;
1156
1157            fn deserialize<D>(self, d: D) -> Result<Self::Value, D::Error>
1158            where
1159                D: serde::Deserializer<'de>,
1160            {
1161                d.deserialize_str(PlainAbiValueVisitor(self.0))
1162            }
1163        }
1164
1165        struct PlainAbiValueVisitor(PlainAbiType);
1166
1167        impl<'de> Visitor<'de> for PlainAbiValueVisitor {
1168            type Value = PlainAbiValue;
1169
1170            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1171                match self.0 {
1172                    PlainAbiType::Uint(bits) => {
1173                        write!(f, "an {bits}-bit unsigned integer as string")
1174                    }
1175                    PlainAbiType::Int(bits) => {
1176                        write!(f, "a {bits}-bit signed integer as string")
1177                    }
1178                    PlainAbiType::Address => write!(f, "an address"),
1179                    PlainAbiType::AddressStd => write!(f, "an address_std"),
1180                    PlainAbiType::Bool => write!(f, "a bool as string"),
1181                    PlainAbiType::FixedBytes(n) => write!(f, "hex-encoded {n} bytes as string"),
1182                }
1183            }
1184
1185            fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
1186                match self.0 {
1187                    PlainAbiType::Uint(bits) => parse_uint(v, format_args!("uint{bits}"), bits)
1188                        .map(|v| PlainAbiValue::Uint(bits, v)),
1189                    PlainAbiType::Int(bits) => parse_int(v, format_args!("int{bits}"), bits)
1190                        .map(|v| PlainAbiValue::Int(bits, v)),
1191                    PlainAbiType::Bool => {
1192                        let value = bool::from_str(v)
1193                            .map_err(|e| Error::custom(format_args!("invalid bool: {e}")))?;
1194                        Ok(PlainAbiValue::Bool(value))
1195                    }
1196                    PlainAbiType::Address => {
1197                        let (addr, _) = StdAddr::from_str_ext(v, StdAddrFormat::any())
1198                            .map_err(|e| Error::custom(format_args!("invalid address: {e}")))?;
1199                        Ok(PlainAbiValue::Address(Box::new(IntAddr::Std(addr))))
1200                    }
1201                    PlainAbiType::AddressStd => {
1202                        let (addr, _) = StdAddr::from_str_ext(v, StdAddrFormat::any())
1203                            .map_err(|e| Error::custom(format_args!("invalid address_std: {e}")))?;
1204                        Ok(PlainAbiValue::AddressStd(Box::new(addr)))
1205                    }
1206                    PlainAbiType::FixedBytes(n) => {
1207                        let Some(str_len) = n.checked_mul(2) else {
1208                            return Err(Error::custom(format_args!(
1209                                "{n} bytes cannot be parsed as a hex string"
1210                            )));
1211                        };
1212                        if v.len() != str_len {
1213                            return Err(Error::custom(format_args!(
1214                                "invalid string length {}, expected {str_len}",
1215                                v.len(),
1216                            )));
1217                        }
1218
1219                        let value = hex::decode(v).map_err(Error::custom)?;
1220                        debug_assert_eq!(value.len(), n);
1221                        Ok(PlainAbiValue::FixedBytes(value.into()))
1222                    }
1223                }
1224            }
1225        }
1226
1227        struct UintVisitor<T>(T, u16);
1228
1229        impl<'de, T: std::fmt::Display> Visitor<'de> for UintVisitor<T> {
1230            type Value = BigUint;
1231
1232            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1233                write!(f, "an unsigned integer as string or number")
1234            }
1235
1236            fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
1237                parse_uint(v, self.0, self.1)
1238            }
1239
1240            fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
1241                let value = BigUint::from(v);
1242                ensure_fits(&value, self.0, self.1, false)?;
1243                Ok(value)
1244            }
1245
1246            fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> {
1247                if v >= 0 {
1248                    self.visit_u64(v as u64)
1249                } else {
1250                    Err(Error::custom("expected an unsigned integer"))
1251                }
1252            }
1253        }
1254
1255        struct IntVisitor<T>(T, u16);
1256
1257        impl<'de, T: std::fmt::Display> Visitor<'de> for IntVisitor<T> {
1258            type Value = BigInt;
1259
1260            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1261                write!(f, "a signed integer as string or number")
1262            }
1263
1264            fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
1265                parse_int(v, self.0, self.1)
1266            }
1267
1268            fn visit_u64<E: Error>(self, v: u64) -> Result<Self::Value, E> {
1269                let value = BigInt::from(v);
1270                ensure_fits(&value, self.0, self.1, true)?;
1271                Ok(value)
1272            }
1273
1274            fn visit_i64<E: Error>(self, v: i64) -> Result<Self::Value, E> {
1275                let value = BigInt::from(v);
1276                ensure_fits(&value, self.0, self.1, true)?;
1277                Ok(value)
1278            }
1279        }
1280
1281        struct AddressVisitor {
1282            std_only: bool,
1283        }
1284
1285        impl<'de> Visitor<'de> for AddressVisitor {
1286            type Value = AbiValue;
1287
1288            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1289                if self.std_only {
1290                    write!(f, "an std address as string")
1291                } else {
1292                    write!(f, "an address as string")
1293                }
1294            }
1295
1296            fn visit_none<E: Error>(self) -> Result<Self::Value, E> {
1297                Ok(if self.std_only {
1298                    AbiValue::AddressStd(None)
1299                } else {
1300                    AbiValue::Address(Box::new(AnyAddr::None))
1301                })
1302            }
1303
1304            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1305            where
1306                D: serde::Deserializer<'de>,
1307            {
1308                deserializer.deserialize_str(self)
1309            }
1310
1311            fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
1312                if v.is_empty() {
1313                    return self.visit_none();
1314                }
1315
1316                let is_extaddr = v.starts_with(':');
1317                if self.std_only && (is_extaddr || v == "varaddr") {
1318                    return Err(Error::custom("expected an std address"));
1319                }
1320
1321                if is_extaddr {
1322                    let addr = ExtAddr::from_str(v)
1323                        .map_err(|e| Error::custom(format_args!("invalid address: {e}")))?;
1324                    return Ok(AbiValue::Address(Box::new(AnyAddr::Ext(addr))));
1325                }
1326
1327                let (addr, _) = StdAddr::from_str_ext(v, StdAddrFormat::any())
1328                    .map_err(|e| Error::custom(format_args!("invalid address: {e}")))?;
1329                Ok(if self.std_only {
1330                    AbiValue::AddressStd(Some(Box::new(addr)))
1331                } else {
1332                    AbiValue::Address(Box::new(AnyAddr::Std(addr)))
1333                })
1334            }
1335        }
1336
1337        struct BytesVisitor(Option<usize>);
1338
1339        impl BytesVisitor {
1340            fn make_value<E: Error>(&self, bytes: Vec<u8>) -> Result<AbiValue, E> {
1341                match self.0 {
1342                    None => Ok(AbiValue::Bytes(Bytes::from(bytes))),
1343                    Some(len) if bytes.len() == len => Ok(AbiValue::FixedBytes(Bytes::from(bytes))),
1344                    Some(_) => Err(Error::invalid_length(bytes.len(), self)),
1345                }
1346            }
1347        }
1348
1349        impl<'de> Visitor<'de> for BytesVisitor {
1350            type Value = AbiValue;
1351
1352            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1353                match self.0 {
1354                    None => write!(f, "base64-encoded bytes as string"),
1355                    Some(n) => write!(f, "hex-encoded {n} bytes as string"),
1356                }
1357            }
1358
1359            fn visit_bytes<E: Error>(self, v: &[u8]) -> Result<Self::Value, E> {
1360                self.make_value(v.to_vec())
1361            }
1362
1363            fn visit_byte_buf<E: Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {
1364                self.make_value(v)
1365            }
1366
1367            fn visit_str<E: Error>(self, v: &str) -> Result<Self::Value, E> {
1368                let value = match self.0 {
1369                    // `bytes` are parsed as a base64 string
1370                    None => BASE64_STANDARD.decode(v).map_err(|e| {
1371                        E::custom(format_args!("failed to deserialize a base64 string: {e}"))
1372                    })?,
1373                    // `fixedbytes` are parsed as a hex string
1374                    Some(_) => hex::decode(v).map_err(|e| {
1375                        E::custom(format_args!("failed to deserialize a hex string: {e}"))
1376                    })?,
1377                };
1378
1379                self.make_value(value)
1380            }
1381        }
1382
1383        struct ArrayVisitor<'a>(&'a Arc<AbiType>, Option<usize>);
1384
1385        impl<'de> Visitor<'de> for ArrayVisitor<'_> {
1386            type Value = AbiValue;
1387
1388            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1389                match self.1 {
1390                    None => write!(f, "an array of values"),
1391                    Some(n) => write!(f, "an array of {n} values"),
1392                }
1393            }
1394
1395            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
1396            where
1397                A: serde::de::SeqAccess<'de>,
1398            {
1399                let mut result = Vec::with_capacity(seq.size_hint().unwrap_or_default());
1400                while let Some(value) = seq.next_element_seed(DeserializeAbiValue { ty: self.0 })? {
1401                    result.push(value);
1402                }
1403
1404                match self.1 {
1405                    None => Ok(AbiValue::Array(self.0.clone(), result)),
1406                    Some(len) if result.len() == len => {
1407                        Ok(AbiValue::FixedArray(self.0.clone(), result))
1408                    }
1409                    Some(_) => Err(Error::invalid_length(result.len(), &self)),
1410                }
1411            }
1412        }
1413
1414        struct MapVisitor<'a>(PlainAbiType, &'a Arc<AbiType>);
1415
1416        impl<'de> Visitor<'de> for MapVisitor<'_> {
1417            type Value = AbiValue;
1418
1419            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1420                write!(f, "a map")
1421            }
1422
1423            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
1424            where
1425                A: serde::de::MapAccess<'de>,
1426            {
1427                let mut result = BTreeMap::new();
1428                while let Some(key) = map.next_key_seed(PlainAbiValueSeed(self.0))? {
1429                    let value = map.next_value_seed(DeserializeAbiValue { ty: self.1 })?;
1430                    result.insert(key, value);
1431                }
1432                Ok(AbiValue::Map(self.0, self.1.clone(), result))
1433            }
1434        }
1435
1436        struct OptionVisitor<'a>(&'a Arc<AbiType>);
1437
1438        impl<'de> Visitor<'de> for OptionVisitor<'_> {
1439            type Value = AbiValue;
1440
1441            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1442                write!(f, "an optional value")
1443            }
1444
1445            fn visit_none<E: Error>(self) -> Result<Self::Value, E> {
1446                Ok(AbiValue::Optional(self.0.clone(), None))
1447            }
1448
1449            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
1450            where
1451                D: serde::Deserializer<'de>,
1452            {
1453                let value = DeserializeAbiValue {
1454                    ty: self.0.as_ref(),
1455                }
1456                .deserialize(deserializer)?;
1457                Ok(AbiValue::Optional(self.0.clone(), Some(Box::new(value))))
1458            }
1459        }
1460
1461        match self.ty {
1462            AbiType::Uint(bits) => {
1463                let value = d.deserialize_any(UintVisitor(format_args!("uint{bits}"), *bits))?;
1464                Ok(AbiValue::Uint(*bits, value))
1465            }
1466            AbiType::Int(bits) => {
1467                let value = d.deserialize_any(IntVisitor(format_args!("int{bits}"), *bits))?;
1468                Ok(AbiValue::Int(*bits, value))
1469            }
1470            AbiType::VarUint(bytes) => {
1471                let bytes = *bytes;
1472                let value = d.deserialize_any(UintVisitor(
1473                    format_args!("varuint{bytes}"),
1474                    bytes.get() as u16 * 8,
1475                ))?;
1476                Ok(AbiValue::VarUint(bytes, value))
1477            }
1478            AbiType::VarInt(bytes) => {
1479                let bytes = *bytes;
1480                let value = d.deserialize_any(IntVisitor(
1481                    format_args!("varint{bytes}"),
1482                    bytes.get() as u16 * 8,
1483                ))?;
1484                Ok(AbiValue::VarInt(bytes, value))
1485            }
1486            AbiType::Bool => bool::deserialize(d).map(AbiValue::Bool),
1487            AbiType::Cell => Boc::deserialize(d).map(AbiValue::Cell),
1488            AbiType::Address => d.deserialize_option(AddressVisitor { std_only: false }),
1489            AbiType::AddressStd => d.deserialize_option(AddressVisitor { std_only: true }),
1490            AbiType::Bytes => {
1491                if d.is_human_readable() {
1492                    d.deserialize_str(BytesVisitor(None))
1493                } else {
1494                    d.deserialize_byte_buf(BytesVisitor(None))
1495                }
1496            }
1497            AbiType::FixedBytes(len) => {
1498                if d.is_human_readable() {
1499                    d.deserialize_str(BytesVisitor(Some(*len)))
1500                } else {
1501                    d.deserialize_byte_buf(BytesVisitor(Some(*len)))
1502                }
1503            }
1504            AbiType::String => String::deserialize(d).map(AbiValue::String),
1505            AbiType::Token => {
1506                let Some(value) = d
1507                    .deserialize_any(UintVisitor("tokens", Tokens::VALUE_BITS))?
1508                    .to_u128()
1509                else {
1510                    return Err(Error::custom("tokens integer out of range"));
1511                };
1512                Ok(AbiValue::Token(Tokens::new(value)))
1513            }
1514            AbiType::Tuple(types) => DeserializeAbiValues { types }
1515                .deserialize(d)
1516                .map(AbiValue::Tuple),
1517            AbiType::Array(ty) => d.deserialize_seq(ArrayVisitor(ty, None)),
1518            AbiType::FixedArray(ty, len) => d.deserialize_seq(ArrayVisitor(ty, Some(*len))),
1519            AbiType::Map(key, value) => d.deserialize_map(MapVisitor(*key, value)),
1520            AbiType::Optional(ty) => d.deserialize_option(OptionVisitor(ty)),
1521            AbiType::Ref(ty) => DeserializeAbiValue { ty }
1522                .deserialize(d)
1523                .map(|value| AbiValue::Ref(Box::new(value))),
1524        }
1525    }
1526}
1527
1528#[cfg(test)]
1529mod tests {
1530    use super::*;
1531    use crate::abi::AbiVersion;
1532    use crate::cell::HashBytes;
1533
1534    #[test]
1535    fn to_from_json_works() -> Result<()> {
1536        for (value, json) in [
1537            // uint
1538            (AbiValue::uint(32, 0u32), "0"),
1539            (AbiValue::uint(32, 123u32), "123"),
1540            (AbiValue::uint(32, 0u32), r#""0""#),
1541            (AbiValue::uint(32, 123u32), r#""123""#),
1542            (AbiValue::uint(32, 123u32), r#""0x7b""#),
1543            (AbiValue::uint(32, 123u32), r#""0x000007b""#),
1544            (AbiValue::uint(32, 123u32), r#""0b01111011""#),
1545            // int (positive)
1546            (AbiValue::int(32, 0), "0"),
1547            (AbiValue::int(32, 123), "123"),
1548            (AbiValue::int(32, 0), r#""0""#),
1549            (AbiValue::int(32, 123), r#""123""#),
1550            (AbiValue::int(32, 123), r#""0x7b""#),
1551            (AbiValue::int(32, 123), r#""0x000007b""#),
1552            (AbiValue::int(32, 123), r#""0b01111011""#),
1553            // int (negative)
1554            (AbiValue::int(32, -123), "-123"),
1555            (AbiValue::int(32, 0), r#""-0""#),
1556            (AbiValue::int(32, -123), r#""-123""#),
1557            (AbiValue::int(32, -123), r#""-0x7b""#),
1558            (AbiValue::int(32, -123), r#""-0x0000007b""#),
1559            (AbiValue::int(32, -123), r#""-0b01111011""#),
1560            // varuint
1561            (AbiValue::varuint(16, 0u32), "0"),
1562            (AbiValue::varuint(16, 123u32), "123"),
1563            (AbiValue::varuint(16, 0u32), r#""0""#),
1564            (AbiValue::varuint(16, 123u32), r#""123""#),
1565            (AbiValue::varuint(16, 123u32), r#""0x7b""#),
1566            (AbiValue::varuint(16, 123u32), r#""0b01111011""#),
1567            // int (positive)
1568            (AbiValue::varint(16, 0), "0"),
1569            (AbiValue::varint(16, 123), "123"),
1570            (AbiValue::varint(16, 0), r#""0""#),
1571            (AbiValue::varint(16, 123), r#""123""#),
1572            (AbiValue::varint(16, 123), r#""0x7b""#),
1573            (AbiValue::varint(16, 123), r#""0b01111011""#),
1574            // int (negative)
1575            (AbiValue::varint(16, -123), "-123"),
1576            (AbiValue::varint(16, 0), r#""-0""#),
1577            (AbiValue::varint(16, -123), r#""-123""#),
1578            (AbiValue::varint(16, -123), r#""-0x7b""#),
1579            (AbiValue::varint(16, -123), r#""-0b01111011""#),
1580            // bool
1581            (AbiValue::Bool(false), "false"),
1582            (AbiValue::Bool(true), "true"),
1583            // cell
1584            (
1585                AbiValue::Cell(Cell::empty_cell()),
1586                "\"te6ccgEBAQEAAgAAAA==\"",
1587            ),
1588            // address
1589            (AbiValue::Address(Box::new(AnyAddr::None)), "null"),
1590            (AbiValue::Address(Box::new(AnyAddr::None)), "\"\""),
1591            (
1592                AbiValue::Address(Box::new(AnyAddr::Std(StdAddr::new(0, HashBytes([0; 32]))))),
1593                "\"0:0000000000000000000000000000000000000000000000000000000000000000\"",
1594            ),
1595            (
1596                AbiValue::Address(Box::new(AnyAddr::Std(StdAddr::new(
1597                    -1,
1598                    HashBytes([0x33; 32]),
1599                )))),
1600                "\"Uf8zMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMxYA\"",
1601            ),
1602            (
1603                AbiValue::Address(Box::new(AnyAddr::Ext(ExtAddr::new(0, []).unwrap()))),
1604                "\":\"",
1605            ),
1606            (
1607                AbiValue::Address(Box::new(AnyAddr::Ext(ExtAddr::new(5, vec![0x84]).unwrap()))),
1608                "\":84_\"",
1609            ),
1610            // std address
1611            (AbiValue::AddressStd(None), "null"),
1612            (AbiValue::AddressStd(None), "\"\""),
1613            (
1614                AbiValue::AddressStd(Some(Box::new(StdAddr::new(0, HashBytes([0; 32]))))),
1615                "\"0:0000000000000000000000000000000000000000000000000000000000000000\"",
1616            ),
1617            (
1618                AbiValue::AddressStd(Some(Box::new(StdAddr::new(-1, HashBytes([0x33; 32]))))),
1619                "\"Uf8zMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMxYA\"",
1620            ),
1621            // bytes
1622            (AbiValue::Bytes(Bytes::new()), "\"\""),
1623            (AbiValue::Bytes(Bytes::from(&[0x7bu8] as &[_])), "\"ew==\""),
1624            // fixed bytes
1625            (AbiValue::FixedBytes(Bytes::new()), "\"\""),
1626            (
1627                AbiValue::FixedBytes(Bytes::from(&[0x7bu8] as &[_])),
1628                "\"7b\"",
1629            ),
1630            // string
1631            (AbiValue::String(String::new()), "\"\""),
1632            (AbiValue::String("hello".to_owned()), "\"hello\""),
1633            // token
1634            (AbiValue::Token(Tokens::new(0)), "0"),
1635            (AbiValue::Token(Tokens::new(123)), "123"),
1636            (AbiValue::Token(Tokens::new(0)), r#""0""#),
1637            (AbiValue::Token(Tokens::new(123)), r#""123""#),
1638            (AbiValue::Token(Tokens::new(123)), r#""0x7b""#),
1639            (AbiValue::Token(Tokens::new(123)), r#""0b01111011""#),
1640            // tuple
1641            (AbiValue::tuple([] as [NamedAbiValue; 0]), "{}"),
1642            (
1643                AbiValue::tuple([
1644                    AbiValue::Bool(false).named("hi"),
1645                    AbiValue::String("hello".to_owned()).named("mark"),
1646                ]),
1647                "{\"mark\":\"hello\",\"hi\":false}",
1648            ),
1649            // array
1650            (AbiValue::array::<bool, _>([]), "[]"),
1651            (AbiValue::array([0u32, 123u32]), "[0,\"123\"]"),
1652            // fixed array
1653            (AbiValue::fixedarray::<bool, _>([]), "[]"),
1654            (AbiValue::fixedarray([0u32, 123u32]), "[0,\"123\"]"),
1655            // bool map
1656            (AbiValue::map(std::iter::empty::<(bool, u32)>()), "{}"),
1657            (
1658                AbiValue::map([(false, 123), (true, 234)]),
1659                "{\"true\":234,\"false\":123}",
1660            ),
1661            // uint map
1662            (AbiValue::map(std::iter::empty::<(u32, u32)>()), "{}"),
1663            (
1664                AbiValue::map([(10000, 123), (1000, 234)]),
1665                "{\"1000\":234,\"10000\":123}",
1666            ),
1667            // uint map
1668            (AbiValue::map(std::iter::empty::<(u32, u32)>()), "{}"),
1669            (
1670                AbiValue::map([(HashBytes([0; 32]), 123), (HashBytes([0x33; 32]), 234)]),
1671                "{\"0x0000000000000000000000000000000000000000000000000000000000000000\":123,\
1672                \"0x3333333333333333333333333333333333333333333333333333333333333333\":234}",
1673            ),
1674            // int map
1675            (AbiValue::map(std::iter::empty::<(u32, u32)>()), "{}"),
1676            (
1677                AbiValue::map([(-1000, 123), (1000, 234)]),
1678                "{\"1000\":234,\"-1000\":123}",
1679            ),
1680            // address map
1681            (AbiValue::map(std::iter::empty::<(StdAddr, u32)>()), "{}"),
1682            (
1683                AbiValue::map([
1684                    (StdAddr::new(0, HashBytes::ZERO), 123),
1685                    (StdAddr::new(-1, HashBytes([0x33; 32])), 234),
1686                ]),
1687                "{\"0:0000000000000000000000000000000000000000000000000000000000000000\":123,\
1688                \"Uf8zMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMxYA\":234}",
1689            ),
1690            // fixedbytes map
1691            (
1692                AbiValue::map([([0x33u8; 32], 123), ([0x55; 32], 234)]),
1693                "{\"3333333333333333333333333333333333333333333333333333333333333333\":123,\
1694                \"5555555555555555555555555555555555555555555555555555555555555555\": 234}",
1695            ),
1696            // optional
1697            (AbiValue::optional(None::<u32>), "null"),
1698            (AbiValue::optional(Some(123u32)), "\"123\""),
1699            // ref
1700            (AbiValue::reference(AbiValue::uint(32, 123u32)), "\"123\""),
1701        ] {
1702            let ty = value.get_type();
1703            println!("parsing provided `{json}` with {ty:?}");
1704            assert_eq!(AbiValue::from_json_str(json, &ty)?, value,);
1705
1706            let serialized =
1707                serde_json::to_string(&SerializeAbiValue::with_params(&value, Default::default()))?;
1708            println!("parsing auto `{serialized}` with {ty:?}");
1709            let parsed = AbiValue::from_json_str(&serialized, &ty)?;
1710            assert_eq!(parsed, value);
1711        }
1712
1713        Ok(())
1714    }
1715
1716    #[test]
1717    fn custom_json_params_works() -> Result<()> {
1718        fn check_parsed(value: &AbiValue, json: &str) {
1719            let parsed = AbiValue::from_json_str(json, &value.get_type()).unwrap();
1720            assert_eq!(value, &parsed);
1721        }
1722
1723        //
1724
1725        let params = SerializeAbiValueParams {
1726            big_numbers_as_hex: true,
1727            ..Default::default()
1728        };
1729
1730        let value = AbiValue::map([(HashBytes([0; 32]), ()), (HashBytes([0x33; 32]), ())]);
1731        let json = serde_json::to_string(&SerializeAbiValue::with_params(&value, params))?;
1732        assert_eq!(
1733            json,
1734            "{\"0x0000000000000000000000000000000000000000000000000000000000000000\":{},\
1735            \"0x3333333333333333333333333333333333333333333333333333333333333333\":{}}"
1736        );
1737        check_parsed(&value, &json);
1738
1739        //
1740
1741        let params = SerializeAbiValueParams {
1742            small_numbers_as_is: true,
1743            ..Default::default()
1744        };
1745
1746        let max_uint = (1u64 << SerializeAbiValueParams::NUMBERS_AS_IS_THRESHOLD) - 1;
1747
1748        for (value, json) in [
1749            // uint
1750            (AbiValue::uint(256, 123u32), "123".to_owned()),
1751            (AbiValue::uint(256, max_uint), format!("{max_uint}")),
1752            (
1753                AbiValue::uint(256, max_uint + 1),
1754                format!("\"{}\"", max_uint + 1),
1755            ),
1756            (AbiValue::uint(256, u64::MAX), format!("\"{}\"", u64::MAX)),
1757            // int
1758            (AbiValue::int(64, 123), "123".to_owned()),
1759            (AbiValue::int(256, max_uint), format!("{max_uint}")),
1760            (
1761                AbiValue::int(256, -(max_uint as i64)),
1762                format!("-{max_uint}"),
1763            ),
1764            (
1765                AbiValue::int(256, -((max_uint + 1) as i64)),
1766                format!("\"-{}\"", max_uint + 1),
1767            ),
1768            (AbiValue::int(256, i64::MAX), format!("\"{}\"", i64::MAX)),
1769            (AbiValue::int(256, i64::MIN), format!("\"{}\"", i64::MIN)),
1770            // varuint
1771            (AbiValue::varuint(16, 123u32), "123".to_owned()),
1772            (AbiValue::varuint(16, max_uint), format!("{max_uint}")),
1773            (
1774                AbiValue::varuint(16, max_uint + 1),
1775                format!("\"{}\"", max_uint + 1),
1776            ),
1777            (AbiValue::varuint(16, u64::MAX), format!("\"{}\"", u64::MAX)),
1778            // varint
1779            (AbiValue::varint(16, 123), "123".to_owned()),
1780            (AbiValue::varint(16, max_uint), format!("{max_uint}")),
1781            (
1782                AbiValue::varint(16, -(max_uint as i64)),
1783                format!("-{max_uint}"),
1784            ),
1785            (
1786                AbiValue::varint(16, -((max_uint + 1) as i64)),
1787                format!("\"-{}\"", max_uint + 1),
1788            ),
1789            (AbiValue::varint(16, i64::MAX), format!("\"{}\"", i64::MAX)),
1790            (AbiValue::varint(16, i64::MIN), format!("\"{}\"", i64::MIN)),
1791            // tokens
1792            (AbiValue::Token(Tokens::new(123)), "123".to_owned()),
1793            (
1794                AbiValue::Token(Tokens::new(max_uint as _)),
1795                format!("{max_uint}"),
1796            ),
1797            (
1798                AbiValue::Token(Tokens::new(max_uint as u128 + 1)),
1799                format!("\"{}\"", max_uint + 1),
1800            ),
1801        ] {
1802            let serialized =
1803                serde_json::to_string(&SerializeAbiValue::with_params(&value, params))?;
1804            assert_eq!(serialized, json);
1805            check_parsed(&value, &json);
1806        }
1807
1808        Ok(())
1809    }
1810
1811    #[test]
1812    fn fixed_bytes_as_map_key() -> Result<()> {
1813        let map = AbiValue::map([([0x33u8; 32], 123), ([0x55; 32], 234)]);
1814        let serialized = map.make_cell(AbiVersion::V2_7)?;
1815        let parsed = AbiValue::load(
1816            &map.get_type(),
1817            AbiVersion::V2_7,
1818            &mut serialized.as_slice()?,
1819        )?;
1820        assert_eq!(map, parsed);
1821
1822        let map_as_uints = AbiValue::Map(
1823            PlainAbiType::Uint(256),
1824            Arc::new(AbiType::Int(32)),
1825            BTreeMap::from_iter([
1826                (
1827                    PlainAbiValue::Uint(256, BigUint::from_bytes_be(&[0x33; 32])),
1828                    AbiValue::int(32, 123),
1829                ),
1830                (
1831                    PlainAbiValue::Uint(256, BigUint::from_bytes_be(&[0x55; 32])),
1832                    AbiValue::int(32, 234),
1833                ),
1834            ]),
1835        );
1836        let serialized_as_uints = map_as_uints.make_cell(AbiVersion::V2_7)?;
1837        assert_eq!(serialized, serialized_as_uints);
1838
1839        Ok(())
1840    }
1841
1842    #[test]
1843    fn tuple_tu_from_json() -> Result<()> {
1844        let json = "{\"a\":\"123\",\"b\":false}";
1845        let types = [AbiType::int(32).named("a"), AbiType::Bool.named("b")];
1846        let parsed = NamedAbiValue::tuple_from_json_str(json, &types)?;
1847        let serialized = serde_json::to_string(&SerializeAbiValues {
1848            values: &parsed,
1849            params: Default::default(),
1850        })?;
1851        assert_eq!(serialized, json);
1852        Ok(())
1853    }
1854}