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
//! Solidity ABI abstraction.

use crate::Arg;
use core::{convert::Infallible, fmt, str::FromStr};

#[cfg(not(feature = "std"))]
use crate::std::{String, ToString, Vec};

/// Solidity ABI abstraction.
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Abi {
    /// ABI name.
    pub name: String,
    /// ABI type.
    #[cfg_attr(feature = "serde", serde(rename = "type"))]
    pub ty: Type,
    /// An array of arguments.
    pub inputs: Vec<Arg>,
    /// An array of arguments, similar to inputs.
    pub outputs: Vec<Arg>,
}

#[cfg(feature = "syn")]
impl From<&syn::Signature> for Abi {
    fn from(sig: &syn::Signature) -> Self {
        let inputs = sig
            .inputs
            .iter()
            .filter_map(|arg| {
                if let syn::FnArg::Typed(syn::PatType { ty, .. }) = arg {
                    Some(Arg {
                        name: sig.ident.to_string(),
                        ty: crate::Param::from(ty),
                    })
                } else {
                    None
                }
            })
            .collect();

        let outputs = if let syn::ReturnType::Type(_, ty) = &sig.output {
            vec![Arg {
                name: sig.ident.to_string(),
                ty: crate::Param::from(ty),
            }]
        } else {
            vec![]
        };

        let name = sig.ident.to_string();
        Abi {
            ty: Type::from(name.as_str()),
            name,
            inputs,
            outputs,
        }
    }
}

/// Solidity ABI type.
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
pub enum Type {
    /// Constructor ABI.
    Constructor,
    /// Function ABI.
    #[default]
    Function,
}

impl From<&str> for Type {
    fn from(s: &str) -> Self {
        match s {
            "constructor" => Type::Constructor,
            _ => Type::Function,
        }
    }
}

impl FromStr for Type {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::from(s))
    }
}

impl AsRef<str> for Type {
    fn as_ref(&self) -> &str {
        match self {
            Type::Constructor => "constructor",
            Type::Function => "function",
        }
    }
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let ty: &str = self.as_ref();
        write!(f, "{ty}")
    }
}