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
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
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
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
278
279
280
281
282
283
284
285
286
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
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
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
383
384
385
386
387
388
389
390
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// 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.

use crate::{
    call::{
        utils::{
            EmptyArgumentList,
            ReturnType,
            Set,
            Unset,
            Unwrap,
        },
        ExecutionInput,
    },
    Environment,
    Error,
};
use core::marker::PhantomData;

/// The final parameters to the cross-contract call.
#[derive(Debug)]
pub struct CallParams<E, Args, R>
where
    E: Environment,
{
    /// The account ID of the to-be-called smart contract.
    callee: E::AccountId,
    /// The maximum gas costs allowed for the call.
    gas_limit: u64,
    /// The transferred value for the call.
    transferred_value: E::Balance,
    /// The expected return type.
    return_type: ReturnType<R>,
    /// The inputs to the execution which is a selector and encoded arguments.
    exec_input: ExecutionInput<Args>,
}

#[cfg(
    // We do not currently support cross-contract calling in the off-chain
    // environment so we do not have to provide these getters in case of
    // off-chain environment compilation.
    all(not(feature = "std"), target_arch = "wasm32")
)]
impl<E, Args, R> CallParams<E, Args, R>
where
    E: Environment,
{
    /// Returns the account ID of the called contract instance.
    #[inline]
    pub(crate) fn callee(&self) -> &E::AccountId {
        &self.callee
    }

    /// Returns the chosen gas limit for the called contract execution.
    #[inline]
    pub(crate) fn gas_limit(&self) -> u64 {
        self.gas_limit
    }

    /// Returns the transferred value for the called contract.
    #[inline]
    pub(crate) fn transferred_value(&self) -> &E::Balance {
        &self.transferred_value
    }

    /// Returns the execution input.
    #[inline]
    pub(crate) fn exec_input(&self) -> &ExecutionInput<Args> {
        &self.exec_input
    }
}

impl<E, Args> CallParams<E, Args, ()>
where
    E: Environment,
    Args: scale::Encode,
{
    /// Invokes the contract with the given built-up call parameters.
    ///
    /// # Note
    ///
    /// Prefer [`invoke`](`Self::invoke`) over [`eval`](`Self::eval`) if the
    /// called contract message does not return anything because it is more efficient.
    pub fn invoke(&self) -> Result<(), crate::Error> {
        crate::invoke_contract(self)
    }
}

impl<E, Args, R> CallParams<E, Args, ReturnType<R>>
where
    E: Environment,
    Args: scale::Encode,
    R: scale::Decode,
{
    /// Evaluates the contract with the given built-up call parameters.
    ///
    /// Returns the result of the contract execution.
    ///
    /// # Note
    ///
    /// Prefer [`invoke`](`Self::invoke`) over [`eval`](`Self::eval`) if the
    /// called contract message does not return anything because it is more efficient.
    pub fn eval(&self) -> Result<R, crate::Error> {
        crate::eval_contract(self)
    }
}

/// Returns a new [`CallBuilder`] to build up the parameters to a cross-contract call.
///
/// # Example
///
/// **Note:** The shown examples panic because there is currently no cross-calling
///           support in the off-chain testing environment. However, this code
///           should work fine in on-chain environments.
///
/// ## Example 1: No Return Value
///
/// The below example shows calling of a message of another contract that does
/// not return any value back to its caller. The called function ...
///
/// - has a selector equal to `0xDEADBEEF`
/// - is provided with 5000 units of gas for its execution
/// - is provided with 10 units of transferred value for the contract instance
/// - receives the following arguments in order
///    1. an `i32` with value `42`
///    2. a `bool` with value `true`
///    3. an array of 32 `u8` with value `0x10`
///
/// ```should_panic
/// # use ::ink_env::{
/// #     Environment,
/// #     DefaultEnvironment,
/// #     call::{build_call, Selector, ExecutionInput}
/// # };
/// # type AccountId = <DefaultEnvironment as Environment>::AccountId;
/// build_call::<DefaultEnvironment>()
///     .callee(AccountId::from([0x42; 32]))
///     .gas_limit(5000)
///     .transferred_value(10)
///     .exec_input(
///         ExecutionInput::new(Selector::new([0xDE, 0xAD, 0xBE, 0xEF]))
///             .push_arg(42)
///             .push_arg(true)
///             .push_arg(&[0x10u8; 32])
///     )
///     .returns::<()>()
///     .fire()
///     .unwrap();
/// ```
///
/// ## Example 2: With Return Value
///
/// The below example shows calling of a message of another contract that does
/// return a `i32` value back to its caller. The called function ...
///
/// - has a selector equal to `0xDEADBEEF`
/// - is provided with 5000 units of gas for its execution
/// - is provided with 10 units of transferred value for the contract instance
/// - receives the following arguments in order
///    1. an `i32` with value `42`
///    2. a `bool` with value `true`
///    3. an array of 32 `u8` with value `0x10`
///
/// ```should_panic
/// # use ::ink_env::{
/// #     Environment,
/// #     DefaultEnvironment,
/// #     call::{build_call, Selector, ExecutionInput, utils::ReturnType},
/// # };
/// # type AccountId = <DefaultEnvironment as Environment>::AccountId;
/// let my_return_value: i32 = build_call::<DefaultEnvironment>()
///     .callee(AccountId::from([0x42; 32]))
///     .gas_limit(5000)
///     .transferred_value(10)
///     .exec_input(
///         ExecutionInput::new(Selector::new([0xDE, 0xAD, 0xBE, 0xEF]))
///             .push_arg(42)
///             .push_arg(true)
///             .push_arg(&[0x10; 32])
///     )
///     .returns::<ReturnType<i32>>()
///     .fire()
///     .unwrap();
/// ```
#[allow(clippy::type_complexity)]
pub fn build_call<E>() -> CallBuilder<
    E,
    Unset<E::AccountId>,
    Unset<u64>,
    Unset<E::Balance>,
    Unset<ExecutionInput<EmptyArgumentList>>,
    Unset<ReturnType<()>>,
>
where
    E: Environment,
{
    CallBuilder {
        env: Default::default(),
        callee: Default::default(),
        gas_limit: Default::default(),
        transferred_value: Default::default(),
        exec_input: Default::default(),
        return_type: Default::default(),
    }
}

/// Builds up a cross contract call.
pub struct CallBuilder<E, Callee, GasLimit, TransferredValue, Args, RetType>
where
    E: Environment,
{
    env: PhantomData<fn() -> E>,
    /// The current parameters that have been built up so far.
    callee: Callee,
    gas_limit: GasLimit,
    transferred_value: TransferredValue,
    exec_input: Args,
    return_type: RetType,
}

impl<E, GasLimit, TransferredValue, Args, RetType>
    CallBuilder<E, Unset<E::AccountId>, GasLimit, TransferredValue, Args, RetType>
where
    E: Environment,
{
    /// Sets the called smart contract instance account ID to the given value.
    #[inline]
    pub fn callee(
        self,
        callee: E::AccountId,
    ) -> CallBuilder<E, Set<E::AccountId>, GasLimit, TransferredValue, Args, RetType>
    {
        CallBuilder {
            env: Default::default(),
            callee: Set(callee),
            gas_limit: self.gas_limit,
            transferred_value: self.transferred_value,
            exec_input: self.exec_input,
            return_type: self.return_type,
        }
    }
}

impl<E, Callee, TransferredValue, Args, RetType>
    CallBuilder<E, Callee, Unset<u64>, TransferredValue, Args, RetType>
where
    E: Environment,
{
    /// Sets the maximum allowed gas costs for the call.
    #[inline]
    pub fn gas_limit(
        self,
        gas_limit: u64,
    ) -> CallBuilder<E, Callee, Set<u64>, TransferredValue, Args, RetType> {
        CallBuilder {
            env: Default::default(),
            callee: self.callee,
            gas_limit: Set(gas_limit),
            transferred_value: self.transferred_value,
            exec_input: self.exec_input,
            return_type: self.return_type,
        }
    }
}

impl<E, Callee, GasLimit, Args, RetType>
    CallBuilder<E, Callee, GasLimit, Unset<E::Balance>, Args, RetType>
where
    E: Environment,
{
    /// Sets the value transferred upon the execution of the call.
    #[inline]
    pub fn transferred_value(
        self,
        transferred_value: E::Balance,
    ) -> CallBuilder<E, Callee, GasLimit, Set<E::Balance>, Args, RetType> {
        CallBuilder {
            env: Default::default(),
            callee: self.callee,
            gas_limit: self.gas_limit,
            transferred_value: Set(transferred_value),
            exec_input: self.exec_input,
            return_type: self.return_type,
        }
    }
}

mod seal {
    /// Used to prevent users from implementing `IndicateReturnType` for their own types.
    pub trait Sealed {}
    impl Sealed for () {}
    impl<T> Sealed for super::ReturnType<T> {}
}
/// Types that can be used in [`CallBuilder::returns`] to signal return type.
pub trait IndicateReturnType: Default + self::seal::Sealed {}
impl IndicateReturnType for () {}
impl<T> IndicateReturnType for ReturnType<T> {}

impl<E, Callee, GasLimit, TransferredValue, Args>
    CallBuilder<E, Callee, GasLimit, TransferredValue, Args, Unset<ReturnType<()>>>
where
    E: Environment,
{
    /// Sets the type of the returned value upon the execution of the call.
    ///
    /// # Note
    ///
    /// Either use `.returns::<()>` to signal that the call does not return a value
    /// or use `.returns::<ReturnType<T>>` to signal that the call returns a value of
    /// type `T`.
    #[inline]
    pub fn returns<R>(
        self,
    ) -> CallBuilder<E, Callee, GasLimit, TransferredValue, Args, Set<R>>
    where
        R: IndicateReturnType,
    {
        CallBuilder {
            env: Default::default(),
            callee: self.callee,
            gas_limit: self.gas_limit,
            transferred_value: self.transferred_value,
            exec_input: self.exec_input,
            return_type: Set(Default::default()),
        }
    }
}

impl<E, Callee, GasLimit, TransferredValue, RetType>
    CallBuilder<
        E,
        Callee,
        GasLimit,
        TransferredValue,
        Unset<ExecutionInput<EmptyArgumentList>>,
        RetType,
    >
where
    E: Environment,
{
    /// Sets the execution input to the given value.
    pub fn exec_input<Args>(
        self,
        exec_input: ExecutionInput<Args>,
    ) -> CallBuilder<
        E,
        Callee,
        GasLimit,
        TransferredValue,
        Set<ExecutionInput<Args>>,
        RetType,
    > {
        CallBuilder {
            env: Default::default(),
            callee: self.callee,
            gas_limit: self.gas_limit,
            transferred_value: self.transferred_value,
            exec_input: Set(exec_input),
            return_type: self.return_type,
        }
    }
}

impl<E, GasLimit, TransferredValue, Args, RetType>
    CallBuilder<
        E,
        Set<E::AccountId>,
        GasLimit,
        TransferredValue,
        Set<ExecutionInput<Args>>,
        Set<RetType>,
    >
where
    E: Environment,
    GasLimit: Unwrap<Output = u64>,
    TransferredValue: Unwrap<Output = E::Balance>,
{
    /// Finalizes the call builder to call a function.
    pub fn params(self) -> CallParams<E, Args, RetType> {
        CallParams {
            callee: self.callee.value(),
            gas_limit: self.gas_limit.unwrap_or_else(|| 0),
            transferred_value: self
                .transferred_value
                .unwrap_or_else(|| E::Balance::from(0u32)),
            return_type: Default::default(),
            exec_input: self.exec_input.value(),
        }
    }
}

impl<E, GasLimit, TransferredValue, Args>
    CallBuilder<
        E,
        Set<E::AccountId>,
        GasLimit,
        TransferredValue,
        Set<ExecutionInput<Args>>,
        Set<()>,
    >
where
    E: Environment,
    GasLimit: Unwrap<Output = u64>,
    Args: scale::Encode,
    TransferredValue: Unwrap<Output = E::Balance>,
{
    /// Invokes the cross-chain function call.
    pub fn fire(self) -> Result<(), Error> {
        self.params().invoke()
    }
}

impl<E, GasLimit, TransferredValue, Args, R>
    CallBuilder<
        E,
        Set<E::AccountId>,
        GasLimit,
        TransferredValue,
        Set<ExecutionInput<Args>>,
        Set<ReturnType<R>>,
    >
where
    E: Environment,
    GasLimit: Unwrap<Output = u64>,
    Args: scale::Encode,
    R: scale::Decode,
    TransferredValue: Unwrap<Output = E::Balance>,
{
    /// Invokes the cross-chain function call and returns the result.
    pub fn fire(self) -> Result<R, Error> {
        self.params().eval()
    }
}