1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>
16

            
17
#![cfg(test)]
18

            
19
use sp_runtime::traits::BadOrigin;
20
use {
21
    crate::{
22
        tests::common::*, Balances, CollatorConfiguration, ContainerRegistrar, DataPreservers,
23
        ForeignAssetsCreator, Registrar, RuntimeEvent, StreamPayment,
24
    },
25
    cumulus_primitives_core::{relay_chain::HeadData, ParaId},
26
    dancelight_runtime_constants::currency::EXISTENTIAL_DEPOSIT,
27
    frame_support::{assert_err, assert_noop, assert_ok, BoundedVec},
28
    pallet_foreign_asset_creator::{AssetIdToForeignAsset, ForeignAssetToAssetId},
29
    pallet_registrar_runtime_api::{
30
        runtime_decl_for_registrar_api::RegistrarApi, ContainerChainGenesisData,
31
    },
32
    pallet_stream_payment::StreamConfig,
33
    sp_std::vec,
34
    tp_stream_payment_common::{
35
        AssetId as StreamPaymentAssetId, TimeUnit as StreamPaymentTimeUnit,
36
    },
37
    xcm::latest::prelude::{Junctions::X2, *},
38
};
39

            
40
#[test]
41
1
fn genesis_balances() {
42
1
    ExtBuilder::default()
43
1
        .with_balances(vec![
44
1
            // Alice gets 10k extra tokens for her mapping deposit
45
1
            (AccountId::from(ALICE), 210_000 * UNIT),
46
1
            (AccountId::from(BOB), 100_000 * UNIT),
47
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
48
1
            (AccountId::from(DAVE), 100_000 * UNIT),
49
1
        ])
50
1
        .build()
51
1
        .execute_with(|| {
52
1
            assert_eq!(
53
1
                Balances::usable_balance(AccountId::from(ALICE)) + EXISTENTIAL_DEPOSIT,
54
1
                210_000 * UNIT,
55
1
            );
56
1
            assert_eq!(
57
1
                Balances::usable_balance(AccountId::from(BOB)) + EXISTENTIAL_DEPOSIT,
58
1
                100_000 * UNIT,
59
1
            );
60
1
        });
61
1
}
62

            
63
#[test]
64
1
fn genesis_para_registrar() {
65
1
    ExtBuilder::default()
66
1
        .with_empty_parachains(vec![1001, 1002])
67
1
        .build()
68
1
        .execute_with(|| {
69
1
            assert_eq!(
70
1
                ContainerRegistrar::registered_para_ids(),
71
1
                vec![1001.into(), 1002.into()]
72
1
            );
73
1
        });
74
1
}
75

            
76
#[test]
77
1
fn genesis_para_registrar_deregister() {
78
1
    ExtBuilder::default()
79
1
        .with_empty_parachains(vec![1001, 1002])
80
1
        .build()
81
1
        .execute_with(|| {
82
1
            assert_eq!(
83
1
                ContainerRegistrar::registered_para_ids(),
84
1
                vec![1001.into(), 1002.into()]
85
1
            );
86

            
87
1
            run_to_block(2);
88
1
            assert_ok!(
89
1
                ContainerRegistrar::deregister(root_origin(), 1002.into()),
90
1
                ()
91
1
            );
92

            
93
            // Pending
94
1
            assert_eq!(
95
1
                ContainerRegistrar::pending_registered_para_ids(),
96
1
                vec![(2u32, BoundedVec::try_from(vec![1001u32.into()]).unwrap())]
97
1
            );
98

            
99
1
            run_to_session(1);
100
1
            assert_eq!(
101
1
                ContainerRegistrar::pending_registered_para_ids(),
102
1
                vec![(2u32, BoundedVec::try_from(vec![1001u32.into()]).unwrap())]
103
1
            );
104
1
            assert_eq!(
105
1
                ContainerRegistrar::registered_para_ids(),
106
1
                vec![1001.into(), 1002.into()]
107
1
            );
108

            
109
1
            run_to_session(2);
110
1
            assert_eq!(ContainerRegistrar::pending_registered_para_ids(), vec![]);
111
1
            assert_eq!(ContainerRegistrar::registered_para_ids(), vec![1001.into()]);
112
1
        });
113
1
}
114

            
115
#[test]
116
1
fn genesis_para_registrar_runtime_api() {
117
1
    ExtBuilder::default()
118
1
        .with_empty_parachains(vec![1001, 1002])
119
1
        .build()
120
1
        .execute_with(|| {
121
1
            assert_eq!(
122
1
                ContainerRegistrar::registered_para_ids(),
123
1
                vec![1001.into(), 1002.into()]
124
1
            );
125
1
            assert_eq!(Runtime::registered_paras(), vec![1001.into(), 1002.into()]);
126

            
127
1
            run_to_block(2);
128
1
            assert_ok!(
129
1
                ContainerRegistrar::deregister(root_origin(), 1002.into()),
130
1
                ()
131
1
            );
132
1
            assert_eq!(Runtime::registered_paras(), vec![1001.into(), 1002.into()]);
133

            
134
1
            run_to_session(1);
135
1
            assert_eq!(
136
1
                ContainerRegistrar::registered_para_ids(),
137
1
                vec![1001.into(), 1002.into()]
138
1
            );
139
1
            assert_eq!(Runtime::registered_paras(), vec![1001.into(), 1002.into()]);
140

            
141
1
            run_to_session(2);
142
1
            assert_eq!(ContainerRegistrar::registered_para_ids(), vec![1001.into()]);
143
1
            assert_eq!(Runtime::registered_paras(), vec![1001.into()]);
144
1
        });
145
1
}
146

            
147
#[test]
148
1
fn genesis_para_registrar_container_chain_genesis_data_runtime_api() {
149
1
    let genesis_data_2001 = empty_genesis_data();
150
1
    let genesis_data_2002 = ContainerChainGenesisData {
151
1
        storage: BoundedVec::try_from(vec![(b"key".to_vec(), b"value".to_vec()).into()]).unwrap(),
152
1
        name: Default::default(),
153
1
        id: Default::default(),
154
1
        fork_id: Default::default(),
155
1
        extensions: BoundedVec::try_from(vec![]).unwrap(),
156
1
        properties: Default::default(),
157
1
    };
158
1
    ExtBuilder::default()
159
1
        .with_para_ids(vec![
160
1
            ParaRegistrationParams {
161
1
                para_id: 2001,
162
1
                genesis_data: genesis_data_2001.clone(),
163
1
                block_production_credits: u32::MAX,
164
1
                collator_assignment_credits: u32::MAX,
165
1
                parathread_params: None,
166
1
            },
167
1
            ParaRegistrationParams {
168
1
                para_id: 2002,
169
1
                genesis_data: genesis_data_2002.clone(),
170
1
                block_production_credits: u32::MAX,
171
1
                collator_assignment_credits: u32::MAX,
172
1
                parathread_params: None,
173
1
            },
174
1
        ])
175
1
        .with_next_free_para_id(2003.into())
176
1
        .build()
177
1
        .execute_with(|| {
178
1
            assert_eq!(
179
1
                ContainerRegistrar::registered_para_ids(),
180
1
                vec![2001.into(), 2002.into()]
181
1
            );
182
1
            assert_eq!(Runtime::registered_paras(), vec![2001.into(), 2002.into()]);
183

            
184
1
            assert_eq!(
185
1
                Runtime::genesis_data(2001.into()).as_ref(),
186
1
                Some(&genesis_data_2001)
187
1
            );
188
1
            assert_eq!(
189
1
                Runtime::genesis_data(2002.into()).as_ref(),
190
1
                Some(&genesis_data_2002)
191
1
            );
192
1
            assert_eq!(Runtime::genesis_data(2003.into()).as_ref(), None);
193

            
194
1
            run_to_block(2);
195
1
            assert_ok!(ContainerRegistrar::deregister(root_origin(), 2002.into()), ());
196

            
197
1
            assert_eq!(Runtime::genesis_data(2002.into()).as_ref(), Some(&genesis_data_2002), "Deregistered container chain genesis data should not be removed until after 2 sessions");
198
1
            assert_ok!(Registrar::reserve(origin_of(ALICE.into())));
199
1
            assert_ok!(
200
1
                ContainerRegistrar::register(
201
1
                    origin_of(ALICE.into()),
202
1
                    2003.into(),
203
1
                    get_genesis_data_with_validation_code().0,
204
1
                    Some(HeadData(vec![1u8, 1u8, 1u8]))
205
1
                ),
206
1
                ()
207
1
            );
208

            
209
            // Registered container chains are inserted immediately
210
1
            assert_eq!(
211
1
                Runtime::genesis_data(2003.into()).as_ref(),
212
1
                Some(&get_genesis_data_with_validation_code().0)
213
1
            );
214

            
215
            // Deregistered container chain genesis data is removed after 2 sessions
216
1
            run_to_session(2u32);
217
1
            assert_eq!(Runtime::genesis_data(2002.into()).as_ref(), None);
218
1
        });
219
1
}
220

            
221
#[test]
222
1
fn test_configuration_on_session_change() {
223
1
    ExtBuilder::default().build().execute_with(|| {
224
1
        assert_eq!(CollatorConfiguration::config().max_collators, 100);
225
1
        assert_eq!(
226
1
            CollatorConfiguration::config().min_orchestrator_collators,
227
1
            2
228
1
        );
229
1
        assert_eq!(CollatorConfiguration::config().collators_per_container, 2);
230

            
231
1
        assert_ok!(
232
1
            CollatorConfiguration::set_max_collators(root_origin(), 50),
233
1
            ()
234
1
        );
235
1
        run_to_session(1u32);
236
1

            
237
1
        assert_ok!(
238
1
            CollatorConfiguration::set_min_orchestrator_collators(root_origin(), 20),
239
1
            ()
240
1
        );
241
1
        assert_eq!(CollatorConfiguration::config().max_collators, 100);
242
1
        assert_eq!(
243
1
            CollatorConfiguration::config().min_orchestrator_collators,
244
1
            2
245
1
        );
246
1
        assert_eq!(CollatorConfiguration::config().collators_per_container, 2);
247

            
248
1
        run_to_session(2u32);
249
1
        assert_ok!(
250
1
            CollatorConfiguration::set_collators_per_container(root_origin(), 10),
251
1
            ()
252
1
        );
253
1
        assert_eq!(CollatorConfiguration::config().max_collators, 50);
254
1
        assert_eq!(
255
1
            CollatorConfiguration::config().min_orchestrator_collators,
256
1
            2
257
1
        );
258
1
        assert_eq!(CollatorConfiguration::config().collators_per_container, 2);
259

            
260
1
        run_to_session(3u32);
261
1

            
262
1
        assert_eq!(CollatorConfiguration::config().max_collators, 50);
263
1
        assert_eq!(
264
1
            CollatorConfiguration::config().min_orchestrator_collators,
265
1
            20
266
1
        );
267
1
        assert_eq!(CollatorConfiguration::config().collators_per_container, 2);
268

            
269
1
        run_to_session(4u32);
270
1

            
271
1
        assert_eq!(CollatorConfiguration::config().max_collators, 50);
272
1
        assert_eq!(
273
1
            CollatorConfiguration::config().min_orchestrator_collators,
274
1
            20
275
1
        );
276
1
        assert_eq!(CollatorConfiguration::config().collators_per_container, 10);
277
1
    });
278
1
}
279

            
280
#[test]
281
1
fn test_cannot_mark_valid_para_with_no_bootnodes() {
282
1
    ExtBuilder::default()
283
1
        .with_balances(vec![
284
1
            // Alice gets 10k extra tokens for her mapping deposit
285
1
            (AccountId::from(ALICE), 210_000 * UNIT),
286
1
            (AccountId::from(BOB), 100_000 * UNIT),
287
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
288
1
            (AccountId::from(DAVE), 100_000 * UNIT),
289
1
        ])
290
1
        .with_collators(vec![
291
1
            (AccountId::from(ALICE), 210 * UNIT),
292
1
            (AccountId::from(BOB), 100 * UNIT),
293
1
            (AccountId::from(CHARLIE), 100 * UNIT),
294
1
            (AccountId::from(DAVE), 100 * UNIT),
295
1
        ])
296
1
        .build()
297
1
        .execute_with(|| {
298
1
            run_to_block(2);
299
1
            assert_ok!(Registrar::reserve(origin_of(ALICE.into())));
300
1
            assert_ok!(ContainerRegistrar::register(
301
1
                origin_of(ALICE.into()),
302
1
                2000.into(),
303
1
                get_genesis_data_with_validation_code().0,
304
1
                Some(HeadData(vec![1u8, 1u8, 1u8]))
305
1
            ));
306
1
            assert_noop!(
307
1
                ContainerRegistrar::mark_valid_for_collating(root_origin(), 2000.into()),
308
1
                pallet_data_preservers::Error::<Runtime>::NoBootNodes,
309
1
            );
310
1
        });
311
1
}
312

            
313
#[test]
314
1
fn test_container_deregister_unassign_data_preserver() {
315
1
    ExtBuilder::default()
316
1
        .with_balances(vec![
317
1
            (AccountId::from(ALICE), 210_000 * UNIT),
318
1
            (AccountId::from(BOB), 100_000 * UNIT),
319
1
        ])
320
1
        .build()
321
1
        .execute_with(|| {
322
            use pallet_data_preservers::{
323
                AssignerParameterOf, ParaIdsFilter, Profile, ProfileMode, ProviderRequestOf,
324
            };
325

            
326
1
            let profile = Profile {
327
1
                url: b"test".to_vec().try_into().unwrap(),
328
1
                para_ids: ParaIdsFilter::AnyParaId,
329
1
                mode: ProfileMode::Bootnode,
330
1
                assignment_request: ProviderRequestOf::<Runtime>::Free,
331
1
            };
332
1

            
333
1
            let para_id = ParaId::from(2000);
334
1
            let profile_id = 0u64;
335
1
            assert_ok!(Registrar::reserve(origin_of(ALICE.into())));
336
1
            assert_ok!(ContainerRegistrar::register(
337
1
                origin_of(ALICE.into()),
338
1
                para_id,
339
1
                get_genesis_data_with_validation_code().0,
340
1
                Some(HeadData(vec![1u8, 1u8, 1u8]))
341
1
            ));
342

            
343
1
            assert_ok!(DataPreservers::create_profile(
344
1
                origin_of(BOB.into()),
345
1
                profile.clone(),
346
1
            ));
347

            
348
            // Start assignment
349
1
            assert_ok!(DataPreservers::start_assignment(
350
1
                origin_of(ALICE.into()),
351
1
                profile_id,
352
1
                para_id,
353
1
                AssignerParameterOf::<Runtime>::Free
354
1
            ));
355
1
            assert!(pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&0u64));
356

            
357
            // Deregister from Registrar
358
1
            assert_ok!(ContainerRegistrar::deregister(root_origin(), para_id), ());
359

            
360
            // Check DataPreserver assignment has been cleared
361
1
            assert!(pallet_data_preservers::Assignments::<Runtime>::get(para_id).is_empty());
362
1
        });
363
1
}
364

            
365
#[test]
366
1
fn stream_payment_works() {
367
1
    ExtBuilder::default()
368
1
        .with_balances(vec![
369
1
            (AccountId::from(ALICE), 100_000 * UNIT),
370
1
            (AccountId::from(BOB), 100_000 * UNIT),
371
1
            (AccountId::from(CHARLIE), 100_000 * UNIT),
372
1
        ])
373
1
        .with_collators(vec![
374
1
            (AccountId::from(CHARLIE), 100 * UNIT),
375
1
            (AccountId::from(DAVE), 100 * UNIT),
376
1
        ])
377
1
        .build()
378
1
        .execute_with(|| {
379
            use pallet_stream_payment::{ChangeKind, StreamConfig};
380

            
381
1
            assert_ok!(StreamPayment::open_stream(
382
1
                origin_of(ALICE.into()),
383
1
                BOB.into(),
384
1
                StreamConfig {
385
1
                    rate: 2 * UNIT,
386
1
                    asset_id: StreamPaymentAssetId::Native,
387
1
                    time_unit: StreamPaymentTimeUnit::BlockNumber,
388
1
                    minimum_request_deadline_delay: 0,
389
1
                    soft_minimum_deposit: 0,
390
1
                },
391
1
                1_000 * UNIT,
392
1
            ));
393

            
394
1
            run_block();
395
1

            
396
1
            assert_ok!(StreamPayment::perform_payment(origin_of(CHARLIE.into()), 0));
397
1
            assert_eq!(
398
1
                Balances::free_balance(AccountId::from(BOB)),
399
1
                100_000 * UNIT + 2 * UNIT
400
1
            );
401

            
402
1
            assert_ok!(StreamPayment::request_change(
403
1
                origin_of(ALICE.into()),
404
1
                0,
405
1
                ChangeKind::Suggestion,
406
1
                StreamConfig {
407
1
                    rate: 1 * UNIT,
408
1
                    asset_id: StreamPaymentAssetId::Native,
409
1
                    time_unit: StreamPaymentTimeUnit::BlockNumber,
410
1
                    minimum_request_deadline_delay: 0,
411
1
                    soft_minimum_deposit: 0,
412
1
                },
413
1
                None,
414
1
            ));
415

            
416
1
            assert_ok!(StreamPayment::accept_requested_change(
417
1
                origin_of(BOB.into()),
418
1
                0,
419
1
                1, // nonce
420
1
                None,
421
1
            ));
422

            
423
1
            run_block();
424
1

            
425
1
            assert_ok!(StreamPayment::close_stream(origin_of(BOB.into()), 0));
426

            
427
1
            assert_eq!(
428
1
                Balances::free_balance(AccountId::from(BOB)),
429
1
                100_000 * UNIT + 3 * UNIT
430
1
            );
431
1
            assert_eq!(
432
1
                Balances::free_balance(AccountId::from(ALICE)),
433
1
                100_000 * UNIT - 3 * UNIT
434
1
            );
435
1
        });
436
1
}
437

            
438
#[test]
439
1
fn test_data_preserver_with_stream_payment() {
440
1
    ExtBuilder::default()
441
1
        .with_balances(vec![
442
1
            (AccountId::from(ALICE), 210_000 * UNIT),
443
1
            (AccountId::from(BOB), 100_000 * UNIT),
444
1
        ])
445
1
        .build()
446
1
        .execute_with(|| {
447
            use pallet_data_preservers::{
448
                AssignerParameterOf, ParaIdsFilter, Profile, ProfileMode, ProviderRequestOf,
449
            };
450

            
451
1
            let profile = Profile {
452
1
                url: b"test".to_vec().try_into().unwrap(),
453
1
                para_ids: ParaIdsFilter::AnyParaId,
454
1
                mode: ProfileMode::Bootnode,
455
1
                assignment_request: ProviderRequestOf::<Runtime>::StreamPayment {
456
1
                    config: StreamConfig {
457
1
                        time_unit: StreamPaymentTimeUnit::BlockNumber,
458
1
                        asset_id: StreamPaymentAssetId::Native,
459
1
                        rate: 42,
460
1
                        minimum_request_deadline_delay: 0,
461
1
                        soft_minimum_deposit: 0,
462
1
                    },
463
1
                },
464
1
            };
465
1

            
466
1
            let para_id = ParaId::from(2000);
467
1
            let profile_id = 0u64;
468
1

            
469
1
            assert_ok!(Registrar::reserve(origin_of(ALICE.into())));
470
1
            assert_ok!(ContainerRegistrar::register(
471
1
                origin_of(ALICE.into()),
472
1
                para_id,
473
1
                get_genesis_data_with_validation_code().0,
474
1
                Some(HeadData(vec![1u8, 1u8, 1u8]))
475
1
            ));
476

            
477
1
            assert_ok!(DataPreservers::create_profile(
478
1
                origin_of(BOB.into()),
479
1
                profile.clone(),
480
1
            ));
481

            
482
            // Start assignment
483
1
            assert_ok!(DataPreservers::start_assignment(
484
1
                origin_of(ALICE.into()),
485
1
                profile_id,
486
1
                para_id,
487
1
                AssignerParameterOf::<Runtime>::StreamPayment {
488
1
                    initial_deposit: 1_000
489
1
                }
490
1
            ));
491
1
            assert!(
492
1
                pallet_data_preservers::Assignments::<Runtime>::get(para_id).contains(&profile_id)
493
1
            );
494
1
            let profile = pallet_data_preservers::Profiles::<Runtime>::get(&profile_id)
495
1
                .expect("profile to exists");
496
1
            let (assigned_para_id, witness) = profile.assignment.expect("profile to be assigned");
497
1
            assert_eq!(assigned_para_id, para_id);
498
1
            assert_eq!(
499
1
                witness,
500
1
                tp_data_preservers_common::AssignmentWitness::StreamPayment { stream_id: 0 }
501
1
            );
502
1
        });
503
1
}
504

            
505
#[test]
506
1
fn test_data_preserver_kind_needs_to_match() {
507
1
    ExtBuilder::default()
508
1
        .with_balances(vec![
509
1
            (AccountId::from(ALICE), 210_000 * UNIT),
510
1
            (AccountId::from(BOB), 100_000 * UNIT),
511
1
        ])
512
1
        .build()
513
1
        .execute_with(|| {
514
            use pallet_data_preservers::{
515
                AssignerParameterOf, ParaIdsFilter, Profile, ProfileMode, ProviderRequestOf,
516
            };
517

            
518
1
            let profile = Profile {
519
1
                url: b"test".to_vec().try_into().unwrap(),
520
1
                para_ids: ParaIdsFilter::AnyParaId,
521
1
                mode: ProfileMode::Bootnode,
522
1
                assignment_request: ProviderRequestOf::<Runtime>::Free,
523
1
            };
524
1

            
525
1
            let para_id = ParaId::from(2000);
526
1
            let profile_id = 0u64;
527
1

            
528
1
            assert_ok!(Registrar::reserve(origin_of(ALICE.into())));
529
1
            assert_ok!(ContainerRegistrar::register(
530
1
                origin_of(ALICE.into()),
531
1
                para_id,
532
1
                get_genesis_data_with_validation_code().0,
533
1
                Some(HeadData(vec![1u8, 1u8, 1u8]))
534
1
            ));
535

            
536
1
            assert_ok!(DataPreservers::create_profile(
537
1
                origin_of(BOB.into()),
538
1
                profile.clone(),
539
1
            ));
540

            
541
            // Start assignment
542
1
            assert_err!(
543
1
                DataPreservers::start_assignment(
544
1
                    origin_of(ALICE.into()),
545
1
                    profile_id,
546
1
                    para_id,
547
1
                    AssignerParameterOf::<Runtime>::StreamPayment {
548
1
                        initial_deposit: 1_000
549
1
                    }
550
1
                ),
551
1
                pallet_data_preservers::Error::<Runtime>::AssignmentPaymentRequestParameterMismatch
552
1
            );
553
1
        });
554
1
}
555

            
556
#[test]
557
1
fn test_registrar_extrinsic_permissions() {
558
1
    ExtBuilder::default()
559
1
        .with_balances(vec![
560
1
            (AccountId::from(ALICE), 210_000 * UNIT),
561
1
            (AccountId::from(BOB), 100_000 * UNIT),
562
1
        ])
563
1
        .with_empty_parachains(vec![1001])
564
1
        .build()
565
1
        .execute_with(|| {
566
1
            let para_id = ParaId::from(1001);
567
1

            
568
1
            // Pause container chain should fail if not para manager
569
1
            assert_noop!(
570
1
                ContainerRegistrar::pause_container_chain(origin_of(BOB.into()), para_id),
571
1
                BadOrigin
572
1
            );
573

            
574
            // Set Bob as para manager
575
1
            assert_ok!(ContainerRegistrar::set_para_manager(
576
1
                root_origin(),
577
1
                para_id,
578
1
                AccountId::from(BOB)
579
1
            ));
580

            
581
            // Pause container chain should succeed if para manager
582
1
            assert_ok!(
583
1
                ContainerRegistrar::pause_container_chain(origin_of(BOB.into()), para_id),
584
1
                ()
585
1
            );
586
1
        });
587
1
}
588

            
589
#[test]
590
1
fn stream_payment_stored_profile_correct_size() {
591
    use crate::OPEN_STREAM_HOLD_AMOUNT;
592
    use pallet_stream_payment::{
593
        ChangeKind, ChangeRequest, DepositChange, Party, Stream, StreamConfig, StreamOf,
594
    };
595
    use parity_scale_codec::Encode;
596

            
597
1
    let stream: StreamOf<Runtime> = Stream {
598
1
        source: ALICE.into(),
599
1
        target: BOB.into(),
600
1
        config: StreamConfig {
601
1
            time_unit: StreamPaymentTimeUnit::Timestamp,
602
1
            asset_id: StreamPaymentAssetId::Native,
603
1
            rate: 41,
604
1
            minimum_request_deadline_delay: 0,
605
1
            soft_minimum_deposit: 0,
606
1
        },
607
1
        deposit: 42,
608
1
        last_time_updated: 43,
609
1
        request_nonce: 44,
610
1
        pending_request: Some(ChangeRequest {
611
1
            requester: Party::Source,
612
1
            kind: ChangeKind::Mandatory { deadline: 45 },
613
1
            new_config: StreamConfig {
614
1
                time_unit: StreamPaymentTimeUnit::BlockNumber,
615
1
                asset_id: StreamPaymentAssetId::Native,
616
1
                rate: 46,
617
1
                minimum_request_deadline_delay: 0,
618
1
                soft_minimum_deposit: 0,
619
1
            },
620
1
            deposit_change: Some(DepositChange::Absolute(47)),
621
1
        }),
622
1
        opening_deposit: 48,
623
1
    };
624
1
    let size = stream.encoded_size();
625
1
    assert_eq!(
626
        size, OPEN_STREAM_HOLD_AMOUNT as usize,
627
        "encoded len doesn't match size configured for hold"
628
    );
629
1
}
630

            
631
#[test]
632
1
fn test_register_eth_foreign_asset() {
633
1
    ExtBuilder::default()
634
1
        .with_balances(vec![
635
1
            (AccountId::from(ALICE), 210_000 * UNIT),
636
1
            (AccountId::from(BOB), 100_000 * UNIT),
637
1
        ])
638
1
        .build()
639
1
        .execute_with(|| {
640
1
            let asset_location = Location {
641
1
                parents: 1,
642
1
                interior: X2([
643
1
                    GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }),
644
1
                    AccountKey20 {
645
1
                        network: Some(NetworkId::Ethereum { chain_id: 1 }),
646
1
                        key: [0; 20],
647
1
                    },
648
1
                ]
649
1
                .into()),
650
1
            };
651
1

            
652
1
            let asset_id = 42u16;
653
1

            
654
1
            assert_ok!(ForeignAssetsCreator::create_foreign_asset(
655
1
                root_origin(),
656
1
                asset_location.clone(),
657
1
                asset_id,
658
1
                AccountId::from(BOB),
659
1
                true,
660
1
                1
661
1
            ));
662

            
663
1
            let foreign_asset_created_event = System::events()
664
1
                .iter()
665
1
                .filter(|r| match r.event {
666
                    RuntimeEvent::ForeignAssetsCreator(
667
                        pallet_foreign_asset_creator::Event::ForeignAssetCreated { .. },
668
1
                    ) => true,
669
1
                    _ => false,
670
2
                })
671
1
                .count();
672
1

            
673
1
            assert_eq!(
674
                foreign_asset_created_event, 1,
675
                "ForeignAssetCreated event should be emitted!"
676
            );
677

            
678
1
            assert_eq!(
679
1
                AssetIdToForeignAsset::<Runtime>::get(asset_id),
680
1
                Some(asset_location.clone())
681
1
            );
682

            
683
1
            assert_eq!(
684
1
                ForeignAssetToAssetId::<Runtime>::get(asset_location.clone()),
685
1
                Some(asset_id)
686
1
            );
687
1
        });
688
1
}
689

            
690
#[test]
691
1
fn test_register_eth_foreign_asset_not_root_should_fail() {
692
1
    ExtBuilder::default()
693
1
        .with_balances(vec![
694
1
            (AccountId::from(ALICE), 210_000 * UNIT),
695
1
            (AccountId::from(BOB), 100_000 * UNIT),
696
1
        ])
697
1
        .build()
698
1
        .execute_with(|| {
699
1
            let asset_location = Location {
700
1
                parents: 1,
701
1
                interior: X2([
702
1
                    GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }),
703
1
                    AccountKey20 {
704
1
                        network: Some(NetworkId::Ethereum { chain_id: 1 }),
705
1
                        key: [0; 20],
706
1
                    },
707
1
                ]
708
1
                .into()),
709
1
            };
710
1

            
711
1
            let asset_id = 42u16;
712
1

            
713
1
            assert_noop!(
714
1
                ForeignAssetsCreator::create_foreign_asset(
715
1
                    origin_of(AccountId::from(ALICE)),
716
1
                    asset_location,
717
1
                    asset_id,
718
1
                    AccountId::from(BOB),
719
1
                    true,
720
1
                    1
721
1
                ),
722
1
                BadOrigin
723
1
            );
724
1
        });
725
1
}
726

            
727
#[test]
728
1
fn test_register_same_eth_foreign_asset_twice_should_fail() {
729
1
    ExtBuilder::default()
730
1
        .with_balances(vec![
731
1
            (AccountId::from(ALICE), 210_000 * UNIT),
732
1
            (AccountId::from(BOB), 100_000 * UNIT),
733
1
        ])
734
1
        .build()
735
1
        .execute_with(|| {
736
1
            let asset_location = Location {
737
1
                parents: 1,
738
1
                interior: X2([
739
1
                    GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }),
740
1
                    AccountKey20 {
741
1
                        network: Some(NetworkId::Ethereum { chain_id: 1 }),
742
1
                        key: [0; 20],
743
1
                    },
744
1
                ]
745
1
                .into()),
746
1
            };
747
1

            
748
1
            let asset_id = 42u16;
749
1

            
750
1
            assert_ok!(ForeignAssetsCreator::create_foreign_asset(
751
1
                root_origin(),
752
1
                asset_location,
753
1
                asset_id,
754
1
                AccountId::from(BOB),
755
1
                true,
756
1
                1
757
1
            ));
758

            
759
1
            let asset_location = Location {
760
1
                parents: 1,
761
1
                interior: X2([
762
1
                    GlobalConsensus(NetworkId::Ethereum { chain_id: 1 }),
763
1
                    AccountKey20 {
764
1
                        network: Some(NetworkId::Ethereum { chain_id: 1 }),
765
1
                        key: [1; 20],
766
1
                    },
767
1
                ]
768
1
                .into()),
769
1
            };
770
1

            
771
1
            assert_noop!(
772
1
                ForeignAssetsCreator::create_foreign_asset(
773
1
                    root_origin(),
774
1
                    asset_location,
775
1
                    asset_id,
776
1
                    AccountId::from(BOB),
777
1
                    true,
778
1
                    1
779
1
                ),
780
1
                pallet_foreign_asset_creator::Error::<Runtime>::AssetAlreadyExists
781
1
            );
782
1
        });
783
1
}