ethers_abi/param_type/
writer.rs1#[cfg(not(feature = "std"))]
10use crate::no_std_prelude::*;
11use crate::ParamType;
12
13pub struct Writer;
15
16impl Writer {
17 pub fn write(param: &ParamType) -> String {
19 Writer::write_for_abi(param, true)
20 }
21
22 pub fn write_for_abi(param: &ParamType, serialize_tuple_contents: bool) -> String {
26 match *param {
27 ParamType::Address => "address".to_owned(),
28 ParamType::Bytes => "bytes".to_owned(),
29 ParamType::FixedBytes(len) => format!("bytes{len}"),
30 ParamType::Int(len) => format!("int{len}"),
31 ParamType::Uint(len) => format!("uint{len}"),
32 ParamType::Bool => "bool".to_owned(),
33 ParamType::String => "string".to_owned(),
34 ParamType::FixedArray(ref param, len) => {
35 format!("{}[{len}]", Writer::write_for_abi(param, serialize_tuple_contents))
36 }
37 ParamType::Array(ref param) => {
38 format!("{}[]", Writer::write_for_abi(param, serialize_tuple_contents))
39 }
40 ParamType::Tuple(ref params) => {
41 if serialize_tuple_contents {
42 let formatted = params
43 .iter()
44 .map(|t| Writer::write_for_abi(t, serialize_tuple_contents))
45 .collect::<Vec<String>>()
46 .join(",");
47 format!("({formatted})")
48 } else {
49 "tuple".to_owned()
50 }
51 }
52 }
53 }
54}
55
56#[cfg(test)]
57mod tests {
58 use super::Writer;
59 #[cfg(not(feature = "std"))]
60 use crate::no_std_prelude::*;
61 use crate::ParamType;
62
63 #[test]
64 fn test_write_param() {
65 assert_eq!(Writer::write(&ParamType::Address), "address".to_owned());
66 assert_eq!(Writer::write(&ParamType::Bytes), "bytes".to_owned());
67 assert_eq!(Writer::write(&ParamType::FixedBytes(32)), "bytes32".to_owned());
68 assert_eq!(Writer::write(&ParamType::Uint(256)), "uint256".to_owned());
69 assert_eq!(Writer::write(&ParamType::Int(64)), "int64".to_owned());
70 assert_eq!(Writer::write(&ParamType::Bool), "bool".to_owned());
71 assert_eq!(Writer::write(&ParamType::String), "string".to_owned());
72 assert_eq!(Writer::write(&ParamType::Array(Box::new(ParamType::Bool))), "bool[]".to_owned());
73 assert_eq!(Writer::write(&ParamType::FixedArray(Box::new(ParamType::String), 2)), "string[2]".to_owned());
74 assert_eq!(
75 Writer::write(&ParamType::FixedArray(Box::new(ParamType::Array(Box::new(ParamType::Bool))), 2)),
76 "bool[][2]".to_owned()
77 );
78 assert_eq!(
79 Writer::write(&ParamType::Array(Box::new(ParamType::Tuple(vec![
80 ParamType::Array(Box::new(ParamType::Tuple(vec![ParamType::Int(256), ParamType::Uint(256)]))),
81 ParamType::FixedBytes(32),
82 ])))),
83 "((int256,uint256)[],bytes32)[]".to_owned()
84 );
85
86 assert_eq!(
87 Writer::write_for_abi(
88 &ParamType::Array(Box::new(ParamType::Tuple(vec![
89 ParamType::Array(Box::new(ParamType::Int(256))),
90 ParamType::FixedBytes(32),
91 ]))),
92 false
93 ),
94 "tuple[]".to_owned()
95 );
96 }
97}