ink_e2e 6.0.0-beta.2

[ink!] End-to-end testing framework for smart contracts.
Documentation
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
// 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 ink_env::{
    Environment,
    call::utils::{
        DecodeMessageResult,
        EncodeArgsWith,
    },
};
use ink_primitives::H160;
use ink_revive_types::evm::CallTrace;
use jsonrpsee::core::async_trait;
use sp_weights::Weight;
use subxt::dynamic::Value;

use super::{
    H256,
    InstantiateDryRunResult,
    Keypair,
};
use crate::{
    CallBuilder,
    CallBuilderFinal,
    CallDryRunResult,
    UploadResult,
    backend_calls::{
        InstantiateBuilder,
        RemoveCodeBuilder,
        UploadBuilder,
    },
    builders::CreateBuilderPartial,
    contract_results::BareInstantiationResult,
};

/// Full E2E testing backend: combines general chain API and contract-specific operations.
#[async_trait]
pub trait E2EBackend<E: Environment>: ChainBackend + BuilderClient<E> {}

/// General chain operations useful in contract testing.
#[async_trait]
pub trait ChainBackend {
    /// Account type.
    type AccountId;
    /// Balance type.
    type Balance: Send + From<u32> + std::fmt::Debug;
    /// Error type.
    type Error;
    /// Event log type.
    type EventLog;

    /// Generate a new account and fund it with the given `amount` of tokens from the
    /// `origin`.
    async fn create_and_fund_account(
        &mut self,
        origin: &Keypair,
        amount: Self::Balance,
    ) -> Keypair;

    /// Returns the free balance of `account`.
    async fn free_balance(
        &mut self,
        account: Self::AccountId,
    ) -> Result<Self::Balance, Self::Error>;

    /// Executes a runtime call `call_name` for the `pallet_name`.
    /// The `call_data` is a `Vec<Value>`.
    ///
    /// Note:
    /// - `pallet_name` must be in camel case, for example `Balances`.
    /// - `call_name` must be snake case, for example `force_transfer`.
    /// - `call_data` is a `Vec<subxt::dynamic::Value>` that holds a representation of
    ///   some value.
    ///
    /// Returns when the transaction is included in a block. The return value contains all
    /// events that are associated with this transaction.
    ///
    /// Since we might run node with an arbitrary runtime, this method inherently must
    /// support dynamic calls.
    async fn runtime_call<'a>(
        &mut self,
        origin: &Keypair,
        pallet_name: &'a str,
        call_name: &'a str,
        call_data: Vec<Value>,
    ) -> Result<Self::EventLog, Self::Error>;

    /// Attempt to transfer the `value` from `origin` to `dest`.
    ///
    /// Returns `Ok` on success, and a [`subxt::Error`] if the extrinsic is
    /// invalid (e.g. out of date nonce)
    async fn transfer_allow_death(
        &mut self,
        origin: &Keypair,
        dest: Self::AccountId,
        value: Self::Balance,
    ) -> Result<(), Self::Error>;
}

/// Contract-specific operations.
#[async_trait]
pub trait ContractsBackend<E: Environment> {
    /// Error type.
    type Error;
    /// Event log type.
    type EventLog;

    /// Start building an instantiate call using a builder pattern.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Constructor method
    /// let mut constructor = FlipperRef::new(false);
    /// let contract = client
    ///     .instantiate("flipper", &ink_e2e::alice(), &mut constructor)
    ///     // Optional arguments
    ///     // Send 100 units with the call.
    ///     .value(100)
    ///     // Add 10% margin to the gas limit
    ///     .extra_gas_portion(10)
    ///     .storage_deposit_limit(100)
    ///     // Submit the call for on-chain execution.
    ///     .submit()
    ///     .await
    ///     .expect("instantiate failed");
    /// ```
    fn instantiate<
        'a,
        Contract: Clone,
        Args: Send + Clone + EncodeArgsWith<Abi> + Sync,
        R,
        Abi: Send + Sync + Clone,
    >(
        &'a mut self,
        contract_name: &'a str,
        caller: &'a Keypair,
        constructor: &'a mut CreateBuilderPartial<E, Contract, Args, R, Abi>,
    ) -> InstantiateBuilder<'a, E, Contract, Args, R, Self, Abi>
    where
        Self: Sized + BuilderClient<E>,
    {
        InstantiateBuilder::new(self, caller, contract_name, constructor)
    }

    /// Start building an upload call.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let contract = client
    ///     .upload("flipper", &ink_e2e::alice())
    ///     // Optional arguments
    ///     .storage_deposit_limit(100)
    ///     // Submit the call for on-chain execution.
    ///     .submit()
    ///     .await
    ///     .expect("upload failed");
    /// ```
    fn upload<'a>(
        &'a mut self,
        contract_name: &'a str,
        caller: &'a Keypair,
    ) -> UploadBuilder<'a, E, Self>
    where
        Self: Sized + BuilderClient<E>,
    {
        UploadBuilder::new(self, contract_name, caller)
    }

    /// Start building a remove code call.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let contract = client
    ///     .remove_code(&ink_e2e::alice(), code_hash)
    ///     // Submit the call for on-chain execution.
    ///     .submit()
    ///     .await
    ///     .expect("remove failed");
    /// ```
    fn remove_code<'a>(
        &'a mut self,
        caller: &'a Keypair,
        code_hash: H256,
    ) -> RemoveCodeBuilder<'a, E, Self>
    where
        Self: Sized + BuilderClient<E>,
    {
        RemoveCodeBuilder::new(self, caller, code_hash)
    }

    /// Start building a call using a builder pattern.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Message method
    /// let get = call_builder.get();
    /// let get_res = client
    ///    .call(&ink_e2e::bob(), &get)
    ///     // Optional arguments
    ///     // Send 100 units with the call.
    ///     .value(100)
    ///     // Add 10% margin to the gas limit
    ///     .extra_gas_portion(10)
    ///     .storage_deposit_limit(100)
    ///     // Submit the call for on-chain execution.
    ///     .submit()
    ///     .await
    ///     .expect("instantiate failed");
    /// ```
    fn call<
        'a,
        Args: Sync + EncodeArgsWith<Abi> + Clone,
        RetType: Send + DecodeMessageResult<Abi>,
        Abi: Sync + Clone,
    >(
        &'a mut self,
        caller: &'a Keypair,
        message: &'a CallBuilderFinal<E, Args, RetType, Abi>,
    ) -> CallBuilder<'a, E, Args, RetType, Self, Abi>
    where
        Self: Sized + BuilderClient<E>,
    {
        CallBuilder::new(self, caller, message)
    }
}

#[async_trait]
pub trait BuilderClient<E: Environment>: ContractsBackend<E> {
    /// Executes a bare `call` for the contract at `account_id`. This function does
    /// _not_ perform a dry-run, and the user is expected to provide the gas limit.
    ///
    /// Use it when you want to have a more precise control over submitting extrinsic.
    ///
    /// Returns when the transaction is included in a block. The return value
    /// contains all events that are associated with this transaction.
    async fn bare_call<
        Args: Sync + EncodeArgsWith<Abi> + Clone,
        RetType: Send + DecodeMessageResult<Abi>,
        Abi: Sync + Clone,
    >(
        &mut self,
        caller: &Keypair,
        message: &CallBuilderFinal<E, Args, RetType, Abi>,
        value: E::Balance,
        gas_limit: Weight,
        storage_deposit_limit: E::Balance,
    ) -> Result<(Self::EventLog, Option<CallTrace>), Self::Error>
    where
        CallBuilderFinal<E, Args, RetType, Abi>: Clone;

    /// Executes a dry-run `call`.
    ///
    /// Returns the result of the dry run, together with the decoded return value of the
    /// invoked message.
    ///
    /// Important: For an uncomplicated UX of the E2E testing environment we
    /// decided to automatically map the account in `pallet-revive`, if not
    /// yet mapped. This is a side effect, as a transaction is then issued
    /// on-chain and the user incurs costs!
    async fn bare_call_dry_run<
        Args: Sync + EncodeArgsWith<Abi> + Clone,
        RetType: Send + DecodeMessageResult<Abi>,
        Abi: Sync + Clone,
    >(
        &mut self,
        caller: &Keypair,
        message: &CallBuilderFinal<E, Args, RetType, Abi>,
        value: E::Balance,
        storage_deposit_limit: Option<E::Balance>,
    ) -> Result<CallDryRunResult<E, RetType, Abi>, Self::Error>
    where
        CallBuilderFinal<E, Args, RetType, Abi>: Clone;

    /// Executes a dry-run `call`.
    ///
    /// Returns the result of the dry run, together with the decoded return value of the
    /// invoked message.
    ///
    /// Important: For an uncomplicated UX of the E2E testing environment we
    /// decided to automatically map the account in `pallet-revive`, if not
    /// yet mapped. This is a side effect, as a transaction is then issued
    /// on-chain and the user incurs costs!
    async fn raw_call_dry_run<
        RetType: Send + DecodeMessageResult<Abi>,
        Abi: Sync + Clone,
    >(
        &mut self,
        dest: H160,
        input_data: Vec<u8>,
        value: E::Balance,
        storage_deposit_limit: Option<E::Balance>,
        signer: &Keypair,
    ) -> Result<CallDryRunResult<E, RetType, Abi>, Self::Error>;

    /// Executes a dry-run `call`.
    ///
    /// Returns the result of the dry run, together with the decoded return value of the
    /// invoked message.
    async fn raw_call(
        &mut self,
        dest: H160,
        input_data: Vec<u8>,
        value: E::Balance,
        gas_limit: Weight,
        storage_deposit_limit: E::Balance,
        signer: &Keypair,
    ) -> Result<(Self::EventLog, Option<CallTrace>), Self::Error>;

    /// Uploads the contract call.
    ///
    /// This function extracts the binary of the contract for the specified contract.
    ///
    /// Calling this function multiple times should be idempotent, the contract is
    /// newly instantiated each time using a unique salt. No existing contract
    /// instance is reused!
    async fn bare_upload(
        &mut self,
        contract_name: &str,
        caller: &Keypair,
        storage_deposit_limit: Option<E::Balance>,
    ) -> Result<UploadResult<E, Self::EventLog>, Self::Error>;

    /// Removes the code of the contract at `code_hash`.
    async fn bare_remove_code(
        &mut self,
        caller: &Keypair,
        code_hash: crate::H256,
    ) -> Result<Self::EventLog, Self::Error>;

    /// Bare instantiate call. This function does not perform a dry-run,
    /// and user is expected to provide the gas limit.
    ///
    /// Use it when you want to have a more precise control over submitting extrinsic.
    ///
    /// The function subsequently uploads and instantiates an instance of the contract.
    ///
    /// This function extracts the metadata of the contract at the file path
    /// `target/ink/$contract_name.contract`.
    ///
    /// Calling this function multiple times should be idempotent, the contract is
    /// newly instantiated each time using a unique salt. No existing contract
    /// instance is reused!
    async fn bare_instantiate<
        Contract: Clone,
        Args: Send + Sync + EncodeArgsWith<Abi> + Clone,
        R,
        Abi: Send + Sync + Clone,
    >(
        &mut self,
        code: Vec<u8>,
        caller: &Keypair,
        constructor: &mut CreateBuilderPartial<E, Contract, Args, R, Abi>,
        value: E::Balance,
        gas_limit: Weight,
        storage_deposit_limit: E::Balance,
    ) -> Result<BareInstantiationResult<E, Self::EventLog>, Self::Error>;

    async fn raw_instantiate(
        &mut self,
        code: Vec<u8>,
        caller: &Keypair,
        constructor: Vec<u8>,
        value: E::Balance,
        gas_limit: Weight,
        storage_deposit_limit: E::Balance,
    ) -> Result<BareInstantiationResult<E, Self::EventLog>, Self::Error>;

    async fn raw_instantiate_dry_run<Abi: Sync + Clone>(
        &mut self,
        code: Vec<u8>,
        caller: &Keypair,
        constructor: Vec<u8>,
        value: E::Balance,
        storage_deposit_limit: Option<E::Balance>,
    ) -> Result<InstantiateDryRunResult<E, Abi>, Self::Error>;

    async fn exec_instantiate(
        &mut self,
        signer: &Keypair,
        contract_name: &str,
        data: Vec<u8>,
        value: E::Balance,
        gas_limit: Weight,
        storage_deposit_limit: E::Balance,
    ) -> Result<BareInstantiationResult<E, Self::EventLog>, Self::Error>;

    /// Dry run contract instantiation.
    ///
    /// Important: For an uncomplicated UX of the E2E testing environment we
    /// decided to automatically map the account in `pallet-revive`, if not
    /// yet mapped. This is a side effect, as a transaction is then issued
    /// on-chain and the user incurs costs!
    async fn bare_instantiate_dry_run<
        Contract: Clone,
        Args: Send + Sync + EncodeArgsWith<Abi> + Clone,
        R,
        Abi: Send + Sync + Clone,
    >(
        &mut self,
        contract_name: &str,
        caller: &Keypair,
        constructor: &mut CreateBuilderPartial<E, Contract, Args, R, Abi>,
        value: E::Balance,
        storage_deposit_limit: Option<E::Balance>,
    ) -> Result<InstantiateDryRunResult<E, Abi>, Self::Error>;

    /// Checks if `caller` was already mapped in `pallet-revive`. If not, it will do so
    /// and return the events associated with that transaction.
    async fn map_account(
        &mut self,
        caller: &Keypair,
    ) -> Result<Option<Self::EventLog>, Self::Error>;

    /// Returns the `Environment::AccountId` for an `H160` address.
    async fn to_account_id(&mut self, addr: &H160) -> Result<E::AccountId, Self::Error>;

    fn load_code(&self, contract_name: &str) -> Vec<u8>;
}