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 ident = ctor.ident();
76                let name = ident.to_string();
77                let inputs = params_info(ctor.inputs());
78                let is_payable = ctor.is_payable();
79                let is_default = ctor.is_default();
80                let docs = extract_docs(ctor.attrs());
81
82                quote! {
83                    ::ink::metadata::sol::ConstructorMetadata {
84                        name: #name.into(),
85                        inputs: vec![ #( #inputs ),* ],
86                        is_payable: #is_payable,
87                        is_default: #is_default,
88                        docs: #docs.into(),
89                    }
90                }
91            })
92    }
93
94    /// Generates Solidity ABI compatible metadata for all ink! messages.
95    fn messages(&self) -> impl Iterator<Item = TokenStream2> + '_ {
96        self.contract
97            .module()
98            .impls()
99            .flat_map(|item_impl| item_impl.iter_messages())
100            .map(|msg| {
101                let ident = msg.ident();
102                let name = ident.to_string();
103                let inputs = params_info(msg.inputs());
104                let output = msg
105                    .output()
106                    .map(|ty| {
107                        let sol_ty = sol_return_type(ty);
108                        quote! { ::core::option::Option::Some(#sol_ty.into()) }
109                    })
110                    .unwrap_or_else(|| {
111                        quote! { ::core::option::Option::None }
112                    });
113                let mutates = msg.receiver().is_ref_mut();
114                let is_payable = msg.is_payable();
115                let is_default = msg.is_default();
116                let docs = extract_docs(msg.attrs());
117
118                quote! {
119                    ::ink::metadata::sol::FunctionMetadata {
120                        name: #name.into(),
121                        inputs: vec![ #( #inputs ),* ],
122                        output: #output,
123                        mutates: #mutates,
124                        is_payable: #is_payable,
125                        is_default: #is_default,
126                        docs: #docs.into(),
127                    }
128                }
129            })
130    }
131}
132
133/// Returns the Solidity ABI compatible parameter type and name for the given inputs.
134fn params_info(inputs: InputsIter) -> impl Iterator<Item = TokenStream2> + '_ {
135    inputs.map(|input| {
136        let ty = &*input.ty;
137        let sol_ty = sol_type(ty);
138        let ident = match &*input.pat {
139            Pat::Ident(ident) => &ident.ident,
140            _ => unreachable!("Expected an input identifier"),
141        };
142        let name = ident.to_string();
143        quote! {
144            ::ink::metadata::sol::ParamMetadata {
145                name: #name.into(),
146                ty: #sol_ty.into(),
147            }
148        }
149    })
150}