cross_calling.rs 31.1 KB
Newer Older
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
// Copyright 2018-2020 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::GenerateCode;
use derive_more::From;
use heck::CamelCase as _;
use ir::Callable;
use itertools::Itertools as _;
use proc_macro2::{
    Ident,
    TokenStream as TokenStream2,
};
use quote::{
    format_ident,
    quote,
    quote_spanned,
};
use syn::spanned::Spanned as _;

/// Generates `#[cfg(..)]` code to guard against compilation under `ink-as-dependency`.
#[derive(From)]
pub struct CrossCallingConflictCfg<'a> {
    contract: &'a ir::Contract,
}

impl GenerateCode for CrossCallingConflictCfg<'_> {
    fn generate_code(&self) -> TokenStream2 {
        if self.contract.config().is_compile_as_dependency_enabled() {
            return quote! { #[cfg(feature = "__ink_DO_NOT_COMPILE")] }
        }
        quote! { #[cfg(not(feature = "ink-as-dependency"))] }
    }
}

/// Generates code for using this ink! contract as a dependency.
#[derive(From)]
pub struct CrossCalling<'a> {
    contract: &'a ir::Contract,
}

impl GenerateCode for CrossCalling<'_> {
    fn generate_code(&self) -> TokenStream2 {
        let storage = self.generate_storage();
        let standard_impls = self.generate_standard_impls();
        let call_forwarder = self.generate_call_forwarders();
        let impl_blocks = self.generate_impl_blocks();
        quote! {
            #storage
            #standard_impls
            #call_forwarder
            // #short_hand_impls
            #impl_blocks
        }
    }
}

impl CrossCalling<'_> {
    /// Generates code for conditionally compiling code only if the contract
    /// is compiled as dependency.
    fn generate_cfg(&self) -> Option<TokenStream2> {
        if self.contract.config().is_compile_as_dependency_enabled() {
            return None
        }
        Some(quote! {
            #[cfg(feature = "ink-as-dependency")]
        })
    }

    /// Generates code for the ink! storage struct for cross-calling purposes.
    ///
    /// # Note
    ///
    /// This always consists of a single `AccountId` and can be viewed as a
    /// reference to a live smart contract instance of the same type. It will
    /// forward all calls via ink!'s provided cross-calling infrastructure
    /// automatically over the chain.
    fn generate_storage(&self) -> TokenStream2 {
        let cfg = self.generate_cfg();
        let storage = self.contract.module().storage();
        let span = storage.span();
        let ident = storage.ident();
        let attrs = storage.attrs();
        quote_spanned!(span =>
            #cfg
            #( #attrs )*
            #[derive(
                Clone,
                Debug,
                ::scale::Encode,
                ::scale::Decode,
                ::ink_core::storage2::traits::SpreadLayout,
                ::ink_core::storage2::traits::PackedLayout,
            )]
            #[cfg_attr(
                feature = "std",
                derive(
                    ::scale_info::TypeInfo,
                    ::ink_core::storage2::traits::StorageLayout,
                )
            )]
            pub struct #ident {
                account_id: AccountId,
            }
        )
    }

    /// Generates code for the trait implementations required to make the
    /// generated ink! storage struct for cross-calling work out of the box
    /// for the cross-calling infrastructure.
    fn generate_standard_impls(&self) -> TokenStream2 {
        let cfg = self.generate_cfg();
        let ident = self.contract.module().storage().ident();
        quote! {
            #cfg
            const _: () = {
                impl ::ink_core::env::call::FromAccountId<EnvTypes> for #ident {
                    #[inline]
                    fn from_account_id(account_id: AccountId) -> Self {
                        Self { account_id }
                    }
                }

                impl ::ink_lang::ToAccountId<EnvTypes> for #ident {
                    #[inline]
                    fn to_account_id(&self) -> AccountId {
                        self.account_id
                    }
                }
            };
        }
    }

    /// Builds up the [`ink_core::env::call::ArgumentList`] type structure for the given types.
    fn generate_arg_list<'a, Args>(args: Args) -> TokenStream2
    where
        Args: IntoIterator<Item = &'a syn::Type>,
        <Args as IntoIterator>::IntoIter: DoubleEndedIterator,
    {
        args.into_iter().fold(
            quote! { ::ink_core::env::call::utils::EmptyArgumentList },
            |rest, arg| quote! {
                ::ink_core::env::call::utils::ArgumentList<::ink_core::env::call::utils::Argument<#arg>, #rest>
            }
        )
    }

    /// Returns the identifier for the generated call forwarder utility.
    fn call_forwarder_ident() -> Ident {
        format_ident!("__ink_CallForwarder")
    }

    fn generate_call_forwarder_trait_ghost_message(
        message: ir::CallableWithSelector<ir::Message>,
    ) -> TokenStream2 {
        let span = message.span();
        let ident = message.ident();
        let output_ident = format_ident!("{}Out", ident.to_string().to_camel_case());
        let composed_selector = message.composed_selector().as_bytes().to_owned();
        let linker_error_ident = format_ident!(
            "__ink_enforce_error_for_message_0x{:02X}{:02X}{:02X}{:02X}",
            composed_selector[0],
            composed_selector[1],
            composed_selector[2],
            composed_selector[3]
        );
        let attrs = message.attrs();
        let input_bindings = message
            .inputs()
            .enumerate()
            .map(|(n, _)| format_ident!("__ink_binding_{}", n))
            .collect::<Vec<_>>();
        let input_types = message
            .inputs()
            .map(|pat_type| &*pat_type.ty)
            .collect::<Vec<_>>();
        let output_ty = message
            .output()
            .cloned()
            .unwrap_or_else(|| syn::parse_quote! { () });
        let pub_tok = match message.item_impl().trait_path() {
            Some(_) => None,
            None => Some(quote! { pub }),
        };
        let mut_tok = match message.receiver() {
            ir::Receiver::Ref => None,
            ir::Receiver::RefMut => Some(quote! { mut }),
        };
        quote_spanned!(span=>
            type #output_ident = #output_ty;

            #( #attrs )*
            #[cold]
            #[doc(hidden)]
            #pub_tok fn #ident(
                & #mut_tok self,
                #( #input_bindings : #input_types ),*
            ) -> Self::#output_ident {
                extern {
                    fn #linker_error_ident() -> !;
                }
                unsafe { #linker_error_ident() }
            }
        )
    }

    fn generate_call_forwarder_trait_proper_message(
        message: ir::CallableWithSelector<ir::Message>,
    ) -> TokenStream2 {
        let span = message.span();
        let ident = message.ident();
        let output_ident = format_ident!("{}Out", ident.to_string().to_camel_case());
        let composed_selector = message.composed_selector().as_bytes().to_owned();
        let attrs = message.attrs();
        let input_bindings = message
            .inputs()
            .enumerate()
            .map(|(n, _)| format_ident!("__ink_binding_{}", n))
            .collect::<Vec<_>>();
        let input_types = message
            .inputs()
            .map(|pat_type| &*pat_type.ty)
            .collect::<Vec<_>>();
        let arg_list = Self::generate_arg_list(input_types.iter().cloned());
        let output = message.output();
        let output_sig = output.map_or_else(
            || quote! { () },
            |output| quote! { ::ink_core::env::call::utils::ReturnType<#output> },
        );
        let pub_tok = match message.item_impl().trait_path() {
            Some(_) => None,
            None => Some(quote! { pub }),
        };
        let receiver = match message.receiver() {
            ir::Receiver::Ref => Some(quote! { &self }),
            ir::Receiver::RefMut => Some(quote! { &mut self }),
        };
        quote_spanned!(span=>
            type #output_ident = ::ink_core::env::call::CallBuilder<
                EnvTypes,
                ::ink_core::env::call::utils::Set<AccountId>,
                ::ink_core::env::call::utils::Unset<u64>,
                ::ink_core::env::call::utils::Unset<Balance>,
                ::ink_core::env::call::utils::Set<::ink_core::env::call::ExecutionInput<#arg_list>>,
                ::ink_core::env::call::utils::Set<#output_sig>,
            >;

            #( #attrs )*
            #[inline]
            #pub_tok fn #ident(
                #receiver #(, #input_bindings : #input_types )*
            ) -> Self::#output_ident {
                ::ink_core::env::call::build_call::<EnvTypes>()
                    .callee(::ink_lang::ToAccountId::to_account_id(self.contract))
                    .exec_input(
                        ::ink_core::env::call::ExecutionInput::new(
                            ::ink_core::env::call::Selector::new([ #( #composed_selector ),* ])
                        )
                        #(
                            .push_arg(#input_bindings)
                        )*
                    )
                    .returns::<#output_sig>()
            }
        )
    }

    /// Generates code for a single call forwarder trait message.
    ///
    /// The `mutable` parameter indicates whether only read-only (`false`) or
    /// write-only (`true`) messages shall be valid calls. For non valid messages
    /// an invalid implementation is provided so that actually calling those
    /// will result in a compiler or linker error.
    fn generate_call_forwarder_trait_message(
        mutable: bool,
        message: ir::CallableWithSelector<ir::Message>,
    ) -> TokenStream2 {
        if mutable == message.receiver().is_ref_mut() {
            Self::generate_call_forwarder_trait_proper_message(message)
        } else {
            Self::generate_call_forwarder_trait_ghost_message(message)
        }
    }

    /// Generates code for a single call forwarder trait constructor.
    ///
    /// Note that constructors never need to be forwarded and that we only
    /// provide their implementations to satisfy the implementation block.
    /// We generally try to generate code in a way that actually calling
    /// those constructors will result in a compiler or linker error.
    fn generate_call_forwarder_trait_constructor(
        constructor: ir::CallableWithSelector<ir::Constructor>,
    ) -> TokenStream2 {
        let span = constructor.span();
        let attrs = constructor.attrs();
        let ident = constructor.ident();
        let output_ident = format_ident!("{}Out", ident.to_string().to_camel_case());
        let composed_selector = constructor.composed_selector().as_bytes().to_owned();
        let linker_error_ident = format_ident!(
            "__ink_enforce_error_for_constructor_0x{:02X}{:02X}{:02X}{:02X}",
            composed_selector[0],
            composed_selector[1],
            composed_selector[2],
            composed_selector[3]
        );
        let input_bindings = constructor
            .inputs()
            .enumerate()
            .map(|(n, _)| format_ident!("__ink_binding_{}", n))
            .collect::<Vec<_>>();
        let input_types = constructor
            .inputs()
            .map(|pat_type| &*pat_type.ty)
            .collect::<Vec<_>>();
        quote_spanned!(span =>
            type #output_ident = ::ink_lang::NeverReturns;

            #( #attrs )*
            #[cold]
            #[doc(hidden)]
            fn #ident(
                #( #input_bindings : #input_types ),*
            ) -> Self::#output_ident {
                extern {
                    fn #linker_error_ident() -> !;
                }
                unsafe { #linker_error_ident() }
            }
        )
    }

    /// Generates code for a single call forwarder trait implementation block.
    ///
    /// The `mutable` parameter indicates whether only read-only (`false`) or
    /// write-only (`true`) messages and constructors are to be considered.
    fn generate_call_forwarder_trait_impl_block(
        &self,
        mutable: bool,
        item_impl: &ir::ItemImpl,
    ) -> TokenStream2 {
        assert!(item_impl.trait_path().is_some());
        let span = item_impl.span();
        let attrs = item_impl.attrs();
        let forwarder_ident = Self::call_forwarder_ident();
        let storage_ident = self.contract.module().storage().ident();
        let mut_tok = if mutable { Some(quote! { mut }) } else { None };
        let constructors = item_impl.iter_constructors().map(|constructor| {
            Self::generate_call_forwarder_trait_constructor(constructor)
        });
        let messages = item_impl
            .iter_messages()
            .map(|message| Self::generate_call_forwarder_trait_message(mutable, message));
        let trait_path = item_impl
            .trait_path()
            .expect("encountered missing trait path for trait impl block");
        let trait_ident = item_impl
            .trait_ident()
            .expect("encountered missing trait identifier for trait impl block");
        let hash = ir::InkTrait::compute_verify_hash(
            trait_ident,
            item_impl.iter_constructors().map(|constructor| {
                let ident = constructor.ident().clone();
                let len_inputs = constructor.inputs().count();
                (ident, len_inputs)
            }),
            item_impl.iter_messages().map(|message| {
                let ident = message.ident().clone();
                let len_inputs = message.inputs().count() + 1;
                let is_mut = message.receiver().is_ref_mut();
                (ident, len_inputs, is_mut)
            }),
        );
        let checksum = u32::from_be_bytes([hash[0], hash[1], hash[2], hash[3]]) as usize;
        quote_spanned!(span =>
            unsafe impl<'a> ::ink_lang::CheckedInkTrait<[(); #checksum]> for #forwarder_ident<&'a #mut_tok #storage_ident> {}

            #( #attrs )*
            impl<'a> #trait_path for #forwarder_ident<&'a #mut_tok #storage_ident> {
                type __ink_Checksum = [(); #checksum];

                #( #constructors )*
                #( #messages )*
            }
        )
    }

    fn generate_call_forwarder_inherent_message(
        message: ir::CallableWithSelector<ir::Message>,
    ) -> TokenStream2 {
        let span = message.span();
        let ident = message.ident();
        let composed_selector = message.composed_selector().as_bytes().to_owned();
        let attrs = message.attrs();
        let input_bindings = message
            .inputs()
            .enumerate()
            .map(|(n, _)| format_ident!("__ink_binding_{}", n))
            .collect::<Vec<_>>();
        let input_types = message
            .inputs()
            .map(|pat_type| &*pat_type.ty)
            .collect::<Vec<_>>();
        let arg_list = Self::generate_arg_list(input_types.iter().cloned());
        let output = message.output();
        let output_sig = output.map_or_else(
            || quote! { () },
            |output| quote! { ::ink_core::env::call::utils::ReturnType<#output> },
        );
        let pub_tok = match message.item_impl().trait_path() {
            Some(_) => None,
            None => Some(quote! { pub }),
        };
        quote_spanned!(span=>
            #( #attrs )*
            #[inline]
            #pub_tok fn #ident(
                self,
                #( #input_bindings : #input_types ),*
            ) -> ::ink_core::env::call::CallBuilder<
                EnvTypes,
                ::ink_core::env::call::utils::Set<AccountId>,
                ::ink_core::env::call::utils::Unset<u64>,
                ::ink_core::env::call::utils::Unset<Balance>,
                ::ink_core::env::call::utils::Set<::ink_core::env::call::ExecutionInput<#arg_list>>,
                ::ink_core::env::call::utils::Set<#output_sig>,
            > {
                ::ink_core::env::call::build_call::<EnvTypes>()
                    .callee(::ink_lang::ToAccountId::to_account_id(self.contract))
                    .exec_input(
                        ::ink_core::env::call::ExecutionInput::new(
                            ::ink_core::env::call::Selector::new([ #( #composed_selector ),* ])
                        )
                        #(
                            .push_arg(#input_bindings)
                        )*
                    )
                    .returns::<#output_sig>()
            }
        )
    }

    /// Generates code for a single call forwarder inherent implementation block.
    ///
    /// The `mutable` parameter indicates whether only read-only (`false`) or
    /// write-only (`true`) messages and constructors are to be considered.
    fn generate_call_forwarder_inherent_impl_block(
        &self,
        mutable: bool,
        item_impl: &ir::ItemImpl,
    ) -> TokenStream2 {
        assert!(item_impl.trait_path().is_none());
        let span = item_impl.span();
        let attrs = item_impl.attrs();
        let forwarder_ident = Self::call_forwarder_ident();
        let storage_ident = self.contract.module().storage().ident();
        let mut_tok = if mutable { Some(quote! { mut }) } else { None };
        let messages = item_impl
            .iter_messages()
            .filter(|message| mutable == message.receiver().is_ref_mut())
            .map(Self::generate_call_forwarder_inherent_message);
        quote_spanned!(span =>
            #( #attrs )*
            impl<'a> #forwarder_ident<&'a #mut_tok #storage_ident> {
                #( #messages )*
            }
        )
    }

    /// Generates code for the call forwarder implementation blocks.
    ///
    /// The `mutable` parameter indicates whether only read-only (`false`) or
    /// write-only (`true`) messages and constructors are to be considered.
    fn generate_call_forwarder_impl_blocks(&self, mutable: bool) -> TokenStream2 {
        let impl_blocks = self.contract.module().impls().map(|item_impl| {
            match item_impl.trait_path() {
                Some(_) => {
                    self.generate_call_forwarder_trait_impl_block(mutable, item_impl)
                }
                None => {
                    self.generate_call_forwarder_inherent_impl_block(mutable, item_impl)
                }
            }
        });
        quote! { #( #impl_blocks )* }
    }

    /// Generates code for the call forwarder utility struct.
    fn generate_call_forwarders(&self) -> TokenStream2 {
        let forwarder_ident = Self::call_forwarder_ident();
        let storage_ident = self.contract.module().storage().ident();
        let impl_blocks_ref = self.generate_call_forwarder_impl_blocks(false);
        let impl_blocks_refmut = self.generate_call_forwarder_impl_blocks(true);
        let cfg = self.generate_cfg();
        quote! {
            #cfg
            const _: () = {
                impl<'a> ::ink_lang::ForwardCall for &'a #storage_ident {
                    type Forwarder = #forwarder_ident<&'a #storage_ident>;

                    #[inline]
                    fn call(self) -> Self::Forwarder {
                        #forwarder_ident { contract: self }
                    }
                }

                impl<'a> ::ink_lang::ForwardCallMut for &'a mut #storage_ident {
                    type Forwarder = #forwarder_ident<&'a mut #storage_ident>;

                    #[inline]
                    fn call_mut(self) -> Self::Forwarder {
                        #forwarder_ident { contract: self }
                    }
                }

                // Forwards contract messages to the chain.
                #[doc(hidden)]
                pub struct #forwarder_ident<T> {
                    contract: T,
                }

                #impl_blocks_ref
                #impl_blocks_refmut
            };
        }
    }

    /// Generates the code to allow short-hand cross-chain contract calls for messages.
    fn generate_trait_impl_block_message(
        &self,
        message: ir::CallableWithSelector<ir::Message>,
    ) -> TokenStream2 {
        let storage_ident_str = self.contract.module().storage().ident().to_string();
        let span = message.span();
        let ident = message.ident();
        let output_ident = format_ident!("{}Out", ident.to_string().to_camel_case());
        let ident_str = ident.to_string();
        let trait_path = message
            .item_impl()
            .trait_path()
            .expect("encountered missing trait path for trait impl block")
            .segments
            .iter()
            .map(|path_segment| &path_segment.ident)
            .map(ToString::to_string)
            .join("::");
        let error_str = format!(
            "encountered error while calling <{} as {}>::{}",
            storage_ident_str, trait_path, ident_str
        );
        let inputs_sig = message.inputs();
        let inputs_params = message.inputs().map(|pat_type| &pat_type.pat);
        let output_ty = message
            .output()
            .cloned()
            .unwrap_or_else(|| syn::parse_quote! { () });
        let receiver = message.receiver();
        let forward_ident = match receiver {
            ir::Receiver::Ref => format_ident!("call"),
            ir::Receiver::RefMut => format_ident!("call_mut"),
        };
        let forward_trait = match receiver {
            ir::Receiver::Ref => format_ident!("ForwardCall"),
            ir::Receiver::RefMut => format_ident!("ForwardCallMut"),
        };
        let opt_mut = match receiver {
            ir::Receiver::Ref => None,
            ir::Receiver::RefMut => Some(quote! { mut }),
        };
        let opt_pub = match message.item_impl().trait_path() {
            None => Some(quote! { pub }),
            Some(_) => None,
        };
        quote_spanned!(span =>
            type #output_ident = #output_ty;

            #[inline]
            #opt_pub fn #ident( #receiver #(, #inputs_sig )* ) -> Self::#output_ident {
                <&#opt_mut Self as ::ink_lang::#forward_trait>::#forward_ident(self)
                    .#ident( #( #inputs_params ),* )
                    .fire()
                    .expect(#error_str)
            }
        )
    }

    /// Generates the code to allow cross-chain contract calls for trait constructors.
    fn generate_trait_impl_block_constructor(
        constructor: ir::CallableWithSelector<ir::Constructor>,
    ) -> TokenStream2 {
        let span = constructor.span();
        let attrs = constructor.attrs();
        let ident = constructor.ident();
        let output_ident = format_ident!("{}Out", ident.to_string().to_camel_case());
        let composed_selector = constructor.composed_selector().as_bytes().to_owned();
        let input_bindings = constructor
            .inputs()
            .enumerate()
            .map(|(n, _)| format_ident!("__ink_binding_{}", n))
            .collect::<Vec<_>>();
        let input_types = constructor
            .inputs()
            .map(|pat_type| &*pat_type.ty)
            .collect::<Vec<_>>();
        let arg_list = Self::generate_arg_list(input_types.iter().cloned());
        quote_spanned!(span =>
            type #output_ident = ::ink_core::env::call::CreateBuilder<
                EnvTypes,
                ::ink_core::env::call::utils::Unset<Hash>,
                ::ink_core::env::call::utils::Unset<u64>,
                ::ink_core::env::call::utils::Unset<Balance>,
                ::ink_core::env::call::utils::Set<::ink_core::env::call::ExecutionInput<#arg_list>>,
                Self,
            >;

            #( #attrs )*
            #[inline]
            fn #ident(
                #( #input_bindings : #input_types ),*
            ) -> Self::#output_ident {
                ::ink_core::env::call::build_create::<EnvTypes, Self>()
                    .exec_input(
                        ::ink_core::env::call::ExecutionInput::new(
                            ::ink_core::env::call::Selector::new([ #( #composed_selector ),* ])
                        )
                        #(
                            .push_arg(#input_bindings)
                        )*
                    )
            }
        )
    }

    fn generate_trait_impl_block(&self, impl_block: &ir::ItemImpl) -> TokenStream2 {
        assert!(impl_block.trait_path().is_some());
        let cfg = self.generate_cfg();
        let span = impl_block.span();
        let attrs = impl_block.attrs();
        let trait_path = impl_block
            .trait_path()
            .expect("encountered missing trait path");
        let trait_ident = impl_block
            .trait_ident()
            .expect("encountered missing trait identifier");
        let self_type = impl_block.self_type();
        let messages = impl_block
            .iter_messages()
            .map(|message| self.generate_trait_impl_block_message(message));
        let constructors = impl_block
            .iter_constructors()
            .map(Self::generate_trait_impl_block_constructor);
        let hash = ir::InkTrait::compute_verify_hash(
            trait_ident,
            impl_block.iter_constructors().map(|constructor| {
                let ident = constructor.ident().clone();
                let len_inputs = constructor.inputs().count();
                (ident, len_inputs)
            }),
            impl_block.iter_messages().map(|message| {
                let ident = message.ident().clone();
                let len_inputs = message.inputs().count() + 1;
                let is_mut = message.receiver().is_ref_mut();
                (ident, len_inputs, is_mut)
            }),
        );
        let checksum = u32::from_be_bytes([hash[0], hash[1], hash[2], hash[3]]) as usize;
        quote_spanned!(span =>
            #cfg
            unsafe impl ::ink_lang::CheckedInkTrait<[(); #checksum]> for #self_type {}

            #cfg
            #( #attrs )*
            impl #trait_path for #self_type {
                type __ink_Checksum = [(); #checksum];

                #( #messages )*
                #( #constructors )*
            }
        )
    }

    /// Generates the code to allow short-hand cross-chain contract calls for constructors.
    ///
    /// # Note
    ///
    /// For constructors this is the only way they are able to be called.
    fn generate_inherent_impl_block_constructor(
        constructor: ir::CallableWithSelector<ir::Constructor>,
    ) -> TokenStream2 {
        let span = constructor.span();
        let attrs = constructor.attrs();
        let ident = constructor.ident();
        let composed_selector = constructor.composed_selector().as_bytes().to_owned();
        let input_bindings = constructor
            .inputs()
            .enumerate()
            .map(|(n, _)| format_ident!("__ink_binding_{}", n))
            .collect::<Vec<_>>();
        let input_types = constructor
            .inputs()
            .map(|pat_type| &*pat_type.ty)
            .collect::<Vec<_>>();
        let arg_list = Self::generate_arg_list(input_types.iter().cloned());
        quote_spanned!(span =>
            #( #attrs )*
            #[inline]
            pub fn #ident(
                #( #input_bindings : #input_types ),*
            ) -> ::ink_core::env::call::CreateBuilder<
                EnvTypes,
                ::ink_core::env::call::utils::Unset<Hash>,
                ::ink_core::env::call::utils::Unset<u64>,
                ::ink_core::env::call::utils::Unset<Balance>,
                ::ink_core::env::call::utils::Set<::ink_core::env::call::ExecutionInput<#arg_list>>,
                Self,
            > {
                ::ink_core::env::call::build_create::<EnvTypes, Self>()
                    .exec_input(
                        ::ink_core::env::call::ExecutionInput::new(
                            ::ink_core::env::call::Selector::new([ #( #composed_selector ),* ])
                        )
                        #(
                            .push_arg(#input_bindings)
                        )*
                    )
            }
        )
    }

    /// Generates the code to allow short-hand cross-chain contract calls for messages.
    fn generate_inherent_impl_block_message(
        &self,
        message: ir::CallableWithSelector<ir::Message>,
    ) -> TokenStream2 {
        let storage_ident_str = self.contract.module().storage().ident().to_string();
        let span = message.span();
        let ident = message.ident();
        let ident_str = ident.to_string();
        let error_str = format!(
            "encountered error while calling {}::{}",
            storage_ident_str, ident_str
        );
        let inputs_sig = message.inputs();
        let inputs_params = message.inputs().map(|pat_type| &pat_type.pat);
        let output_sig = message.output().map(|output| quote! { -> #output });
        let receiver = message.receiver();
        let forward_ident = match receiver {
            ir::Receiver::Ref => format_ident!("call"),
            ir::Receiver::RefMut => format_ident!("call_mut"),
        };
        let forward_trait = match receiver {
            ir::Receiver::Ref => format_ident!("ForwardCall"),
            ir::Receiver::RefMut => format_ident!("ForwardCallMut"),
        };
        let opt_mut = match receiver {
            ir::Receiver::Ref => None,
            ir::Receiver::RefMut => Some(quote! { mut }),
        };
        let opt_pub = match message.item_impl().trait_path() {
            None => Some(quote! { pub }),
            Some(_) => None,
        };
        quote_spanned!(span =>
            #[inline]
            #opt_pub fn #ident( #receiver #(, #inputs_sig )* ) #output_sig {
                <&#opt_mut Self as ::ink_lang::#forward_trait>::#forward_ident(self)
                    .#ident( #( #inputs_params ),* )
                    .fire()
                    .expect(#error_str)
            }
        )
    }

    fn generate_inherent_impl_block(&self, impl_block: &ir::ItemImpl) -> TokenStream2 {
        assert!(impl_block.trait_path().is_none());
        let cfg = self.generate_cfg();
        let span = impl_block.span();
        let attrs = impl_block.attrs();
        let self_type = impl_block.self_type();
        let messages = impl_block
            .iter_messages()
            .map(|message| self.generate_inherent_impl_block_message(message));
        let constructors = impl_block.iter_constructors().map(|constructor| {
            Self::generate_inherent_impl_block_constructor(constructor)
        });
        quote_spanned!(span =>
            #cfg
            #( #attrs )*
            impl #self_type {
                #( #messages )*
                #( #constructors )*
            }
        )
    }

    fn generate_impl_blocks(&self) -> TokenStream2 {
        let impl_blocks = self.contract.module().impls().map(|impl_block| {
            match impl_block.trait_path() {
                Some(_) => self.generate_trait_impl_block(impl_block),
                None => self.generate_inherent_impl_block(impl_block),
            }
        });
        quote! {
            #( #impl_blocks )*
        }
    }
}