impls.rs 12.3 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
// Copyright 2019-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 super::{
    ext,
    EnvInstance,
};
use crate::env::{
    call::{
        CallParams,
        InstantiateParams,
        ReturnType,
    },
    Env,
    EnvTypes,
    Result,
    Topics,
    TypedEnv,
};
use ink_primitives::Key;

impl EnvInstance {
    /// Empties the contract-side scratch buffer.
    ///
    /// # Note
    ///
    /// This is useful to perform before invoking a series of
    /// [`WasmEnv::append_encode_into_buffer`].
    fn reset_buffer(&mut self) {
        self.buffer.clear();
    }

    /// Resizes the amount of used bytes of the internal buffer.
    fn resize_buffer(&mut self, new_len: usize) {
        self.buffer.resize(new_len);
    }

    /// Reads the current scratch buffer into the contract-side buffer.
    ///
    /// Returns the amount of bytes read.
    fn read_scratch_buffer(&mut self) -> usize {
        let req_len = ext::scratch_size();
        self.resize_buffer(req_len);
        ext::scratch_read(&mut self.buffer[0..req_len], 0);
        req_len
    }

    /// Reads from the scratch buffer and directly decodes into a value of `T`.
    ///
    /// # Errors
    ///
    /// If the decoding into a value of `T` failed.
    fn decode_scratch_buffer<T>(&mut self) -> Result<T>
    where
        T: scale::Decode,
    {
        let req_len = self.read_scratch_buffer();
        scale::Decode::decode(&mut &self.buffer[0..req_len]).map_err(Into::into)
    }

    /// Encodes the value into the contract-side scratch buffer.
    fn encode_into_buffer<T>(&mut self, value: T)
    where
        T: scale::Encode,
    {
        self.reset_buffer();
        scale::Encode::encode_to(&value, &mut self.buffer);
    }

    /// Appends the encoded value into the contract-side scratch buffer
    /// and returns the byte ranges into the encoded region.
    fn append_encode_into_buffer<T>(&mut self, value: T) -> core::ops::Range<usize>
    where
        T: scale::Encode,
    {
        let start = self.buffer.len();
        scale::Encode::encode_to(&value, &mut self.buffer);
        let end = self.buffer.len();
        core::ops::Range { start, end }
    }

    /// Returns the contract property value.
    fn get_property<T>(&mut self, ext_fn: fn()) -> Result<T>
    where
        T: scale::Decode,
    {
        ext_fn();
        self.decode_scratch_buffer().map_err(Into::into)
    }

    /// Reusable implementation for invoking another contract message.
103
    fn invoke_contract_impl<T, Args, RetType>(
104
        &mut self,
105
        call_params: &CallParams<T, Args, RetType>,
106
107
108
    ) -> Result<()>
    where
        T: EnvTypes,
109
        Args: scale::Encode,
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
    {
        // Reset the contract-side buffer to append onto clean slate.
        self.reset_buffer();
        // Append the encoded `call_data`, `endowment` and `call_data`
        // in order and remember their encoded regions within the buffer.
        let callee = self.append_encode_into_buffer(call_params.callee());
        let transferred_value =
            self.append_encode_into_buffer(call_params.transferred_value());
        let call_data = self.append_encode_into_buffer(call_params.input_data());
        // Resolve the encoded regions into actual byte slices.
        let callee = &self.buffer[callee];
        let transferred_value = &self.buffer[transferred_value];
        let call_data = &self.buffer[call_data];
        // Perform the actual contract call.
        ext::call(
            callee,
            call_params.gas_limit(),
            transferred_value,
            call_data,
        )
    }
}

impl Env for EnvInstance {
134
    fn set_contract_storage<V>(&mut self, key: &Key, value: &V)
135
136
137
138
139
140
141
    where
        V: scale::Encode,
    {
        self.encode_into_buffer(value);
        ext::set_storage(key.as_bytes(), &self.buffer[..]);
    }

142
    fn get_contract_storage<R>(&mut self, key: &Key) -> Option<Result<R>>
143
144
145
146
147
148
149
150
151
    where
        R: scale::Decode,
    {
        if ext::get_storage(key.as_bytes()).is_err() {
            return None
        }
        Some(self.decode_scratch_buffer().map_err(Into::into))
    }

152
    fn clear_contract_storage(&mut self, key: &Key) {
153
154
155
156
157
158
159
160
161
162
163
164
165
        ext::clear_storage(key.as_bytes())
    }

    fn get_runtime_storage<R>(&mut self, runtime_key: &[u8]) -> Option<Result<R>>
    where
        R: scale::Decode,
    {
        if ext::get_runtime_storage(runtime_key).is_err() {
            return None
        }
        Some(self.decode_scratch_buffer().map_err(Into::into))
    }

166
167
168
169
170
    fn decode_input<T>(&mut self) -> Result<T>
    where
        T: scale::Decode,
    {
        self.get_property::<T>(|| ())
171
172
173
174
175
176
177
178
179
180
181
182
183
    }

    fn output<R>(&mut self, return_value: &R)
    where
        R: scale::Encode,
    {
        self.encode_into_buffer(return_value);
        ext::scratch_write(&self.buffer[..]);
    }

    fn println(&mut self, content: &str) {
        ext::println(content)
    }
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199

    fn hash_keccak_256(input: &[u8], output: &mut [u8; 32]) {
        ext::hash_keccak_256(input, output)
    }

    fn hash_blake2_256(input: &[u8], output: &mut [u8; 32]) {
        ext::hash_blake2_256(input, output)
    }

    fn hash_blake2_128(input: &[u8], output: &mut [u8; 16]) {
        ext::hash_blake2_128(input, output)
    }

    fn hash_sha2_256(input: &[u8], output: &mut [u8; 32]) {
        ext::hash_sha2_256(input, output)
    }
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
}

impl TypedEnv for EnvInstance {
    fn caller<T: EnvTypes>(&mut self) -> Result<T::AccountId> {
        self.get_property::<T::AccountId>(ext::caller)
    }

    fn transferred_balance<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.get_property::<T::Balance>(ext::value_transferred)
    }

    fn gas_left<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.get_property::<T::Balance>(ext::gas_left)
    }

    fn block_timestamp<T: EnvTypes>(&mut self) -> Result<T::Timestamp> {
        self.get_property::<T::Timestamp>(ext::now)
    }

    fn account_id<T: EnvTypes>(&mut self) -> Result<T::AccountId> {
        self.get_property::<T::AccountId>(ext::address)
    }

    fn balance<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.get_property::<T::Balance>(ext::balance)
    }

    fn rent_allowance<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.get_property::<T::Balance>(ext::rent_allowance)
    }

    fn block_number<T: EnvTypes>(&mut self) -> Result<T::BlockNumber> {
        self.get_property::<T::BlockNumber>(ext::block_number)
    }

    fn minimum_balance<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.get_property::<T::Balance>(ext::minimum_balance)
    }

    fn tombstone_deposit<T: EnvTypes>(&mut self) -> Result<T::Balance> {
        self.get_property::<T::Balance>(ext::tombstone_deposit)
    }

    fn emit_event<T, Event>(&mut self, event: Event)
    where
        T: EnvTypes,
        Event: Topics<T> + scale::Encode,
    {
        // Reset the contract-side buffer to append onto clean slate.
        self.reset_buffer();
        // Append the encoded `topics` and the raw encoded `data`
        // in order and remember their encoded regions within the buffer.
        let topics = self.append_encode_into_buffer(event.topics());
        let data = self.append_encode_into_buffer(event);
        // Resolve the encoded regions into actual byte slices.
        let topics = &self.buffer[topics];
        let data = &self.buffer[data];
        // Do the actual depositing of the event.
        ext::deposit_event(topics, data);
    }

    fn set_rent_allowance<T>(&mut self, new_value: T::Balance)
    where
        T: EnvTypes,
    {
        self.encode_into_buffer(&new_value);
        ext::set_rent_allowance(&self.buffer[..])
    }

    fn invoke_runtime<T>(&mut self, call: &T::Call) -> Result<()>
    where
        T: EnvTypes,
    {
        self.encode_into_buffer(call);
        ext::dispatch_call(&self.buffer[..]);
        Ok(())
    }

278
279
280
281
    fn invoke_contract<T, Args>(
        &mut self,
        call_params: &CallParams<T, Args, ()>,
    ) -> Result<()>
282
283
    where
        T: EnvTypes,
284
        Args: scale::Encode,
285
286
287
288
    {
        self.invoke_contract_impl(call_params)
    }

289
    fn eval_contract<T, Args, R>(
290
        &mut self,
291
        call_params: &CallParams<T, Args, ReturnType<R>>,
292
293
294
    ) -> Result<R>
    where
        T: EnvTypes,
295
        Args: scale::Encode,
296
297
298
299
300
301
        R: scale::Decode,
    {
        self.invoke_contract_impl(call_params)?;
        self.decode_scratch_buffer().map_err(Into::into)
    }

302
    fn instantiate_contract<T, Args, C>(
303
        &mut self,
304
        params: &InstantiateParams<T, Args, C>,
305
306
307
    ) -> Result<T::AccountId>
    where
        T: EnvTypes,
308
        Args: scale::Encode,
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
    {
        // Reset the contract-side buffer to append onto clean slate.
        self.reset_buffer();
        // Append the encoded `code_hash`, `endowment` and `create_data`
        // in order and remember their encoded regions within the buffer.
        let code_hash = self.append_encode_into_buffer(params.code_hash());
        let endowment = self.append_encode_into_buffer(params.endowment());
        let create_data = self.append_encode_into_buffer(params.input_data());
        // Resolve the encoded regions into actual byte slices.
        let code_hash = &self.buffer[code_hash];
        let endowment = &self.buffer[endowment];
        let create_data = &self.buffer[create_data];
        // Do the actual contract instantiation.
        ext::create(code_hash, params.gas_limit(), endowment, create_data)?;
        // At this point our contract instantiation was successful
        // and we can now fetch the returned data and decode it for
        // the result value.
        self.decode_scratch_buffer().map_err(Into::into)
    }

    fn restore_contract<T>(
        &mut self,
        account_id: T::AccountId,
        code_hash: T::Hash,
        rent_allowance: T::Balance,
        filtered_keys: &[Key],
    ) where
        T: EnvTypes,
    {
        // Reset the contract-side buffer to append onto clean slate.
        self.reset_buffer();
        // Append the encoded `account_id`, `code_hash` and `rent_allowance`
        // and `filtered_keys` in order and remember their encoded regions
        // within the buffer.
        let account_id = self.append_encode_into_buffer(account_id);
        let code_hash = self.append_encode_into_buffer(code_hash);
        let rent_allowance = self.append_encode_into_buffer(rent_allowance);
        // Resolve the encoded regions into actual byte slices.
        let account_id = &self.buffer[account_id];
        let code_hash = &self.buffer[code_hash];
        let rent_allowance = &self.buffer[rent_allowance];
        // Perform the actual contract restoration.
        ext::restore_to(account_id, code_hash, rent_allowance, filtered_keys);
    }

354
355
356
357
358
359
360
361
    fn terminate_contract<T>(&mut self, beneficiary: T::AccountId) -> !
    where
        T: EnvTypes,
    {
        self.encode_into_buffer(beneficiary);
        ext::terminate(&self.buffer[..]);
    }

362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
    fn transfer<T>(&mut self, destination: T::AccountId, value: T::Balance) -> Result<()>
    where
        T: EnvTypes,
    {
        // Reset the contract-side buffer to append onto clean slate.
        self.reset_buffer();
        // Append the encoded `destination` and `value` in order and remember
        // their encoded regions within the buffer.
        let destination = self.append_encode_into_buffer(destination);
        let value = self.append_encode_into_buffer(value);
        // Resolve the encoded regions into actual byte slices.
        let destination = &self.buffer[destination];
        let value = &self.buffer[value];
        // Perform the actual transfer call.
        ext::transfer(destination, value)
    }

379
380
381
382
383
    fn gas_price<T: EnvTypes>(&mut self, gas: u64) -> Result<T::Balance> {
        ext::gas_price(gas);
        self.decode_scratch_buffer().map_err(Into::into)
    }

384
385
386
387
388
389
390
391
    fn random<T>(&mut self, subject: &[u8]) -> Result<T::Hash>
    where
        T: EnvTypes,
    {
        ext::random_seed(subject);
        self.decode_scratch_buffer().map_err(Into::into)
    }
}