ethers_core/abi/
raw.rs

1//! This is a basic representation of a contract ABI that does no post processing but contains the
2//! raw content of the ABI.
3
4#![allow(missing_docs)]
5use crate::types::Bytes;
6use serde::{
7    de::{MapAccess, SeqAccess, Visitor},
8    Deserialize, Deserializer, Serialize,
9};
10
11/// Contract ABI as a list of items where each item can be a function, constructor or event
12#[derive(Debug, Clone, Serialize)]
13#[serde(transparent)]
14pub struct RawAbi(Vec<Item>);
15
16impl IntoIterator for RawAbi {
17    type Item = Item;
18    type IntoIter = std::vec::IntoIter<Self::Item>;
19
20    #[inline]
21    fn into_iter(self) -> Self::IntoIter {
22        self.0.into_iter()
23    }
24}
25
26struct RawAbiVisitor;
27
28impl<'de> Visitor<'de> for RawAbiVisitor {
29    type Value = RawAbi;
30
31    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
32        formatter.write_str("a sequence or map with `abi` key")
33    }
34
35    fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
36    where
37        A: SeqAccess<'de>,
38    {
39        let mut vec = Vec::new();
40
41        while let Some(element) = seq.next_element()? {
42            vec.push(element);
43        }
44
45        Ok(RawAbi(vec))
46    }
47
48    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
49    where
50        A: MapAccess<'de>,
51    {
52        let mut vec = None;
53
54        while let Some(key) = map.next_key::<String>()? {
55            if key == "abi" {
56                vec = Some(RawAbi(map.next_value::<Vec<Item>>()?));
57            } else {
58                map.next_value::<serde::de::IgnoredAny>()?;
59            }
60        }
61
62        vec.ok_or_else(|| serde::de::Error::missing_field("abi"))
63    }
64}
65
66impl<'de> Deserialize<'de> for RawAbi {
67    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
68    where
69        D: Deserializer<'de>,
70    {
71        deserializer.deserialize_any(RawAbiVisitor)
72    }
73}
74
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
76#[serde(rename_all = "camelCase")]
77pub struct Item {
78    #[serde(default)]
79    pub inputs: Vec<Component>,
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub state_mutability: Option<String>,
82    #[serde(rename = "type")]
83    pub type_field: String,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub name: Option<String>,
86    #[serde(default)]
87    pub outputs: Vec<Component>,
88    // required to satisfy solidity events
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub anonymous: Option<bool>,
91}
92
93/// Either an input/output or a nested component of an input/output
94#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
95pub struct Component {
96    #[serde(rename = "internalType", default, skip_serializing_if = "Option::is_none")]
97    pub internal_type: Option<String>,
98    #[serde(default)]
99    pub name: String,
100    #[serde(rename = "type")]
101    pub type_field: String,
102    #[serde(default)]
103    pub components: Vec<Component>,
104    /// Indexed flag. for solidity events
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub indexed: Option<bool>,
107}
108
109/// Represents contract ABI input variants
110#[derive(Deserialize)]
111#[serde(untagged)]
112pub enum JsonAbi {
113    /// json object input as `{"abi": [..], "bin": "..."}`
114    Object(AbiObject),
115    /// json array input as `[]`
116    #[serde(deserialize_with = "deserialize_abi_array")]
117    Array(RawAbi),
118}
119
120// === impl JsonAbi ===
121
122impl JsonAbi {
123    /// Returns the bytecode object
124    pub fn bytecode(&self) -> Option<Bytes> {
125        match self {
126            JsonAbi::Object(abi) => abi.bytecode.clone(),
127            JsonAbi::Array(_) => None,
128        }
129    }
130
131    /// Returns the deployed bytecode object
132    pub fn deployed_bytecode(&self) -> Option<Bytes> {
133        match self {
134            JsonAbi::Object(abi) => abi.deployed_bytecode.clone(),
135            JsonAbi::Array(_) => None,
136        }
137    }
138}
139
140fn deserialize_abi_array<'de, D>(deserializer: D) -> Result<RawAbi, D::Error>
141where
142    D: Deserializer<'de>,
143{
144    deserializer.deserialize_seq(RawAbiVisitor)
145}
146
147/// Contract ABI and optional bytecode as JSON object
148pub struct AbiObject {
149    pub abi: RawAbi,
150    pub bytecode: Option<Bytes>,
151    pub deployed_bytecode: Option<Bytes>,
152}
153
154struct AbiObjectVisitor;
155
156impl<'de> Visitor<'de> for AbiObjectVisitor {
157    type Value = AbiObject;
158
159    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
160        formatter.write_str("a sequence or map with `abi` key")
161    }
162
163    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
164    where
165        A: MapAccess<'de>,
166    {
167        let mut abi = None;
168        let mut bytecode = None;
169        let mut deployed_bytecode = None;
170
171        #[derive(Deserialize)]
172        #[serde(untagged)]
173        enum Bytecode {
174            Object { object: Bytes },
175            Bytes(Bytes),
176        }
177
178        impl Bytecode {
179            fn into_bytes(self) -> Option<Bytes> {
180                let bytecode = match self {
181                    Bytecode::Object { object } => object,
182                    Bytecode::Bytes(bytes) => bytes,
183                };
184                if bytecode.is_empty() {
185                    None
186                } else {
187                    Some(bytecode)
188                }
189            }
190        }
191
192        /// represents nested bytecode objects of the `evm` value
193        #[derive(Deserialize)]
194        struct EvmObj {
195            bytecode: Option<Bytecode>,
196            #[serde(rename = "deployedBytecode")]
197            deployed_bytecode: Option<Bytecode>,
198        }
199
200        struct DeserializeBytes(Bytes);
201
202        impl<'de> Deserialize<'de> for DeserializeBytes {
203            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
204            where
205                D: Deserializer<'de>,
206            {
207                Ok(DeserializeBytes(crate::types::deserialize_bytes(deserializer)?.into()))
208            }
209        }
210
211        while let Some(key) = map.next_key::<String>()? {
212            match key.as_str() {
213                "abi" => {
214                    abi = Some(RawAbi(map.next_value::<Vec<Item>>()?));
215                }
216                "evm" => {
217                    if let Ok(evm) = map.next_value::<EvmObj>() {
218                        bytecode = evm.bytecode.and_then(|b| b.into_bytes());
219                        deployed_bytecode = evm.deployed_bytecode.and_then(|b| b.into_bytes())
220                    }
221                }
222                "bytecode" | "byteCode" => {
223                    bytecode = map.next_value::<Bytecode>().ok().and_then(|b| b.into_bytes());
224                }
225                "deployedbytecode" | "deployedBytecode" => {
226                    deployed_bytecode =
227                        map.next_value::<Bytecode>().ok().and_then(|b| b.into_bytes());
228                }
229                "bin" => {
230                    bytecode = map
231                        .next_value::<DeserializeBytes>()
232                        .ok()
233                        .map(|b| b.0)
234                        .filter(|b| !b.0.is_empty());
235                }
236                "runtimebin" | "runtimeBin" => {
237                    deployed_bytecode = map
238                        .next_value::<DeserializeBytes>()
239                        .ok()
240                        .map(|b| b.0)
241                        .filter(|b| !b.0.is_empty());
242                }
243                _ => {
244                    map.next_value::<serde::de::IgnoredAny>()?;
245                }
246            }
247        }
248
249        let abi = abi.ok_or_else(|| serde::de::Error::missing_field("abi"))?;
250        Ok(AbiObject { abi, bytecode, deployed_bytecode })
251    }
252}
253
254impl<'de> Deserialize<'de> for AbiObject {
255    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
256    where
257        D: Deserializer<'de>,
258    {
259        deserializer.deserialize_map(AbiObjectVisitor)
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use crate::abi::Abi;
267
268    fn assert_has_bytecode(s: &str) {
269        match serde_json::from_str::<JsonAbi>(s).unwrap() {
270            JsonAbi::Object(abi) => {
271                assert!(abi.bytecode.is_some());
272            }
273            _ => {
274                panic!("expected abi object")
275            }
276        }
277    }
278
279    #[test]
280    fn can_parse_raw_abi() {
281        const VERIFIER_ABI: &str =
282            include_str!("../../../ethers-contract/tests/solidity-contracts/verifier_abi.json");
283        let _ = serde_json::from_str::<RawAbi>(VERIFIER_ABI).unwrap();
284    }
285
286    #[test]
287    fn can_parse_hardhat_raw_abi() {
288        const VERIFIER_ABI: &str = include_str!(
289            "../../../ethers-contract/tests/solidity-contracts/verifier_abi_hardhat.json"
290        );
291        let _ = serde_json::from_str::<RawAbi>(VERIFIER_ABI).unwrap();
292    }
293
294    /// due to ethabi's limitations some may be stripped when ethers-solc generates the abi, such as
295    /// the name of the component
296    #[test]
297    fn can_parse_ethers_solc_generated_abi() {
298        let s = r#"[{"type":"function","name":"greet","inputs":[{"internalType":"struct Greeter.Stuff","name":"stuff","type":"tuple","components":[{"type":"bool"}]}],"outputs":[{"internalType":"struct Greeter.Stuff","name":"","type":"tuple","components":[{"type":"bool"}]}],"stateMutability":"view"}]"#;
299        let _ = serde_json::from_str::<RawAbi>(s).unwrap();
300    }
301
302    #[test]
303    fn can_ethabi_round_trip() {
304        let s = r#"[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint64","name":"number","type":"uint64"}],"name":"MyEvent","type":"event"},{"inputs":[],"name":"greet","outputs":[],"stateMutability":"nonpayable","type":"function"}]"#;
305
306        let raw = serde_json::from_str::<RawAbi>(s).unwrap();
307        let abi = serde_json::from_str::<Abi>(s).unwrap();
308        let de = serde_json::to_string(&raw).unwrap();
309        assert_eq!(abi, serde_json::from_str::<Abi>(&de).unwrap());
310    }
311
312    #[test]
313    fn can_deserialize_abi_object() {
314        let abi_str = r#"[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint64","name":"number","type":"uint64"}],"name":"MyEvent","type":"event"},{"inputs":[],"name":"greet","outputs":[],"stateMutability":"nonpayable","type":"function"}]"#;
315        let abi = serde_json::from_str::<JsonAbi>(abi_str).unwrap();
316        assert!(matches!(abi, JsonAbi::Array(_)));
317
318        let code = "0x608060405234801561001057600080fd5b50610242806100206000396000f3fe608060405234801561001057600080fd5b506004361061002b5760003560e01c80635581701b14610030575b600080fd5b61004a60048036038101906100459190610199565b610060565b60405161005791906101f1565b60405180910390f35b610068610070565b819050919050565b60405180602001604052806000151581525090565b6000604051905090565b600080fd5b600080fd5b6000601f19601f8301169050919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b6100e282610099565b810181811067ffffffffffffffff82111715610101576101006100aa565b5b80604052505050565b6000610114610085565b905061012082826100d9565b919050565b60008115159050919050565b61013a81610125565b811461014557600080fd5b50565b60008135905061015781610131565b92915050565b60006020828403121561017357610172610094565b5b61017d602061010a565b9050600061018d84828501610148565b60008301525092915050565b6000602082840312156101af576101ae61008f565b5b60006101bd8482850161015d565b91505092915050565b6101cf81610125565b82525050565b6020820160008201516101eb60008501826101c6565b50505050565b600060208201905061020660008301846101d5565b9291505056fea2646970667358221220890202b0964477379a457ab3725a21d7c14581e4596552e32a54e23f1c6564e064736f6c634300080c0033";
319        let s = format!(r#"{{"abi": {abi_str}, "bin" : "{code}" }}"#);
320        assert_has_bytecode(&s);
321
322        let s = format!(r#"{{"abi": {abi_str}, "bytecode" : {{ "object": "{code}" }} }}"#);
323        assert_has_bytecode(&s);
324
325        let s = format!(r#"{{"abi": {abi_str}, "bytecode" : "{code}" }}"#);
326        assert_has_bytecode(&s);
327
328        let hh_artifact = include_str!(
329            "../../../ethers-contract/tests/solidity-contracts/verifier_abi_hardhat.json"
330        );
331        match serde_json::from_str::<JsonAbi>(hh_artifact).unwrap() {
332            JsonAbi::Object(abi) => {
333                assert!(abi.bytecode.is_none());
334            }
335            _ => {
336                panic!("expected abi object")
337            }
338        }
339    }
340
341    #[test]
342    fn can_parse_greeter_bytecode() {
343        let artifact =
344            include_str!("../../../ethers-contract/tests/solidity-contracts/greeter.json");
345        assert_has_bytecode(artifact);
346    }
347
348    #[test]
349    fn ignores_empty_bytecode() {
350        let abi_str = r#"[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint64","name":"number","type":"uint64"}],"name":"MyEvent","type":"event"},{"inputs":[],"name":"greet","outputs":[],"stateMutability":"nonpayable","type":"function"}]"#;
351        let s = format!(r#"{{"abi": {abi_str}, "bin" : "0x" }}"#);
352
353        match serde_json::from_str::<JsonAbi>(&s).unwrap() {
354            JsonAbi::Object(abi) => {
355                assert!(abi.bytecode.is_none());
356            }
357            _ => {
358                panic!("expected abi object")
359            }
360        }
361
362        let s = format!(r#"{{"abi": {abi_str}, "bytecode" : {{ "object": "0x" }} }}"#);
363
364        match serde_json::from_str::<JsonAbi>(&s).unwrap() {
365            JsonAbi::Object(abi) => {
366                assert!(abi.bytecode.is_none());
367            }
368            _ => {
369                panic!("expected abi object")
370            }
371        }
372    }
373
374    #[test]
375    fn can_parse_deployed_bytecode() {
376        let artifact = include_str!("../../testdata/solc-obj.json");
377        match serde_json::from_str::<JsonAbi>(artifact).unwrap() {
378            JsonAbi::Object(abi) => {
379                assert!(abi.bytecode.is_some());
380                assert!(abi.deployed_bytecode.is_some());
381            }
382            _ => {
383                panic!("expected abi object")
384            }
385        }
386    }
387}