env_access.rs 9.34 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
// Copyright 2018-2019 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 core::marker::PhantomData;
use ink_core::{
    env,
    env::{
        call::{
            CallParams,
            InstantiateParams,
            ReturnType,
        },
        EnvTypes,
        Result,
    },
};
use ink_primitives::Key;

30
/// Simplifies interaction with the host environment via `self`.
31
32
33
34
35
36
37
///
/// # 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 {
38
    /// The access wrapper.
39
40
41
42
43
44
    type EnvAccess;

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

45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/// 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;
}

60
61
62
63
/// 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.
64
#[derive(Copy, Clone)]
65
66
67
68
69
70
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> {
71
    #[inline]
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
    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()
    }
}

impl<'a, T> EnvAccess<'a, T>
where
    T: EnvTypes,
{
    /// Returns the address of the caller of the executed contract.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::caller`]
    pub fn caller(self) -> T::AccountId {
        env::caller::<T>().expect("couldn't decode caller")
    }

    /// Returns the transferred balance for the contract execution.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::transferred_balance`]
    pub fn transferred_balance(self) -> T::Balance {
        env::transferred_balance::<T>().expect("couldn't decode transferred balance")
    }

107
    /// Returns the price for the specified amount of gas.
108
109
110
111
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::gas_price`]
112
113
    pub fn gas_price(self, gas: u64) -> T::Balance {
        env::gas_price::<T>(gas).expect("couldn't decode gas price")
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
    }

    /// Returns the amount of gas left for the contract execution.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::gas_left`]
    pub fn gas_left(self) -> T::Balance {
        env::gas_left::<T>().expect("couldn't decode gas left")
    }

    /// Returns the timstamp of the current block.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::block_timestamp`]
    pub fn block_timestamp(self) -> T::Timestamp {
        env::block_timestamp::<T>().expect("couldn't decode block time stamp")
    }

    /// Returns the account ID of the executed contract.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::account_id`]
    pub fn account_id(self) -> T::AccountId {
        env::account_id::<T>().expect("couldn't decode contract account ID")
    }

    /// Returns the account ID of the executed contract.
    ///
    /// # Note
    ///
    /// - This functionality is deprecated. Please use [`EnvAccess::account_id`]
    ///   instead.
    /// - For more details visit: [`ink_core::env::account_id`]
    ///
    /// # Panics
    ///
    /// If the returned value cannot be properly decoded.
    #[deprecated(note = "please use self.env().account_id")]
    pub fn address(self) -> T::AccountId {
        env::account_id::<T>().expect("couldn't decode contract account ID")
    }

    /// Returns the balance of the executed contract.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::balance`]
    pub fn balance(self) -> T::Balance {
        env::balance::<T>().expect("couldn't decode contract balance")
    }

    /// Returns the current rent allowance for the executed contract.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::rent_allowance`]
    pub fn rent_allowance(self) -> T::Balance {
        env::rent_allowance::<T>().expect("couldn't decode contract rent allowance")
    }

    /// Returns the current block number.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::block_number`]
    pub fn block_number(self) -> T::BlockNumber {
        env::block_number::<T>().expect("couldn't decode block number")
    }

    /// Returns the minimum balance for the contracts chain.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::minimum_balance`]
    pub fn minimum_balance(self) -> T::Balance {
        env::minimum_balance::<T>().expect("couldn't decode minimum account balance")
    }

    /// Returns the tombstone deposit for the contracts chain.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::tombstone_deposit`]
    pub fn tombstone_deposit(self) -> T::Balance {
        env::tombstone_deposit::<T>().expect("couldn't decode tombstone deposits")
    }

    /// Sets the rent allowance of the executed contract to the new value.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::set_rent_allowance`]
    pub fn set_rent_allowance(self, new_value: T::Balance) {
        env::set_rent_allowance::<T>(new_value)
    }

    /// Invokes a call to the runtime.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::invoke_runtime`]
    pub fn invoke_runtime(self, params: &T::Call) -> Result<()> {
        env::invoke_runtime::<T>(params)
    }

    /// Invokes a contract message.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::invoke_contract`]
227
228
229
230
231
    pub fn invoke_contract<Args>(self, params: &CallParams<T, Args, ()>) -> Result<()>
    where
        Args: scale::Encode,
    {
        env::invoke_contract::<T, Args>(params)
232
233
234
235
236
237
238
    }

    /// Evaluates a contract message and returns its result.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::eval_contract`]
239
240
241
242
    pub fn eval_contract<Args, R>(
        self,
        params: &CallParams<T, Args, ReturnType<R>>,
    ) -> Result<R>
243
    where
244
        Args: scale::Encode,
245
246
        R: scale::Decode,
    {
247
        env::eval_contract::<T, Args, R>(params)
248
249
250
251
252
253
254
    }

    /// Instantiates another contract.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::instantiate_contract`]
255
    pub fn instantiate_contract<Args, C>(
256
        self,
257
258
259
260
261
262
        params: &InstantiateParams<T, Args, C>,
    ) -> Result<T::AccountId>
    where
        Args: scale::Encode,
    {
        env::instantiate_contract::<T, Args, C>(params)
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
    }

    /// Restores a smart contract in tombstone state.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::restore_contract`]
    pub fn restore_contract(
        self,
        account_id: T::AccountId,
        code_hash: T::Hash,
        rent_allowance: T::Balance,
        filtered_keys: &[Key],
    ) {
        env::restore_contract::<T>(account_id, code_hash, rent_allowance, filtered_keys)
    }

280
281
282
283
284
285
286
287
288
289
290
291
    /// Terminates the existence of a smart contract.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::terminate_contract`]
    pub fn terminate_contract(self, beneficiary: T::AccountId) -> !
    where
        T: EnvTypes,
    {
        env::terminate_contract::<T>(beneficiary)
    }

292
293
294
295
296
297
298
299
300
301
302
303
    /// Transfers value from the contract to the destination account ID.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::transfer`]
    pub fn transfer(self, destination: T::AccountId, value: T::Balance) -> Result<()>
    where
        T: EnvTypes,
    {
        env::transfer::<T>(destination, value)
    }

304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
    /// Returns a random hash seed.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::random`]
    pub fn random(self, subject: &[u8]) -> T::Hash
    where
        T: EnvTypes,
    {
        env::random::<T>(subject).expect("couldn't decode randomized hash")
    }

    /// Returns the value from the *runtime* storage at the position of the key if any.
    ///
    /// # Note
    ///
    /// For more details visit: [`ink_core::env::get_runtime_storage`]
    pub fn get_runtime_storage<R>(self, runtime_key: &[u8]) -> Option<Result<R>>
    where
        R: scale::Decode,
    {
        env::get_runtime_storage::<R>(runtime_key)
    }
}