Skip to main content

foundry_cheatcodes/
json.rs

1//! Implementations of [`Json`](spec::Group::Json) cheatcodes.
2
3use crate::{Cheatcode, CheatcodesCore, Result, Vm::*, string};
4use alloy_dyn_abi::{DynSolType, DynSolValue, Resolver, eip712_parser::EncodeType};
5use alloy_primitives::{Address, B256, I256, U256, hex};
6use alloy_sol_types::SolValue;
7use foundry_common::{fmt::StructDefinitions, fs};
8use foundry_config::fs_permissions::FsAccessKind;
9use serde_json::{Map, Value};
10use std::{
11    borrow::Cow,
12    collections::{BTreeMap, BTreeSet},
13};
14
15impl Cheatcode for keyExistsCall {
16    fn apply_context_free(&self) -> Result {
17        let Self { json, key } = self;
18        check_json_key_exists(json, key)
19    }
20}
21
22impl Cheatcode for keyExistsJsonCall {
23    fn apply_context_free(&self) -> Result {
24        let Self { json, key } = self;
25        check_json_key_exists(json, key)
26    }
27}
28
29impl Cheatcode for parseJson_0Call {
30    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
31        let Self { json } = self;
32        parse_json(json, "$", state.struct_defs())
33    }
34}
35
36impl Cheatcode for parseJson_1Call {
37    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
38        let Self { json, key } = self;
39        parse_json(json, key, state.struct_defs())
40    }
41}
42
43macro_rules! impl_parse_json {
44    ($call:ident, $call_with_default:ident, $ty:expr) => {
45        impl Cheatcode for $call {
46            fn apply_context_free(&self) -> Result {
47                let Self { json, key } = self;
48                parse_json_coerce(json, key, &$ty)
49            }
50        }
51
52        impl Cheatcode for $call_with_default {
53            fn apply_context_free(&self) -> Result {
54                let Self { json, key, defaultValue } = self;
55                parse_json_coerce_default(json, key, &$ty, defaultValue)
56            }
57        }
58    };
59}
60
61impl_parse_json!(parseJsonUint_0Call, parseJsonUint_1Call, DynSolType::Uint(256));
62impl_parse_json!(
63    parseJsonUintArray_0Call,
64    parseJsonUintArray_1Call,
65    DynSolType::Array(Box::new(DynSolType::Uint(256)))
66);
67impl_parse_json!(parseJsonInt_0Call, parseJsonInt_1Call, DynSolType::Int(256));
68impl_parse_json!(
69    parseJsonIntArray_0Call,
70    parseJsonIntArray_1Call,
71    DynSolType::Array(Box::new(DynSolType::Int(256)))
72);
73impl_parse_json!(parseJsonBool_0Call, parseJsonBool_1Call, DynSolType::Bool);
74impl_parse_json!(
75    parseJsonBoolArray_0Call,
76    parseJsonBoolArray_1Call,
77    DynSolType::Array(Box::new(DynSolType::Bool))
78);
79impl_parse_json!(parseJsonAddress_0Call, parseJsonAddress_1Call, DynSolType::Address);
80impl_parse_json!(
81    parseJsonAddressArray_0Call,
82    parseJsonAddressArray_1Call,
83    DynSolType::Array(Box::new(DynSolType::Address))
84);
85impl_parse_json!(parseJsonString_0Call, parseJsonString_1Call, DynSolType::String);
86impl_parse_json!(
87    parseJsonStringArray_0Call,
88    parseJsonStringArray_1Call,
89    DynSolType::Array(Box::new(DynSolType::String))
90);
91
92impl Cheatcode for parseJsonArrayLengthCall {
93    fn apply_context_free(&self) -> Result {
94        let Self { json, key } = self;
95        parse_json_array_length(json, key)
96    }
97}
98
99impl_parse_json!(parseJsonBytes_0Call, parseJsonBytes_1Call, DynSolType::Bytes);
100impl_parse_json!(
101    parseJsonBytesArray_0Call,
102    parseJsonBytesArray_1Call,
103    DynSolType::Array(Box::new(DynSolType::Bytes))
104);
105impl_parse_json!(parseJsonBytes32_0Call, parseJsonBytes32_1Call, DynSolType::FixedBytes(32));
106impl_parse_json!(
107    parseJsonBytes32Array_0Call,
108    parseJsonBytes32Array_1Call,
109    DynSolType::Array(Box::new(DynSolType::FixedBytes(32)))
110);
111
112impl Cheatcode for parseJsonType_0Call {
113    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
114        let Self { json, typeDescription } = self;
115        parse_json_coerce(json, "$", &resolve_type(typeDescription, state.struct_defs())?)
116            .map(|v| v.abi_encode())
117    }
118}
119
120impl Cheatcode for parseJsonType_1Call {
121    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
122        let Self { json, key, typeDescription } = self;
123        parse_json_coerce(json, key, &resolve_type(typeDescription, state.struct_defs())?)
124            .map(|v| v.abi_encode())
125    }
126}
127
128impl Cheatcode for parseJsonTypeArrayCall {
129    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
130        let Self { json, key, typeDescription } = self;
131        let ty = resolve_type(typeDescription, state.struct_defs())?;
132        parse_json_coerce(json, key, &DynSolType::Array(Box::new(ty))).map(|v| v.abi_encode())
133    }
134}
135
136impl Cheatcode for parseJsonKeysCall {
137    fn apply_context_free(&self) -> Result {
138        let Self { json, key } = self;
139        parse_json_keys(json, key)
140    }
141}
142
143impl Cheatcode for serializeJsonCall {
144    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
145        let Self { objectKey, value } = self;
146        *state.serialized_jsons.entry(objectKey.into()).or_default() = serde_json::from_str(value)?;
147        Ok(value.abi_encode())
148    }
149}
150
151impl Cheatcode for serializeBool_0Call {
152    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
153        let Self { objectKey, valueKey, value } = self;
154        serialize_json(state, objectKey, valueKey, (*value).into())
155    }
156}
157
158impl Cheatcode for serializeUint_0Call {
159    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
160        let Self { objectKey, valueKey, value } = self;
161        serialize_json(state, objectKey, valueKey, (*value).into())
162    }
163}
164
165impl Cheatcode for serializeInt_0Call {
166    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
167        let Self { objectKey, valueKey, value } = self;
168        serialize_json(state, objectKey, valueKey, (*value).into())
169    }
170}
171
172impl Cheatcode for serializeAddress_0Call {
173    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
174        let Self { objectKey, valueKey, value } = self;
175        serialize_json(state, objectKey, valueKey, (*value).into())
176    }
177}
178
179impl Cheatcode for serializeBytes32_0Call {
180    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
181        let Self { objectKey, valueKey, value } = self;
182        serialize_json(state, objectKey, valueKey, DynSolValue::FixedBytes(*value, 32))
183    }
184}
185
186impl Cheatcode for serializeString_0Call {
187    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
188        let Self { objectKey, valueKey, value } = self;
189        serialize_json(state, objectKey, valueKey, value.clone().into())
190    }
191}
192
193impl Cheatcode for serializeBytes_0Call {
194    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
195        let Self { objectKey, valueKey, value } = self;
196        serialize_json(state, objectKey, valueKey, value.to_vec().into())
197    }
198}
199
200impl Cheatcode for serializeBool_1Call {
201    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
202        let Self { objectKey, valueKey, values } = self;
203        serialize_json(
204            state,
205            objectKey,
206            valueKey,
207            DynSolValue::Array(values.iter().copied().map(DynSolValue::Bool).collect()),
208        )
209    }
210}
211
212impl Cheatcode for serializeUint_1Call {
213    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
214        let Self { objectKey, valueKey, values } = self;
215        serialize_json(
216            state,
217            objectKey,
218            valueKey,
219            DynSolValue::Array(values.iter().map(|v| DynSolValue::Uint(*v, 256)).collect()),
220        )
221    }
222}
223
224impl Cheatcode for serializeInt_1Call {
225    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
226        let Self { objectKey, valueKey, values } = self;
227        serialize_json(
228            state,
229            objectKey,
230            valueKey,
231            DynSolValue::Array(values.iter().map(|v| DynSolValue::Int(*v, 256)).collect()),
232        )
233    }
234}
235
236impl Cheatcode for serializeAddress_1Call {
237    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
238        let Self { objectKey, valueKey, values } = self;
239        serialize_json(
240            state,
241            objectKey,
242            valueKey,
243            DynSolValue::Array(values.iter().copied().map(DynSolValue::Address).collect()),
244        )
245    }
246}
247
248impl Cheatcode for serializeBytes32_1Call {
249    fn apply_context(&self, state: &mut CheatcodesCore) -> 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::FixedBytes(*v, 32)).collect()),
256        )
257    }
258}
259
260impl Cheatcode for serializeString_1Call {
261    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
262        let Self { objectKey, valueKey, values } = self;
263        serialize_json(
264            state,
265            objectKey,
266            valueKey,
267            DynSolValue::Array(values.iter().cloned().map(DynSolValue::String).collect()),
268        )
269    }
270}
271
272impl Cheatcode for serializeBytes_1Call {
273    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
274        let Self { objectKey, valueKey, values } = self;
275        serialize_json(
276            state,
277            objectKey,
278            valueKey,
279            DynSolValue::Array(
280                values.iter().cloned().map(Into::into).map(DynSolValue::Bytes).collect(),
281            ),
282        )
283    }
284}
285
286impl Cheatcode for serializeJsonType_0Call {
287    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
288        let Self { typeDescription, value } = self;
289        let ty = resolve_type(typeDescription, state.struct_defs())?;
290        let value = ty.abi_decode(value)?;
291        let value =
292            foundry_common::fmt::serialize_value_as_json(value, state.struct_defs(), false)?;
293        Ok(value.to_string().abi_encode())
294    }
295}
296
297impl Cheatcode for serializeJsonType_1Call {
298    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
299        let Self { objectKey, valueKey, typeDescription, value } = self;
300        let ty = resolve_type(typeDescription, state.struct_defs())?;
301        let value = ty.abi_decode(value)?;
302        serialize_json(state, objectKey, valueKey, value)
303    }
304}
305
306impl Cheatcode for serializeUintToHexCall {
307    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
308        let Self { objectKey, valueKey, value } = self;
309        let hex = format!("0x{value:x}");
310        serialize_json(state, objectKey, valueKey, hex.into())
311    }
312}
313
314impl Cheatcode for writeJson_0Call {
315    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
316        let Self { json, path } = self;
317        let json = serde_json::from_str(json).unwrap_or_else(|_| Value::String(json.to_owned()));
318        let json_string = serde_json::to_string_pretty(&json)?;
319        super::fs::write_file(state, path.as_ref(), json_string.as_bytes())
320    }
321}
322
323impl Cheatcode for writeJson_1Call {
324    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
325        let Self { json: value, path, valueKey } = self;
326
327        // Read, parse, and update the JSON object.
328        // If the file doesn't exist, start with an empty JSON object so the file is created.
329        let data_path = state.config.ensure_path_allowed(path, FsAccessKind::Read)?;
330        let mut data = if data_path.exists() {
331            let data_string = fs::locked_read_to_string(&data_path)?;
332            serde_json::from_str(&data_string).unwrap_or_else(|_| Value::String(data_string))
333        } else {
334            Value::Object(Default::default())
335        };
336        upsert_json_value(&mut data, value, valueKey)?;
337
338        // Write the updated content back to the file
339        let json_string = serde_json::to_string_pretty(&data)?;
340        super::fs::write_file(state, path.as_ref(), json_string.as_bytes())
341    }
342}
343
344pub(super) fn check_json_key_exists(json: &str, key: &str) -> Result {
345    let json = parse_json_str(json)?;
346    let values = select(&json, key)?;
347    let exists = !values.is_empty();
348    Ok(exists.abi_encode())
349}
350
351pub(super) fn parse_json(json: &str, path: &str, defs: Option<&StructDefinitions>) -> Result {
352    let value = parse_json_str(json)?;
353    let selected = select(&value, path)?;
354    let sol = json_to_sol(defs, &selected)?;
355    Ok(encode(sol))
356}
357
358pub(super) fn parse_json_coerce(json: &str, path: &str, ty: &DynSolType) -> Result {
359    let json = parse_json_str(json)?;
360    let [value] = select(&json, path)?[..] else {
361        bail!("path {path:?} must return exactly one JSON value");
362    };
363
364    parse_json_as(value, ty).map(|v| v.abi_encode())
365}
366
367pub(super) fn parse_json_coerce_default<T: SolValue>(
368    json: &str,
369    path: &str,
370    ty: &DynSolType,
371    default: &T,
372) -> Result {
373    let json = parse_json_str(json)?;
374    match select(&json, path)?.as_slice() {
375        [] => Ok(default.abi_encode()),
376        [value] => parse_json_as(value, ty).map(|value| value.abi_encode()),
377        _ => bail!("path {path:?} must return exactly one JSON value"),
378    }
379}
380
381/// Parses given [serde_json::Value] as a [DynSolValue].
382pub(super) fn parse_json_as(value: &Value, ty: &DynSolType) -> Result<DynSolValue> {
383    let to_string = |v: &Value| {
384        let mut s = v.to_string();
385        s.retain(|c: char| c != '"');
386        s
387    };
388
389    match (value, ty) {
390        (Value::Array(array), ty) => parse_json_array(array, ty),
391        (Value::Object(object), ty) => parse_json_map(object, ty),
392        (Value::String(s), DynSolType::String) => Ok(DynSolValue::String(s.clone())),
393        (Value::String(s), DynSolType::Uint(_) | DynSolType::Int(_)) => string::parse_value(s, ty),
394        _ => string::parse_value(&to_string(value), ty),
395    }
396}
397
398pub(super) fn parse_json_array(array: &[Value], ty: &DynSolType) -> Result<DynSolValue> {
399    match ty {
400        DynSolType::Tuple(types) => {
401            ensure!(array.len() == types.len(), "array length mismatch");
402            let values = array
403                .iter()
404                .zip(types)
405                .map(|(e, ty)| parse_json_as(e, ty))
406                .collect::<Result<Vec<_>>>()?;
407
408            Ok(DynSolValue::Tuple(values))
409        }
410        DynSolType::Array(inner) => {
411            let values =
412                array.iter().map(|e| parse_json_as(e, inner)).collect::<Result<Vec<_>>>()?;
413            Ok(DynSolValue::Array(values))
414        }
415        DynSolType::FixedArray(inner, len) => {
416            ensure!(array.len() == *len, "array length mismatch");
417            let values =
418                array.iter().map(|e| parse_json_as(e, inner)).collect::<Result<Vec<_>>>()?;
419            Ok(DynSolValue::FixedArray(values))
420        }
421        _ => bail!("expected {ty}, found array"),
422    }
423}
424
425pub(super) fn parse_json_map(map: &Map<String, Value>, ty: &DynSolType) -> Result<DynSolValue> {
426    let Some((name, fields, types)) = ty.as_custom_struct() else {
427        bail!("expected {ty}, found JSON object");
428    };
429
430    let mut values = Vec::with_capacity(fields.len());
431    for (field, ty) in fields.iter().zip(types.iter()) {
432        let Some(value) = map.get(field) else { bail!("field {field:?} not found in JSON object") };
433        values.push(parse_json_as(value, ty)?);
434    }
435
436    Ok(DynSolValue::CustomStruct {
437        name: name.to_string(),
438        prop_names: fields.to_vec(),
439        tuple: values,
440    })
441}
442
443pub(super) fn parse_json_keys(json: &str, key: &str) -> Result {
444    let json = parse_json_str(json)?;
445    let values = select(&json, key)?;
446    let [value] = values[..] else {
447        bail!("key {key:?} must return exactly one JSON object");
448    };
449    let Value::Object(object) = value else {
450        bail!("JSON value at {key:?} is not an object");
451    };
452    let keys = object.keys().collect::<Vec<_>>();
453    Ok(keys.abi_encode())
454}
455
456pub(super) fn parse_json_array_length(json: &str, key: &str) -> Result {
457    let json = parse_json_str(json)?;
458    let values = select(&json, key)?;
459    let [value] = values[..] else {
460        bail!("key {key:?} must return exactly one JSON array");
461    };
462    let Value::Array(array) = value else {
463        bail!("JSON value at {key:?} is not an array");
464    };
465    Ok(U256::from(array.len()).abi_encode())
466}
467
468fn parse_json_str(json: &str) -> Result<Value> {
469    let json = strip_json_comments(json)?;
470    serde_json::from_str(&json).map_err(|e| fmt_err!("failed parsing JSON: {e}"))
471}
472
473fn strip_json_comments(json: &str) -> Result<Cow<'_, str>> {
474    let bytes = json.as_bytes();
475    let mut stripped = None;
476    let mut index = 0;
477    let mut in_string = false;
478
479    while index < bytes.len() {
480        if in_string {
481            match bytes[index] {
482                b'\\' => index += 2,
483                b'"' => {
484                    in_string = false;
485                    index += 1;
486                }
487                _ => index += 1,
488            }
489            continue;
490        }
491
492        match (bytes[index], bytes.get(index + 1)) {
493            (b'"', _) => {
494                in_string = true;
495                index += 1;
496            }
497            (b'/', Some(b'/')) => {
498                let stripped = stripped.get_or_insert_with(|| bytes.to_vec());
499                while index < bytes.len() && !matches!(bytes[index], b'\r' | b'\n') {
500                    stripped[index] = b' ';
501                    index += 1;
502                }
503            }
504            (b'/', Some(b'*')) => {
505                let stripped = stripped.get_or_insert_with(|| bytes.to_vec());
506                stripped[index] = b' ';
507                stripped[index + 1] = b' ';
508                index += 2;
509
510                let mut closed = false;
511                while index < bytes.len() {
512                    if bytes[index] == b'*' && bytes.get(index + 1) == Some(&b'/') {
513                        stripped[index] = b' ';
514                        stripped[index + 1] = b' ';
515                        index += 2;
516                        closed = true;
517                        break;
518                    }
519                    if !matches!(bytes[index], b'\r' | b'\n') {
520                        stripped[index] = b' ';
521                    }
522                    index += 1;
523                }
524                ensure!(closed, "failed parsing JSON: unterminated block comment");
525            }
526            _ => index += 1,
527        }
528    }
529
530    Ok(match stripped {
531        Some(stripped) => {
532            String::from_utf8(stripped).expect("comment stripping preserves valid UTF-8").into()
533        }
534        None => json.into(),
535    })
536}
537
538fn json_to_sol(defs: Option<&StructDefinitions>, json: &[&Value]) -> Result<Vec<DynSolValue>> {
539    let mut sol = Vec::with_capacity(json.len());
540    for value in json {
541        sol.push(json_value_to_token(value, defs)?);
542    }
543    Ok(sol)
544}
545
546fn select<'a>(value: &'a Value, mut path: &str) -> Result<Vec<&'a Value>> {
547    // Handle the special case of the root key
548    if path == "." {
549        path = "$";
550    }
551    // format error with debug string because json_path errors may contain newlines
552    jsonpath_lib::select(value, &canonicalize_json_path(path))
553        .map_err(|e| fmt_err!("failed selecting from JSON: {:?}", e.to_string()))
554}
555
556fn encode(values: Vec<DynSolValue>) -> Vec<u8> {
557    // Double `abi_encode` is intentional
558    let bytes = match &values[..] {
559        [] => Vec::new(),
560        [one] => one.abi_encode(),
561        _ => DynSolValue::Array(values).abi_encode(),
562    };
563    bytes.abi_encode()
564}
565
566/// Canonicalize a json path key to always start from the root of the document.
567/// Read more about json path syntax: <https://goessner.net/articles/JsonPath/>
568pub(super) fn canonicalize_json_path(path: &str) -> Cow<'_, str> {
569    if path.starts_with('$') { path.into() } else { format!("${path}").into() }
570}
571
572/// Converts a JSON [`Value`] to a [`DynSolValue`] by trying to guess encoded type. For safer
573/// decoding, use [`parse_json_as`].
574///
575/// The function is designed to run recursively, so that in case of an object
576/// it will call itself to convert each of it's value and encode the whole as a
577/// Tuple
578#[instrument(target = "cheatcodes", level = "trace", ret)]
579pub(super) fn json_value_to_token(
580    value: &Value,
581    defs: Option<&StructDefinitions>,
582) -> Result<DynSolValue> {
583    if let Some(defs) = defs {
584        _json_value_to_token(value, defs)
585    } else {
586        _json_value_to_token(value, &StructDefinitions::default())
587    }
588}
589
590fn _json_value_to_token(value: &Value, defs: &StructDefinitions) -> Result<DynSolValue> {
591    match value {
592        Value::Null => Ok(DynSolValue::FixedBytes(B256::ZERO, 32)),
593        Value::Bool(boolean) => Ok(DynSolValue::Bool(*boolean)),
594        Value::Array(array) => array
595            .iter()
596            .map(|v| _json_value_to_token(v, defs))
597            .collect::<Result<_>>()
598            .map(DynSolValue::Array),
599        Value::Object(map) => {
600            // Try to find a struct definition that matches the object keys.
601            let keys: BTreeSet<_> = map.keys().map(|s| s.as_str()).collect();
602            let matching_defs = defs
603                .values()
604                .filter(|fields| {
605                    fields.len() == keys.len()
606                        && fields.iter().map(|(name, _)| name.as_str()).collect::<BTreeSet<_>>()
607                            == keys
608                })
609                .collect::<Vec<_>>();
610
611            if let Some(fields) = matching_defs.first() {
612                // Found a struct with matching field names, use the order from the definition.
613                fields
614                    .iter()
615                    .map(|(name, type_description)| {
616                        // unwrap is safe because we know the key exists.
617                        let value = map.get(name).unwrap();
618                        let unambiguous = matching_defs.iter().all(|fields| {
619                            fields
620                                .iter()
621                                .find(|(field, _)| field == name)
622                                .is_some_and(|(_, ty)| ty == type_description)
623                        });
624                        if unambiguous
625                            && let Some(parsed) = parse_fixed_array(value, type_description, defs)
626                        {
627                            parsed
628                        } else {
629                            _json_value_to_token(value, defs)
630                        }
631                    })
632                    .collect::<Result<_>>()
633                    .map(DynSolValue::Tuple)
634            } else {
635                // Fallback to alphabetical sorting if no matching struct is found.
636                // See: [#3647](https://github.com/foundry-rs/foundry/pull/3647)
637                let ordered_object: BTreeMap<_, _> =
638                    map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
639                ordered_object
640                    .values()
641                    .map(|value| _json_value_to_token(value, defs))
642                    .collect::<Result<_>>()
643                    .map(DynSolValue::Tuple)
644            }
645        }
646        Value::Number(number) => {
647            if let Some(f) = number.as_f64() {
648                // Check if the number has decimal digits because the EVM does not support floating
649                // point math
650                if f.fract() == 0.0 {
651                    // Use the string representation of the `serde_json` Number type instead of
652                    // calling f.to_string(), because some numbers are wrongly rounded up after
653                    // being convented to f64.
654                    // Example: 18446744073709551615 becomes 18446744073709552000 after parsing it
655                    // to f64.
656                    let s = number.to_string();
657
658                    // Coerced to scientific notation, so short-circuit to using fallback.
659                    // This will not have a problem with hex numbers, as for parsing these
660                    // We'd need to prefix this with 0x.
661                    // See also <https://docs.soliditylang.org/en/latest/types.html#rational-and-integer-literals>
662                    if s.contains('e') {
663                        // Calling Number::to_string with powers of ten formats the number using
664                        // scientific notation and causes from_dec_str to fail. Using format! with
665                        // f64 keeps the full number representation.
666                        // Example: 100000000000000000000 becomes 1e20 when Number::to_string is
667                        // used.
668                        let fallback_s = f.to_string();
669                        if let Ok(n) = fallback_s.parse() {
670                            return Ok(DynSolValue::Uint(n, 256));
671                        }
672                        if let Ok(n) = I256::from_dec_str(&fallback_s) {
673                            return Ok(DynSolValue::Int(n, 256));
674                        }
675                    }
676
677                    if let Ok(n) = s.parse() {
678                        return Ok(DynSolValue::Uint(n, 256));
679                    }
680                    if let Ok(n) = s.parse() {
681                        return Ok(DynSolValue::Int(n, 256));
682                    }
683                }
684            }
685
686            Err(fmt_err!("unsupported JSON number: {number}"))
687        }
688        Value::String(string) => {
689            //  Hanfl hex strings
690            if let Some(mut val) = string.strip_prefix("0x") {
691                let s;
692                if val.len() == 39 {
693                    return Err(format!("Cannot parse \"{val}\" as an address. If you want to specify address, prepend zero to the value.").into());
694                }
695                if !val.len().is_multiple_of(2) {
696                    s = format!("0{val}");
697                    val = &s[..];
698                }
699                if let Ok(bytes) = hex::decode(val) {
700                    return Ok(match bytes.len() {
701                        20 => DynSolValue::Address(Address::from_slice(&bytes)),
702                        32 => DynSolValue::FixedBytes(B256::from_slice(&bytes), 32),
703                        _ => DynSolValue::Bytes(bytes),
704                    });
705                }
706            }
707
708            // Handle large numbers that were potentially encoded as strings because they exceed the
709            // capacity of a 64-bit integer.
710            // Note that number-like strings that *could* fit in an `i64`/`u64` will fall through
711            // and be treated as literal strings.
712            if let Ok(n) = string.parse::<I256>()
713                && i64::try_from(n).is_err()
714            {
715                return Ok(DynSolValue::Int(n, 256));
716            } else if let Ok(n) = string.parse::<U256>()
717                && u64::try_from(n).is_err()
718            {
719                return Ok(DynSolValue::Uint(n, 256));
720            }
721
722            // Otherwise, treat as a regular string
723            Ok(DynSolValue::String(string.to_owned()))
724        }
725    }
726}
727
728fn parse_fixed_array(
729    value: &Value,
730    type_description: &str,
731    defs: &StructDefinitions,
732) -> Option<Result<DynSolValue>> {
733    let root_end = type_description.find('[')?;
734    let root = &type_description[..root_end];
735    let (ty, custom) = match defs.get(root) {
736        Ok(Some(_)) => {
737            (DynSolType::parse(&format!("bool{}", &type_description[root_end..])).ok()?, true)
738        }
739        Ok(None) if root.contains('.') => return None,
740        Ok(None) => (DynSolType::parse(type_description).ok()?, false),
741        Err(_) => return None,
742    };
743    if !contains_fixed_array(&ty) {
744        return None;
745    }
746
747    Some(if custom { parse_json_custom_array(value, &ty, defs) } else { parse_json_as(value, &ty) })
748}
749
750fn parse_json_custom_array(
751    value: &Value,
752    ty: &DynSolType,
753    defs: &StructDefinitions,
754) -> Result<DynSolValue> {
755    match (value, ty) {
756        (Value::Array(values), DynSolType::Array(inner)) => values
757            .iter()
758            .map(|value| parse_json_custom_array(value, inner, defs))
759            .collect::<Result<_>>()
760            .map(DynSolValue::Array),
761        (Value::Array(values), DynSolType::FixedArray(inner, len)) => {
762            ensure!(values.len() == *len, "array length mismatch");
763            values
764                .iter()
765                .map(|value| parse_json_custom_array(value, inner, defs))
766                .collect::<Result<_>>()
767                .map(DynSolValue::FixedArray)
768        }
769        (_, DynSolType::Bool) => _json_value_to_token(value, defs),
770        _ => bail!("expected array"),
771    }
772}
773
774fn contains_fixed_array(ty: &DynSolType) -> bool {
775    match ty {
776        DynSolType::FixedArray(_, _) => true,
777        DynSolType::Array(inner) => contains_fixed_array(inner),
778        _ => false,
779    }
780}
781
782/// Serializes a key:value pair to a specific object. If the key is valueKey, the value is
783/// expected to be an object, which will be set as the root object for the provided object key,
784/// overriding the whole root object if the object key already exists. By calling this function
785/// multiple times, the user can serialize multiple KV pairs to the same object. The value can be of
786/// any type, even a new object in itself. The function will return a stringified version of the
787/// object, so that the user can use that as a value to a new invocation of the same function with a
788/// new object key. This enables the user to reuse the same function to crate arbitrarily complex
789/// object structures (JSON).
790fn serialize_json(
791    state: &mut CheatcodesCore,
792    object_key: &str,
793    value_key: &str,
794    value: DynSolValue,
795) -> Result {
796    let value = foundry_common::fmt::serialize_value_as_json(value, state.struct_defs(), false)?;
797    let map = state.serialized_jsons.entry(object_key.into()).or_default();
798    map.insert(value_key.into(), value);
799    let stringified = serde_json::to_string(map).unwrap();
800    Ok(stringified.abi_encode())
801}
802
803/// Resolves a [DynSolType] from user input.
804pub(super) fn resolve_type(
805    type_description: &str,
806    struct_defs: Option<&StructDefinitions>,
807) -> Result<DynSolType> {
808    let ordered_ty = |ty| -> Result<DynSolType> {
809        if let Some(defs) = struct_defs { reorder_type(ty, defs) } else { Ok(ty) }
810    };
811
812    if let Ok(ty) = DynSolType::parse(type_description) {
813        return ordered_ty(ty);
814    };
815
816    if let Ok(encoded) = EncodeType::parse(type_description)
817        && let Some(main) = encoded.types.first()
818    {
819        let main_type = main.type_name;
820        let mut resolver = Resolver::default();
821        for t in &encoded.types {
822            resolver.ingest(t.to_owned());
823        }
824
825        // Get the alphabetically-sorted type from the resolver, and reorder if necessary.
826        return ordered_ty(resolver.resolve(main_type)?);
827    }
828
829    bail!("type description should be a valid Solidity type or a EIP712 `encodeType` string")
830}
831
832/// Upserts a value into a JSON object based on an object-key path.
833///
834/// This function navigates through a mutable `serde_json::Value` object using a
835/// path-like key. It creates nested JSON objects if they do not exist along the path.
836/// The value is inserted at the final key in the path.
837///
838/// # Arguments
839///
840/// * `data` - A mutable reference to the `serde_json::Value` to be modified.
841/// * `value` - The string representation of the value to upsert. This string is first parsed as
842///   JSON, and if that fails, it's treated as a plain JSON string.
843/// * `key` - A path of dot-separated or bracket-quoted object keys.
844pub(super) fn upsert_json_value(data: &mut Value, value: &str, key: &str) -> Result<()> {
845    let parts = split_json_value_key(key)?;
846
847    // Separate the final key from the path.
848    // Traverse the objects, creating intermediary ones if necessary.
849    if let Some((key_to_insert, path_to_parent)) = parts.split_last() {
850        let mut current_level = data;
851
852        for segment in path_to_parent {
853            if !current_level.is_object() {
854                return Err(fmt_err!("path segment '{segment}' does not resolve to an object."));
855            }
856            current_level = current_level
857                .as_object_mut()
858                .unwrap()
859                .entry(segment.clone())
860                .or_insert(Value::Object(Map::new()));
861        }
862
863        // Upsert the new value
864        if let Some(parent_obj) = current_level.as_object_mut() {
865            parent_obj.insert(
866                key_to_insert.clone(),
867                serde_json::from_str(value).unwrap_or_else(|_| Value::String(value.to_owned())),
868            );
869        } else {
870            return Err(fmt_err!("final destination is not an object, cannot insert key."));
871        }
872    }
873
874    Ok(())
875}
876
877/// Parses only literal object keys; JSONPath selectors cannot create missing keys unambiguously.
878fn split_json_value_key(key: &str) -> Result<Vec<String>> {
879    let invalid = || {
880        fmt_err!(
881            "invalid JSON write path '{key}': expected dot-separated keys or quoted bracket keys"
882        )
883    };
884    let mut path =
885        if key == "$" || key.starts_with("$.") || key.starts_with("$[") { &key[1..] } else { key };
886    let mut parts = Vec::new();
887
888    while !path.is_empty() {
889        if let Some(rest) = path.strip_prefix('.') {
890            path = rest;
891            if path.is_empty() || path.starts_with('.') {
892                return Err(invalid());
893            }
894        } else if !parts.is_empty() && !path.starts_with('[') {
895            return Err(invalid());
896        }
897
898        if let Some(quoted) = path.strip_prefix('[') {
899            let Some(quote @ ('\'' | '"')) = quoted.chars().next() else {
900                return Err(invalid());
901            };
902            let quoted = &quoted[quote.len_utf8()..];
903            let mut chars = quoted.char_indices().peekable();
904            let mut segment = String::new();
905            let mut end = None;
906            while let Some((index, ch)) = chars.next() {
907                if ch == '\\' && chars.peek().is_some_and(|(_, next)| *next == quote) {
908                    chars.next();
909                    segment.push(quote);
910                } else if ch == quote {
911                    end = Some(index + ch.len_utf8());
912                    break;
913                } else {
914                    segment.push(ch);
915                }
916            }
917            let Some(end) = end else { return Err(invalid()) };
918            path = quoted[end..].strip_prefix(']').ok_or_else(invalid)?;
919            parts.push(segment);
920        } else {
921            let end = path.find(['.', '[']).unwrap_or(path.len());
922            let segment = &path[..end];
923            if segment.is_empty() || segment.chars().any(|ch| matches!(ch, ']' | '*' | '?')) {
924                return Err(invalid());
925            }
926            parts.push(segment.to_owned());
927            path = &path[end..];
928        }
929    }
930
931    if parts.is_empty() {
932        return Err(fmt_err!("'valueKey' cannot be empty or just '$'"));
933    }
934    Ok(parts)
935}
936
937/// Splits the `valueKey` of a write cheatcode into the object keys leading to the value.
938pub(super) fn split_value_key(key: &str) -> Result<Vec<String>> {
939    // Parse the path key into segments.
940    let canonical_key = canonicalize_json_path(key);
941    let parts = canonical_key
942        .strip_prefix("$.")
943        .unwrap_or(key)
944        .split('.')
945        .filter(|s| !s.is_empty())
946        .map(str::to_string)
947        .collect::<Vec<_>>();
948
949    if parts.is_empty() {
950        return Err(fmt_err!("'valueKey' cannot be empty or just '$'"));
951    }
952
953    Ok(parts)
954}
955
956/// Recursively traverses a `DynSolType` and reorders the fields of any
957/// `CustomStruct` variants according to the provided `StructDefinitions`.
958///
959/// This is necessary because the EIP-712 resolver sorts struct fields alphabetically,
960/// but we want to respect the order defined in the Solidity source code.
961fn reorder_type(ty: DynSolType, struct_defs: &StructDefinitions) -> Result<DynSolType> {
962    match ty {
963        DynSolType::CustomStruct { name, prop_names, tuple } => {
964            if let Some(def) = struct_defs.get(&name)? {
965                // The incoming `prop_names` and `tuple` are alphabetically sorted.
966                let type_map: std::collections::HashMap<String, DynSolType> =
967                    prop_names.into_iter().zip(tuple).collect();
968
969                let mut sorted_props = Vec::with_capacity(def.len());
970                let mut sorted_tuple = Vec::with_capacity(def.len());
971                for (field_name, _) in def {
972                    sorted_props.push(field_name.clone());
973                    if let Some(field_ty) = type_map.get(field_name) {
974                        sorted_tuple.push(reorder_type(field_ty.clone(), struct_defs)?);
975                    } else {
976                        bail!(
977                            "mismatch between struct definition and type description: field '{field_name}' not found in provided type for struct '{name}'"
978                        );
979                    }
980                }
981                Ok(DynSolType::CustomStruct { name, prop_names: sorted_props, tuple: sorted_tuple })
982            } else {
983                // No definition found, so we can't reorder. However, we still reorder its children
984                // in case they have known structs.
985                let new_tuple = tuple
986                    .into_iter()
987                    .map(|t| reorder_type(t, struct_defs))
988                    .collect::<Result<Vec<_>>>()?;
989                Ok(DynSolType::CustomStruct { name, prop_names, tuple: new_tuple })
990            }
991        }
992        DynSolType::Array(inner) => {
993            Ok(DynSolType::Array(Box::new(reorder_type(*inner, struct_defs)?)))
994        }
995        DynSolType::FixedArray(inner, len) => {
996            Ok(DynSolType::FixedArray(Box::new(reorder_type(*inner, struct_defs)?), len))
997        }
998        DynSolType::Tuple(inner) => Ok(DynSolType::Tuple(
999            inner.into_iter().map(|t| reorder_type(t, struct_defs)).collect::<Result<Vec<_>>>()?,
1000        )),
1001        _ => Ok(ty),
1002    }
1003}
1004
1005#[cfg(test)]
1006mod tests {
1007    use super::*;
1008    use alloy_primitives::FixedBytes;
1009    use foundry_common::fmt::{TypeDefMap, serialize_value_as_json};
1010    use proptest::{arbitrary::any, prop_oneof, strategy::Strategy};
1011    use serde_json::json;
1012    use std::collections::HashSet;
1013
1014    #[test]
1015    fn test_write_json_quoted_object_keys() {
1016        let mut data = json!({"a.b": 1, "x": {"0xAb.c": 2}, "can't": 0, "a\"b": 0});
1017        for (path, number) in [
1018            (r#".["a.b"]"#, 3),
1019            ("$['a.b']", 4),
1020            (r#".x["0xAb.c"]"#, 5),
1021            (".x.['0xAb.c']", 6),
1022            (".new['child.key'].value", 7),
1023            (".parent.child.value", 8),
1024            (r#".["a\"b]"]"#, 9),
1025            (r#".['a\'b]']"#, 10),
1026            (".can't", 11),
1027            (r#".a"b"#, 12),
1028            (".new.can't.value", 13),
1029        ] {
1030            upsert_json_value(&mut data, &number.to_string(), path).unwrap();
1031            assert_eq!(select(&data, path).unwrap(), vec![&json!(number)], "{path}");
1032        }
1033
1034        assert_eq!(
1035            data,
1036            json!({
1037                "a.b": 4,
1038                "x": {"0xAb.c": 6},
1039                "new": {"child.key": {"value": 7}, "can't": {"value": 13}},
1040                "parent": {"child": {"value": 8}},
1041                "a\"b]": 9,
1042                "a'b]": 10,
1043                "can't": 11,
1044                "a\"b": 12,
1045            })
1046        );
1047    }
1048
1049    #[test]
1050    fn test_write_json_rejects_unsupported_paths_without_mutation() {
1051        for path in [
1052            "",
1053            "$",
1054            ".",
1055            ".x[0]",
1056            ".x[*]",
1057            ".x[?(@.a)]",
1058            ".x.*",
1059            ".x..y",
1060            ".x['unterminated]",
1061            ".x['a.b']tail",
1062            ".x[foo]",
1063            ".x.",
1064        ] {
1065            let mut data = json!({"x": {"a": 1}});
1066            let original = data.clone();
1067            assert!(upsert_json_value(&mut data, "2", path).is_err(), "{path}");
1068            assert_eq!(data, original, "{path}");
1069        }
1070    }
1071
1072    #[test]
1073    fn test_parse_json_comments() {
1074        let value = parse_json_str(
1075            r#"{
1076                // A line comment.
1077                "value": 42,
1078                /* A block comment. */
1079                "url": "https://example.com/path/*literal*/"
1080            }"#,
1081        )
1082        .unwrap();
1083
1084        assert_eq!(value["value"], 42);
1085        assert_eq!(value["url"], "https://example.com/path/*literal*/");
1086
1087        let error = parse_json_str(r#"{"value": 42} /* unterminated"#).unwrap_err();
1088        assert!(error.to_string().contains("unterminated block comment"));
1089    }
1090
1091    /// Returns `true` if `serialize_value_as_json` writes `s` as a JSON object, which does not
1092    /// roundtrip.
1093    fn is_json_object(s: &str) -> bool {
1094        serialize_value_as_json(DynSolValue::String(s.to_string()), None, false)
1095            .is_ok_and(|json| json.is_object())
1096    }
1097
1098    /// Returns `true` if `value` holds a string that `is_json_object` matches.
1099    fn has_json_object_string(value: &DynSolValue) -> bool {
1100        match value {
1101            DynSolValue::String(s) => is_json_object(s),
1102            DynSolValue::Array(v) | DynSolValue::FixedArray(v) | DynSolValue::Tuple(v) => {
1103                v.iter().any(has_json_object_string)
1104            }
1105            DynSolValue::CustomStruct { tuple, .. } => tuple.iter().any(has_json_object_string),
1106            _ => false,
1107        }
1108    }
1109
1110    fn valid_value(value: &DynSolValue) -> bool {
1111        (match value {
1112            DynSolValue::String(s) if is_json_object(s) => false,
1113
1114            DynSolValue::Tuple(_) | DynSolValue::CustomStruct { .. } => false,
1115
1116            DynSolValue::Array(v) | DynSolValue::FixedArray(v) => v.iter().all(valid_value),
1117            _ => true,
1118        }) && value.as_type().is_some()
1119    }
1120
1121    /// [DynSolValue::Bytes] of length 32 and 20 are converted to [DynSolValue::FixedBytes] and
1122    /// [DynSolValue::Address] respectively. Thus, we can't distinguish between address and bytes of
1123    /// length 20 during decoding. Because of that, there are issues with handling of arrays of
1124    /// those types.
1125    fn fixup_guessable(value: DynSolValue) -> DynSolValue {
1126        match value {
1127            DynSolValue::Array(mut v) | DynSolValue::FixedArray(mut v) => {
1128                if let Some(DynSolValue::Bytes(_)) = v.first() {
1129                    v.retain(|v| {
1130                        let len = v.as_bytes().unwrap().len();
1131                        len != 32 && len != 20
1132                    })
1133                }
1134                DynSolValue::Array(v.into_iter().map(fixup_guessable).collect())
1135            }
1136            DynSolValue::FixedBytes(v, _) => DynSolValue::FixedBytes(v, 32),
1137            DynSolValue::Bytes(v) if v.len() == 32 => {
1138                DynSolValue::FixedBytes(FixedBytes::from_slice(&v), 32)
1139            }
1140            DynSolValue::Bytes(v) if v.len() == 20 => DynSolValue::Address(Address::from_slice(&v)),
1141            _ => value,
1142        }
1143    }
1144
1145    fn guessable_types() -> impl proptest::strategy::Strategy<Value = DynSolValue> {
1146        any::<DynSolValue>().prop_map(fixup_guessable).prop_filter("invalid value", valid_value)
1147    }
1148
1149    /// A proptest strategy for generating a (simple) `DynSolValue::CustomStruct`
1150    /// and its corresponding `StructDefinitions` object.
1151    fn custom_struct_strategy() -> impl Strategy<Value = (StructDefinitions, DynSolValue)> {
1152        // Define a strategy for basic field names and values.
1153        let field_name_strat = "[a-z]{4,12}";
1154        let field_value_strat = prop_oneof![
1155            any::<bool>().prop_map(DynSolValue::Bool),
1156            any::<u32>().prop_map(|v| DynSolValue::Uint(U256::from(v), 256)),
1157            any::<[u8; 20]>().prop_map(Address::from).prop_map(DynSolValue::Address),
1158            any::<[u8; 32]>().prop_map(B256::from).prop_map(|b| DynSolValue::FixedBytes(b, 32)),
1159            ".*".prop_filter("invalid string value", |s| !is_json_object(s))
1160                .prop_map(DynSolValue::String),
1161        ];
1162
1163        // Combine them to create a list of unique fields that preserve the random order.
1164        let fields_strat = proptest::collection::vec((field_name_strat, field_value_strat), 1..8)
1165            .prop_map(|fields| {
1166                let mut unique_fields = Vec::with_capacity(fields.len());
1167                let mut seen_names = HashSet::new();
1168                for (name, value) in fields {
1169                    if seen_names.insert(name.clone()) {
1170                        unique_fields.push((name, value));
1171                    }
1172                }
1173                unique_fields
1174            });
1175
1176        // Generate the `CustomStruct` and its definition.
1177        ("[A-Z][a-z]{4,8}", fields_strat).prop_map(|(struct_name, fields)| {
1178            let (prop_names, tuple): (Vec<String>, Vec<DynSolValue>) =
1179                fields.clone().into_iter().unzip();
1180            let def_fields: Vec<(String, String)> = fields
1181                .iter()
1182                .map(|(name, value)| (name.clone(), value.as_type().unwrap().to_string()))
1183                .collect();
1184            let mut defs_map = TypeDefMap::default();
1185            defs_map.insert(struct_name.clone(), def_fields);
1186            (defs_map.into(), DynSolValue::CustomStruct { name: struct_name, prop_names, tuple })
1187        })
1188    }
1189
1190    // Tests to ensure that conversion [DynSolValue] -> [serde_json::Value] -> [DynSolValue]
1191    proptest::proptest! {
1192        #[test]
1193        fn test_json_roundtrip_guessed(v in guessable_types()) {
1194            let json = serialize_value_as_json(v.clone(), None, false).unwrap();
1195            let value = json_value_to_token(&json, None).unwrap();
1196
1197            // do additional abi_encode -> abi_decode to avoid zero signed integers getting decoded as unsigned and causing assert_eq to fail.
1198            let decoded = v.as_type().unwrap().abi_decode(&value.abi_encode()).unwrap();
1199            assert_eq!(decoded, v);
1200        }
1201
1202        #[test]
1203        fn test_json_roundtrip(v in any::<DynSolValue>().prop_filter("filter out values without type", |v| v.as_type().is_some() && !has_json_object_string(v))) {
1204            let json = serialize_value_as_json(v.clone(), None, false).unwrap();
1205            let value = parse_json_as(&json, &v.as_type().unwrap()).unwrap();
1206            assert_eq!(value, v);
1207        }
1208
1209        #[test]
1210        fn test_json_roundtrip_with_struct_defs((struct_defs, v) in custom_struct_strategy()) {
1211            let json = serialize_value_as_json(v.clone(), Some(&struct_defs), false).unwrap();
1212            let sol_type = v.as_type().unwrap();
1213            let parsed_value = parse_json_as(&json, &sol_type).unwrap();
1214            assert_eq!(parsed_value, v);
1215        }
1216    }
1217
1218    #[test]
1219    fn test_resolve_type_with_definitions() -> Result<()> {
1220        // Define a struct with fields in a specific order (not alphabetical)
1221        let mut struct_defs = TypeDefMap::new();
1222        struct_defs.insert(
1223            "Apple".to_string(),
1224            vec![
1225                ("color".to_string(), "string".to_string()),
1226                ("sweetness".to_string(), "uint8".to_string()),
1227                ("sourness".to_string(), "uint8".to_string()),
1228            ],
1229        );
1230        struct_defs.insert(
1231            "FruitStall".to_string(),
1232            vec![
1233                ("name".to_string(), "string".to_string()),
1234                ("apples".to_string(), "Apple[]".to_string()),
1235            ],
1236        );
1237
1238        // Simulate resolver output: type string, using alphabetical order for fields.
1239        let ty_desc = "FruitStall(Apple[] apples,string name)Apple(string color,uint8 sourness,uint8 sweetness)";
1240
1241        // Resolve type and ensure struct definition order is preserved.
1242        let ty = resolve_type(ty_desc, Some(&struct_defs.into())).unwrap();
1243        if let DynSolType::CustomStruct { name, prop_names, tuple } = ty {
1244            assert_eq!(name, "FruitStall");
1245            assert_eq!(prop_names, vec!["name", "apples"]);
1246            assert_eq!(tuple.len(), 2);
1247            assert_eq!(tuple[0], DynSolType::String);
1248
1249            if let DynSolType::Array(apple_ty_boxed) = &tuple[1]
1250                && let DynSolType::CustomStruct { name, prop_names, tuple } = &**apple_ty_boxed
1251            {
1252                assert_eq!(*name, "Apple");
1253                // Check that the inner struct's fields are also in definition order.
1254                assert_eq!(*prop_names, vec!["color", "sweetness", "sourness"]);
1255                assert_eq!(
1256                    *tuple,
1257                    vec![DynSolType::String, DynSolType::Uint(8), DynSolType::Uint(8)]
1258                );
1259
1260                return Ok(());
1261            }
1262        }
1263        panic!("Expected FruitStall and Apple to be CustomStruct");
1264    }
1265
1266    #[test]
1267    fn test_resolve_type_without_definitions() -> Result<()> {
1268        // Simulate resolver output: type string, using alphabetical order for fields.
1269        let ty_desc = "Person(bool active,uint256 age,string name)";
1270
1271        // Resolve the type without providing any struct definitions and ensure that original
1272        // (alphabetical) order is unchanged.
1273        let ty = resolve_type(ty_desc, None).unwrap();
1274        if let DynSolType::CustomStruct { name, prop_names, tuple } = ty {
1275            assert_eq!(name, "Person");
1276            assert_eq!(prop_names, vec!["active", "age", "name"]);
1277            assert_eq!(tuple.len(), 3);
1278            assert_eq!(tuple, vec![DynSolType::Bool, DynSolType::Uint(256), DynSolType::String]);
1279            return Ok(());
1280        }
1281        panic!("Expected Person to be CustomStruct");
1282    }
1283
1284    #[test]
1285    fn test_resolve_type_bare_struct_name_errors_instead_of_panicking() {
1286        // `EncodeType::parse` succeeds with an empty type list for inputs without `(`.
1287        let err = resolve_type("Foo", None).unwrap_err();
1288        assert!(
1289            err.to_string().contains("valid Solidity type or a EIP712 `encodeType` string"),
1290            "unexpected error: {err}"
1291        );
1292    }
1293
1294    #[test]
1295    fn test_parse_fixed_array() {
1296        let mut struct_defs = TypeDefMap::new();
1297        struct_defs.insert(
1298            "Contract.Child".to_string(),
1299            vec![("value".to_string(), "uint256".to_string())],
1300        );
1301        let struct_defs = StructDefinitions::from(struct_defs);
1302
1303        let value = serde_json::json!([[1], [2]]);
1304        assert!(parse_fixed_array(&value, "uint256[1][]", &struct_defs).unwrap().is_ok());
1305        assert!(parse_fixed_array(&value, "uint256[", &struct_defs).is_none());
1306        assert!(parse_fixed_array(&value, "uint256[0]", &struct_defs).is_none());
1307        assert!(parse_fixed_array(&value, "Contract.Child[", &struct_defs).is_none());
1308        assert!(parse_fixed_array(&value, "Missing.Child[1]", &struct_defs).is_none());
1309
1310        let value = serde_json::json!([[{"value": 1}, {"value": 2}]]);
1311        let parsed =
1312            parse_fixed_array(&value, "Contract.Child[2][1]", &struct_defs).unwrap().unwrap();
1313        assert!(matches!(
1314            parsed,
1315            DynSolValue::FixedArray(outer)
1316                if matches!(&outer[..], [DynSolValue::FixedArray(inner)] if matches!(&inner[..], [DynSolValue::Tuple(_), DynSolValue::Tuple(_)]))
1317        ));
1318
1319        let value = serde_json::json!([[{"value": 1}], [{"value": 2}]]);
1320        assert!(parse_fixed_array(&value, "Contract.Child[1][]", &struct_defs).unwrap().is_ok());
1321        let value = serde_json::json!([[]]);
1322        assert!(parse_fixed_array(&value, "Contract.Child[][1]", &struct_defs).unwrap().is_ok());
1323
1324        let mut ambiguous_defs = TypeDefMap::new();
1325        ambiguous_defs
1326            .insert("A.Child".to_string(), vec![("value".to_string(), "uint256".to_string())]);
1327        ambiguous_defs
1328            .insert("B.Child".to_string(), vec![("value".to_string(), "uint256".to_string())]);
1329        let ambiguous_defs = StructDefinitions::from(ambiguous_defs);
1330        let value = serde_json::json!([{"value": 1}]);
1331        assert!(parse_fixed_array(&value, "Child[1]", &ambiguous_defs).is_none());
1332        assert!(parse_fixed_array(&value, "A.Child[1]", &ambiguous_defs).unwrap().is_ok());
1333    }
1334
1335    #[test]
1336    fn test_resolve_type_for_array_of_structs() -> Result<()> {
1337        // Define a struct with fields in a specific, non-alphabetical order.
1338        let mut struct_defs = TypeDefMap::new();
1339        struct_defs.insert(
1340            "Item".to_string(),
1341            vec![
1342                ("name".to_string(), "string".to_string()),
1343                ("price".to_string(), "uint256".to_string()),
1344                ("id".to_string(), "uint256".to_string()),
1345            ],
1346        );
1347
1348        // Simulate resolver output: type string, using alphabetical order for fields.
1349        let ty_desc = "Item(uint256 id,string name,uint256 price)";
1350
1351        // Resolve type and ensure struct definition order is preserved.
1352        let ty = resolve_type(ty_desc, Some(&struct_defs.into())).unwrap();
1353        let array_ty = DynSolType::Array(Box::new(ty));
1354        if let DynSolType::Array(item_ty) = array_ty
1355            && let DynSolType::CustomStruct { name, prop_names, tuple } = *item_ty
1356        {
1357            assert_eq!(name, "Item");
1358            assert_eq!(prop_names, vec!["name", "price", "id"]);
1359            assert_eq!(
1360                tuple,
1361                vec![DynSolType::String, DynSolType::Uint(256), DynSolType::Uint(256)]
1362            );
1363            return Ok(());
1364        }
1365        panic!("Expected CustomStruct in array");
1366    }
1367
1368    #[test]
1369    fn test_parse_json_missing_field() {
1370        // Define a struct with a specific field order.
1371        let mut struct_defs = TypeDefMap::new();
1372        struct_defs.insert(
1373            "Person".to_string(),
1374            vec![
1375                ("name".to_string(), "string".to_string()),
1376                ("age".to_string(), "uint256".to_string()),
1377            ],
1378        );
1379
1380        // JSON missing the "age" field
1381        let json_str = r#"{ "name": "Alice" }"#;
1382
1383        // Simulate resolver output: type string, using alphabetical order for fields.
1384        let type_description = "Person(uint256 age,string name)";
1385        let ty = resolve_type(type_description, Some(&struct_defs.into())).unwrap();
1386
1387        // Now, attempt to parse the incomplete JSON using the ordered type.
1388        let json_value: Value = serde_json::from_str(json_str).unwrap();
1389        let result = parse_json_as(&json_value, &ty);
1390
1391        // Should fail with a missing field error because `parse_json_map` requires all fields.
1392        assert!(result.is_err());
1393        assert!(result.unwrap_err().to_string().contains("field \"age\" not found in JSON object"));
1394    }
1395
1396    #[test]
1397    fn test_serialize_json_with_struct_def_order() {
1398        // Define a struct with a specific, non-alphabetical field order.
1399        let mut struct_defs = TypeDefMap::new();
1400        struct_defs.insert(
1401            "Item".to_string(),
1402            vec![
1403                ("name".to_string(), "string".to_string()),
1404                ("id".to_string(), "uint256".to_string()),
1405                ("active".to_string(), "bool".to_string()),
1406            ],
1407        );
1408
1409        // Create a DynSolValue instance for the struct.
1410        let item_struct = DynSolValue::CustomStruct {
1411            name: "Item".to_string(),
1412            prop_names: vec!["name".to_string(), "id".to_string(), "active".to_string()],
1413            tuple: vec![
1414                DynSolValue::String("Test Item".to_string()),
1415                DynSolValue::Uint(U256::from(123), 256),
1416                DynSolValue::Bool(true),
1417            ],
1418        };
1419
1420        // Serialize the value to JSON and verify that the order is preserved.
1421        let json_value =
1422            serialize_value_as_json(item_struct, Some(&struct_defs.into()), false).unwrap();
1423        let json_string = serde_json::to_string(&json_value).unwrap();
1424        assert_eq!(json_string, r#"{"name":"Test Item","id":123,"active":true}"#);
1425    }
1426
1427    #[test]
1428    fn test_json_full_cycle_typed_with_struct_defs() {
1429        // Define a struct with a specific, non-alphabetical field order.
1430        let mut struct_defs = TypeDefMap::new();
1431        struct_defs.insert(
1432            "Wallet".to_string(),
1433            vec![
1434                ("owner".to_string(), "address".to_string()),
1435                ("balance".to_string(), "uint256".to_string()),
1436                ("id".to_string(), "bytes32".to_string()),
1437            ],
1438        );
1439
1440        // Create the "original" DynSolValue instance.
1441        let owner_address = Address::repeat_byte(1);
1442        let wallet_id = B256::repeat_byte(2);
1443        let original_wallet = DynSolValue::CustomStruct {
1444            name: "Wallet".to_string(),
1445            prop_names: vec!["owner".to_string(), "balance".to_string(), "id".to_string()],
1446            tuple: vec![
1447                DynSolValue::Address(owner_address),
1448                DynSolValue::Uint(U256::from(5000), 256),
1449                DynSolValue::FixedBytes(wallet_id, 32),
1450            ],
1451        };
1452
1453        // Serialize it. The resulting JSON should respect the struct definition order.
1454        let json_value = serialize_value_as_json(
1455            original_wallet.clone(),
1456            Some(&struct_defs.clone().into()),
1457            false,
1458        )
1459        .unwrap();
1460        let json_string = serde_json::to_string(&json_value).unwrap();
1461        assert_eq!(
1462            json_string,
1463            format!(r#"{{"owner":"{owner_address}","balance":5000,"id":"{wallet_id}"}}"#)
1464        );
1465
1466        // Resolve the type, which should also respect the struct definition order.
1467        let type_description = "Wallet(uint256 balance,bytes32 id,address owner)";
1468        let resolved_type = resolve_type(type_description, Some(&struct_defs.into())).unwrap();
1469
1470        // Parse the JSON using the correctly ordered resolved type. Ensure that it is identical to
1471        // the original one.
1472        let parsed_value = parse_json_as(&json_value, &resolved_type).unwrap();
1473        assert_eq!(parsed_value, original_wallet);
1474    }
1475}