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                #[unsafe(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                        errors: ::ink::collect_errors_sol(),
60                        docs: #docs.into(),
61                    }
62                }
63            };
64        }
65    }
66}
67
68impl SolidityMetadata<'_> {
69    /// Generates Solidity ABI compatible metadata for all ink! constructors.
70    fn constructors(&self) -> impl Iterator<Item = TokenStream2> + '_ {
71        self.contract
72            .module()
73            .impls()
74            .flat_map(|item_impl| item_impl.iter_constructors())
75            .map(|ctor| {
76                let name = ctor.normalized_name();
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 name = msg.normalized_name();
102                let inputs = params_info(msg.inputs());
103                let output = msg
104                    .output()
105                    .map(|ty| {
106                        let sol_ty = sol_return_type(ty);
107                        quote! { ::core::option::Option::Some(#sol_ty.into()) }
108                    })
109                    .unwrap_or_else(|| {
110                        quote! { ::core::option::Option::None }
111                    });
112                let mutates = msg.receiver().is_ref_mut();
113                let is_payable = msg.is_payable();
114                let is_default = msg.is_default();
115                let docs = extract_docs(msg.attrs());
116
117                quote! {
118                    ::ink::metadata::sol::FunctionMetadata {
119                        name: #name.into(),
120                        inputs: vec![ #( #inputs ),* ],
121                        output: #output,
122                        mutates: #mutates,
123                        is_payable: #is_payable,
124                        is_default: #is_default,
125                        docs: #docs.into(),
126                    }
127                }
128            })
129    }
130}
131
132/// Returns the Solidity ABI compatible parameter type and name for the given inputs.
133fn params_info(inputs: InputsIter<'_>) -> impl Iterator<Item = TokenStream2> + '_ {
134    inputs.map(|input| {
135        let ty = &*input.ty;
136        let sol_ty = sol_type(ty);
137        let ident = match &*input.pat {
138            Pat::Ident(ident) => &ident.ident,
139            _ => unreachable!("Expected an input identifier"),
140        };
141        let name = ident.to_string();
142        quote! {
143            ::ink::metadata::sol::ParamMetadata {
144                name: #name.into(),
145                ty: #sol_ty.into(),
146            }
147        }
148    })
149}