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
use crate::{param::Param, utils::*, EventParam, StateMutability};
use alloc::{borrow::Cow, string::String, vec::Vec};
use alloy_primitives::{keccak256, Selector, B256};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

// Serde order:
// Public items -> public enum -> private enum -> private items
//
// Items are duplicated to be able to make use of the derived `serde` impl,
// while enforcing that the public items emit their tag, as per the spec.
//
// They are all declared with `repr(C)` because the default repr (`Rust`) does
// not have any layout guarantees, which we need to be able to transmute between
// the private and public types.
macro_rules! abi_items {
    ($(
        $(#[$attr:meta])*
        $vis:vis struct $name:ident {$(
            $(#[$fattr:meta])*
            $fvis:vis $field:ident : $type:ty,
        )*}
    )*) => {
        $(
            $(#[$attr])*
            #[derive(Clone, Debug, PartialEq, Eq, Hash)]
            #[repr(C)]
            $vis struct $name {$(
                $(#[$fattr])*
                $fvis $field: $type,
            )*}

            impl From<$name> for AbiItem<'_> {
                #[inline]
                fn from(item: $name) -> Self {
                    AbiItem::$name(Cow::Owned(item))
                }
            }

            impl<'a> From<&'a $name> for AbiItem<'a> {
                #[inline]
                fn from(item: &'a $name) -> Self {
                    AbiItem::$name(Cow::Borrowed(item))
                }
            }

            impl<'de> Deserialize<'de> for $name {
                #[inline]
                fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
                    AbiItem::deserialize(deserializer).and_then(|item| {
                        if let Some(name) = item.name() {
                            validate_identifier!(name);
                        };
                        match item {
                            AbiItem::$name(item) => Ok(item.into_owned()),
                            item => Err(serde::de::Error::invalid_type(
                                serde::de::Unexpected::Other(item.debug_name()),
                                &stringify!($name),
                            )),
                        }
                    })
                }
            }

            impl Serialize for $name {
                #[inline]
                fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                    AbiItem::$name(Cow::Borrowed(self)).serialize(serializer)
                }
            }
        )*

        /// A JSON ABI item.
        #[derive(Clone, Debug, PartialEq, Eq, Hash)]
        #[repr(C)]
        pub enum AbiItem<'a> {$(
            #[doc = concat!("A JSON ABI [`", stringify!($name), "`].")]
            $name(Cow<'a, $name>),
        )*}

        #[doc(hidden)]
        mod private {
            use super::*;

            $(
                #[derive(Clone, Serialize, Deserialize)]
                #[serde(rename_all = "camelCase")]
                #[repr(C)]
                pub(super) struct $name {$(
                    $field: $type,
                )*}
            )*

            #[derive(Serialize, Deserialize)]
            #[serde(rename_all = "lowercase", tag = "type")]
            #[repr(C)]
            pub(super) enum AbiItem<'a> {$(
                $name(Cow<'a, self::$name>),
            )*}
        }
    };
}

abi_items! {
    /// A JSON ABI constructor function.
    pub struct Constructor {
        /// The input types of the constructor. May be empty.
        pub inputs: Vec<Param>,
        /// The state mutability of the constructor.
        pub state_mutability: StateMutability,
    }

    /// A JSON ABI fallback function.
    #[derive(Copy)]
    pub struct Fallback {
        /// The state mutability of the fallback function.
        pub state_mutability: StateMutability,
    }

    /// A JSON ABI receive function.
    #[derive(Copy)]
    pub struct Receive {
        /// The state mutability of the receive function.
        pub state_mutability: StateMutability,
    }

    /// A JSON ABI function.
    pub struct Function {
        /// The name of the function.
        pub name: String,
        /// The input types of the function. May be empty.
        pub inputs: Vec<Param>,
        /// The output types of the function. May be empty.
        pub outputs: Vec<Param>,
        /// The state mutability of the function.
        pub state_mutability: StateMutability,
    }

    /// A JSON ABI event.
    pub struct Event {
        /// The name of the event.
        pub name: String,
        /// A list of the event's inputs, in order.
        pub inputs: Vec<EventParam>,
        /// Whether the event is anonymous. Anonymous events do not have their
        /// Signature included in the topic 0. Instead, the indexed arguments
        /// are 0-indexed.
        pub anonymous: bool,
    }

    /// A JSON ABI error.
    pub struct Error {
        /// The name of the error.
        pub name: String,
        /// A list of the error's components, in order.
        pub inputs: Vec<Param>,
    }
}

impl Serialize for AbiItem<'_> {
    #[inline]
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        <&private::AbiItem<'_>>::from(self).serialize(serializer)
    }
}

impl<'de: 'a, 'a> Deserialize<'de> for AbiItem<'a> {
    #[inline]
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        private::AbiItem::deserialize(deserializer).map(Into::into)
    }
}

// SAFETY: `AbiItem` and `private::AbiItem` have the exact same variants, and
// all the items use a non-Rust repr.
// This is enforced in the macro.
#[doc(hidden)]
impl<'a> From<private::AbiItem<'a>> for AbiItem<'a> {
    #[inline(always)]
    fn from(item: private::AbiItem<'a>) -> AbiItem<'a> {
        unsafe { core::mem::transmute(item) }
    }
}

#[doc(hidden)]
impl<'a> From<AbiItem<'a>> for private::AbiItem<'a> {
    #[inline(always)]
    fn from(item: AbiItem<'a>) -> private::AbiItem<'a> {
        unsafe { core::mem::transmute(item) }
    }
}

#[doc(hidden)]
impl<'a, 'r> From<&'r private::AbiItem<'a>> for &'r AbiItem<'a> {
    #[inline(always)]
    fn from(item: &'r private::AbiItem<'a>) -> &'r AbiItem<'a> {
        unsafe { core::mem::transmute(item) }
    }
}

#[doc(hidden)]
impl<'a, 'r> From<&'r AbiItem<'a>> for &'r private::AbiItem<'a> {
    #[inline(always)]
    fn from(item: &'r AbiItem<'a>) -> &'r private::AbiItem<'a> {
        unsafe { core::mem::transmute(item) }
    }
}

impl AbiItem<'_> {
    /// Returns the debug name of the item.
    #[inline]
    pub const fn debug_name(&self) -> &'static str {
        match self {
            AbiItem::Constructor(_) => "Constructor",
            AbiItem::Fallback(_) => "Fallback",
            AbiItem::Receive(_) => "Receive",
            AbiItem::Function(_) => "Function",
            AbiItem::Event(_) => "Event",
            AbiItem::Error(_) => "Error",
        }
    }

    /// Returns an immutable reference to the name of the item.
    #[inline]
    pub fn name(&self) -> Option<&String> {
        match self {
            Self::Event(item) => Some(&item.name),
            Self::Error(item) => Some(&item.name),
            Self::Function(item) => Some(&item.name),
            Self::Constructor(_) | Self::Fallback(_) | Self::Receive(_) => None,
        }
    }

    /// Returns a mutable reference to the name of the item.
    ///
    /// Clones the item if it is not already owned.
    #[inline]
    pub fn name_mut(&mut self) -> Option<&mut String> {
        match self {
            Self::Event(item) => Some(&mut item.to_mut().name),
            Self::Error(item) => Some(&mut item.to_mut().name),
            Self::Function(item) => Some(&mut item.to_mut().name),
            Self::Constructor(_) | Self::Fallback(_) | Self::Receive(_) => None,
        }
    }

    /// Returns the state mutability of the item.
    #[inline]
    pub fn state_mutability(&self) -> Option<StateMutability> {
        match self {
            Self::Constructor(item) => Some(item.state_mutability),
            Self::Fallback(item) => Some(item.state_mutability),
            Self::Receive(item) => Some(item.state_mutability),
            Self::Function(item) => Some(item.state_mutability),
            Self::Event(_) | Self::Error(_) => None,
        }
    }

    /// Returns a mutable reference to the state mutability of the item.
    ///
    /// Clones the item if it is not already owned.
    #[inline]
    pub fn state_mutability_mut(&mut self) -> Option<&mut StateMutability> {
        match self {
            Self::Constructor(item) => Some(&mut item.to_mut().state_mutability),
            Self::Fallback(item) => Some(&mut item.to_mut().state_mutability),
            Self::Receive(item) => Some(&mut item.to_mut().state_mutability),
            Self::Function(item) => Some(&mut item.to_mut().state_mutability),
            Self::Event(_) | Self::Error(_) => None,
        }
    }

    /// Returns an immutable reference to the inputs of the item.
    ///
    /// Use [`event_inputs`](Self::event_inputs) for events instead.
    #[inline]
    pub fn inputs(&self) -> Option<&Vec<Param>> {
        match self {
            Self::Error(item) => Some(&item.inputs),
            Self::Constructor(item) => Some(&item.inputs),
            Self::Function(item) => Some(&item.inputs),
            Self::Event(_) | Self::Fallback(_) | Self::Receive(_) => None,
        }
    }

    /// Returns a mutable reference to the inputs of the item.
    ///
    /// Clones the item if it is not already owned.
    ///
    /// Use [`event_inputs`](Self::event_inputs) for events instead.
    #[inline]
    pub fn inputs_mut(&mut self) -> Option<&mut Vec<Param>> {
        match self {
            Self::Error(item) => Some(&mut item.to_mut().inputs),
            Self::Constructor(item) => Some(&mut item.to_mut().inputs),
            Self::Function(item) => Some(&mut item.to_mut().inputs),
            Self::Event(_) | Self::Fallback(_) | Self::Receive(_) => None,
        }
    }

    /// Returns an immutable reference to the event inputs of the item.
    ///
    /// Use [`inputs`](Self::inputs) for other items instead.
    #[inline]
    pub fn event_inputs(&self) -> Option<&Vec<EventParam>> {
        match self {
            Self::Event(item) => Some(&item.inputs),
            Self::Constructor(_)
            | Self::Fallback(_)
            | Self::Receive(_)
            | Self::Error(_)
            | Self::Function(_) => None,
        }
    }

    /// Returns a mutable reference to the event inputs of the item.
    ///
    /// Clones the item if it is not already owned.
    ///
    /// Use [`inputs`](Self::inputs) for other items instead.
    #[inline]
    pub fn event_inputs_mut(&mut self) -> Option<&mut Vec<EventParam>> {
        match self {
            Self::Event(item) => Some(&mut item.to_mut().inputs),
            Self::Constructor(_)
            | Self::Fallback(_)
            | Self::Receive(_)
            | Self::Error(_)
            | Self::Function(_) => None,
        }
    }

    /// Returns an immutable reference to the outputs of the item.
    #[inline]
    pub fn outputs(&self) -> Option<&Vec<Param>> {
        match self {
            Self::Function(item) => Some(&item.outputs),
            Self::Constructor(_)
            | Self::Fallback(_)
            | Self::Receive(_)
            | Self::Error(_)
            | Self::Event(_) => None,
        }
    }

    /// Returns an immutable reference to the outputs of the item.
    #[inline]
    pub fn outputs_mut(&mut self) -> Option<&mut Vec<Param>> {
        match self {
            Self::Function(item) => Some(&mut item.to_mut().outputs),
            Self::Constructor(_)
            | Self::Fallback(_)
            | Self::Receive(_)
            | Self::Error(_)
            | Self::Event(_) => None,
        }
    }
}

impl Error {
    /// Computes this error's signature: `$name($($inputs),*)`.
    ///
    /// This is the preimage input used to [compute the
    /// selector](Self::selector).
    #[inline]
    pub fn signature(&self) -> String {
        signature(&self.name, &self.inputs, None)
    }

    /// Computes this error's selector: `keccak256(self.signature())[..4]`
    #[inline]
    pub fn selector(&self) -> Selector {
        selector(&self.signature())
    }
}

impl Function {
    /// Returns this function's signature: `$name($($inputs),*)`.
    ///
    /// This is the preimage input used to [compute the
    /// selector](Self::selector).
    #[inline]
    pub fn signature(&self) -> String {
        signature(&self.name, &self.inputs, None)
    }

    /// Returns this function's full signature:
    /// `$name($($inputs),*)($(outputs),*)`.
    ///
    /// This is the same as [`signature`](Self::signature), but also includes
    /// the output types.
    #[inline]
    pub fn signature_full(&self) -> String {
        signature(&self.name, &self.inputs, Some(&self.outputs))
    }

    /// Computes this error's selector: `keccak256(self.signature())[..4]`
    #[inline]
    pub fn selector(&self) -> Selector {
        selector(&self.signature())
    }
}

impl Event {
    /// Returns this event's signature: `$name($($inputs),*)`.
    ///
    /// This is the preimage input used to [compute the
    /// selector](Self::selector).
    #[inline]
    pub fn signature(&self) -> String {
        event_signature(&self.name, &self.inputs)
    }

    /// Computes this event's selector: `keccak256(self.signature())`
    #[inline]
    pub fn selector(&self) -> B256 {
        keccak256(self.signature().as_bytes())
    }
}