chain_extension.rs 17 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
// Copyright 2018-2021 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.

//! Definitions and utilities for calling chain extension methods.
//!
//! Users should not use these types and definitions directly but rather use the provided
//! `#[ink::chain_extension]` procedural macro defined in the `ink_lang` crate.

use crate::{
    backend::EnvBackend,
    engine::{
        EnvInstance,
        OnInstance,
    },
};
use core::marker::PhantomData;

/// Implemented by error codes in order to construct them from status codes.
///
/// A status code is returned by calling an ink! chain extension method.
/// It is the `u32` return value.
///
/// The purpose of an `ErrorCode` type that implements this trait is to provide
/// more context information about the status of an ink! chain extension method call.
pub trait FromStatusCode: Sized {
    /// Returns `Ok` if the status code for the called chain extension method is valid.
    ///
    /// Returning `Ok` will query the output buffer of the call if the chain extension
    /// method definition has a return value.
    ///
    /// # Note
    ///
    /// The convention is to use `0` as the only `raw` value that yields `Ok` whereas
    /// every other value represents one error code. By convention this mapping should
    /// never panic and therefore every `raw` value must map to either `Ok` or to a proper
    /// `ErrorCode` variant.
    fn from_status_code(status_code: u32) -> Result<(), Self>;
}

/// A concrete instance of a chain extension method.
///
/// This is a utility type used to drive the execution of a chain extension method call.
54
55
/// It has several specializations of its `call` method for different ways to manage
/// error handling when calling a predefined chain extension method.
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
///
/// - `I` represents the input type of the chain extension method.
///   All tuple types that may act as input parameters for the chain extension method are valid.
///   Examples include `()`, `i32`, `(u8, [u8; 5], i32)`, etc.
/// - `O` represents the return (or output) type of the chain extension method.
///   Only `Result<T, E>` or `NoResult<O>` generic types are allowed for `O`.
///   The `Result<T, E>` type says that the chain extension method returns a `Result` type
///   whereas the `NoResult<O>` type says that the chain extension method returns a non-`Result` value
///   of type `O`.
/// - `ErrorCode` represents how the chain extension method handles the chain extension's error code.
///   Only `HandleErrorCode<E>` and `IgnoreErrorCode` types are allowed that each say to either properly
///   handle or ignore the chain extension's error code respectively.
///
/// The type states for type parameter `O` and `ErrorCode` represent 4 different states:
///
/// 1. The chain extension method makes use of the chain extension's error code: `HandleErrorCode(E)`
///     - **A:** The chain extension method returns a `Result<T, E>` type.
///     - **B:** The chain extension method returns a type `T` that is not a `Result` type: `NoResult<T>`
/// 2. The chain extension ignores the chain extension's error code: `IgnoreErrorCode`
///     - **A:** The chain extension method returns a `Result<T, E>` type.
///     - **B:** The chain extension method returns a type `T` that is not a `Result` type: `NoResult<T>`
#[derive(Debug)]
pub struct ChainExtensionMethod<I, O, ErrorCode> {
    func_id: u32,
    #[allow(clippy::type_complexity)]
    state: PhantomData<fn() -> (I, O, ErrorCode)>,
}

impl ChainExtensionMethod<(), (), ()> {
    /// Creates a new chain extension method instance.
    #[inline(always)]
    pub fn build(func_id: u32) -> Self {
        Self {
            func_id,
            state: Default::default(),
        }
    }
}

impl<O, ErrorCode> ChainExtensionMethod<(), O, ErrorCode> {
    /// Sets the input types of the chain extension method call to `I`.
    ///
    /// # Note
    ///
    /// `I` represents the input type of the chain extension method.
    /// All tuple types that may act as input parameters for the chain extension method are valid.
    /// Examples include `()`, `i32`, `(u8, [u8; 5], i32)`, etc.
    #[inline(always)]
    pub fn input<I>(self) -> ChainExtensionMethod<I, O, ErrorCode>
    where
        I: scale::Encode,
    {
        ChainExtensionMethod {
            func_id: self.func_id,
            state: Default::default(),
        }
    }
}

impl<I, ErrorCode> ChainExtensionMethod<I, (), ErrorCode> {
    /// Sets the output type of the chain extension method call to `Result<T, E>`.
    ///
    /// # Note
    ///
    /// This indicates that the chain extension method return value might represent a failure.
    #[inline(always)]
    pub fn output_result<T, E>(self) -> ChainExtensionMethod<I, Result<T, E>, ErrorCode>
    where
        Result<T, E>: scale::Decode,
        E: From<scale::Error>,
    {
        ChainExtensionMethod {
            func_id: self.func_id,
            state: Default::default(),
        }
    }

    /// Sets the output type of the chain extension method call to `O`.
    ///
    /// # Note
    ///
    /// The set returned type `O` must not be of type `Result<T, E>`.
    /// When using the `#[ink::chain_extension]` procedural macro to define
    /// this chain extension method the above constraint is enforced at
    /// compile time.
    #[inline(always)]
    pub fn output<O>(self) -> ChainExtensionMethod<I, state::NoResult<O>, ErrorCode>
    where
        O: scale::Decode,
    {
        ChainExtensionMethod {
            func_id: self.func_id,
            state: Default::default(),
        }
    }
}

impl<I, O> ChainExtensionMethod<I, O, ()> {
    /// Makes the chain extension method call assume that the returned status code is always success.
    ///
    /// # Note
    ///
    /// This will avoid handling of failure status codes returned by the chain extension method call.
    /// Use this only if you are sure that the chain extension method call will never return an error
    /// code that represents failure.
    ///
    /// The output of the chain extension method call is always decoded and returned in this case.
    #[inline(always)]
    pub fn ignore_error_code(self) -> ChainExtensionMethod<I, O, state::IgnoreErrorCode> {
        ChainExtensionMethod {
            func_id: self.func_id,
            state: Default::default(),
        }
    }

171
    /// Makes the chain extension method call handle the returned status code.
172
173
174
175
    ///
    /// # Note
    ///
    /// This will handle the returned status code and only loads and decodes the value
176
    /// returned as the output of the chain extension method call in case of success.
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
    #[inline(always)]
    pub fn handle_error_code<ErrorCode>(
        self,
    ) -> ChainExtensionMethod<I, O, state::HandleErrorCode<ErrorCode>>
    where
        ErrorCode: FromStatusCode,
    {
        ChainExtensionMethod {
            func_id: self.func_id,
            state: Default::default(),
        }
    }
}

/// Type states of the chain extension method instance.
pub mod state {
    use core::marker::PhantomData;

    /// Type state meaning that the chain extension method ignores the chain extension's error code.
    #[derive(Debug)]
    pub enum IgnoreErrorCode {}

    /// Type state meaning that the chain extension method uses the chain extension's error code.
    #[derive(Debug)]
    pub struct HandleErrorCode<T> {
        error_code: PhantomData<fn() -> T>,
    }

    /// Type state meaning that the chain extension method deliberately does not return a `Result` type.
    ///
207
    /// Additionally this is enforced by the `#[ink::chain_extension]` procedural macro when used.
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    #[derive(Debug)]
    pub struct NoResult<T> {
        no_result: PhantomData<fn() -> T>,
    }
}

impl<I, T, E, ErrorCode>
    ChainExtensionMethod<I, Result<T, E>, state::HandleErrorCode<ErrorCode>>
where
    I: scale::Encode,
    T: scale::Decode,
    E: scale::Decode + From<ErrorCode> + From<scale::Error>,
    ErrorCode: FromStatusCode,
{
222
    /// Calls the chain extension method for case 1.A described [here].
223
    ///
224
    /// [here]: [`ChainExtensionMethod`]
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
    ///
    /// # Errors
    ///
    /// - If the called chain extension method returns a non-successful error code.
    /// - If the `Result` return value of the called chain extension represents an error.
    /// - If the `Result` return value cannot be SCALE decoded properly.
    /// - If custom constraints specified by the called chain extension method are violated.
    ///     - These constraints are determined and defined by the author of the chain extension method.
    ///
    /// # Example
    ///
    /// Declares a chain extension method with the unique ID of 5 that requires a `bool` and an `i32`
    /// as input parameters and returns a `Result<i32, MyError>` upon completion.
    /// It will handle the shared error code from the chain extension.
    /// The call is finally invoked with arguments `true` and `42` for the `bool` and `i32` input
    /// parameter respectively.
    ///
    /// ```should_panic
    /// # // Panics because the off-chain environment has not
    /// # // registered a chain extension method for the ID.
    /// # use ink_env::chain_extension::{ChainExtensionMethod, FromStatusCode};
    /// let result = ChainExtensionMethod::build(5)
    ///     .input::<(bool, i32)>()
    ///     .output_result::<i32, MyError>()
    ///     .handle_error_code::<MyErrorCode>()
    ///     .call(&(true, 42));
    /// # #[derive(scale::Encode, scale::Decode)]
    /// # pub struct MyError {}
    /// # impl From<scale::Error> for MyError {
    /// #     fn from(_error: scale::Error) -> Self { Self {} }
    /// # }
    /// # impl From<MyErrorCode> for MyError {
    /// #     fn from(_error: MyErrorCode) -> Self { Self {} }
    /// # }
    /// # pub struct MyErrorCode {}
    /// # impl FromStatusCode for MyErrorCode {
    /// #     fn from_status_code(status_code: u32) -> Result<(), Self> { Ok(()) }
    /// # }
    /// ```
    #[inline(always)]
    pub fn call(self, input: &I) -> Result<T, E> {
        <EnvInstance as OnInstance>::on_instance(|instance| {
            EnvBackend::call_chain_extension::<I, T, E, ErrorCode, _, _>(
                instance,
                self.func_id,
                input,
                ErrorCode::from_status_code,
272
                |mut output| scale::Decode::decode(&mut output).map_err(Into::into),
273
274
275
276
277
278
279
280
281
282
283
            )
        })
    }
}

impl<I, T, E> ChainExtensionMethod<I, Result<T, E>, state::IgnoreErrorCode>
where
    I: scale::Encode,
    T: scale::Decode,
    E: scale::Decode + From<scale::Error>,
{
284
    /// Calls the chain extension method for case 2.A described [here].
285
    ///
286
    /// [here]: [`ChainExtensionMethod`]
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
    ///
    /// # Errors
    ///
    /// - If the `Result` return value of the called chain extension represents an error.
    /// - If the `Result` return value cannot be SCALE decoded properly.
    /// - If custom constraints specified by the called chain extension method are violated.
    ///     - These constraints are determined and defined by the author of the chain extension method.
    ///
    /// # Example
    ///
    /// Declares a chain extension method with the unique ID of 5 that requires a `bool` and an `i32`
    /// as input parameters and returns a `Result<i32, MyError>` upon completion.
    /// It will ignore the shared error code from the chain extension and assumes that the call succeeds.
    /// The call is finally invoked with arguments `true` and `42` for the `bool` and `i32` input
    /// parameter respectively.
    ///
    /// ```should_panic
    /// # // Panics because the off-chain environment has not
    /// # // registered a chain extension method for the ID.
    /// # use ink_env::chain_extension::{ChainExtensionMethod};
    /// let result = ChainExtensionMethod::build(5)
    ///     .input::<(bool, i32)>()
    ///     .output_result::<i32, MyError>()
    ///     .ignore_error_code()
    ///     .call(&(true, 42));
    /// # #[derive(scale::Encode, scale::Decode)]
    /// # pub struct MyError {}
    /// # impl From<scale::Error> for MyError {
    /// #     fn from(_error: scale::Error) -> Self { Self {} }
    /// # }
    /// ```
    #[inline(always)]
    pub fn call(self, input: &I) -> Result<T, E> {
        <EnvInstance as OnInstance>::on_instance(|instance| {
            EnvBackend::call_chain_extension::<I, T, E, E, _, _>(
                instance,
                self.func_id,
                input,
                |_status_code| Ok(()),
326
                |mut output| scale::Decode::decode(&mut output).map_err(Into::into),
327
328
329
330
331
332
333
334
335
336
337
338
            )
        })
    }
}

impl<I, O, ErrorCode>
    ChainExtensionMethod<I, state::NoResult<O>, state::HandleErrorCode<ErrorCode>>
where
    I: scale::Encode,
    O: scale::Decode,
    ErrorCode: FromStatusCode,
{
339
    /// Calls the chain extension method for case 1.B described [here].
340
    ///
341
    /// [here]: [`ChainExtensionMethod`]
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
    ///
    /// # Errors
    ///
    /// - If the called chain extension method returns a non-successful error code.
    /// - If custom constraints specified by the called chain extension method are violated.
    ///     - These constraints are determined and defined by the author of the chain extension method.
    ///
    /// # Panics
    ///
    /// - If the return value cannot be SCALE decoded properly.
    ///
    /// # Example
    ///
    /// Declares a chain extension method with the unique ID of 5 that requires a `bool` and an `i32`
    /// as input parameters and returns a `Result<i32, MyErrorCode>` upon completion.
    /// It will handle the shared error code from the chain extension.
    /// The call is finally invoked with arguments `true` and `42` for the `bool` and `i32` input
    /// parameter respectively.
    ///
    /// ```should_panic
    /// # // Panics because the off-chain environment has not
    /// # // registered a chain extension method for the ID.
    /// # use ink_env::chain_extension::{ChainExtensionMethod, FromStatusCode};
    /// let result = ChainExtensionMethod::build(5)
    ///     .input::<(bool, i32)>()
    ///     .output::<i32>()
    ///     .handle_error_code::<MyErrorCode>()
    ///     .call(&(true, 42));
    /// # pub struct MyErrorCode {}
    /// # impl FromStatusCode for MyErrorCode {
    /// #     fn from_status_code(status_code: u32) -> Result<(), Self> { Ok(()) }
    /// # }
    /// ```
    #[inline(always)]
    pub fn call(self, input: &I) -> Result<O, ErrorCode> {
        <EnvInstance as OnInstance>::on_instance(|instance| {
            EnvBackend::call_chain_extension::<I, O, ErrorCode, ErrorCode, _, _>(
                instance,
                self.func_id,
                input,
                ErrorCode::from_status_code,
383
384
                |mut output| {
                    let decoded = <O as scale::Decode>::decode(&mut output)
385
386
387
388
389
390
391
392
393
394
395
396
397
                        .expect("encountered error while decoding chain extension method call return value");
                    Ok(decoded)
                },
            )
        })
    }
}

impl<I, O> ChainExtensionMethod<I, state::NoResult<O>, state::IgnoreErrorCode>
where
    I: scale::Encode,
    O: scale::Decode,
{
398
    /// Calls the chain extension method for case 2.B described [here].
399
    ///
400
    /// [here]: [`ChainExtensionMethod`]
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
    ///
    /// # Panics
    ///
    /// - If the return value cannot be SCALE decoded properly.
    ///
    /// # Example
    ///
    /// Declares a chain extension method with the unique ID of 5 that requires a `bool` and an `i32`
    /// as input parameters and returns a `Result<i32, MyErrorCode>` upon completion.
    /// It will ignore the shared error code from the chain extension and assumes that the call succeeds.
    /// The call is finally invoked with arguments `true` and `42` for the `bool` and `i32` input
    /// parameter respectively.
    ///
    /// ```should_panic
    /// # // Panics because the off-chain environment has not
    /// # // registered a chain extension method for the ID.
    /// # use ink_env::chain_extension::ChainExtensionMethod;
    /// let result = ChainExtensionMethod::build(5)
    ///     .input::<(bool, i32)>()
    ///     .output::<i32>()
    ///     .ignore_error_code()
    ///     .call(&(true, 42));
    /// ```
    #[inline(always)]
    pub fn call(self, input: &I) -> O {
        <EnvInstance as OnInstance>::on_instance(|instance| {
            EnvBackend::call_chain_extension::<I, O, (), (), _, _>(
                instance,
                self.func_id,
                input,
                |_status_code| Ok(()),
432
433
                |mut output| {
                    let decoded = <O as scale::Decode>::decode(&mut output)
434
435
436
437
438
439
440
                        .expect("encountered error while decoding chain extension method call return value");
                    Ok(decoded)
                },
            ).expect("assume the chain extension method never fails")
        })
    }
}