1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
// Copyright (c) Mysten Labs, Inc.
// Modifications Copyright (c) 2024 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use std::{
    collections::{BTreeMap, VecDeque},
    fmt::{self, Debug, Formatter},
    str::FromStr,
};

use anyhow::{anyhow, bail};
use fastcrypto::encoding::{Encoding, Hex};
use iota_types::{
    MOVE_STDLIB_ADDRESS,
    base_types::{
        IotaAddress, ObjectID, RESOLVED_ASCII_STR, RESOLVED_STD_OPTION, RESOLVED_UTF8_STR,
        STD_ASCII_MODULE_NAME, STD_ASCII_STRUCT_NAME, STD_OPTION_MODULE_NAME,
        STD_OPTION_STRUCT_NAME, STD_UTF8_MODULE_NAME, STD_UTF8_STRUCT_NAME, TxContext,
        TxContextKind, is_primitive_type_tag,
    },
    id::{ID, RESOLVED_IOTA_ID},
    move_package::MovePackage,
    object::bounded_visitor::BoundedVisitor,
    transfer::RESOLVED_RECEIVING_STRUCT,
};
use move_binary_format::{
    CompiledModule, binary_config::BinaryConfig, file_format::SignatureToken,
};
use move_bytecode_utils::resolve_struct;
pub use move_core_types::annotated_value::MoveTypeLayout;
use move_core_types::{
    account_address::AccountAddress,
    annotated_value::{MoveFieldLayout, MoveStruct, MoveStructLayout, MoveValue, MoveVariant},
    ident_str,
    identifier::{IdentStr, Identifier},
    language_storage::{StructTag, TypeTag},
    runtime_value as R,
    u256::U256,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Number, Value as JsonValue, json};

const HEX_PREFIX: &str = "0x";

#[cfg(test)]
mod tests;

/// A list of error categories encountered when parsing numbers.
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
pub enum IotaJsonValueErrorKind {
    /// JSON value must be of specific types.
    ValueTypeNotAllowed,

    /// JSON arrays must be homogeneous.
    ArrayNotHomogeneous,
}

#[derive(Debug)]
pub struct IotaJsonValueError {
    kind: IotaJsonValueErrorKind,
    val: JsonValue,
}

impl IotaJsonValueError {
    pub fn new(val: &JsonValue, kind: IotaJsonValueErrorKind) -> Self {
        Self {
            kind,
            val: val.clone(),
        }
    }
}

impl std::error::Error for IotaJsonValueError {}

impl fmt::Display for IotaJsonValueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let err_str = match self.kind {
            IotaJsonValueErrorKind::ValueTypeNotAllowed => {
                format!("JSON value type {} not allowed.", self.val)
            }
            IotaJsonValueErrorKind::ArrayNotHomogeneous => {
                format!("Array not homogeneous. Mismatched value: {}.", self.val)
            }
        };
        write!(f, "{err_str}")
    }
}

// Intermediate type to hold resolved args
#[derive(Eq, PartialEq, Debug)]
pub enum ResolvedCallArg {
    Object(ObjectID),
    Pure(Vec<u8>),
    ObjVec(Vec<ObjectID>),
}

#[derive(Eq, PartialEq, Clone, Deserialize, Serialize, JsonSchema)]
pub struct IotaJsonValue(JsonValue);
impl IotaJsonValue {
    pub fn new(json_value: JsonValue) -> Result<IotaJsonValue, anyhow::Error> {
        Self::check_value(&json_value)?;
        Ok(Self(json_value))
    }

    fn check_value(json_value: &JsonValue) -> Result<(), anyhow::Error> {
        match json_value {
            // No checks needed for Bool and String
            JsonValue::Bool(_) | JsonValue::String(_) => (),
            JsonValue::Number(n) => {
                // Must be castable to u64
                if !n.is_u64() {
                    return Err(anyhow!(
                        "{n} not allowed. Number must be unsigned integer of at most u32"
                    ));
                }
            }
            // Must be homogeneous
            JsonValue::Array(a) => {
                // Fail if not homogeneous
                check_valid_homogeneous(&JsonValue::Array(a.to_vec()))?
            }
            JsonValue::Object(v) => {
                for (_, value) in v {
                    Self::check_value(value)?;
                }
            }
            JsonValue::Null => bail!("Null not allowed."),
        };
        Ok(())
    }

    pub fn from_object_id(id: ObjectID) -> IotaJsonValue {
        Self(JsonValue::String(id.to_hex_uncompressed()))
    }

    pub fn to_bcs_bytes(&self, ty: &MoveTypeLayout) -> Result<Vec<u8>, anyhow::Error> {
        let move_value = Self::to_move_value(&self.0, ty)?;
        R::MoveValue::simple_serialize(&move_value)
            .ok_or_else(|| anyhow!("Unable to serialize {:?}. Expected {}", move_value, ty))
    }

    pub fn from_bcs_bytes(
        layout: Option<&MoveTypeLayout>,
        bytes: &[u8],
    ) -> Result<Self, anyhow::Error> {
        let json = if let Some(layout) = layout {
            // Try to convert Vec<u8> inputs into string
            fn try_parse_string(layout: &MoveTypeLayout, bytes: &[u8]) -> Option<String> {
                if let MoveTypeLayout::Vector(t) = layout {
                    if let MoveTypeLayout::U8 = **t {
                        return bcs::from_bytes::<String>(bytes).ok();
                    }
                }
                None
            }
            if let Some(s) = try_parse_string(layout, bytes) {
                json!(s)
            } else {
                let result = BoundedVisitor::deserialize_value(bytes, layout).map_or_else(
                    |_| {
                        // fallback to array[u8] if fail to convert to json.
                        JsonValue::Array(
                            bytes
                                .iter()
                                .map(|b| JsonValue::Number(Number::from(*b)))
                                .collect(),
                        )
                    },
                    |move_value| {
                        move_value_to_json(&move_value).unwrap_or_else(|| {
                            // fallback to array[u8] if fail to convert to json.
                            JsonValue::Array(
                                bytes
                                    .iter()
                                    .map(|b| JsonValue::Number(Number::from(*b)))
                                    .collect(),
                            )
                        })
                    },
                );
                result
            }
        } else {
            json!(bytes)
        };
        IotaJsonValue::new(json)
    }

    pub fn to_json_value(&self) -> JsonValue {
        self.0.clone()
    }

    pub fn to_iota_address(&self) -> anyhow::Result<IotaAddress> {
        json_value_to_iota_address(&self.0)
    }

    fn handle_inner_struct_layout(
        inner_vec: &[MoveFieldLayout],
        val: &JsonValue,
        ty: &MoveTypeLayout,
        s: &String,
    ) -> Result<R::MoveValue, anyhow::Error> {
        // delegate MoveValue construction to the case when JsonValue::String and
        // MoveTypeLayout::Vector are handled to get an address (with 0x string
        // prefix) or a vector of u8s (no prefix)
        debug_assert!(matches!(val, JsonValue::String(_)));

        if inner_vec.len() != 1 {
            bail!(
                "Cannot convert string arg {s} to {ty} which is expected \
                 to be a struct with one field"
            );
        }

        match &inner_vec[0].layout {
            MoveTypeLayout::Vector(inner) => match **inner {
                MoveTypeLayout::U8 => Ok(R::MoveValue::Struct(R::MoveStruct(vec![
                    Self::to_move_value(val, &inner_vec[0].layout.clone())?,
                ]))),
                MoveTypeLayout::Address => Ok(R::MoveValue::Struct(R::MoveStruct(vec![
                    Self::to_move_value(val, &MoveTypeLayout::Address)?,
                ]))),
                _ => bail!(
                    "Cannot convert string arg {s} to {ty} \
                             which is expected to be a struct \
                             with one field of address or u8 vector type"
                ),
            },
            MoveTypeLayout::Struct(MoveStructLayout { type_, .. }) if type_ == &ID::type_() => {
                Ok(R::MoveValue::Struct(R::MoveStruct(vec![
                    Self::to_move_value(val, &inner_vec[0].layout.clone())?,
                ])))
            }
            _ => bail!(
                "Cannot convert string arg {s} to {ty} which is expected \
                 to be a struct with one field of a vector type"
            ),
        }
    }

    pub fn to_move_value(
        val: &JsonValue,
        ty: &MoveTypeLayout,
    ) -> Result<R::MoveValue, anyhow::Error> {
        Ok(match (val, ty) {
            // Bool to Bool is simple
            (JsonValue::Bool(b), MoveTypeLayout::Bool) => R::MoveValue::Bool(*b),

            // In constructor, we have already checked that the JSON number is unsigned int of at
            // most U32
            (JsonValue::Number(n), MoveTypeLayout::U8) => match n.as_u64() {
                Some(x) => R::MoveValue::U8(u8::try_from(x)?),
                None => return Err(anyhow!("{} is not a valid number. Only u8 allowed.", n)),
            },
            (JsonValue::Number(n), MoveTypeLayout::U16) => match n.as_u64() {
                Some(x) => R::MoveValue::U16(u16::try_from(x)?),
                None => return Err(anyhow!("{} is not a valid number. Only u16 allowed.", n)),
            },
            (JsonValue::Number(n), MoveTypeLayout::U32) => match n.as_u64() {
                Some(x) => R::MoveValue::U32(u32::try_from(x)?),
                None => return Err(anyhow!("{} is not a valid number. Only u32 allowed.", n)),
            },

            // u8, u16, u32, u64, u128, u256 can be encoded as String
            (JsonValue::String(s), MoveTypeLayout::U8) => {
                R::MoveValue::U8(u8::try_from(convert_string_to_u256(s.as_str())?)?)
            }
            (JsonValue::String(s), MoveTypeLayout::U16) => {
                R::MoveValue::U16(u16::try_from(convert_string_to_u256(s.as_str())?)?)
            }
            (JsonValue::String(s), MoveTypeLayout::U32) => {
                R::MoveValue::U32(u32::try_from(convert_string_to_u256(s.as_str())?)?)
            }
            (JsonValue::String(s), MoveTypeLayout::U64) => {
                R::MoveValue::U64(u64::try_from(convert_string_to_u256(s.as_str())?)?)
            }
            (JsonValue::String(s), MoveTypeLayout::U128) => {
                R::MoveValue::U128(u128::try_from(convert_string_to_u256(s.as_str())?)?)
            }
            (JsonValue::String(s), MoveTypeLayout::U256) => {
                R::MoveValue::U256(convert_string_to_u256(s.as_str())?)
            }
            // For ascii and utf8 strings
            (
                JsonValue::String(s),
                MoveTypeLayout::Struct(MoveStructLayout { type_, fields: _ }),
            ) if is_move_string_type(type_) => {
                R::MoveValue::Vector(s.as_bytes().iter().copied().map(R::MoveValue::U8).collect())
            }
            // For ID
            (JsonValue::String(s), MoveTypeLayout::Struct(MoveStructLayout { type_, fields }))
                if type_ == &ID::type_() =>
            {
                if fields.len() != 1 {
                    bail!(
                        "Cannot convert string arg {s} to {type_} which is expected to be a struct with one field"
                    );
                };
                let addr = IotaAddress::from_str(s)?;
                R::MoveValue::Address(addr.into())
            }
            (JsonValue::Object(o), MoveTypeLayout::Struct(MoveStructLayout { fields, .. })) => {
                let mut field_values = vec![];
                for layout in fields {
                    let field = o
                        .get(layout.name.as_str())
                        .ok_or_else(|| anyhow!("Missing field {} for struct {ty}", layout.name))?;
                    field_values.push(Self::to_move_value(field, &layout.layout)?);
                }
                R::MoveValue::Struct(R::MoveStruct(field_values))
            }
            // Unnest fields
            (value, MoveTypeLayout::Struct(MoveStructLayout { fields, .. }))
                if fields.len() == 1 =>
            {
                Self::to_move_value(value, &fields[0].layout)?
            }
            (JsonValue::String(s), MoveTypeLayout::Vector(t)) => {
                match &**t {
                    MoveTypeLayout::U8 => {
                        // We can encode U8 Vector as string in 2 ways
                        // 1. If it starts with 0x, we treat it as hex strings, where each pair is a
                        //    byte
                        // 2. If it does not start with 0x, we treat each character as an ASCII
                        //    encoded byte
                        // We have to support both for the convenience of the user. This is because
                        // sometime we need Strings as arg Other times we need vec of hex bytes for
                        // address. Issue is both Address and Strings are represented as Vec<u8> in
                        // Move call
                        let vec = if s.starts_with(HEX_PREFIX) {
                            // If starts with 0x, treat as hex vector
                            Hex::decode(s).map_err(|e| anyhow!(e))?
                        } else {
                            // Else raw bytes
                            s.as_bytes().to_vec()
                        };
                        R::MoveValue::Vector(vec.iter().copied().map(R::MoveValue::U8).collect())
                    }
                    MoveTypeLayout::Struct(MoveStructLayout { fields: inner, .. }) => {
                        Self::handle_inner_struct_layout(inner, val, ty, s)?
                    }
                    _ => bail!("Cannot convert string arg {s} to {ty}"),
                }
            }

            // We have already checked that the array is homogeneous in the constructor
            (JsonValue::Array(a), MoveTypeLayout::Vector(inner)) => {
                // Recursively build an IntermediateValue array
                R::MoveValue::Vector(
                    a.iter()
                        .map(|i| Self::to_move_value(i, inner))
                        .collect::<Result<Vec<_>, _>>()?,
                )
            }

            (v, MoveTypeLayout::Address) => {
                let addr = json_value_to_iota_address(v)?;
                R::MoveValue::Address(addr.into())
            }

            _ => bail!("Unexpected arg {val:?} for expected type {ty:?}"),
        })
    }
}

impl Debug for IotaJsonValue {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

fn json_value_to_iota_address(value: &JsonValue) -> anyhow::Result<IotaAddress> {
    match value {
        JsonValue::String(s) => {
            let s = s.trim().to_lowercase();
            if !s.starts_with(HEX_PREFIX) {
                bail!("Address hex string must start with 0x.",);
            }
            Ok(IotaAddress::from_str(&s)?)
        }
        JsonValue::Array(bytes) => {
            fn value_to_byte_array(v: &Vec<JsonValue>) -> Option<Vec<u8>> {
                let mut bytes = vec![];
                for b in v {
                    let b = b.as_u64()?;
                    if b <= u8::MAX as u64 {
                        bytes.push(b as u8);
                    } else {
                        return None;
                    }
                }
                Some(bytes)
            }
            let bytes = value_to_byte_array(bytes)
                .ok_or_else(|| anyhow!("Invalid input: Cannot parse input into IotaAddress."))?;
            Ok(IotaAddress::try_from(bytes)?)
        }
        v => bail!("Unexpected arg {v} for expected type address"),
    }
}

fn move_value_to_json(move_value: &MoveValue) -> Option<JsonValue> {
    Some(match move_value {
        MoveValue::Vector(values) => JsonValue::Array(
            values
                .iter()
                .map(move_value_to_json)
                .collect::<Option<_>>()?,
        ),
        MoveValue::Bool(v) => json!(v),
        MoveValue::Signer(v) | MoveValue::Address(v) => json!(IotaAddress::from(*v).to_string()),
        MoveValue::U8(v) => json!(v),
        MoveValue::U64(v) => json!(v.to_string()),
        MoveValue::U128(v) => json!(v.to_string()),
        MoveValue::U16(v) => json!(v),
        MoveValue::U32(v) => json!(v),
        MoveValue::U256(v) => json!(v.to_string()),
        MoveValue::Struct(move_struct) => match move_struct {
            MoveStruct { fields, type_ } if is_move_string_type(type_) => {
                // ascii::string and utf8::string has a single bytes field.
                let (_, v) = fields.first()?;
                let string: String = bcs::from_bytes(&v.simple_serialize()?).ok()?;
                json!(string)
            }
            MoveStruct { fields, type_ } if is_move_option_type(type_) => {
                // option has a single vec field.
                let (_, v) = fields.first()?;
                if let MoveValue::Vector(v) = v {
                    JsonValue::Array(v.iter().filter_map(move_value_to_json).collect::<Vec<_>>())
                } else {
                    return None;
                }
            }
            MoveStruct { fields, type_ } if type_ == &ID::type_() => {
                // option has a single vec field.
                let (_, v) = fields.first()?;
                if let MoveValue::Address(address) = v {
                    json!(IotaAddress::from(*address))
                } else {
                    return None;
                }
            }
            // We only care about values here, assuming struct type information is known at the
            // client side.
            MoveStruct { fields, .. } => {
                let fields = fields
                    .iter()
                    .map(|(key, value)| (key, move_value_to_json(value)))
                    .collect::<BTreeMap<_, _>>();
                json!(fields)
            }
        },
        // Don't return the type assuming type information is known at the client side.
        MoveValue::Variant(MoveVariant {
            type_: _,
            tag: _,
            variant_name,
            fields,
        }) => {
            let fields = fields
                .iter()
                .map(|(key, value)| (key, move_value_to_json(value)))
                .collect::<BTreeMap<_, _>>();
            json!({
                "variant": variant_name.to_string(),
                "fields": fields,
            })
        }
    })
}

fn is_move_string_type(tag: &StructTag) -> bool {
    (tag.address == MOVE_STDLIB_ADDRESS
        && tag.module.as_ident_str() == STD_UTF8_MODULE_NAME
        && tag.name.as_ident_str() == STD_UTF8_STRUCT_NAME)
        || (tag.address == MOVE_STDLIB_ADDRESS
            && tag.module.as_ident_str() == STD_ASCII_MODULE_NAME
            && tag.name.as_ident_str() == STD_ASCII_STRUCT_NAME)
}
fn is_move_option_type(tag: &StructTag) -> bool {
    tag.address == MOVE_STDLIB_ADDRESS
        && tag.module.as_ident_str() == STD_OPTION_MODULE_NAME
        && tag.name.as_ident_str() == STD_OPTION_STRUCT_NAME
}

impl FromStr for IotaJsonValue {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, anyhow::Error> {
        fn try_escape_array(s: &str) -> JsonValue {
            let s = s.trim();
            if s.starts_with('[') && s.ends_with(']') {
                if let Some(s) = s.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
                    return JsonValue::Array(s.split(',').map(try_escape_array).collect());
                }
            }
            json!(s)
        }
        // if serde_json fails, the failure usually cause by missing quote escapes, try
        // parse array manually.
        IotaJsonValue::new(serde_json::from_str(s).unwrap_or_else(|_| try_escape_array(s)))
    }
}

#[derive(Eq, PartialEq, Debug, Clone, Hash)]
enum ValidJsonType {
    Bool,
    Number,
    String,
    Array,
    // Matches any type
    Any,
}

/// Check via BFS
/// The invariant is that all types at a given level must be the same or be
/// empty, and all must be valid
pub fn check_valid_homogeneous(val: &JsonValue) -> Result<(), IotaJsonValueError> {
    let mut deq: VecDeque<&JsonValue> = VecDeque::new();
    deq.push_back(val);
    check_valid_homogeneous_rec(&mut deq)
}

/// Check via BFS
/// The invariant is that all types at a given level must be the same or be
/// empty
fn check_valid_homogeneous_rec(
    curr_q: &mut VecDeque<&JsonValue>,
) -> Result<(), IotaJsonValueError> {
    if curr_q.is_empty() {
        // Nothing to do
        return Ok(());
    }
    // Queue for the next level
    let mut next_q = VecDeque::new();
    // The types at this level must be the same
    let mut level_type = ValidJsonType::Any;

    // Process all in this queue/level
    while let Some(v) = curr_q.pop_front() {
        let curr = match v {
            JsonValue::Bool(_) => ValidJsonType::Bool,
            JsonValue::Number(x) if x.is_u64() => ValidJsonType::Number,
            JsonValue::String(_) => ValidJsonType::String,
            JsonValue::Array(w) => {
                // Add to the next level
                w.iter().for_each(|t| next_q.push_back(t));
                ValidJsonType::Array
            }
            // Not valid
            _ => {
                return Err(IotaJsonValueError::new(
                    v,
                    IotaJsonValueErrorKind::ValueTypeNotAllowed,
                ));
            }
        };

        if level_type == ValidJsonType::Any {
            // Update the level with the first found type
            level_type = curr;
        } else if level_type != curr {
            // Mismatch in the level
            return Err(IotaJsonValueError::new(
                v,
                IotaJsonValueErrorKind::ArrayNotHomogeneous,
            ));
        }
    }
    // Process the next level
    check_valid_homogeneous_rec(&mut next_q)
}

/// Checks if a give SignatureToken represents a primitive type and, if so,
/// returns MoveTypeLayout for this type (if available). The reason we need to
/// return both information about whether a SignatureToken represents a
/// primitive and an Option representing MoveTypeLayout is that there
/// can be signature tokens that represent primitives but that do not have
/// corresponding MoveTypeLayout (e.g., SignatureToken::DatatypeInstantiation).
pub fn primitive_type(
    view: &CompiledModule,
    type_args: &[TypeTag],
    param: &SignatureToken,
) -> (bool, Option<MoveTypeLayout>) {
    match param {
        SignatureToken::Bool => (true, Some(MoveTypeLayout::Bool)),
        SignatureToken::U8 => (true, Some(MoveTypeLayout::U8)),
        SignatureToken::U16 => (true, Some(MoveTypeLayout::U16)),
        SignatureToken::U32 => (true, Some(MoveTypeLayout::U32)),
        SignatureToken::U64 => (true, Some(MoveTypeLayout::U64)),
        SignatureToken::U128 => (true, Some(MoveTypeLayout::U128)),
        SignatureToken::U256 => (true, Some(MoveTypeLayout::U256)),
        SignatureToken::Address => (true, Some(MoveTypeLayout::Address)),
        SignatureToken::Vector(inner) => {
            let (is_primitive, inner_layout_opt) = primitive_type(view, type_args, inner);
            match inner_layout_opt {
                Some(inner_layout) => (
                    is_primitive,
                    Some(MoveTypeLayout::Vector(Box::new(inner_layout))),
                ),
                None => (is_primitive, None),
            }
        }
        SignatureToken::Datatype(struct_handle_idx) => {
            let resolved_struct = resolve_struct(view, *struct_handle_idx);
            if resolved_struct == RESOLVED_ASCII_STR {
                (
                    true,
                    Some(MoveTypeLayout::Struct(MoveStructLayout {
                        type_: resolved_to_struct(RESOLVED_ASCII_STR),
                        fields: vec![MoveFieldLayout::new(
                            ident_str!("bytes").into(),
                            MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U8)),
                        )],
                    })),
                )
            } else if resolved_struct == RESOLVED_UTF8_STR {
                // both structs structs representing strings have one field - a vector of type
                // u8
                (
                    true,
                    Some(MoveTypeLayout::Struct(MoveStructLayout {
                        type_: resolved_to_struct(RESOLVED_UTF8_STR),
                        fields: vec![MoveFieldLayout::new(
                            ident_str!("bytes").into(),
                            MoveTypeLayout::Vector(Box::new(MoveTypeLayout::U8)),
                        )],
                    })),
                )
            } else if resolved_struct == RESOLVED_IOTA_ID {
                (
                    true,
                    Some(MoveTypeLayout::Struct(MoveStructLayout {
                        type_: resolved_to_struct(RESOLVED_IOTA_ID),
                        fields: vec![MoveFieldLayout::new(
                            ident_str!("bytes").into(),
                            MoveTypeLayout::Address,
                        )],
                    })),
                )
            } else {
                (false, None)
            }
        }
        SignatureToken::DatatypeInstantiation(struct_inst) => {
            let (idx, targs) = &**struct_inst;
            let resolved_struct = resolve_struct(view, *idx);
            // is option of a primitive
            if resolved_struct == RESOLVED_STD_OPTION && targs.len() == 1 {
                // there is no MoveLayout for this so while we can still report whether a type
                // is primitive or not, we can't return the layout
                let (is_primitive, inner_layout) = primitive_type(view, type_args, &targs[0]);
                let layout =
                    inner_layout.map(|inner_layout| MoveTypeLayout::Vector(Box::new(inner_layout)));
                (is_primitive, layout)
            } else {
                (false, None)
            }
        }

        SignatureToken::TypeParameter(idx) => (
            type_args
                .get(*idx as usize)
                .map(is_primitive_type_tag)
                .unwrap_or(false),
            None,
        ),

        SignatureToken::Signer
        | SignatureToken::Reference(_)
        | SignatureToken::MutableReference(_) => (false, None),
    }
}

fn resolved_to_struct(resolved_type: (&AccountAddress, &IdentStr, &IdentStr)) -> StructTag {
    StructTag {
        address: *resolved_type.0,
        module: resolved_type.1.into(),
        name: resolved_type.2.into(),
        type_params: vec![],
    }
}

fn resolve_object_arg(idx: usize, arg: &JsonValue) -> Result<ObjectID, anyhow::Error> {
    // Every elem has to be a string convertible to a ObjectID
    match arg {
        JsonValue::String(s) => {
            let s = s.trim().to_lowercase();
            if !s.starts_with(HEX_PREFIX) {
                bail!("ObjectID hex string must start with 0x.",);
            }
            Ok(ObjectID::from_hex_literal(&s)?)
        }
        _ => bail!(
            "Unable to parse arg {:?} as ObjectID at pos {}. Expected {:?}-byte hex string \
                prefixed with 0x.",
            arg,
            idx,
            ObjectID::LENGTH,
        ),
    }
}

fn resolve_object_vec_arg(idx: usize, arg: &IotaJsonValue) -> Result<Vec<ObjectID>, anyhow::Error> {
    // Every elem has to be a string convertible to a ObjectID
    match arg.to_json_value() {
        JsonValue::Array(a) => {
            let mut object_ids = vec![];
            for id in a {
                object_ids.push(resolve_object_arg(idx, &id)?);
            }
            Ok(object_ids)
        }
        JsonValue::String(s) if s.starts_with('[') && s.ends_with(']') => {
            // Due to how escaping of square bracket works, we may be dealing with a JSON
            // string representing a JSON array rather than with the array
            // itself ("[0x42,0x7]" rather than [0x42,0x7]).
            let mut object_ids = vec![];
            for tok in s[1..s.len() - 1].split(',') {
                let id = JsonValue::String(tok.to_string());
                object_ids.push(resolve_object_arg(idx, &id)?);
            }
            Ok(object_ids)
        }
        _ => bail!(
            "Unable to parse arg {:?} as vector of ObjectIDs at pos {}. \
             Expected a vector of {:?}-byte hex strings prefixed with 0x.\n\
             Consider escaping your curly braces with a backslash (as in \\[0x42,0x7\\]) \
             or enclosing the whole vector in single quotes (as in '[0x42,0x7]')",
            arg.to_json_value(),
            idx,
            ObjectID::LENGTH,
        ),
    }
}

fn resolve_call_arg(
    view: &CompiledModule,
    type_args: &[TypeTag],
    idx: usize,
    arg: &IotaJsonValue,
    param: &SignatureToken,
) -> Result<ResolvedCallArg, anyhow::Error> {
    let (is_primitive, layout_opt) = primitive_type(view, type_args, param);
    if is_primitive {
        match layout_opt {
            Some(layout) => {
                return Ok(ResolvedCallArg::Pure(arg.to_bcs_bytes(&layout).map_err(
                    |e| {
                        anyhow!(
                        "Could not serialize argument of type {:?} at {} into {}. Got error: {:?}",
                        param,
                        idx,
                        layout,
                        e
                    )
                    },
                )?));
            }
            None => {
                debug_assert!(
                    false,
                    "Should be unreachable. All primitive type function args \
                     should have a corresponding MoveLayout"
                );
                bail!(
                    "Could not serialize argument of type {:?} at {}",
                    param,
                    idx
                );
            }
        }
    }

    // in terms of non-primitives we only currently support objects and "flat"
    // (depth == 1) vectors of objects (but not, for example, vectors of
    // references)
    match param {
        SignatureToken::Datatype(_)
        | SignatureToken::DatatypeInstantiation(_)
        | SignatureToken::TypeParameter(_)
        | SignatureToken::Reference(_)
        | SignatureToken::MutableReference(_) => Ok(ResolvedCallArg::Object(resolve_object_arg(
            idx,
            &arg.to_json_value(),
        )?)),
        SignatureToken::Vector(inner) => match &**inner {
            SignatureToken::Datatype(_) | SignatureToken::DatatypeInstantiation(_) => {
                Ok(ResolvedCallArg::ObjVec(resolve_object_vec_arg(idx, arg)?))
            }
            _ => {
                bail!(
                    "Unexpected non-primitive vector arg {:?} at {} with value {:?}",
                    param,
                    idx,
                    arg
                );
            }
        },
        _ => bail!(
            "Unexpected non-primitive arg {:?} at {} with value {:?}",
            param,
            idx,
            arg
        ),
    }
}

pub fn is_receiving_argument(view: &CompiledModule, arg_type: &SignatureToken) -> bool {
    use SignatureToken as ST;

    // Progress down into references to determine if the underlying type is a
    // receiving type or not.
    let mut token = arg_type;
    while let ST::Reference(inner) | ST::MutableReference(inner) = token {
        token = inner;
    }

    matches!(
        token,
        ST::DatatypeInstantiation(inst) if resolve_struct(view, inst.0) == RESOLVED_RECEIVING_STRUCT && inst.1.len() == 1
    )
}

fn resolve_call_args(
    view: &CompiledModule,
    type_args: &[TypeTag],
    json_args: &[IotaJsonValue],
    parameter_types: &[SignatureToken],
) -> Result<Vec<ResolvedCallArg>, anyhow::Error> {
    json_args
        .iter()
        .zip(parameter_types)
        .enumerate()
        .map(|(idx, (arg, param))| resolve_call_arg(view, type_args, idx, arg, param))
        .collect()
}

/// Resolve the JSON args of a function into the expected formats to make them
/// usable by Move call This is because we have special types which we need to
/// specify in other formats
pub fn resolve_move_function_args(
    package: &MovePackage,
    module_ident: Identifier,
    function: Identifier,
    type_args: &[TypeTag],
    combined_args_json: Vec<IotaJsonValue>,
) -> Result<Vec<(ResolvedCallArg, SignatureToken)>, anyhow::Error> {
    // Extract the expected function signature
    let module = package.deserialize_module(&module_ident, &BinaryConfig::standard())?;
    let function_str = function.as_ident_str();
    let fdef = module
        .function_defs
        .iter()
        .find(|fdef| {
            module.identifier_at(module.function_handle_at(fdef.function).name) == function_str
        })
        .ok_or_else(|| {
            anyhow!(
                "Could not resolve function {} in module {}",
                function,
                module_ident
            )
        })?;
    let function_signature = module.function_handle_at(fdef.function);
    let parameters = &module.signature_at(function_signature.parameters).0;

    // Lengths have to match, less one, due to TxContext
    let expected_len = match parameters.last() {
        Some(param) if TxContext::kind(&module, param) != TxContextKind::None => {
            parameters.len() - 1
        }
        _ => parameters.len(),
    };
    if combined_args_json.len() != expected_len {
        bail!(
            "Expected {} args, found {}",
            expected_len,
            combined_args_json.len()
        );
    }
    // Check that the args are valid and convert to the correct format
    let call_args = resolve_call_args(&module, type_args, &combined_args_json, parameters)?;
    let tupled_call_args = call_args
        .into_iter()
        .zip(parameters.iter())
        .map(|(arg, expected_type)| (arg, expected_type.clone()))
        .collect::<Vec<_>>();
    Ok(tupled_call_args)
}

fn convert_string_to_u256(s: &str) -> Result<U256, anyhow::Error> {
    // Try as normal number
    if let Ok(v) = s.parse::<U256>() {
        return Ok(v);
    }

    // Check prefix
    // For now only Hex supported
    // TODO: add support for bin and octal?

    let s = s.trim().to_lowercase();
    if !s.starts_with(HEX_PREFIX) {
        bail!("Unable to convert {s} to unsigned int.",);
    }
    U256::from_str_radix(s.trim_start_matches(HEX_PREFIX), 16).map_err(|e| e.into())
}

#[macro_export]
macro_rules! call_args {
        ($($value:expr),*) => {
        Ok::<_, anyhow::Error>(vec![$(iota_json::call_arg!($value)?,)*])
    };
    }

#[macro_export]
macro_rules! call_arg {
    ($value:expr) => {{
        use iota_json::IotaJsonValue;
        trait IotaJsonArg {
            fn to_iota_json(&self) -> anyhow::Result<IotaJsonValue>;
        }
        // TODO: anyway to condense this?
        impl IotaJsonArg for &str {
            fn to_iota_json(&self) -> anyhow::Result<IotaJsonValue> {
                IotaJsonValue::from_str(self)
            }
        }
        impl IotaJsonArg for String {
            fn to_iota_json(&self) -> anyhow::Result<IotaJsonValue> {
                IotaJsonValue::from_str(&self)
            }
        }
        impl IotaJsonArg for iota_types::base_types::ObjectID {
            fn to_iota_json(&self) -> anyhow::Result<IotaJsonValue> {
                IotaJsonValue::from_str(&self.to_string())
            }
        }
        impl IotaJsonArg for iota_types::base_types::IotaAddress {
            fn to_iota_json(&self) -> anyhow::Result<IotaJsonValue> {
                IotaJsonValue::from_str(&self.to_string())
            }
        }
        impl IotaJsonArg for u64 {
            fn to_iota_json(&self) -> anyhow::Result<IotaJsonValue> {
                IotaJsonValue::from_bcs_bytes(
                    Some(&iota_json::MoveTypeLayout::U64),
                    &bcs::to_bytes(self)?,
                )
            }
        }
        impl IotaJsonArg for Vec<u8> {
            fn to_iota_json(&self) -> anyhow::Result<IotaJsonValue> {
                IotaJsonValue::from_bcs_bytes(None, &self)
            }
        }
        impl IotaJsonArg for &[u8] {
            fn to_iota_json(&self) -> anyhow::Result<IotaJsonValue> {
                IotaJsonValue::from_bcs_bytes(None, self)
            }
        }
        $value.to_iota_json()
    }};
}

#[macro_export]
macro_rules! type_args {
    ($($value:expr), *) => {{
        use iota_json_rpc_types::IotaTypeTag;
        use iota_types::TypeTag;
        trait IotaJsonTypeArg {
            fn to_iota_json(&self) -> anyhow::Result<IotaTypeTag>;
        }
        impl <T: core::fmt::Display> IotaJsonTypeArg for T {
            fn to_iota_json(&self) -> anyhow::Result<IotaTypeTag> {
                Ok(iota_types::parse_iota_type_tag(&self.to_string())?.into())
            }
        }
        Ok::<_, anyhow::Error>(vec![$($value.to_iota_json()?,)*])
    }};
    }