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
// Copyright (C) Use Ink (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::{
    utils::ReturnType,
    Selector,
};
use crate::Environment;

/// The input data and the expected return type of a contract execution.
pub struct Execution<Args, Output> {
    /// The input data for initiating a contract execution.
    pub input: ExecutionInput<Args>,
    /// The type of the expected return value of the contract execution.
    pub output: ReturnType<Output>,
}

impl<Args, Output> Execution<Args, Output>
where
    Args: scale::Encode,
    Output: scale::Decode,
{
    /// Construct a new contract execution with the given input data.
    pub fn new(input: ExecutionInput<Args>) -> Self {
        Self {
            input,
            output: ReturnType::default(),
        }
    }

    /// Perform the execution of the contract with the given executor.
    pub fn exec<I, E>(
        self,
        executor: &I,
    ) -> Result<ink_primitives::MessageResult<Output>, I::Error>
    where
        E: Environment,
        I: Executor<E>,
    {
        executor.exec(&self.input)
    }
}

/// Implemented in different environments to perform contract execution.
pub trait Executor<E: Environment> {
    /// The type of the error that can be returned during execution.
    type Error;
    /// Perform the contract execution with the given input data, and return the result.
    fn exec<Args, Output>(
        &self,
        input: &ExecutionInput<Args>,
    ) -> Result<ink_primitives::MessageResult<Output>, Self::Error>
    where
        Args: scale::Encode,
        Output: scale::Decode;
}

/// The input data for a smart contract execution.
#[derive(Clone, Default, Debug)]
pub struct ExecutionInput<Args> {
    /// The selector for the smart contract execution.
    selector: Selector,
    /// The arguments of the smart contract execution.
    args: Args,
}

impl ExecutionInput<EmptyArgumentList> {
    /// Creates a new execution input with the given selector.
    #[inline]
    pub fn new(selector: Selector) -> Self {
        Self {
            selector,
            args: ArgumentList::empty(),
        }
    }

    /// Pushes an argument to the execution input.
    #[inline]
    pub fn push_arg<T>(
        self,
        arg: T,
    ) -> ExecutionInput<ArgumentList<Argument<T>, EmptyArgumentList>>
    where
        T: scale::Encode,
    {
        ExecutionInput {
            selector: self.selector,
            args: self.args.push_arg(arg),
        }
    }
}

impl<Head, Rest> ExecutionInput<ArgumentList<Argument<Head>, Rest>> {
    /// Pushes an argument to the execution input.
    #[inline]
    pub fn push_arg<T>(self, arg: T) -> ExecutionInput<ArgsList<T, ArgsList<Head, Rest>>>
    where
        T: scale::Encode,
    {
        ExecutionInput {
            selector: self.selector,
            args: self.args.push_arg(arg),
        }
    }
}

impl<Args> ExecutionInput<Args> {
    /// Modify the selector.
    ///
    /// Useful when using the [`ExecutionInput`] generated as part of the
    /// `ContractRef`, but using a custom selector.
    pub fn update_selector(&mut self, selector: Selector) {
        self.selector = selector;
    }
}

/// An argument list.
///
/// This type is constructed mainly at compile type via type constructions
/// to avoid having to allocate heap memory while constructing the encoded
/// arguments. The potentially heap allocating encoding is done right at the end
/// where we can leverage the static environmental buffer instead of allocating
/// heap memory.
#[derive(Clone, Default, Debug)]
pub struct ArgumentList<Head, Rest> {
    /// The first argument of the argument list.
    head: Head,
    /// All the rest arguments.
    rest: Rest,
}

/// Minor simplification of an argument list with a head and rest.
pub type ArgsList<Head, Rest> = ArgumentList<Argument<Head>, Rest>;

/// A single argument and its reference to a known value.
#[derive(Clone, Debug)]
pub struct Argument<T> {
    /// The reference to the known value.
    ///
    /// Used for the encoding at the end of the construction.
    arg: T,
}

impl<T> Argument<T> {
    /// Creates a new argument.
    #[inline]
    fn new(arg: T) -> Self {
        Self { arg }
    }
}

/// The end of an argument list.
#[derive(Clone, Default, Debug)]
pub struct ArgumentListEnd;

/// An empty argument list.
pub type EmptyArgumentList = ArgumentList<ArgumentListEnd, ArgumentListEnd>;

impl EmptyArgumentList {
    /// Creates a new empty argument list.
    #[inline]
    pub fn empty() -> EmptyArgumentList {
        ArgumentList {
            head: ArgumentListEnd,
            rest: ArgumentListEnd,
        }
    }

    /// Pushes the first argument to the empty argument list.
    #[inline]
    pub fn push_arg<T>(self, arg: T) -> ArgumentList<Argument<T>, Self>
    where
        T: scale::Encode,
    {
        ArgumentList {
            head: Argument::new(arg),
            rest: self,
        }
    }
}

impl<Head, Rest> ArgumentList<Argument<Head>, Rest> {
    /// Pushes another argument to the argument list.
    #[inline]
    pub fn push_arg<T>(self, arg: T) -> ArgumentList<Argument<T>, Self>
    where
        T: scale::Encode,
    {
        ArgumentList {
            head: Argument::new(arg),
            rest: self,
        }
    }
}

impl<T> scale::Encode for Argument<T>
where
    T: scale::Encode,
{
    #[inline]
    fn size_hint(&self) -> usize {
        <T as scale::Encode>::size_hint(&self.arg)
    }

    #[inline]
    fn encode_to<O: scale::Output + ?Sized>(&self, output: &mut O) {
        <T as scale::Encode>::encode_to(&self.arg, output)
    }
}

impl scale::Encode for EmptyArgumentList {
    #[inline]
    fn size_hint(&self) -> usize {
        0
    }

    #[inline]
    fn encode_to<O: scale::Output + ?Sized>(&self, _output: &mut O) {}
}

impl<Head, Rest> scale::Encode for ArgumentList<Argument<Head>, Rest>
where
    Head: scale::Encode,
    Rest: scale::Encode,
{
    #[inline]
    fn size_hint(&self) -> usize {
        scale::Encode::size_hint(&self.head)
            .checked_add(scale::Encode::size_hint(&self.rest))
            .unwrap()
    }

    #[inline]
    fn encode_to<O: scale::Output + ?Sized>(&self, output: &mut O) {
        // We reverse the order of encoding because we build up the list of
        // arguments in reverse order, too. This way we encode the arguments
        // in the same order in which they have been pushed to the argument list
        // while the argument list itself organizes them in reverse order.
        scale::Encode::encode_to(&self.rest, output);
        scale::Encode::encode_to(&self.head, output);
    }
}

impl<Args> scale::Encode for ExecutionInput<Args>
where
    Args: scale::Encode,
{
    #[inline]
    fn size_hint(&self) -> usize {
        scale::Encode::size_hint(&self.selector)
            .checked_add(scale::Encode::size_hint(&self.args))
            .unwrap()
    }

    #[inline]
    fn encode_to<O: scale::Output + ?Sized>(&self, output: &mut O) {
        scale::Encode::encode_to(&self.selector, output);
        scale::Encode::encode_to(&self.args, output);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn empty_exec_input_works() {
        let selector = Selector::new([0x01, 0x02, 0x03, 0x04]);
        let exec_input = ExecutionInput::new(selector);
        let encoded = scale::Encode::encode(&exec_input);
        assert!(!encoded.is_empty());
        let decoded = <Selector as scale::Decode>::decode(&mut &encoded[..]).unwrap();
        assert_eq!(decoded, selector);
    }

    #[test]
    fn empty_args_works() {
        let empty_list = ArgumentList::empty();
        let encoded = scale::Encode::encode(&empty_list);
        assert_eq!(encoded, <Vec<u8>>::new());
    }

    #[test]
    fn single_argument_works() {
        let empty_list = ArgumentList::empty().push_arg(&1i32);
        let encoded = scale::Encode::encode(&empty_list);
        assert!(!encoded.is_empty());
        let decoded = <i32 as scale::Decode>::decode(&mut &encoded[..]).unwrap();
        assert_eq!(decoded, 1i32);
    }

    #[test]
    fn multiple_arguments_works() {
        let empty_list = ArgumentList::empty()
            .push_arg(&42i32)
            .push_arg(&true)
            .push_arg(&[0x66u8; 4]);
        let encoded = scale::Encode::encode(&empty_list);
        assert!(!encoded.is_empty());
        let decoded =
            <(i32, bool, [u8; 4]) as scale::Decode>::decode(&mut &encoded[..]).unwrap();
        assert_eq!(decoded, (42i32, true, [0x66; 4]));
    }
}