env_access.rs 29 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//
// 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 core::marker::PhantomData;
16
17
18
19
20
use ink_env::{
    call::{
        utils::ReturnType,
        CallParams,
        CreateParams,
21
    },
Hero Bird's avatar
Hero Bird committed
22
23
24
25
    hash::{
        CryptoHash,
        HashOutput,
    },
26
    Environment,
27
    RentParams,
28
    RentStatus,
29
    Result,
30
31
32
};
use ink_primitives::Key;

33
34
use crate::ChainExtensionInstance;

35
36
37
/// The environment of the compiled ink! smart contract.
pub trait ContractEnv {
    /// The environment type.
38
    type Env: ::ink_env::Environment;
39
40
}

41
/// Simplifies interaction with the host environment via `self`.
42
43
44
45
46
47
48
///
/// # Note
///
/// This is generally implemented for storage structs that include
/// their environment in order to allow the different dispatch functions
/// to use it for returning the contract's output.
pub trait Env {
49
    /// The access wrapper.
50
51
52
53
54
55
    type EnvAccess;

    /// Accesses the environment with predefined environmental types.
    fn env(self) -> Self::EnvAccess;
}

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/// Simplifies interaction with the host environment via `Self`.
///
/// # Note
///
/// This is generally implemented for storage structs that include
/// their environment in order to allow the different dispatch functions
/// to use it for returning the contract's output.
pub trait StaticEnv {
    /// The access wrapper.
    type EnvAccess;

    /// Accesses the environment with predefined environmental types.
    fn env() -> Self::EnvAccess;
}

71
72
73
74
/// A typed accessor to the environment.
///
/// This allows ink! messages to make use of the environment efficiently
/// and user friendly while also maintaining access invariants.
75
#[derive(Copy, Clone)]
76
77
78
79
80
81
pub struct EnvAccess<'a, T> {
    /// Tricks the Rust compiler into thinking that we use `T`.
    marker: PhantomData<fn() -> &'a T>,
}

impl<'a, T> Default for EnvAccess<'a, T> {
82
    #[inline]
83
84
85
86
87
88
89
90
91
92
93
94
95
    fn default() -> Self {
        Self {
            marker: Default::default(),
        }
    }
}

impl<'a, E> core::fmt::Debug for EnvAccess<'a, E> {
    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        f.debug_struct("EnvAccess").finish()
    }
}

96
97
98
99
100
101
102
103
104
105
106
107
108
impl<'a, T> EnvAccess<'a, T>
where
    T: Environment,
    <T as Environment>::ChainExtension: ChainExtensionInstance,
{
    /// Allows to call one of the available defined chain extension methods.
    pub fn extension(
        self,
    ) -> <<T as Environment>::ChainExtension as ChainExtensionInstance>::Instance {
        <<T as Environment>::ChainExtension as ChainExtensionInstance>::instantiate()
    }
}

109
110
impl<'a, T> EnvAccess<'a, T>
where
111
    T: Environment,
112
113
114
{
    /// Returns the address of the caller of the executed contract.
    ///
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
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// #
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// #[ink(message)]
    /// pub fn call_me(&self) {
    ///     let caller = self.env().caller();
    ///     ink_env::debug_println!("got a call from {:?}", &caller);
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
141
142
    /// # Note
    ///
143
    /// For more details visit: [`ink_env::caller`]
144
    pub fn caller(self) -> T::AccountId {
145
        ink_env::caller::<T>().expect("couldn't decode caller")
146
147
148
149
    }

    /// Returns the transferred balance for the contract execution.
    ///
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
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// #
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Allows funding the contract. Prints a debug message with the transferred balance.
    /// #[ink(message, payable)]
    /// pub fn fund(&self) {
    ///     let caller = self.env().caller();
    ///     let value = self.env().transferred_balance();
    ///     ink_env::debug_println!("thanks for the funding of {:?} from {:?}", value, caller);
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
178
179
    /// # Note
    ///
180
    /// For more details visit: [`ink_env::transferred_balance`]
181
    pub fn transferred_balance(self) -> T::Balance {
182
        ink_env::transferred_balance::<T>().expect("couldn't decode transferred balance")
183
184
    }

185
    /// Returns the price for the specified amount of gas.
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
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// #
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Returns a tuple of
    /// ///   - the result of adding the `rhs` to the `lhs`
    /// ///   - the gas costs of this addition operation
    /// ///   - the price for the gas
    /// #[ink(message)]
    /// pub fn addition_gas_cost(&self, rhs: i32, lhs: i32) -> (i32, u64, Balance) {
    ///     let before = self.env().gas_left();
    ///     let result = rhs + lhs;
    ///     let after = self.env().gas_left();
    ///     let gas_used = after - before;
    ///     let gas_cost = self.env().weight_to_fee(gas_used);
    ///     (result, gas_used, gas_cost)
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
221
222
    /// # Note
    ///
223
    /// For more details visit: [`ink_env::weight_to_fee`]
Hero Bird's avatar
Hero Bird committed
224
    pub fn weight_to_fee(self, gas: u64) -> T::Balance {
225
        ink_env::weight_to_fee::<T>(gas).expect("couldn't decode weight fee")
226
227
228
229
    }

    /// Returns the amount of gas left for the contract execution.
    ///
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
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Returns a tuple of
    /// ///   - the result of adding the `rhs` to the `lhs` and
    /// ///   - the gas used for this addition operation.
    /// #[ink(message)]
    /// pub fn addition_gas_cost(&self, rhs: i32, lhs: i32) -> (i32, u64) {
    ///     let before = self.env().gas_left();
    ///     let result = rhs + lhs;
    ///     let after = self.env().gas_left();
    ///     (result, after - before)
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
260
261
    /// # Note
    ///
262
    /// For more details visit: [`ink_env::gas_left`]
263
    pub fn gas_left(self) -> u64 {
264
        ink_env::gas_left::<T>().expect("couldn't decode gas left")
265
266
    }

267
    /// Returns the timestamp of the current block.
268
    ///
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
    /// # Example
    ///
    /// ```
    /// use ink_lang as ink;
    ///
    /// #[ink::contract]
    /// pub mod my_contract {
    ///     #[ink(storage)]
    ///     pub struct MyContract {
    ///         last_invocation: Timestamp
    ///     }
    ///
    ///     impl MyContract {
    ///         #[ink(constructor)]
    ///         pub fn new() -> Self {
    ///             Self {
    ///                 last_invocation: Self::env().block_timestamp()
    ///             }
    ///         }
    ///
289
    ///         /// Records the last time the message was invoked.
290
291
    ///         #[ink(message)]
    ///         pub fn execute_me(&mut self) {
292
    ///             self.last_invocation = self.env().block_timestamp();
293
294
295
296
297
    ///         }
    ///     }
    /// }
    /// ```
    ///
298
299
    /// # Note
    ///
300
301
302
303
    /// The Substrate default for the timestamp type is the milliseconds since the
    /// Unix epoch. However, this is not guaranteed: the specific timestamp is
    /// defined by the chain environment on which this contract runs.
    ///
304
    /// For more details visit: [`ink_env::block_timestamp`]
305
    pub fn block_timestamp(self) -> T::Timestamp {
306
        ink_env::block_timestamp::<T>().expect("couldn't decode block time stamp")
307
308
309
310
    }

    /// Returns the account ID of the executed contract.
    ///
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
    /// # Example
    ///
    /// ```
    /// use ink_lang as ink;
    ///
    /// #[ink::contract]
    /// pub mod only_owner {
    ///     #[ink(storage)]
    ///     pub struct OnlyOwner {
    ///         owner: AccountId,
    ///         value: u32,
    ///     }
    ///
    ///     impl OnlyOwner {
    ///         #[ink(constructor)]
    ///         pub fn new() -> Self {
    ///             Self {
    ///                 owner: Self::env().caller(),
    ///                 value: 0,
    ///             }
    ///         }
    ///
    ///         /// Allows incrementing the contract's `value` only
    ///         /// for the owner (i.e. the account which instantiated
    ///         /// this contract.
    ///         ///
    ///         /// The contract panics if the caller is not the owner.
    ///         #[ink(message)]
    ///         pub fn increment(&mut self) {
    ///             let caller = self.env().caller();
    ///             assert!(self.owner == caller);
    ///             self.value = self.value + 1;
    ///         }
    ///     }
    /// }
    /// ```
    ///
348
349
    /// # Note
    ///
350
    /// For more details visit: [`ink_env::account_id`]
351
    pub fn account_id(self) -> T::AccountId {
352
        ink_env::account_id::<T>().expect("couldn't decode contract account ID")
353
354
355
356
    }

    /// Returns the balance of the executed contract.
    ///
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
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Returns the contract's balance.
    /// #[ink(message)]
    /// pub fn my_balance(&self) -> Balance {
    ///     self.env().balance()
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
382
383
    /// # Note
    ///
384
    /// For more details visit: [`ink_env::balance`]
385
    pub fn balance(self) -> T::Balance {
386
        ink_env::balance::<T>().expect("couldn't decode contract balance")
387
388
389
390
    }

    /// Returns the current rent allowance for the executed contract.
    ///
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
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Returns the amount of the contract's balance which
    /// /// can be used for paying rent.
    /// #[ink(message)]
    /// pub fn rent_allowance(&self) -> Balance {
    ///     self.env().rent_allowance()
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
417
418
    /// # Note
    ///
419
    /// For more details visit: [`ink_env::rent_allowance`]
420
    pub fn rent_allowance(self) -> T::Balance {
421
        ink_env::rent_allowance::<T>().expect("couldn't decode contract rent allowance")
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
    /// Sets the rent allowance of the executed contract to the new value.
    ///
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Limits the amount of contract balance which can be used for paying rent
    /// /// to half of the contract's total balance.
    /// #[ink(message)]
    /// pub fn limit_rent_allowance(&self) {
    ///     self.env().set_rent_allowance(self.env().balance() / 2);
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_env::set_rent_allowance`]
    pub fn set_rent_allowance(self, new_value: T::Balance) {
        ink_env::set_rent_allowance::<T>(new_value)
    }

459
460
    /// Returns information needed for rent calculations.
    ///
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
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Returns the balance every contract needs to deposit on this chain
    /// /// to stay alive indefinitely.
    /// #[ink(message)]
    /// pub fn deposit_per_contract(&self) -> Balance {
    ///     self.env().rent_params().deposit_per_contract
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
487
488
489
490
491
492
493
    /// # Note
    ///
    /// For more details visit: [`ink_env::RentParams`]
    pub fn rent_params(self) -> RentParams<T> {
        ink_env::rent_params::<T>().expect("couldn't decode contract rent params")
    }

494
495
496
497
    /// Returns information about the required deposit and resulting rent.
    ///
    /// # Parameters
    ///
498
    /// - `at_refcount`: The `refcount` assumed for the returned `custom_refcount_*` fields.
499
500
501
    ///   If `None` is supplied the `custom_refcount_*` fields will also be `None`.
    ///
    ///   The `current_*` fields of `RentStatus` do **not** consider changes to the code's
502
    ///   `refcount` made during the currently running call.
503
504
505
506
507
508
509
510
511
512
513
514
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_env::RentStatus`]
    pub fn rent_status(
        self,
        at_refcount: Option<core::num::NonZeroU32>,
    ) -> RentStatus<T> {
        ink_env::rent_status::<T>(at_refcount)
            .expect("couldn't decode contract rent params")
    }

515
516
    /// Returns the current block number.
    ///
517
518
519
    /// # Example
    ///
    /// ```
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
    /// use ink_lang as ink;
    ///
    /// #[ink::contract]
    /// pub mod my_contract {
    ///     #[ink(storage)]
    ///     pub struct MyContract {
    ///         last_invocation: BlockNumber
    ///     }
    ///
    ///     impl MyContract {
    ///         #[ink(constructor)]
    ///         pub fn new() -> Self {
    ///             Self {
    ///                 last_invocation: Self::env().block_number()
    ///             }
    ///         }
    ///
    ///         /// The function can be executed at most once every 100 blocks.
    ///         #[ink(message)]
    ///         pub fn execute_me(&mut self) {
    ///             let now = self.env().block_number();
    ///             assert!(now - self.last_invocation > 100);
    ///             self.last_invocation = now;
    ///         }
    ///     }
545
546
547
    /// }
    /// ```
    ///
548
549
    /// # Note
    ///
550
    /// For more details visit: [`ink_env::block_number`]
551
    pub fn block_number(self) -> T::BlockNumber {
552
        ink_env::block_number::<T>().expect("couldn't decode block number")
553
554
    }

555
    /// Returns the minimum balance that is required for creating an account.
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
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// #[ink(message)]
    /// pub fn minimum_balance(&self) -> Balance {
    ///     self.env().minimum_balance()
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
581
582
    /// # Note
    ///
583
    /// For more details visit: [`ink_env::minimum_balance`]
584
    pub fn minimum_balance(self) -> T::Balance {
585
        ink_env::minimum_balance::<T>().expect("couldn't decode minimum account balance")
586
587
588
589
    }

    /// Returns the tombstone deposit for the contracts chain.
    ///
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// #[ink(message)]
    /// pub fn tombstone_deposit(&self) -> Balance {
    ///     self.env().tombstone_deposit()
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
614
615
    /// # Note
    ///
616
    /// For more details visit: [`ink_env::tombstone_deposit`]
617
    pub fn tombstone_deposit(self) -> T::Balance {
618
        ink_env::tombstone_deposit::<T>().expect("couldn't decode tombstone deposits")
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
    /// Instantiates another contract.
    ///
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     use ink_lang as ink;
    /// #     #[ink::contract(compile_as_dependency = true)]
    /// #     pub mod other_contract {
    /// #         #[ink(storage)]
    /// #         pub struct OtherContract { }
    /// #
    /// #         impl OtherContract {
    /// #             #[ink(constructor)]
    /// #             pub fn new() -> Self {
    /// #                 Self {}
    /// #             }
    /// #
    /// #             #[ink(message)]
    /// #             pub fn some_operation(&self) {
    /// #                 // ...
    /// #             }
    /// #         }
    /// #     }
    /// #
    /// use ink_env::{
    ///     DefaultEnvironment,
    ///     call::{build_create, Selector, ExecutionInput}
    /// };
    /// use other_contract::OtherContract;
    /// #
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    ///
    /// /// Instantiates another contract.
    /// #[ink(message)]
    /// pub fn instantiate_contract(&self) -> AccountId {
    ///     let create_params = build_create::<DefaultEnvironment, OtherContract>()
    ///         .code_hash(Hash::from([0x42; 32]))
    ///         .gas_limit(4000)
    ///         .endowment(25)
    ///         .exec_input(
    ///             ExecutionInput::new(Selector::new([0xCA, 0xFE, 0xBA, 0xBE]))
    ///                 .push_arg(42)
    ///                 .push_arg(true)
    ///                 .push_arg(&[0x10u8; 32])
    ///             )
    ///         .salt_bytes(&[0xCA, 0xFE, 0xBA, 0xBE])
    ///         .params();
    ///     self.env().instantiate_contract(&create_params).expect("instantiation must succeed")
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
    /// See [our `delegator` example](https://github.com/paritytech/ink/tree/master/examples/delegator)
    /// for a complete contract example.
688
689
690
    ///
    /// # Note
    ///
691
692
693
694
695
696
697
698
699
700
    /// For more details visit: [`ink_env::instantiate_contract`]
    pub fn instantiate_contract<Args, Salt, C>(
        self,
        params: &CreateParams<T, Args, Salt, C>,
    ) -> Result<T::AccountId>
    where
        Args: scale::Encode,
        Salt: AsRef<[u8]>,
    {
        ink_env::instantiate_contract::<T, Args, Salt, C>(params)
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
    /// Invokes a contract message without fetching its result.
    ///
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// use ink_env::{
    ///     DefaultEnvironment,
    ///     call::{build_call, Selector, ExecutionInput}
    /// };
    ///
    /// #
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Invokes another contract message without fetching the result.
    /// #[ink(message)]
    /// pub fn invoke_contract(&self) {
    ///     let call_params = build_call::<DefaultEnvironment>()
    ///         .callee(AccountId::from([0x42; 32]))
    ///         .gas_limit(5000)
    ///         .transferred_value(10)
    ///         .exec_input(
    ///             ExecutionInput::new(Selector::new([0xCA, 0xFE, 0xBA, 0xBE]))
    ///                 .push_arg(42)
    ///                 .push_arg(true)
    ///                 .push_arg(&[0x10u8; 32])
    ///         )
    ///         .returns::<()>()
    ///         .params();
    ///     self.env().invoke_contract(&call_params).expect("call invocation must succeed");
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
747
748
749
    ///
    /// # Note
    ///
750
    /// For more details visit: [`ink_env::invoke_contract`]
751
752
753
754
    pub fn invoke_contract<Args>(self, params: &CallParams<T, Args, ()>) -> Result<()>
    where
        Args: scale::Encode,
    {
755
        ink_env::invoke_contract::<T, Args>(params)
756
757
758
759
    }

    /// Evaluates a contract message and returns its result.
    ///
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
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// use ink_env::{
    ///     DefaultEnvironment,
    ///     call::{build_call, Selector, ExecutionInput, utils::ReturnType}
    /// };
    ///
    /// #
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Evaluates a contract message and fetches the result.
    /// #[ink(message)]
    /// pub fn evaluate_contract(&self) -> i32 {
    ///     let call_params = build_call::<DefaultEnvironment>()
    ///         .callee(AccountId::from([0x42; 32]))
    ///         .gas_limit(5000)
    ///         .transferred_value(10)
    ///         .exec_input(
    ///             ExecutionInput::new(Selector::new([0xCA, 0xFE, 0xBA, 0xBE]))
    ///                 .push_arg(42)
    ///                 .push_arg(true)
    ///                 .push_arg(&[0x10u8; 32])
    ///         )
    ///         .returns::<ReturnType<i32>>()
    ///         .params();
    ///     self.env().eval_contract(&call_params).expect("call invocation must succeed")
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
803
804
    /// # Note
    ///
805
    /// For more details visit: [`ink_env::eval_contract`]
806
807
808
809
    pub fn eval_contract<Args, R>(
        self,
        params: &CallParams<T, Args, ReturnType<R>>,
    ) -> Result<R>
810
    where
811
        Args: scale::Encode,
812
813
        R: scale::Decode,
    {
814
        ink_env::eval_contract::<T, Args, R>(params)
815
816
    }

817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
    /// Restores a smart contract from its tombstone state.
    ///
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Simple resurrection of a contract.
    /// #[ink(message)]
    /// pub fn resurrect(&self, contract: AccountId) {
    ///     self.env().restore_contract(
    ///         contract,
    ///         Hash::from([0x42; 32]),
    ///         1000,
    ///         &[]
    ///     )
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
848
849
850
    ///
    /// # Note
    ///
851
    /// For more details visit: [`ink_env::restore_contract`]
852
853
854
855
856
857
858
    pub fn restore_contract(
        self,
        account_id: T::AccountId,
        code_hash: T::Hash,
        rent_allowance: T::Balance,
        filtered_keys: &[Key],
    ) {
859
860
861
862
863
864
        ink_env::restore_contract::<T>(
            account_id,
            code_hash,
            rent_allowance,
            filtered_keys,
        )
865
866
    }

867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
    /// Terminates the existence of a contract without creating a tombstone.
    ///
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Terminates with the caller as beneficiary.
    /// #[ink(message)]
    /// pub fn terminate_me(&mut self) {
    ///     self.env().terminate_contract(self.env().caller());
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
893
894
895
    ///
    /// # Note
    ///
896
    /// For more details visit: [`ink_env::terminate_contract`]
Hero Bird's avatar
Hero Bird committed
897
    pub fn terminate_contract(self, beneficiary: T::AccountId) -> ! {
898
        ink_env::terminate_contract::<T>(beneficiary)
899
900
    }

901
902
    /// Transfers value from the contract to the destination account ID.
    ///
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// /// Transfers the token amount ten to the caller.
    /// #[ink(message)]
    /// pub fn give_me_ten(&mut self) {
    ///     let value: Balance = 10;
    ///     self.env().transfer(self.env().caller(), value).expect("transfer failed");
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
929
930
    /// # Note
    ///
931
    /// For more details visit: [`ink_env::transfer`]
Hero Bird's avatar
Hero Bird committed
932
    pub fn transfer(self, destination: T::AccountId, value: T::Balance) -> Result<()> {
933
        ink_env::transfer::<T>(destination, value)
934
935
    }

936
937
    /// Returns a random hash seed.
    ///
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
    /// # Example
    ///
    /// ```
    /// # use ink_lang as ink;
    /// # #[ink::contract]
    /// # pub mod my_contract {
    /// #     #[ink(storage)]
    /// #     pub struct MyContract { }
    /// #
    /// #     impl MyContract {
    /// #         #[ink(constructor)]
    /// #         pub fn new() -> Self {
    /// #             Self {}
    /// #         }
    /// #
    /// #[ink(message)]
    /// pub fn random_bool(&self) -> bool {
    ///     let additional_randomness = b"seed";
    ///     let (hash, _block_number) = self.env().random(additional_randomness);
    ///     hash.as_ref()[0] != 0
    /// }
    /// #
    /// #     }
    /// # }
    /// ```
    ///
964
965
    /// # Note
    ///
966
    /// For more details visit: [`ink_env::random`]
967
    pub fn random(self, subject: &[u8]) -> (T::Hash, T::BlockNumber) {
Hero Bird's avatar
Hero Bird committed
968
969
970
971
972
        ink_env::random::<T>(subject).expect("couldn't decode randomized hash")
    }

    /// Computes the hash of the given bytes using the cryptographic hash `H`.
    ///
973
974
975
976
977
978
979
980
981
982
    /// # Example
    ///
    /// ```
    /// use ink_env::hash::{Sha2x256, HashOutput};
    ///
    /// let input: &[u8] = &[13, 14, 15];
    /// let mut output = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buffer
    /// let hash  = ink_env::hash_bytes::<Sha2x256>(input, &mut output);
    /// ```
    ///
Hero Bird's avatar
Hero Bird committed
983
984
985
986
    /// # Note
    ///
    /// For more details visit: [`ink_env::hash_bytes`]
    pub fn hash_bytes<H>(self, input: &[u8]) -> <H as HashOutput>::Type
987
    where
Hero Bird's avatar
Hero Bird committed
988
        H: CryptoHash,
989
    {
Hero Bird's avatar
Hero Bird committed
990
991
992
993
994
995
996
        let mut output = <H as HashOutput>::Type::default();
        ink_env::hash_bytes::<H>(input, &mut output);
        output
    }

    /// Computes the hash of the given SCALE encoded value using the cryptographic hash `H`.
    ///
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
    /// # Example
    ///
    /// ```
    /// use ink_env::hash::{Sha2x256, HashOutput};
    ///
    /// let encodable = (42, "foo", true); // Implements `scale::Encode`
    /// let mut output = <Sha2x256 as HashOutput>::Type::default(); // 256-bit buffer
    /// ink_env::hash_encoded::<Sha2x256, _>(&encodable, &mut output);
    ///
    /// const EXPECTED: [u8; 32] = [
    ///   243, 242, 58, 110, 205, 68, 100, 244, 187, 55, 188, 248,  29, 136, 145, 115,
    ///   186, 134, 14, 175, 178, 99, 183,  21,   4, 94,  92,  69, 199, 207, 241, 179,
    /// ];
    /// assert_eq!(output, EXPECTED);
    /// ```
    ///
Hero Bird's avatar
Hero Bird committed
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
    /// # Note
    ///
    /// For more details visit: [`ink_env::hash_encoded`]
    pub fn hash_encoded<H, V>(self, value: &V) -> <H as HashOutput>::Type
    where
        H: CryptoHash,
        V: scale::Encode,
    {
        let mut output = <H as HashOutput>::Type::default();
        ink_env::hash_encoded::<H, V>(value, &mut output);
        output
1024
1025
    }
}