foundry_cheatcodes/
json.rs

1//! Implementations of [`Json`](spec::Group::Json) cheatcodes.
2
3use crate::{Cheatcode, Cheatcodes, Result, Vm::*, string};
4use alloy_dyn_abi::{DynSolType, DynSolValue, Resolver, eip712_parser::EncodeType};
5use alloy_primitives::{Address, B256, I256, hex};
6use alloy_sol_types::SolValue;
7use foundry_common::fs;
8use foundry_config::fs_permissions::FsAccessKind;
9use serde_json::{Map, Value};
10use std::{borrow::Cow, collections::BTreeMap};
11
12impl Cheatcode for keyExistsCall {
13    fn apply(&self, _state: &mut Cheatcodes) -> Result {
14        let Self { json, key } = self;
15        check_json_key_exists(json, key)
16    }
17}
18
19impl Cheatcode for keyExistsJsonCall {
20    fn apply(&self, _state: &mut Cheatcodes) -> Result {
21        let Self { json, key } = self;
22        check_json_key_exists(json, key)
23    }
24}
25
26impl Cheatcode for parseJson_0Call {
27    fn apply(&self, _state: &mut Cheatcodes) -> Result {
28        let Self { json } = self;
29        parse_json(json, "$")
30    }
31}
32
33impl Cheatcode for parseJson_1Call {
34    fn apply(&self, _state: &mut Cheatcodes) -> Result {
35        let Self { json, key } = self;
36        parse_json(json, key)
37    }
38}
39
40impl Cheatcode for parseJsonUintCall {
41    fn apply(&self, _state: &mut Cheatcodes) -> Result {
42        let Self { json, key } = self;
43        parse_json_coerce(json, key, &DynSolType::Uint(256))
44    }
45}
46
47impl Cheatcode for parseJsonUintArrayCall {
48    fn apply(&self, _state: &mut Cheatcodes) -> Result {
49        let Self { json, key } = self;
50        parse_json_coerce(json, key, &DynSolType::Array(Box::new(DynSolType::Uint(256))))
51    }
52}
53
54impl Cheatcode for parseJsonIntCall {
55    fn apply(&self, _state: &mut Cheatcodes) -> Result {
56        let Self { json, key } = self;
57        parse_json_coerce(json, key, &DynSolType::Int(256))
58    }
59}
60
61impl Cheatcode for parseJsonIntArrayCall {
62    fn apply(&self, _state: &mut Cheatcodes) -> Result {
63        let Self { json, key } = self;
64        parse_json_coerce(json, key, &DynSolType::Array(Box::new(DynSolType::Int(256))))
65    }
66}
67
68impl Cheatcode for parseJsonBoolCall {
69    fn apply(&self, _state: &mut Cheatcodes) -> Result {
70        let Self { json, key } = self;
71        parse_json_coerce(json, key, &DynSolType::Bool)
72    }
73}
74
75impl Cheatcode for parseJsonBoolArrayCall {
76    fn apply(&self, _state: &mut Cheatcodes) -> Result {
77        let Self { json, key } = self;
78        parse_json_coerce(json, key, &DynSolType::Array(Box::new(DynSolType::Bool)))
79    }
80}
81
82impl Cheatcode for parseJsonAddressCall {
83    fn apply(&self, _state: &mut Cheatcodes) -> Result {
84        let Self { json, key } = self;
85        parse_json_coerce(json, key, &DynSolType::Address)
86    }
87}
88
89impl Cheatcode for parseJsonAddressArrayCall {
90    fn apply(&self, _state: &mut Cheatcodes) -> Result {
91        let Self { json, key } = self;
92        parse_json_coerce(json, key, &DynSolType::Array(Box::new(DynSolType::Address)))
93    }
94}
95
96impl Cheatcode for parseJsonStringCall {
97    fn apply(&self, _state: &mut Cheatcodes) -> Result {
98        let Self { json, key } = self;
99        parse_json_coerce(json, key, &DynSolType::String)
100    }
101}
102
103impl Cheatcode for parseJsonStringArrayCall {
104    fn apply(&self, _state: &mut Cheatcodes) -> Result {
105        let Self { json, key } = self;
106        parse_json_coerce(json, key, &DynSolType::Array(Box::new(DynSolType::String)))
107    }
108}
109
110impl Cheatcode for parseJsonBytesCall {
111    fn apply(&self, _state: &mut Cheatcodes) -> Result {
112        let Self { json, key } = self;
113        parse_json_coerce(json, key, &DynSolType::Bytes)
114    }
115}
116
117impl Cheatcode for parseJsonBytesArrayCall {
118    fn apply(&self, _state: &mut Cheatcodes) -> Result {
119        let Self { json, key } = self;
120        parse_json_coerce(json, key, &DynSolType::Array(Box::new(DynSolType::Bytes)))
121    }
122}
123
124impl Cheatcode for parseJsonBytes32Call {
125    fn apply(&self, _state: &mut Cheatcodes) -> Result {
126        let Self { json, key } = self;
127        parse_json_coerce(json, key, &DynSolType::FixedBytes(32))
128    }
129}
130
131impl Cheatcode for parseJsonBytes32ArrayCall {
132    fn apply(&self, _state: &mut Cheatcodes) -> Result {
133        let Self { json, key } = self;
134        parse_json_coerce(json, key, &DynSolType::Array(Box::new(DynSolType::FixedBytes(32))))
135    }
136}
137
138impl Cheatcode for parseJsonType_0Call {
139    fn apply(&self, _state: &mut Cheatcodes) -> Result {
140        let Self { json, typeDescription } = self;
141        parse_json_coerce(json, "$", &resolve_type(typeDescription)?).map(|v| v.abi_encode())
142    }
143}
144
145impl Cheatcode for parseJsonType_1Call {
146    fn apply(&self, _state: &mut Cheatcodes) -> Result {
147        let Self { json, key, typeDescription } = self;
148        parse_json_coerce(json, key, &resolve_type(typeDescription)?).map(|v| v.abi_encode())
149    }
150}
151
152impl Cheatcode for parseJsonTypeArrayCall {
153    fn apply(&self, _state: &mut Cheatcodes) -> Result {
154        let Self { json, key, typeDescription } = self;
155        let ty = resolve_type(typeDescription)?;
156        parse_json_coerce(json, key, &DynSolType::Array(Box::new(ty))).map(|v| v.abi_encode())
157    }
158}
159
160impl Cheatcode for parseJsonKeysCall {
161    fn apply(&self, _state: &mut Cheatcodes) -> Result {
162        let Self { json, key } = self;
163        parse_json_keys(json, key)
164    }
165}
166
167impl Cheatcode for serializeJsonCall {
168    fn apply(&self, state: &mut Cheatcodes) -> Result {
169        let Self { objectKey, value } = self;
170        *state.serialized_jsons.entry(objectKey.into()).or_default() = serde_json::from_str(value)?;
171        Ok(value.abi_encode())
172    }
173}
174
175impl Cheatcode for serializeBool_0Call {
176    fn apply(&self, state: &mut Cheatcodes) -> Result {
177        let Self { objectKey, valueKey, value } = self;
178        serialize_json(state, objectKey, valueKey, (*value).into())
179    }
180}
181
182impl Cheatcode for serializeUint_0Call {
183    fn apply(&self, state: &mut Cheatcodes) -> Result {
184        let Self { objectKey, valueKey, value } = self;
185        serialize_json(state, objectKey, valueKey, (*value).into())
186    }
187}
188
189impl Cheatcode for serializeInt_0Call {
190    fn apply(&self, state: &mut Cheatcodes) -> Result {
191        let Self { objectKey, valueKey, value } = self;
192        serialize_json(state, objectKey, valueKey, (*value).into())
193    }
194}
195
196impl Cheatcode for serializeAddress_0Call {
197    fn apply(&self, state: &mut Cheatcodes) -> Result {
198        let Self { objectKey, valueKey, value } = self;
199        serialize_json(state, objectKey, valueKey, (*value).into())
200    }
201}
202
203impl Cheatcode for serializeBytes32_0Call {
204    fn apply(&self, state: &mut Cheatcodes) -> Result {
205        let Self { objectKey, valueKey, value } = self;
206        serialize_json(state, objectKey, valueKey, DynSolValue::FixedBytes(*value, 32))
207    }
208}
209
210impl Cheatcode for serializeString_0Call {
211    fn apply(&self, state: &mut Cheatcodes) -> Result {
212        let Self { objectKey, valueKey, value } = self;
213        serialize_json(state, objectKey, valueKey, value.clone().into())
214    }
215}
216
217impl Cheatcode for serializeBytes_0Call {
218    fn apply(&self, state: &mut Cheatcodes) -> Result {
219        let Self { objectKey, valueKey, value } = self;
220        serialize_json(state, objectKey, valueKey, value.to_vec().into())
221    }
222}
223
224impl Cheatcode for serializeBool_1Call {
225    fn apply(&self, state: &mut Cheatcodes) -> Result {
226        let Self { objectKey, valueKey, values } = self;
227        serialize_json(
228            state,
229            objectKey,
230            valueKey,
231            DynSolValue::Array(values.iter().copied().map(DynSolValue::Bool).collect()),
232        )
233    }
234}
235
236impl Cheatcode for serializeUint_1Call {
237    fn apply(&self, state: &mut Cheatcodes) -> Result {
238        let Self { objectKey, valueKey, values } = self;
239        serialize_json(
240            state,
241            objectKey,
242            valueKey,
243            DynSolValue::Array(values.iter().map(|v| DynSolValue::Uint(*v, 256)).collect()),
244        )
245    }
246}
247
248impl Cheatcode for serializeInt_1Call {
249    fn apply(&self, state: &mut Cheatcodes) -> Result {
250        let Self { objectKey, valueKey, values } = self;
251        serialize_json(
252            state,
253            objectKey,
254            valueKey,
255            DynSolValue::Array(values.iter().map(|v| DynSolValue::Int(*v, 256)).collect()),
256        )
257    }
258}
259
260impl Cheatcode for serializeAddress_1Call {
261    fn apply(&self, state: &mut Cheatcodes) -> Result {
262        let Self { objectKey, valueKey, values } = self;
263        serialize_json(
264            state,
265            objectKey,
266            valueKey,
267            DynSolValue::Array(values.iter().copied().map(DynSolValue::Address).collect()),
268        )
269    }
270}
271
272impl Cheatcode for serializeBytes32_1Call {
273    fn apply(&self, state: &mut Cheatcodes) -> Result {
274        let Self { objectKey, valueKey, values } = self;
275        serialize_json(
276            state,
277            objectKey,
278            valueKey,
279            DynSolValue::Array(values.iter().map(|v| DynSolValue::FixedBytes(*v, 32)).collect()),
280        )
281    }
282}
283
284impl Cheatcode for serializeString_1Call {
285    fn apply(&self, state: &mut Cheatcodes) -> Result {
286        let Self { objectKey, valueKey, values } = self;
287        serialize_json(
288            state,
289            objectKey,
290            valueKey,
291            DynSolValue::Array(values.iter().cloned().map(DynSolValue::String).collect()),
292        )
293    }
294}
295
296impl Cheatcode for serializeBytes_1Call {
297    fn apply(&self, state: &mut Cheatcodes) -> Result {
298        let Self { objectKey, valueKey, values } = self;
299        serialize_json(
300            state,
301            objectKey,
302            valueKey,
303            DynSolValue::Array(
304                values.iter().cloned().map(Into::into).map(DynSolValue::Bytes).collect(),
305            ),
306        )
307    }
308}
309
310impl Cheatcode for serializeJsonType_0Call {
311    fn apply(&self, _state: &mut Cheatcodes) -> Result {
312        let Self { typeDescription, value } = self;
313        let ty = resolve_type(typeDescription)?;
314        let value = ty.abi_decode(value)?;
315        let value = serialize_value_as_json(value)?;
316        Ok(value.to_string().abi_encode())
317    }
318}
319
320impl Cheatcode for serializeJsonType_1Call {
321    fn apply(&self, state: &mut Cheatcodes) -> Result {
322        let Self { objectKey, valueKey, typeDescription, value } = self;
323        let ty = resolve_type(typeDescription)?;
324        let value = ty.abi_decode(value)?;
325        serialize_json(state, objectKey, valueKey, value)
326    }
327}
328
329impl Cheatcode for serializeUintToHexCall {
330    fn apply(&self, state: &mut Cheatcodes) -> Result {
331        let Self { objectKey, valueKey, value } = self;
332        let hex = format!("0x{value:x}");
333        serialize_json(state, objectKey, valueKey, hex.into())
334    }
335}
336
337impl Cheatcode for writeJson_0Call {
338    fn apply(&self, state: &mut Cheatcodes) -> Result {
339        let Self { json, path } = self;
340        let json = serde_json::from_str(json).unwrap_or_else(|_| Value::String(json.to_owned()));
341        let json_string = serde_json::to_string_pretty(&json)?;
342        super::fs::write_file(state, path.as_ref(), json_string.as_bytes())
343    }
344}
345
346impl Cheatcode for writeJson_1Call {
347    fn apply(&self, state: &mut Cheatcodes) -> Result {
348        let Self { json, path, valueKey } = self;
349        let json = serde_json::from_str(json).unwrap_or_else(|_| Value::String(json.to_owned()));
350
351        let data_path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
352        let data_s = fs::read_to_string(data_path)?;
353        let data = serde_json::from_str(&data_s)?;
354        let value =
355            jsonpath_lib::replace_with(data, &canonicalize_json_path(valueKey), &mut |_| {
356                Some(json.clone())
357            })?;
358
359        let json_string = serde_json::to_string_pretty(&value)?;
360        super::fs::write_file(state, path.as_ref(), json_string.as_bytes())
361    }
362}
363
364pub(super) fn check_json_key_exists(json: &str, key: &str) -> Result {
365    let json = parse_json_str(json)?;
366    let values = select(&json, key)?;
367    let exists = !values.is_empty();
368    Ok(exists.abi_encode())
369}
370
371pub(super) fn parse_json(json: &str, path: &str) -> Result {
372    let value = parse_json_str(json)?;
373    let selected = select(&value, path)?;
374    let sol = json_to_sol(&selected)?;
375    Ok(encode(sol))
376}
377
378pub(super) fn parse_json_coerce(json: &str, path: &str, ty: &DynSolType) -> Result {
379    let json = parse_json_str(json)?;
380    let [value] = select(&json, path)?[..] else {
381        bail!("path {path:?} must return exactly one JSON value");
382    };
383
384    parse_json_as(value, ty).map(|v| v.abi_encode())
385}
386
387/// Parses given [serde_json::Value] as a [DynSolValue].
388pub(super) fn parse_json_as(value: &Value, ty: &DynSolType) -> Result<DynSolValue> {
389    let to_string = |v: &Value| {
390        let mut s = v.to_string();
391        s.retain(|c: char| c != '"');
392        s
393    };
394
395    match (value, ty) {
396        (Value::Array(array), ty) => parse_json_array(array, ty),
397        (Value::Object(object), ty) => parse_json_map(object, ty),
398        (Value::String(s), DynSolType::String) => Ok(DynSolValue::String(s.clone())),
399        _ => string::parse_value(&to_string(value), ty),
400    }
401}
402
403pub(super) fn parse_json_array(array: &[Value], ty: &DynSolType) -> Result<DynSolValue> {
404    match ty {
405        DynSolType::Tuple(types) => {
406            ensure!(array.len() == types.len(), "array length mismatch");
407            let values = array
408                .iter()
409                .zip(types)
410                .map(|(e, ty)| parse_json_as(e, ty))
411                .collect::<Result<Vec<_>>>()?;
412
413            Ok(DynSolValue::Tuple(values))
414        }
415        DynSolType::Array(inner) => {
416            let values =
417                array.iter().map(|e| parse_json_as(e, inner)).collect::<Result<Vec<_>>>()?;
418            Ok(DynSolValue::Array(values))
419        }
420        DynSolType::FixedArray(inner, len) => {
421            ensure!(array.len() == *len, "array length mismatch");
422            let values =
423                array.iter().map(|e| parse_json_as(e, inner)).collect::<Result<Vec<_>>>()?;
424            Ok(DynSolValue::FixedArray(values))
425        }
426        _ => bail!("expected {ty}, found array"),
427    }
428}
429
430pub(super) fn parse_json_map(map: &Map<String, Value>, ty: &DynSolType) -> Result<DynSolValue> {
431    let Some((name, fields, types)) = ty.as_custom_struct() else {
432        bail!("expected {ty}, found JSON object");
433    };
434
435    let mut values = Vec::with_capacity(fields.len());
436    for (field, ty) in fields.iter().zip(types.iter()) {
437        let Some(value) = map.get(field) else { bail!("field {field:?} not found in JSON object") };
438        values.push(parse_json_as(value, ty)?);
439    }
440
441    Ok(DynSolValue::CustomStruct {
442        name: name.to_string(),
443        prop_names: fields.to_vec(),
444        tuple: values,
445    })
446}
447
448pub(super) fn parse_json_keys(json: &str, key: &str) -> Result {
449    let json = parse_json_str(json)?;
450    let values = select(&json, key)?;
451    let [value] = values[..] else {
452        bail!("key {key:?} must return exactly one JSON object");
453    };
454    let Value::Object(object) = value else {
455        bail!("JSON value at {key:?} is not an object");
456    };
457    let keys = object.keys().collect::<Vec<_>>();
458    Ok(keys.abi_encode())
459}
460
461fn parse_json_str(json: &str) -> Result<Value> {
462    serde_json::from_str(json).map_err(|e| fmt_err!("failed parsing JSON: {e}"))
463}
464
465fn json_to_sol(json: &[&Value]) -> Result<Vec<DynSolValue>> {
466    let mut sol = Vec::with_capacity(json.len());
467    for value in json {
468        sol.push(json_value_to_token(value)?);
469    }
470    Ok(sol)
471}
472
473fn select<'a>(value: &'a Value, mut path: &str) -> Result<Vec<&'a Value>> {
474    // Handle the special case of the root key
475    if path == "." {
476        path = "$";
477    }
478    // format error with debug string because json_path errors may contain newlines
479    jsonpath_lib::select(value, &canonicalize_json_path(path))
480        .map_err(|e| fmt_err!("failed selecting from JSON: {:?}", e.to_string()))
481}
482
483fn encode(values: Vec<DynSolValue>) -> Vec<u8> {
484    // Double `abi_encode` is intentional
485    let bytes = match &values[..] {
486        [] => Vec::new(),
487        [one] => one.abi_encode(),
488        _ => DynSolValue::Array(values).abi_encode(),
489    };
490    bytes.abi_encode()
491}
492
493/// Canonicalize a json path key to always start from the root of the document.
494/// Read more about json path syntax: <https://goessner.net/articles/JsonPath/>
495pub(super) fn canonicalize_json_path(path: &str) -> Cow<'_, str> {
496    if !path.starts_with('$') { format!("${path}").into() } else { path.into() }
497}
498
499/// Converts a JSON [`Value`] to a [`DynSolValue`] by trying to guess encoded type. For safer
500/// decoding, use [`parse_json_as`].
501///
502/// The function is designed to run recursively, so that in case of an object
503/// it will call itself to convert each of it's value and encode the whole as a
504/// Tuple
505#[instrument(target = "cheatcodes", level = "trace", ret)]
506pub(super) fn json_value_to_token(value: &Value) -> Result<DynSolValue> {
507    match value {
508        Value::Null => Ok(DynSolValue::FixedBytes(B256::ZERO, 32)),
509        Value::Bool(boolean) => Ok(DynSolValue::Bool(*boolean)),
510        Value::Array(array) => {
511            array.iter().map(json_value_to_token).collect::<Result<_>>().map(DynSolValue::Array)
512        }
513        value @ Value::Object(_) => {
514            // See: [#3647](https://github.com/foundry-rs/foundry/pull/3647)
515            let ordered_object: BTreeMap<String, Value> =
516                serde_json::from_value(value.clone()).unwrap();
517            ordered_object
518                .values()
519                .map(json_value_to_token)
520                .collect::<Result<_>>()
521                .map(DynSolValue::Tuple)
522        }
523        Value::Number(number) => {
524            if let Some(f) = number.as_f64() {
525                // Check if the number has decimal digits because the EVM does not support floating
526                // point math
527                if f.fract() == 0.0 {
528                    // Use the string representation of the `serde_json` Number type instead of
529                    // calling f.to_string(), because some numbers are wrongly rounded up after
530                    // being convented to f64.
531                    // Example: 18446744073709551615 becomes 18446744073709552000 after parsing it
532                    // to f64.
533                    let s = number.to_string();
534
535                    // Coerced to scientific notation, so short-circuit to using fallback.
536                    // This will not have a problem with hex numbers, as for parsing these
537                    // We'd need to prefix this with 0x.
538                    // See also <https://docs.soliditylang.org/en/latest/types.html#rational-and-integer-literals>
539                    if s.contains('e') {
540                        // Calling Number::to_string with powers of ten formats the number using
541                        // scientific notation and causes from_dec_str to fail. Using format! with
542                        // f64 keeps the full number representation.
543                        // Example: 100000000000000000000 becomes 1e20 when Number::to_string is
544                        // used.
545                        let fallback_s = f.to_string();
546                        if let Ok(n) = fallback_s.parse() {
547                            return Ok(DynSolValue::Uint(n, 256));
548                        }
549                        if let Ok(n) = I256::from_dec_str(&fallback_s) {
550                            return Ok(DynSolValue::Int(n, 256));
551                        }
552                    }
553
554                    if let Ok(n) = s.parse() {
555                        return Ok(DynSolValue::Uint(n, 256));
556                    }
557                    if let Ok(n) = s.parse() {
558                        return Ok(DynSolValue::Int(n, 256));
559                    }
560                }
561            }
562
563            Err(fmt_err!("unsupported JSON number: {number}"))
564        }
565        Value::String(string) => {
566            if let Some(mut val) = string.strip_prefix("0x") {
567                let s;
568                if val.len() == 39 {
569                    return Err(format!("Cannot parse \"{val}\" as an address. If you want to specify address, prepend zero to the value.").into());
570                }
571                if !val.len().is_multiple_of(2) {
572                    s = format!("0{val}");
573                    val = &s[..];
574                }
575                if let Ok(bytes) = hex::decode(val) {
576                    return Ok(match bytes.len() {
577                        20 => DynSolValue::Address(Address::from_slice(&bytes)),
578                        32 => DynSolValue::FixedBytes(B256::from_slice(&bytes), 32),
579                        _ => DynSolValue::Bytes(bytes),
580                    });
581                }
582            }
583            Ok(DynSolValue::String(string.to_owned()))
584        }
585    }
586}
587
588/// Serializes given [DynSolValue] into a [serde_json::Value].
589fn serialize_value_as_json(value: DynSolValue) -> Result<Value> {
590    match value {
591        DynSolValue::Bool(b) => Ok(Value::Bool(b)),
592        DynSolValue::String(s) => {
593            // Strings are allowed to contain stringified JSON objects, so we try to parse it like
594            // one first.
595            if let Ok(map) = serde_json::from_str(&s) {
596                Ok(Value::Object(map))
597            } else {
598                Ok(Value::String(s))
599            }
600        }
601        DynSolValue::Bytes(b) => Ok(Value::String(hex::encode_prefixed(b))),
602        DynSolValue::FixedBytes(b, size) => Ok(Value::String(hex::encode_prefixed(&b[..size]))),
603        DynSolValue::Int(i, _) => {
604            // let serde handle number parsing
605            let n = serde_json::from_str(&i.to_string())?;
606            Ok(Value::Number(n))
607        }
608        DynSolValue::Uint(i, _) => {
609            // let serde handle number parsing
610            let n = serde_json::from_str(&i.to_string())?;
611            Ok(Value::Number(n))
612        }
613        DynSolValue::Address(a) => Ok(Value::String(a.to_string())),
614        DynSolValue::Array(e) | DynSolValue::FixedArray(e) => {
615            Ok(Value::Array(e.into_iter().map(serialize_value_as_json).collect::<Result<_>>()?))
616        }
617        DynSolValue::CustomStruct { name: _, prop_names, tuple } => {
618            let values =
619                tuple.into_iter().map(serialize_value_as_json).collect::<Result<Vec<_>>>()?;
620            let map = prop_names.into_iter().zip(values).collect();
621
622            Ok(Value::Object(map))
623        }
624        DynSolValue::Tuple(values) => Ok(Value::Array(
625            values.into_iter().map(serialize_value_as_json).collect::<Result<_>>()?,
626        )),
627        DynSolValue::Function(_) => bail!("cannot serialize function pointer"),
628    }
629}
630
631/// Serializes a key:value pair to a specific object. If the key is valueKey, the value is
632/// expected to be an object, which will be set as the root object for the provided object key,
633/// overriding the whole root object if the object key already exists. By calling this function
634/// multiple times, the user can serialize multiple KV pairs to the same object. The value can be of
635/// any type, even a new object in itself. The function will return a stringified version of the
636/// object, so that the user can use that as a value to a new invocation of the same function with a
637/// new object key. This enables the user to reuse the same function to crate arbitrarily complex
638/// object structures (JSON).
639fn serialize_json(
640    state: &mut Cheatcodes,
641    object_key: &str,
642    value_key: &str,
643    value: DynSolValue,
644) -> Result {
645    let value = serialize_value_as_json(value)?;
646    let map = state.serialized_jsons.entry(object_key.into()).or_default();
647    map.insert(value_key.into(), value);
648    let stringified = serde_json::to_string(map).unwrap();
649    Ok(stringified.abi_encode())
650}
651
652/// Resolves a [DynSolType] from user input.
653pub(super) fn resolve_type(type_description: &str) -> Result<DynSolType> {
654    if let Ok(ty) = DynSolType::parse(type_description) {
655        return Ok(ty);
656    };
657
658    if let Ok(encoded) = EncodeType::parse(type_description) {
659        let main_type = encoded.types[0].type_name;
660        let mut resolver = Resolver::default();
661        for t in encoded.types {
662            resolver.ingest(t.to_owned());
663        }
664
665        return Ok(resolver.resolve(main_type)?);
666    };
667
668    bail!("type description should be a valid Solidity type or a EIP712 `encodeType` string")
669}
670
671#[cfg(test)]
672mod tests {
673    use super::*;
674    use alloy_primitives::FixedBytes;
675    use proptest::strategy::Strategy;
676
677    fn contains_tuple(value: &DynSolValue) -> bool {
678        match value {
679            DynSolValue::Tuple(_) | DynSolValue::CustomStruct { .. } => true,
680            DynSolValue::Array(v) | DynSolValue::FixedArray(v) => {
681                v.first().is_some_and(contains_tuple)
682            }
683            _ => false,
684        }
685    }
686
687    /// [DynSolValue::Bytes] of length 32 and 20 are converted to [DynSolValue::FixedBytes] and
688    /// [DynSolValue::Address] respectively. Thus, we can't distinguish between address and bytes of
689    /// length 20 during decoding. Because of that, there are issues with handling of arrays of
690    /// those types.
691    fn fixup_guessable(value: DynSolValue) -> DynSolValue {
692        match value {
693            DynSolValue::Array(mut v) | DynSolValue::FixedArray(mut v) => {
694                if let Some(DynSolValue::Bytes(_)) = v.first() {
695                    v.retain(|v| {
696                        let len = v.as_bytes().unwrap().len();
697                        len != 32 && len != 20
698                    })
699                }
700                DynSolValue::Array(v.into_iter().map(fixup_guessable).collect())
701            }
702            DynSolValue::FixedBytes(v, _) => DynSolValue::FixedBytes(v, 32),
703            DynSolValue::Bytes(v) if v.len() == 32 => {
704                DynSolValue::FixedBytes(FixedBytes::from_slice(&v), 32)
705            }
706            DynSolValue::Bytes(v) if v.len() == 20 => DynSolValue::Address(Address::from_slice(&v)),
707            _ => value,
708        }
709    }
710
711    fn guessable_types() -> impl proptest::strategy::Strategy<Value = DynSolValue> {
712        proptest::arbitrary::any::<DynSolValue>()
713            .prop_map(fixup_guessable)
714            .prop_filter("tuples are not supported", |v| !contains_tuple(v))
715            .prop_filter("filter out values without type", |v| v.as_type().is_some())
716    }
717
718    // Tests to ensure that conversion [DynSolValue] -> [serde_json::Value] -> [DynSolValue]
719    proptest::proptest! {
720        #[test]
721        fn test_json_roundtrip_guessed(v in guessable_types()) {
722            let json = serialize_value_as_json(v.clone()).unwrap();
723            let value = json_value_to_token(&json).unwrap();
724
725            // do additional abi_encode -> abi_decode to avoid zero signed integers getting decoded as unsigned and causing assert_eq to fail.
726            let decoded = v.as_type().unwrap().abi_decode(&value.abi_encode()).unwrap();
727            assert_eq!(decoded, v);
728        }
729
730        #[test]
731        fn test_json_roundtrip(v in proptest::arbitrary::any::<DynSolValue>().prop_filter("filter out values without type", |v| v.as_type().is_some())) {
732                let json = serialize_value_as_json(v.clone()).unwrap();
733            let value = parse_json_as(&json, &v.as_type().unwrap()).unwrap();
734                assert_eq!(value, v);
735        }
736    }
737}