ink_codegen/generator/sol/
metadata.rs

1// Copyright (C) ink! contributors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use derive_more::From;
16use ir::{
17    Callable as _,
18    InputsIter,
19};
20use proc_macro2::TokenStream as TokenStream2;
21use quote::quote;
22use syn::Pat;
23
24use super::utils::{
25    extract_docs,
26    sol_return_type,
27    sol_type,
28};
29use crate::GenerateCode;
30
31/// Generates code for generating Solidity ABI compatibility metadata for the contract.
32#[derive(From)]
33pub struct SolidityMetadata<'a> {
34    /// The contract to generate code for.
35    contract: &'a ir::Contract,
36}
37impl_as_ref_for_generator!(SolidityMetadata);
38
39impl GenerateCode for SolidityMetadata<'_> {
40    fn generate_code(&self) -> TokenStream2 {
41        let ident = self.contract.module().storage().ident();
42        let name = ident.to_string();
43        let ctors = self.constructors();
44        let msgs = self.messages();
45        let docs = extract_docs(self.contract.module().attrs());
46
47        quote! {
48            #[cfg(feature = "std")]
49            #[cfg(not(feature = "ink-as-dependency"))]
50            #[cfg(any(ink_abi = "sol", ink_abi = "all"))]
51            const _: () = {
52                #[no_mangle]
53                pub fn __ink_generate_solidity_metadata() -> ::ink::metadata::sol::ContractMetadata  {
54                    ::ink::metadata::sol::ContractMetadata {
55                        name: #name.into(),
56                        constructors: vec![ #( #ctors ),* ],
57                        functions: vec![ #( #msgs ),* ],
58                        events: ::ink::collect_events_sol(),
59                        docs: #docs.into(),
60                    }
61                }
62            };
63        }
64    }
65}
66
67impl SolidityMetadata<'_> {
68    /// Generates Solidity ABI compatible metadata for all ink! constructors.
69    fn constructors(&self) -> impl Iterator<Item = TokenStream2> + '_ {
70        self.contract
71            .module()
72            .impls()
73            .flat_map(|item_impl| item_impl.iter_constructors())
74            .map(|ctor| {
75                let name = ctor
76                    .name()
77                    .map(ToString::to_string)
78                    .unwrap_or_else(|| ctor.ident().to_string());
79                let inputs = params_info(ctor.inputs());
80                let is_payable = ctor.is_payable();
81                let is_default = ctor.is_default();
82                let docs = extract_docs(ctor.attrs());
83
84                quote! {
85                    ::ink::metadata::sol::ConstructorMetadata {
86                        name: #name.into(),
87                        inputs: vec![ #( #inputs ),* ],
88                        is_payable: #is_payable,
89                        is_default: #is_default,
90                        docs: #docs.into(),
91                    }
92                }
93            })
94    }
95
96    /// Generates Solidity ABI compatible metadata for all ink! messages.
97    fn messages(&self) -> impl Iterator<Item = TokenStream2> + '_ {
98        self.contract
99            .module()
100            .impls()
101            .flat_map(|item_impl| item_impl.iter_messages())
102            .map(|msg| {
103                let name = msg
104                    .name()
105                    .map(ToString::to_string)
106                    .unwrap_or_else(|| msg.ident().to_string());
107                let inputs = params_info(msg.inputs());
108                let output = msg
109                    .output()
110                    .map(|ty| {
111                        let sol_ty = sol_return_type(ty);
112                        quote! { ::core::option::Option::Some(#sol_ty.into()) }
113                    })
114                    .unwrap_or_else(|| {
115                        quote! { ::core::option::Option::None }
116                    });
117                let mutates = msg.receiver().is_ref_mut();
118                let is_payable = msg.is_payable();
119                let is_default = msg.is_default();
120                let docs = extract_docs(msg.attrs());
121
122                quote! {
123                    ::ink::metadata::sol::FunctionMetadata {
124                        name: #name.into(),
125                        inputs: vec![ #( #inputs ),* ],
126                        output: #output,
127                        mutates: #mutates,
128                        is_payable: #is_payable,
129                        is_default: #is_default,
130                        docs: #docs.into(),
131                    }
132                }
133            })
134    }
135}
136
137/// Returns the Solidity ABI compatible parameter type and name for the given inputs.
138fn params_info(inputs: InputsIter) -> impl Iterator<Item = TokenStream2> + '_ {
139    inputs.map(|input| {
140        let ty = &*input.ty;
141        let sol_ty = sol_type(ty);
142        let ident = match &*input.pat {
143            Pat::Ident(ident) => &ident.ident,
144            _ => unreachable!("Expected an input identifier"),
145        };
146        let name = ident.to_string();
147        quote! {
148            ::ink::metadata::sol::ParamMetadata {
149                name: #name.into(),
150                ty: #sol_ty.into(),
151            }
152        }
153    })
154}