backend.rs 10.9 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
//
// 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.

15
use crate::{
16
    call::{
17
        utils::ReturnType,
18
        CallParams,
19
        CreateParams,
20
    },
21
22
23
24
    hash::{
        CryptoHash,
        HashOutput,
    },
25
    topics::Topics,
26
    Environment,
27
28
29
30
    Result,
};
use ink_primitives::Key;

Hero Bird's avatar
Hero Bird committed
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
/// The flags to indicate further information about the end of a contract execution.
pub struct ReturnFlags {
    value: u32,
}

impl Default for ReturnFlags {
    fn default() -> Self {
        Self { value: 0 }
    }
}

impl ReturnFlags {
    /// Sets the bit to indicate that the execution is going to be reverted.
    pub fn set_reverted(mut self, has_reverted: bool) -> Self {
        match has_reverted {
            true => self.value |= has_reverted as u32,
            false => self.value &= !has_reverted as u32,
        }
        self
    }

    /// Returns the underlying `u32` representation.
    pub(crate) fn into_u32(self) -> u32 {
        self.value
    }
}

58
59
/// Environmental contract functionality that does not require `Environment`.
pub trait EnvBackend {
60
    /// Writes the value to the contract storage under the given key.
61
    fn set_contract_storage<V>(&mut self, key: &Key, value: &V)
62
63
64
65
66
67
68
69
    where
        V: scale::Encode;

    /// Returns the value stored under the given key in the contract's storage if any.
    ///
    /// # Errors
    ///
    /// - If the decoding of the typed value failed
Hero Bird's avatar
Hero Bird committed
70
    fn get_contract_storage<R>(&mut self, key: &Key) -> Result<Option<R>>
71
72
73
74
    where
        R: scale::Decode;

    /// Clears the contract's storage key entry.
75
    fn clear_contract_storage(&mut self, key: &Key);
76

77
    /// Returns the execution input to the executed contract and decodes it as `T`.
78
79
80
81
82
    ///
    /// # Note
    ///
    /// - The input is the 4-bytes selector followed by the arguments
    ///   of the called function in their SCALE encoded representation.
83
84
85
86
87
88
    /// - No prior interaction with the environment must take place before
    ///   calling this procedure.
    ///
    /// # Usage
    ///
    /// Normally contracts define their own `enum` dispatch types respective
89
90
    /// to their exported constructors and messages that implement `scale::Decode`
    /// according to the constructors or messages selectors and their arguments.
91
92
93
94
95
96
97
98
99
100
101
102
    /// These `enum` dispatch types are then given to this procedure as the `T`.
    ///
    /// When using ink! users do not have to construct those enum dispatch types
    /// themselves as they are normally generated by the ink! code generation
    /// automatically.
    ///
    /// # Errors
    ///
    /// If the given `T` cannot be properly decoded from the expected input.
    fn decode_input<T>(&mut self) -> Result<T>
    where
        T: scale::Decode;
103
104
105
106
107

    /// Returns the value back to the caller of the executed contract.
    ///
    /// # Note
    ///
Hero Bird's avatar
Hero Bird committed
108
109
110
111
112
113
    /// Calling this method will end contract execution immediately.
    /// It will return the given return value back to its caller.
    ///
    /// The `flags` parameter can be used to revert the state changes of the
    /// entire execution if necessary.
    fn return_value<R>(&mut self, flags: ReturnFlags, return_value: &R) -> !
114
115
116
117
118
    where
        R: scale::Encode;

    /// Prints the given contents to the console log.
    fn println(&mut self, content: &str);
119

120
121
122
123
    /// Conducts the crypto hash of the given input and stores the result in `output`.
    fn hash_bytes<H>(&mut self, input: &[u8], output: &mut <H as HashOutput>::Type)
    where
        H: CryptoHash;
124

125
126
127
128
129
    /// Conducts the crypto hash of the given encoded input and stores the result in `output`.
    fn hash_encoded<H, T>(&mut self, input: &T, output: &mut <H as HashOutput>::Type)
    where
        H: CryptoHash,
        T: scale::Encode;
Hero Bird's avatar
Hero Bird committed
130

131
    /// Low-level interface to call a chain extension method.
Hero Bird's avatar
Hero Bird committed
132
133
134
135
136
137
138
139
140
    ///
    /// Returns the output of the chain extension of the specified type.
    ///
    /// # Errors
    ///
    /// - If the chain extension with the given ID does not exist.
    /// - If the inputs had an unexpected encoding.
    /// - If the output could not be properly decoded.
    /// - If some extension specific condition has not been met.
141
    ///
142
    /// # Developer Note
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    ///
    /// A valid implementation applies the `status_to_result` closure on
    /// the status code returned by the actual call to the chain extension
    /// method.
    /// Only if the closure finds that the given status code indicates a
    /// successful call to the chain extension method is the resulting
    /// output buffer passed to the `decode_to_result` closure, in order to
    /// drive the decoding and error management process from the outside.
    fn call_chain_extension<I, T, E, ErrorCode, F, D>(
        &mut self,
        func_id: u32,
        input: &I,
        status_to_result: F,
        decode_to_result: D,
    ) -> ::core::result::Result<T, E>
Hero Bird's avatar
Hero Bird committed
158
    where
159
160
161
162
163
        I: scale::Encode,
        T: scale::Decode,
        E: From<ErrorCode>,
        F: FnOnce(u32) -> ::core::result::Result<(), ErrorCode>,
        D: FnOnce(&[u8]) -> ::core::result::Result<T, E>;
164
165
166
}

/// Environmental contract functionality.
167
pub trait TypedEnvBackend: EnvBackend {
168
169
170
171
    /// Returns the address of the caller of the executed contract.
    ///
    /// # Note
    ///
172
    /// For more details visit: [`caller`][`crate::caller`]
173
    fn caller<T: Environment>(&mut self) -> Result<T::AccountId>;
174
175
176
177
178

    /// Returns the transferred balance for the contract execution.
    ///
    /// # Note
    ///
179
    /// For more details visit: [`transferred_balance`][`crate::transferred_balance`]
180
    fn transferred_balance<T: Environment>(&mut self) -> Result<T::Balance>;
181

182
    /// Returns the price for the specified amount of gas.
183
184
185
    ///
    /// # Note
    ///
186
    /// For more details visit: [`weight_to_fee`][`crate::weight_to_fee`]
187
    fn weight_to_fee<T: Environment>(&mut self, gas: u64) -> Result<T::Balance>;
188
189
190
191
192

    /// Returns the amount of gas left for the contract execution.
    ///
    /// # Note
    ///
193
    /// For more details visit: [`gas_left`][`crate::gas_left`]
194
    fn gas_left<T: Environment>(&mut self) -> Result<T::Balance>;
195
196
197
198
199

    /// Returns the timestamp of the current block.
    ///
    /// # Note
    ///
200
    /// For more details visit: [`block_timestamp`][`crate::block_timestamp`]
201
    fn block_timestamp<T: Environment>(&mut self) -> Result<T::Timestamp>;
202
203
204
205
206

    /// Returns the address of the executed contract.
    ///
    /// # Note
    ///
207
    /// For more details visit: [`account_id`][`crate::account_id`]
208
    fn account_id<T: Environment>(&mut self) -> Result<T::AccountId>;
209
210
211
212
213

    /// Returns the balance of the executed contract.
    ///
    /// # Note
    ///
214
    /// For more details visit: [`balance`][`crate::balance`]
215
    fn balance<T: Environment>(&mut self) -> Result<T::Balance>;
216
217
218
219
220

    /// Returns the current rent allowance for the executed contract.
    ///
    /// # Note
    ///
221
    /// For more details visit: [`rent_allowance`][`crate::rent_allowance`]
222
    fn rent_allowance<T: Environment>(&mut self) -> Result<T::Balance>;
223
224
225
226
227

    /// Returns the current block number.
    ///
    /// # Note
    ///
228
    /// For more details visit: [`block_number`][`crate::block_number`]
229
    fn block_number<T: Environment>(&mut self) -> Result<T::BlockNumber>;
230

231
    /// Returns the minimum balance that is required for creating an account.
232
233
234
    ///
    /// # Note
    ///
235
    /// For more details visit: [`minimum_balance`][`crate::minimum_balance`]
236
    fn minimum_balance<T: Environment>(&mut self) -> Result<T::Balance>;
237
238
239
240
241

    /// Returns the tombstone deposit of the contract chain.
    ///
    /// # Note
    ///
242
    /// For more details visit: [`tombstone_deposit`][`crate::tombstone_deposit`]
243
    fn tombstone_deposit<T: Environment>(&mut self) -> Result<T::Balance>;
244
245
246
247
248

    /// Emits an event with the given event data.
    ///
    /// # Note
    ///
249
    /// For more details visit: [`emit_event`][`crate::emit_event`]
250
251
    fn emit_event<T, Event>(&mut self, event: Event)
    where
252
        T: Environment,
253
        Event: Topics + scale::Encode;
254
255
256
257
258

    /// Sets the rent allowance of the executed contract to the new value.
    ///
    /// # Note
    ///
259
    /// For more details visit: [`set_rent_allowance`][`crate::set_rent_allowance`]
260
261
    fn set_rent_allowance<T>(&mut self, new_value: T::Balance)
    where
262
        T: Environment;
263
264
265
266
267

    /// Invokes a contract message.
    ///
    /// # Note
    ///
268
    /// For more details visit: [`invoke_contract`][`crate::invoke_contract`]
269
270
271
272
    fn invoke_contract<T, Args>(
        &mut self,
        call_data: &CallParams<T, Args, ()>,
    ) -> Result<()>
273
    where
274
        T: Environment,
275
        Args: scale::Encode;
276
277
278
279
280

    /// Evaluates a contract message and returns its result.
    ///
    /// # Note
    ///
281
    /// For more details visit: [`eval_contract`][`crate::eval_contract`]
282
    fn eval_contract<T, Args, R>(
283
        &mut self,
284
        call_data: &CallParams<T, Args, ReturnType<R>>,
285
286
    ) -> Result<R>
    where
287
        T: Environment,
288
        Args: scale::Encode,
289
290
291
292
293
294
        R: scale::Decode;

    /// Instantiates another contract.
    ///
    /// # Note
    ///
295
    /// For more details visit: [`instantiate_contract`][`crate::instantiate_contract`]
296
    fn instantiate_contract<T, Args, Salt, C>(
297
        &mut self,
298
        params: &CreateParams<T, Args, Salt, C>,
299
300
    ) -> Result<T::AccountId>
    where
301
        T: Environment,
302
303
        Args: scale::Encode,
        Salt: AsRef<[u8]>;
304
305
306
307
308

    /// Restores a smart contract tombstone.
    ///
    /// # Note
    ///
309
    /// For more details visit: [`restore_contract`][`crate::restore_contract`]
310
311
312
313
314
315
316
    fn restore_contract<T>(
        &mut self,
        account_id: T::AccountId,
        code_hash: T::Hash,
        rent_allowance: T::Balance,
        filtered_keys: &[Key],
    ) where
317
        T: Environment;
318

319
320
321
322
    /// Terminates a smart contract.
    ///
    /// # Note
    ///
323
    /// For more details visit: [`terminate_contract`][`crate::terminate_contract`]
324
325
    fn terminate_contract<T>(&mut self, beneficiary: T::AccountId) -> !
    where
326
        T: Environment;
327

328
329
330
331
    /// Transfers value from the contract to the destination account ID.
    ///
    /// # Note
    ///
332
    /// For more details visit: [`transfer`][`crate::transfer`]
333
334
    fn transfer<T>(&mut self, destination: T::AccountId, value: T::Balance) -> Result<()>
    where
335
        T: Environment;
336

337
338
339
340
    /// Returns a random hash seed.
    ///
    /// # Note
    ///
341
    /// For more details visit: [`random`][`crate::random`]
342
343
    fn random<T>(&mut self, subject: &[u8]) -> Result<T::Hash>
    where
344
        T: Environment;
345
}