pezkuwi-runtime-common 7.0.0

Pallets and constants used in Relay Chain networks.
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
// Copyright (C) Parity Technologies (UK) Ltd. and Dijital Kurdistan Tech Institute
// This file is part of Pezkuwi.

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

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

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

//! Mocking utilities for testing with real pallets.

use crate::{
	auctions, crowdloan, identity_migrator,
	mock::{conclude_pvf_checking, validators_public_keys},
	paras_registrar,
	slot_range::SlotRange,
	slots,
	traits::{AuctionStatus, Auctioneer, Leaser, Registrar as RegistrarT},
};
use alloc::sync::Arc;
use codec::Encode;
use pezframe_support::{
	assert_noop, assert_ok, derive_impl, parameter_types,
	traits::{ConstU32, Currency},
	weights::Weight,
	PalletId,
};
use pezframe_support_test::TestRandomness;
use pezframe_system::EnsureRoot;
use pezkuwi_primitives::{
	BlockNumber, HeadData, Id as ParaId, SessionIndex, ValidationCode, LOWEST_PUBLIC_ID,
	MAX_CODE_SIZE,
};
use pezkuwi_runtime_teyrchains::{
	configuration, dmp, origin, paras, shared, Origin as ParaOrigin, ParaLifecycle,
};
use pezpallet_identity::{self, legacy::IdentityInfo};
use pezsp_core::{ConstUint, H256};
use pezsp_io::TestExternalities;
use pezsp_keyring::Sr25519Keyring;
use pezsp_keystore::{testing::MemoryKeystore, KeystoreExt};
use pezsp_runtime::{
	traits::{BlakeTwo256, IdentityLookup, One, Verify},
	transaction_validity::TransactionPriority,
	AccountId32, BuildStorage, MultiSignature,
};

type UncheckedExtrinsic = pezframe_system::mocking::MockUncheckedExtrinsic<Test>;
type Block = pezframe_system::mocking::MockBlockU32<Test>;

type AccountId = AccountId32;
type Balance = u32;
type Moment = u32;

fn account_id(i: u32) -> AccountId32 {
	let b4 = i.encode();
	let b32 = [&b4[..], &b4[..], &b4[..], &b4[..], &b4[..], &b4[..], &b4[..], &b4[..]].concat();
	let array: [u8; 32] = b32.try_into().unwrap();
	array.into()
}

fn signed(i: u32) -> RuntimeOrigin {
	let account_id = account_id(i);
	RuntimeOrigin::signed(account_id)
}

pezframe_support::construct_runtime!(
	pub enum Test
	{
		// System Stuff
		System: pezframe_system,
		Balances: pezpallet_balances,
		Babe: pezpallet_babe,

		// Teyrchains Runtime
		Configuration: configuration,
		Paras: paras,
		ParasShared: shared,
		TeyrchainsOrigin: origin,
		Dmp: dmp,

		// Para Onboarding Pallets
		Registrar: paras_registrar,
		Auctions: auctions,
		Crowdloan: crowdloan,
		Slots: slots,

		// Migrators
		Identity: pezpallet_identity,
		IdentityMigrator: identity_migrator,
	}
);

impl<C> pezframe_system::offchain::CreateTransactionBase<C> for Test
where
	RuntimeCall: From<C>,
{
	type Extrinsic = UncheckedExtrinsic;
	type RuntimeCall = RuntimeCall;
}

impl<C> pezframe_system::offchain::CreateBare<C> for Test
where
	RuntimeCall: From<C>,
{
	fn create_bare(call: Self::RuntimeCall) -> Self::Extrinsic {
		UncheckedExtrinsic::new_bare(call)
	}
}

use crate::{auctions::Error as AuctionsError, crowdloan::Error as CrowdloanError};

parameter_types! {
	pub BlockWeights: pezframe_system::limits::BlockWeights =
		pezframe_system::limits::BlockWeights::simple_max(
			Weight::from_parts(4 * 1024 * 1024, u64::MAX),
		);
}

#[derive_impl(pezframe_system::config_preludes::TestDefaultConfig)]
impl pezframe_system::Config for Test {
	type BaseCallFilter = pezframe_support::traits::Everything;
	type BlockWeights = BlockWeights;
	type BlockLength = ();
	type DbWeight = ();
	type RuntimeOrigin = RuntimeOrigin;
	type RuntimeCall = RuntimeCall;
	type Nonce = u64;
	type Hash = H256;
	type Hashing = BlakeTwo256;
	type AccountId = AccountId;
	type Lookup = IdentityLookup<AccountId>;
	type Block = Block;
	type RuntimeEvent = RuntimeEvent;
	type Version = ();
	type PalletInfo = PalletInfo;
	type AccountData = pezpallet_balances::AccountData<Balance>;
	type OnNewAccount = ();
	type OnKilledAccount = ();
	type SystemWeightInfo = ();
	type SS58Prefix = ();
	type OnSetCode = ();
	type MaxConsumers = pezframe_support::traits::ConstU32<16>;
}

parameter_types! {
	pub const EpochDuration: u64 = 10;
	pub const ExpectedBlockTime: Moment = 6_000;
	pub const ReportLongevity: u64 = 10;
	pub const MaxAuthorities: u32 = 100_000;
}

impl pezpallet_babe::Config for Test {
	type EpochDuration = EpochDuration;
	type ExpectedBlockTime = ExpectedBlockTime;
	type EpochChangeTrigger = pezpallet_babe::ExternalTrigger;
	type DisabledValidators = ();
	type WeightInfo = ();
	type MaxAuthorities = MaxAuthorities;
	type MaxNominators = ConstU32<0>;
	type KeyOwnerProof = pezsp_core::Void;
	type EquivocationReportSystem = ();
}

parameter_types! {
	pub const MinimumPeriod: Moment = 6_000 / 2;
}

impl pezpallet_timestamp::Config for Test {
	type Moment = Moment;
	type OnTimestampSet = ();
	type MinimumPeriod = MinimumPeriod;
	type WeightInfo = ();
}

parameter_types! {
	pub static ExistentialDeposit: Balance = 1;
}
#[derive_impl(pezpallet_balances::config_preludes::TestDefaultConfig)]
impl pezpallet_balances::Config for Test {
	type Balance = Balance;
	type ExistentialDeposit = ExistentialDeposit;
	type AccountStore = System;
}

impl configuration::Config for Test {
	type WeightInfo = configuration::TestWeightInfo;
}

impl shared::Config for Test {
	type DisabledValidators = ();
}

impl dmp::Config for Test {}

impl origin::Config for Test {}

parameter_types! {
	pub const ParasUnsignedPriority: TransactionPriority = TransactionPriority::max_value();
}

impl paras::Config for Test {
	type RuntimeEvent = RuntimeEvent;
	type WeightInfo = paras::TestWeightInfo;
	type UnsignedPriority = ParasUnsignedPriority;
	type QueueFootprinter = ();
	type NextSessionRotation = crate::mock::TestNextSessionRotation;
	type OnNewHead = ();
	type AssignCoretime = ();
	type Fungible = Balances;
	type CooldownRemovalMultiplier = ConstUint<1>;
	type AuthorizeCurrentCodeOrigin = EnsureRoot<Self::AccountId>;
}

parameter_types! {
	pub const ParaDeposit: Balance = 500;
	pub const DataDepositPerByte: Balance = 1;
}

impl paras_registrar::Config for Test {
	type RuntimeEvent = RuntimeEvent;
	type OnSwap = (Crowdloan, Slots);
	type ParaDeposit = ParaDeposit;
	type DataDepositPerByte = DataDepositPerByte;
	type Currency = Balances;
	type RuntimeOrigin = RuntimeOrigin;
	type WeightInfo = crate::paras_registrar::TestWeightInfo;
}

parameter_types! {
	pub const EndingPeriod: BlockNumber = 10;
	pub const SampleLength: BlockNumber = 1;
}

impl auctions::Config for Test {
	type RuntimeEvent = RuntimeEvent;
	type Leaser = Slots;
	type Registrar = Registrar;
	type EndingPeriod = EndingPeriod;
	type SampleLength = SampleLength;
	type Randomness = TestRandomness<Self>;
	type InitiateOrigin = EnsureRoot<AccountId>;
	type WeightInfo = crate::auctions::TestWeightInfo;
}

parameter_types! {
	pub const LeasePeriod: BlockNumber = 100;
	pub static LeaseOffset: BlockNumber = 5;
}

impl slots::Config for Test {
	type RuntimeEvent = RuntimeEvent;
	type Currency = Balances;
	type Registrar = Registrar;
	type LeasePeriod = LeasePeriod;
	type LeaseOffset = LeaseOffset;
	type ForceOrigin = EnsureRoot<AccountId>;
	type WeightInfo = crate::slots::TestWeightInfo;
}

parameter_types! {
	pub const CrowdloanId: PalletId = PalletId(*b"py/cfund");
	pub const SubmissionDeposit: Balance = 100;
	pub const MinContribution: Balance = 1;
	pub const RemoveKeysLimit: u32 = 100;
	pub const MaxMemoLength: u8 = 32;
}

impl crowdloan::Config for Test {
	type RuntimeEvent = RuntimeEvent;
	type PalletId = CrowdloanId;
	type SubmissionDeposit = SubmissionDeposit;
	type MinContribution = MinContribution;
	type RemoveKeysLimit = RemoveKeysLimit;
	type Registrar = Registrar;
	type Auctioneer = Auctions;
	type MaxMemoLength = MaxMemoLength;
	type WeightInfo = crate::crowdloan::TestWeightInfo;
}

impl pezpallet_identity::Config for Test {
	type RuntimeEvent = RuntimeEvent;
	type Currency = Balances;
	type Slashed = ();
	type BasicDeposit = ConstU32<100>;
	type ByteDeposit = ConstU32<10>;
	type UsernameDeposit = ConstU32<10>;
	type SubAccountDeposit = ConstU32<100>;
	type MaxSubAccounts = ConstU32<2>;
	type IdentityInformation = IdentityInfo<ConstU32<2>>;
	type MaxRegistrars = ConstU32<20>;
	type RegistrarOrigin = EnsureRoot<AccountId>;
	type ForceOrigin = EnsureRoot<AccountId>;
	type OffchainSignature = MultiSignature;
	type SigningPublicKey = <MultiSignature as Verify>::Signer;
	type UsernameAuthorityOrigin = EnsureRoot<AccountId>;
	type PendingUsernameExpiration = ConstU32<100>;
	type UsernameGracePeriod = ConstU32<10>;
	type MaxSuffixLength = ConstU32<7>;
	type MaxUsernameLength = ConstU32<32>;
	#[cfg(feature = "runtime-benchmarks")]
	type BenchmarkHelper = ();
	type WeightInfo = ();
}

impl identity_migrator::Config for Test {
	type RuntimeEvent = RuntimeEvent;
	type Reaper = EnsureRoot<AccountId>;
	type ReapIdentityHandler = ();
	type WeightInfo = crate::identity_migrator::TestWeightInfo;
}

/// Create a new set of test externalities.
pub fn new_test_ext() -> TestExternalities {
	let mut t = pezframe_system::GenesisConfig::<Test>::default().build_storage().unwrap();
	configuration::GenesisConfig::<Test> {
		config: configuration::HostConfiguration {
			max_code_size: MAX_CODE_SIZE,
			max_head_data_size: 1 * 1024 * 1024, // 1 MB
			..Default::default()
		},
	}
	.assimilate_storage(&mut t)
	.unwrap();
	let keystore = MemoryKeystore::new();
	let mut ext: pezsp_io::TestExternalities = t.into();
	ext.register_extension(KeystoreExt(Arc::new(keystore)));
	ext.execute_with(|| System::set_block_number(1));
	ext
}

#[cfg(feature = "runtime-benchmarks")]
pub fn new_test_ext_with_offset(n: BlockNumber) -> TestExternalities {
	LeaseOffset::set(n);
	new_test_ext()
}

const BLOCKS_PER_SESSION: u32 = 10;

const VALIDATORS: &[Sr25519Keyring] = &[
	Sr25519Keyring::Alice,
	Sr25519Keyring::Bob,
	Sr25519Keyring::Charlie,
	Sr25519Keyring::Dave,
	Sr25519Keyring::Ferdie,
];

fn maybe_new_session(n: u32) {
	if n.is_multiple_of(BLOCKS_PER_SESSION) {
		let session_index = shared::CurrentSessionIndex::<Test>::get() + 1;
		let validators_pub_keys = validators_public_keys(VALIDATORS);

		shared::Pezpallet::<Test>::set_session_index(session_index);
		shared::Pezpallet::<Test>::set_active_validators_ascending(validators_pub_keys);
		Paras::test_on_new_session();
	}
}

fn test_genesis_head(size: usize) -> HeadData {
	HeadData(vec![0u8; size])
}

fn test_validation_code(size: usize) -> ValidationCode {
	let validation_code = vec![0u8; size as usize];
	ValidationCode(validation_code)
}

fn para_origin(id: u32) -> ParaOrigin {
	ParaOrigin::Teyrchain(id.into())
}

fn add_blocks(n: u32) {
	let block_number = System::block_number();
	run_to_block(block_number + n);
}

fn run_to_block(n: u32) {
	System::run_to_block_with::<AllPalletsWithSystem>(
		n,
		pezframe_system::RunToBlockHooks::default().before_initialize(|bn| {
			maybe_new_session(bn);
		}),
	);
}

fn run_to_session(n: u32) {
	let block_number = BLOCKS_PER_SESSION * n;
	run_to_block(block_number);
}

fn last_event() -> RuntimeEvent {
	System::events().pop().expect("RuntimeEvent expected").event
}

fn contains_event(event: RuntimeEvent) -> bool {
	System::events().iter().any(|x| x.event == event)
}

// Runs an end to end test of the auction, crowdloan, slots, and onboarding process over varying
// lease period offsets.
#[test]
fn basic_end_to_end_works() {
	for offset in [0u32, 50, 100, 200].iter() {
		LeaseOffset::set(*offset);
		new_test_ext().execute_with(|| {
			let para_1 = LOWEST_PUBLIC_ID;
			let para_2 = LOWEST_PUBLIC_ID + 1;
			assert!(System::block_number().is_one());
			const START_SESSION_INDEX: SessionIndex = 1;
			run_to_session(START_SESSION_INDEX);
			let start_block = System::block_number();

			// User 1 and 2 will own teyrchains
			Balances::make_free_balance_be(&account_id(1), 1_000_000_000);
			Balances::make_free_balance_be(&account_id(2), 1_000_000_000);
			// First register 2 on-demand teyrchains
			let genesis_head = Registrar::worst_head_data();
			let validation_code = Registrar::worst_validation_code();
			assert_ok!(Registrar::reserve(signed(1)));
			assert_ok!(Registrar::register(
				signed(1),
				ParaId::from(para_1),
				genesis_head.clone(),
				validation_code.clone(),
			));
			conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);
			assert_ok!(Registrar::reserve(signed(2)));
			assert_ok!(Registrar::register(
				signed(2),
				ParaId::from(2001),
				genesis_head,
				validation_code,
			));

			// Paras should be onboarding
			assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::Onboarding));
			assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::Onboarding));

			// Start a new auction in the future
			let duration = 99u32 + offset;
			let lease_period_index_start = 4u32;
			assert_ok!(Auctions::new_auction(
				RuntimeOrigin::root(),
				duration,
				lease_period_index_start
			));

			// 2 sessions later they are parathreads (on-demand teyrchains)
			run_to_session(START_SESSION_INDEX + 2);
			assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::Parathread));
			assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::Parathread));

			// Para 1 will bid directly for slot 1, 2
			// Open a crowdloan for Para 2 for slot 3, 4
			assert_ok!(Crowdloan::create(
				signed(2),
				ParaId::from(para_2),
				1_000,                        // Cap
				lease_period_index_start + 2, // First Slot
				lease_period_index_start + 3, // Last Slot
				200 + offset,                 // Block End
				None,
			));
			let fund_2 = crowdloan::Funds::<Test>::get(ParaId::from(para_2)).unwrap();
			let crowdloan_account = Crowdloan::fund_account_id(fund_2.fund_index);

			// Auction ending begins on block 100 + offset, so we make a bid before then.
			run_to_block(start_block + 90 + offset);

			Balances::make_free_balance_be(&account_id(10), 1_000_000_000);
			Balances::make_free_balance_be(&account_id(20), 1_000_000_000);

			// User 10 will bid directly for teyrchain 1
			assert_ok!(Auctions::bid(
				signed(10),
				ParaId::from(para_1),
				1,                            // Auction Index
				lease_period_index_start + 0, // First Slot
				lease_period_index_start + 1, // Last slot
				910,                          // Amount
			));

			// User 2 will be a contribute to crowdloan for teyrchain 2
			Balances::make_free_balance_be(&account_id(2), 1_000_000_000);
			assert_ok!(Crowdloan::contribute(signed(2), ParaId::from(para_2), 920, None));

			// Auction ends at block 110 + offset
			run_to_block(start_block + 109 + offset);
			assert!(contains_event(
				crowdloan::Event::<Test>::HandleBidResult {
					para_id: ParaId::from(para_2),
					result: Ok(())
				}
				.into()
			));
			run_to_block(start_block + 110 + offset);
			assert_eq!(
				last_event(),
				auctions::Event::<Test>::AuctionClosed { auction_index: 1 }.into()
			);

			// Paras should have won slots
			assert_eq!(
				slots::Leases::<Test>::get(ParaId::from(para_1)),
				// -- 1 --- 2 --- 3 --------- 4 ------------ 5 --------
				vec![None, None, None, Some((account_id(10), 910)), Some((account_id(10), 910))],
			);
			assert_eq!(
				slots::Leases::<Test>::get(ParaId::from(para_2)),
				// -- 1 --- 2 --- 3 --- 4 --- 5 ---------------- 6 --------------------------- 7
				// ----------------
				vec![
					None,
					None,
					None,
					None,
					None,
					Some((crowdloan_account.clone(), 920)),
					Some((crowdloan_account.clone(), 920))
				],
			);

			// Should not be able to contribute to a winning crowdloan
			Balances::make_free_balance_be(&account_id(3), 1_000_000_000);
			assert_noop!(
				Crowdloan::contribute(signed(3), ParaId::from(2001), 10, None),
				CrowdloanError::<Test>::BidOrLeaseActive
			);

			// New leases will start on block 400
			let lease_start_block = start_block + 400 + offset;
			run_to_block(lease_start_block);

			// First slot, Para 1 should be transitioning to lease holding Teyrchain
			assert_eq!(
				Paras::lifecycle(ParaId::from(para_1)),
				Some(ParaLifecycle::UpgradingParathread)
			);
			assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::Parathread));

			// Two sessions later, it has upgraded
			run_to_block(lease_start_block + 20);
			assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::Teyrchain));
			assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::Parathread));

			// Second slot nothing happens :)
			run_to_block(lease_start_block + 100);
			assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::Teyrchain));
			assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::Parathread));

			// Third slot, Para 2 should be upgrading, and Para 1 is downgrading
			run_to_block(lease_start_block + 200);
			assert_eq!(
				Paras::lifecycle(ParaId::from(para_1)),
				Some(ParaLifecycle::DowngradingTeyrchain)
			);
			assert_eq!(
				Paras::lifecycle(ParaId::from(para_2)),
				Some(ParaLifecycle::UpgradingParathread)
			);

			// Two sessions later, they have transitioned
			run_to_block(lease_start_block + 220);
			assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::Parathread));
			assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::Teyrchain));

			// Fourth slot nothing happens :)
			run_to_block(lease_start_block + 300);
			assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::Parathread));
			assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::Teyrchain));

			// Fifth slot, Para 2 is downgrading
			run_to_block(lease_start_block + 400);
			assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::Parathread));
			assert_eq!(
				Paras::lifecycle(ParaId::from(para_2)),
				Some(ParaLifecycle::DowngradingTeyrchain)
			);

			// Two sessions later, Para 2 is downgraded
			run_to_block(lease_start_block + 420);
			assert_eq!(Paras::lifecycle(ParaId::from(para_1)), Some(ParaLifecycle::Parathread));
			assert_eq!(Paras::lifecycle(ParaId::from(para_2)), Some(ParaLifecycle::Parathread));
		});
	}
}

#[test]
fn basic_errors_fail() {
	new_test_ext().execute_with(|| {
		assert!(System::block_number().is_one());
		let para_id = LOWEST_PUBLIC_ID;
		// Can't double register
		Balances::make_free_balance_be(&account_id(1), 1_000_000_000);
		Balances::make_free_balance_be(&account_id(2), 1_000_000_000);

		let genesis_head = Registrar::worst_head_data();
		let validation_code = Registrar::worst_validation_code();
		assert_ok!(Registrar::reserve(signed(1)));
		assert_ok!(Registrar::register(
			signed(1),
			para_id,
			genesis_head.clone(),
			validation_code.clone(),
		));
		assert_ok!(Registrar::reserve(signed(2)));
		assert_noop!(
			Registrar::register(signed(2), para_id, genesis_head, validation_code,),
			paras_registrar::Error::<Test>::NotOwner
		);

		// Start an auction
		let duration = 99u32;
		let lease_period_index_start = 4u32;
		assert_ok!(Auctions::new_auction(
			RuntimeOrigin::root(),
			duration,
			lease_period_index_start
		));

		// Cannot create a crowdloan if you do not own the para
		assert_noop!(
			Crowdloan::create(
				signed(2),
				para_id,
				1_000,                        // Cap
				lease_period_index_start + 2, // First Slot
				lease_period_index_start + 3, // Last Slot
				200,                          // Block End
				None,
			),
			crowdloan::Error::<Test>::InvalidOrigin
		);
	});
}

#[test]
fn competing_slots() {
	// This test will verify that competing slots, from different sources will resolve
	// appropriately.
	new_test_ext().execute_with(|| {
		assert!(System::block_number().is_one());
		let max_bids = 10u32;
		let para_id = LOWEST_PUBLIC_ID;

		const START_SESSION_INDEX: SessionIndex = 1;
		run_to_session(START_SESSION_INDEX);

		// Create n paras and owners
		let validation_code = Registrar::worst_validation_code();
		for n in 1..=max_bids {
			Balances::make_free_balance_be(&account_id(n), 1_000_000_000);
			let genesis_head = Registrar::worst_head_data();
			assert_ok!(Registrar::reserve(signed(n)));
			assert_ok!(Registrar::register(
				signed(n),
				para_id + n - 1,
				genesis_head,
				validation_code.clone(),
			));
		}
		// The code undergoing the prechecking is the same for all paras.
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		// Start a new auction in the future
		let duration = 149u32;
		let lease_period_index_start = 4u32;
		assert_ok!(Auctions::new_auction(
			RuntimeOrigin::root(),
			duration,
			lease_period_index_start
		));

		// Paras should be onboarded
		run_to_session(START_SESSION_INDEX + 2);

		for n in 1..=max_bids {
			// Increment block number
			run_to_block(System::block_number() + 10);

			Balances::make_free_balance_be(&account_id(n * 10), n * 1_000);

			let (start, end) = match n {
				1 => (0, 0),
				2 => (0, 1),
				3 => (0, 2),
				4 => (0, 3),
				5 => (1, 1),
				6 => (1, 2),
				7 => (1, 3),
				8 => (2, 2),
				9 => (2, 3),
				10 => (3, 3),
				_ => panic!("test not meant for this"),
			};

			// Users will bid directly for teyrchain
			assert_ok!(Auctions::bid(
				signed(n * 10),
				para_id + n - 1,
				1,                                // Auction Index
				lease_period_index_start + start, // First Slot
				lease_period_index_start + end,   // Last slot
				n * 900,                          // Amount
			));
		}

		// Auction should be done after ending period
		run_to_block(180);

		// Appropriate Paras should have won slots
		// 900 + 4500 + 2x 8100 = 21,600
		// 900 + 4500 + 7200 + 9000 = 21,600
		assert_eq!(
			slots::Leases::<Test>::get(para_id),
			// -- 1 --- 2 --- 3 ---------- 4 ------
			vec![None, None, None, Some((account_id(10), 900))],
		);
		assert_eq!(
			slots::Leases::<Test>::get(para_id + 4),
			// -- 1 --- 2 --- 3 --- 4 ---------- 5 -------
			vec![None, None, None, None, Some((account_id(50), 4500))],
		);
		// TODO: Is this right?
		assert_eq!(
			slots::Leases::<Test>::get(para_id + 8),
			// -- 1 --- 2 --- 3 --- 4 --- 5 ---------- 6 --------------- 7 -------
			vec![
				None,
				None,
				None,
				None,
				None,
				Some((account_id(90), 8100)),
				Some((account_id(90), 8100))
			],
		);
	});
}

#[test]
fn competing_bids() {
	// This test will verify that competing bids, from different sources will resolve appropriately.
	new_test_ext().execute_with(|| {
		assert!(System::block_number().is_one());

		const START_SESSION_INDEX: SessionIndex = 1;
		run_to_session(START_SESSION_INDEX);

		let start_para = LOWEST_PUBLIC_ID - 1;
		// Create 3 paras and owners
		let validation_code = Registrar::worst_validation_code();
		for n in 1..=3 {
			Balances::make_free_balance_be(&account_id(n), 1_000_000_000);
			let genesis_head = Registrar::worst_head_data();
			assert_ok!(Registrar::reserve(signed(n)));
			assert_ok!(Registrar::register(
				signed(n),
				ParaId::from(start_para + n),
				genesis_head,
				validation_code.clone(),
			));
		}
		// The code undergoing the prechecking is the same for all paras.
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		// Finish registration of paras.
		run_to_session(START_SESSION_INDEX + 2);

		// Start a new auction in the future
		let starting_block = System::block_number();
		let duration = 99u32;
		let lease_period_index_start = 4u32;
		assert_ok!(Auctions::new_auction(
			RuntimeOrigin::root(),
			duration,
			lease_period_index_start
		));

		for n in 1..=3 {
			// Create a crowdloan for each para
			assert_ok!(Crowdloan::create(
				signed(n),
				ParaId::from(start_para + n),
				100_000,                      // Cap
				lease_period_index_start + 2, // First Slot
				lease_period_index_start + 3, // Last Slot
				200,                          // Block End,
				None,
			));
		}

		for n in 1..=9 {
			// Increment block number
			run_to_block(starting_block + n * 10);

			Balances::make_free_balance_be(&account_id(n * 10), n * 1_000);

			let para = start_para + n % 3 + 1;

			if n % 2 == 0 {
				// User 10 will bid directly for teyrchain 1
				assert_ok!(Auctions::bid(
					signed(n * 10),
					ParaId::from(para),
					1,                            // Auction Index
					lease_period_index_start + 0, // First Slot
					lease_period_index_start + 1, // Last slot
					n * 900,                      // Amount
				));
			} else {
				// User 20 will be a contribute to crowdloan for teyrchain 2
				assert_ok!(Crowdloan::contribute(
					signed(n * 10),
					ParaId::from(para),
					n + 900,
					None,
				));
			}
		}

		// Auction should be done
		run_to_block(starting_block + 110);

		// Appropriate Paras should have won slots
		let fund_1 = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
		let crowdloan_1 = Crowdloan::fund_account_id(fund_1.fund_index);
		assert_eq!(
			slots::Leases::<Test>::get(ParaId::from(2000)),
			// -- 1 --- 2 --- 3 --- 4 --- 5 ------------- 6 ------------------------ 7
			// -------------
			vec![
				None,
				None,
				None,
				None,
				None,
				Some((crowdloan_1.clone(), 1812)),
				Some((crowdloan_1.clone(), 1812))
			],
		);
		assert_eq!(
			slots::Leases::<Test>::get(ParaId::from(2002)),
			// -- 1 --- 2 --- 3 ---------- 4 --------------- 5 -------
			vec![None, None, None, Some((account_id(80), 7200)), Some((account_id(80), 7200))],
		);
	});
}

#[test]
fn basic_swap_works() {
	// This test will test a swap between a lease holding teyrchain and on-demand teyrchain works
	// successfully.
	new_test_ext().execute_with(|| {
		assert!(System::block_number().is_one()); /* So events are emitted */

		const START_SESSION_INDEX: SessionIndex = 1;
		run_to_session(START_SESSION_INDEX);

		// User 1 and 2 will own paras
		Balances::make_free_balance_be(&account_id(1), 1_000_000_000);
		Balances::make_free_balance_be(&account_id(2), 1_000_000_000);
		// First register 2 on-demand teyrchains with different data
		let validation_code = test_validation_code(10);
		assert_ok!(Registrar::reserve(signed(1)));
		assert_ok!(Registrar::register(
			signed(1),
			ParaId::from(2000),
			test_genesis_head(10),
			validation_code.clone(),
		));
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		let validation_code = test_validation_code(20);
		assert_ok!(Registrar::reserve(signed(2)));
		assert_ok!(Registrar::register(
			signed(2),
			ParaId::from(2001),
			test_genesis_head(20),
			validation_code.clone(),
		));
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		// Paras should be onboarding
		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::Onboarding));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Onboarding));

		// Start a new auction in the future
		let duration = 99u32;
		let lease_period_index_start = 4u32;
		assert_ok!(Auctions::new_auction(
			RuntimeOrigin::root(),
			duration,
			lease_period_index_start
		));

		// 2 sessions later they are on-demand teyrchains
		run_to_session(START_SESSION_INDEX + 2);
		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::Parathread));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Parathread));

		// Open a crowdloan for Para 1 for slots 0-3
		assert_ok!(Crowdloan::create(
			signed(1),
			ParaId::from(2000),
			1_000_000,                    // Cap
			lease_period_index_start + 0, // First Slot
			lease_period_index_start + 3, // Last Slot
			200,                          // Block End
			None,
		));
		let fund = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
		let crowdloan_account = Crowdloan::fund_account_id(fund.fund_index);

		// Bunch of contributions
		let mut total = 0;
		for i in 10..20 {
			Balances::make_free_balance_be(&account_id(i), 1_000_000_000);
			assert_ok!(Crowdloan::contribute(signed(i), ParaId::from(2000), 900 - i, None));
			total += 900 - i;
		}
		assert!(total > 0);
		assert_eq!(Balances::free_balance(&crowdloan_account), total);

		// Go to end of auction where everyone won their slots
		run_to_block(200);

		// Deposit is appropriately taken
		// ----------------------------------------- para deposit --- crowdloan
		let crowdloan_deposit = 100;
		let para_id_deposit = <Test as paras_registrar::Config>::ParaDeposit::get();
		let code_deposit = configuration::ActiveConfig::<Test>::get().max_code_size
			* <Test as paras_registrar::Config>::DataDepositPerByte::get();

		// Para 2000 has a genesis head size of 10.
		assert_eq!(
			Balances::reserved_balance(&account_id(1)),
			crowdloan_deposit + para_id_deposit + code_deposit + 10
		);
		// Para 2001 has a genesis head size of 20.
		assert_eq!(Balances::reserved_balance(&account_id(2)), para_id_deposit + code_deposit + 20);
		assert_eq!(Balances::reserved_balance(&crowdloan_account), total);
		// Crowdloan is appropriately set
		assert!(crowdloan::Funds::<Test>::get(ParaId::from(2000)).is_some());
		assert!(crowdloan::Funds::<Test>::get(ParaId::from(2001)).is_none());

		// New leases will start on block 400
		let lease_start_block = 400;
		run_to_block(lease_start_block);

		// Slots are won by Para 1
		assert!(!slots::Leases::<Test>::get(ParaId::from(2000)).is_empty());
		assert!(slots::Leases::<Test>::get(ParaId::from(2001)).is_empty());

		// 2 sessions later it is a teyrchain
		run_to_block(lease_start_block + 20);
		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::Teyrchain));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Parathread));

		// Initiate a swap
		assert_ok!(Registrar::swap(
			para_origin(2000).into(),
			ParaId::from(2000),
			ParaId::from(2001)
		));
		assert_ok!(Registrar::swap(
			para_origin(2001).into(),
			ParaId::from(2001),
			ParaId::from(2000)
		));

		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::DowngradingTeyrchain));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::UpgradingParathread));

		// 2 session later they have swapped
		run_to_block(lease_start_block + 40);
		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::Parathread));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Teyrchain));

		// Deregister on-demand teyrchain
		assert_ok!(Registrar::deregister(para_origin(2000).into(), ParaId::from(2000)));
		// Correct deposit is unreserved
		assert_eq!(Balances::reserved_balance(&account_id(1)), crowdloan_deposit);
		assert_eq!(Balances::reserved_balance(&account_id(2)), para_id_deposit + code_deposit + 20);
		// Crowdloan ownership is swapped
		assert!(crowdloan::Funds::<Test>::get(ParaId::from(2000)).is_none());
		assert!(crowdloan::Funds::<Test>::get(ParaId::from(2001)).is_some());
		// Slot is swapped
		assert!(slots::Leases::<Test>::get(ParaId::from(2000)).is_empty());
		assert!(!slots::Leases::<Test>::get(ParaId::from(2001)).is_empty());

		// Cant dissolve
		assert_noop!(
			Crowdloan::dissolve(signed(1), ParaId::from(2000)),
			CrowdloanError::<Test>::InvalidParaId
		);
		assert_noop!(
			Crowdloan::dissolve(signed(2), ParaId::from(2001)),
			CrowdloanError::<Test>::NotReadyToDissolve
		);

		// Go way in the future when the para is offboarded
		run_to_block(lease_start_block + 1000);

		// Withdraw of contributions works
		assert_eq!(Balances::free_balance(&crowdloan_account), total);
		for i in 10..20 {
			assert_ok!(Crowdloan::withdraw(signed(i), account_id(i), ParaId::from(2001)));
		}
		assert_eq!(Balances::free_balance(&crowdloan_account), 0);

		// Dissolve returns the balance of the person who put a deposit for crowdloan
		assert_ok!(Crowdloan::dissolve(signed(1), ParaId::from(2001)));
		assert_eq!(Balances::reserved_balance(&account_id(1)), 0);
		assert_eq!(Balances::reserved_balance(&account_id(2)), para_id_deposit + code_deposit + 20);

		// Final deregister sets everything back to the start
		assert_ok!(Registrar::deregister(para_origin(2001).into(), ParaId::from(2001)));
		assert_eq!(Balances::reserved_balance(&account_id(2)), 0);
	})
}

#[test]
fn teyrchain_swap_works() {
	// This test will test a swap between two teyrchains works successfully.
	new_test_ext().execute_with(|| {
		assert!(System::block_number().is_one()); /* So events are emitted */

		const START_SESSION_INDEX: SessionIndex = 1;
		run_to_session(START_SESSION_INDEX);

		// User 1 and 2 will own paras
		Balances::make_free_balance_be(&account_id(1), 1_000_000_000);
		Balances::make_free_balance_be(&account_id(2), 1_000_000_000);
		// First register 2 on-demand teyrchains with different data
		let validation_code = test_validation_code(10);
		assert_ok!(Registrar::reserve(signed(1)));
		assert_ok!(Registrar::register(
			signed(1),
			ParaId::from(2000),
			test_genesis_head(10),
			validation_code.clone(),
		));
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		let validation_code = test_validation_code(20);
		assert_ok!(Registrar::reserve(signed(2)));
		assert_ok!(Registrar::register(
			signed(2),
			ParaId::from(2001),
			test_genesis_head(20),
			validation_code.clone(),
		));
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		// Paras should be onboarding
		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::Onboarding));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Onboarding));

		assert_eq!(
			Balances::total_balance(&Crowdloan::fund_account_id(
				crowdloan::NextFundIndex::<Test>::get()
			)),
			0
		);

		// Start a new auction in the future
		let start_auction = |lease_period_index_start, winner, end| {
			let unique_id = winner - 1999u32;
			let starting_block = System::block_number();
			let duration = 99u32;
			assert_ok!(Auctions::new_auction(
				RuntimeOrigin::root(),
				duration,
				lease_period_index_start
			));

			// 2 sessions later they are on-demand teyrchains
			run_to_block(starting_block + 20);
			assert_eq!(Paras::lifecycle(ParaId::from(winner)), Some(ParaLifecycle::Parathread));

			// Open a crowdloan for Para 1 for slots 0-3
			assert_ok!(Crowdloan::create(
				signed(unique_id),
				ParaId::from(winner),
				1_000_000,                    // Cap
				lease_period_index_start + 0, // First Slot
				lease_period_index_start + 7, // Last Slot
				end,                          // Block End
				None,
			));
			let winner_fund = crowdloan::Funds::<Test>::get(ParaId::from(winner)).unwrap();
			let crowdloan_account = Crowdloan::fund_account_id(winner_fund.fund_index);

			// Bunch of contributions
			let mut total = 0;
			for i in (unique_id * 10)..(unique_id + 1) * 10 {
				Balances::make_free_balance_be(&account_id(i), 1_000_000_000);
				assert_ok!(Crowdloan::contribute(signed(i), ParaId::from(winner), 900 - i, None));
				total += 900 - i;
			}
			assert!(total > 0);
			assert_eq!(Balances::free_balance(&crowdloan_account), total);

			// Go to end of auction where everyone won their slots
			run_to_block(end);

			// Crowdloan is appropriately set
			assert!(crowdloan::Funds::<Test>::get(ParaId::from(winner)).is_some());

			// New leases will start on block lease period index * 100
			let lease_start_block = lease_period_index_start * 100;
			run_to_block(lease_start_block);
		};

		start_auction(4u32, 2000, 200);
		// Slots are won by Para 1
		assert!(!slots::Leases::<Test>::get(ParaId::from(2000)).is_empty());
		assert!(slots::Leases::<Test>::get(ParaId::from(2001)).is_empty());

		// 2 sessions later it is a teyrchain
		run_to_block(4 * 100 + 20);
		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::Teyrchain));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Parathread));

		// Let's repeat the process now for another teyrchain.
		start_auction(6u32, 2001, 500);
		// Slots are won by Para 1
		assert!(!slots::Leases::<Test>::get(ParaId::from(2000)).is_empty());
		assert!(!slots::Leases::<Test>::get(ParaId::from(2001)).is_empty());

		// 2 sessions later it is a teyrchain
		run_to_block(6 * 100 + 20);
		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::Teyrchain));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Teyrchain));

		// Currently we are on lease 6
		assert_eq!(
			<Slots as Leaser<_>>::lease_period_index(System::block_number()),
			Some((6u32, false))
		);

		// This means that teyrchain 1 should only have 6 slots left, and teyrchain 2 has all 8.
		assert_eq!(slots::Leases::<Test>::get(ParaId::from(2000)).len(), 6);
		assert_eq!(slots::Leases::<Test>::get(ParaId::from(2001)).len(), 8);

		let fund_2000 = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
		assert_eq!(fund_2000.fund_index, 0);
		assert_eq!(
			Balances::reserved_balance(&Crowdloan::fund_account_id(fund_2000.fund_index)),
			fund_2000.raised
		);

		let fund_2001 = crowdloan::Funds::<Test>::get(ParaId::from(2001)).unwrap();
		assert_eq!(fund_2001.fund_index, 1);
		assert_eq!(
			Balances::reserved_balance(&Crowdloan::fund_account_id(fund_2001.fund_index)),
			fund_2001.raised
		);

		assert_eq!(slots::Leases::<Test>::get(ParaId::from(2000)).len(), 6);
		assert_eq!(slots::Leases::<Test>::get(ParaId::from(2001)).len(), 8);

		// Now we swap them.
		assert_ok!(Registrar::swap(
			para_origin(2000).into(),
			ParaId::from(2000),
			ParaId::from(2001)
		));
		assert_ok!(Registrar::swap(
			para_origin(2001).into(),
			ParaId::from(2001),
			ParaId::from(2000)
		));
		assert!(contains_event(
			paras_registrar::Event::<Test>::Swapped {
				para_id: ParaId::from(2001),
				other_id: ParaId::from(2000)
			}
			.into()
		));

		// Crowdloan Swapped
		let fund_2000 = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
		assert_eq!(fund_2000.fund_index, 1);
		assert_eq!(
			Balances::reserved_balance(&Crowdloan::fund_account_id(fund_2000.fund_index)),
			fund_2000.raised
		);

		let fund_2001 = crowdloan::Funds::<Test>::get(ParaId::from(2001)).unwrap();
		assert_eq!(fund_2001.fund_index, 0);
		assert_eq!(
			Balances::reserved_balance(&Crowdloan::fund_account_id(fund_2001.fund_index)),
			fund_2001.raised
		);

		// Slots Swapped
		assert_eq!(slots::Leases::<Test>::get(ParaId::from(2000)).len(), 8);
		assert_eq!(slots::Leases::<Test>::get(ParaId::from(2001)).len(), 6);
	})
}

#[test]
fn crowdloan_ending_period_bid() {
	new_test_ext().execute_with(|| {
		assert!(System::block_number().is_one()); /* So events are emitted */

		const START_SESSION_INDEX: SessionIndex = 1;
		run_to_session(START_SESSION_INDEX);

		// User 1 and 2 will own paras
		Balances::make_free_balance_be(&account_id(1), 1_000_000_000);
		Balances::make_free_balance_be(&account_id(2), 1_000_000_000);
		// First register 2 on-demand teyrchains
		let validation_code = test_validation_code(10);
		assert_ok!(Registrar::reserve(signed(1)));
		assert_ok!(Registrar::register(
			signed(1),
			ParaId::from(2000),
			test_genesis_head(10),
			validation_code.clone(),
		));
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		let validation_code = test_validation_code(20);
		assert_ok!(Registrar::reserve(signed(2)));
		assert_ok!(Registrar::register(
			signed(2),
			ParaId::from(2001),
			test_genesis_head(20),
			validation_code.clone(),
		));
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		// Paras should be onboarding
		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::Onboarding));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Onboarding));

		// Start a new auction in the future
		let duration = 99u32;
		let ends_at = System::block_number() + duration;
		let lease_period_index_start = 4u32;
		assert_ok!(Auctions::new_auction(
			RuntimeOrigin::root(),
			duration,
			lease_period_index_start
		));

		// 2 sessions later they are on-demand teyrchains
		run_to_session(START_SESSION_INDEX + 2);
		assert_eq!(Paras::lifecycle(ParaId::from(2000)), Some(ParaLifecycle::Parathread));
		assert_eq!(Paras::lifecycle(ParaId::from(2001)), Some(ParaLifecycle::Parathread));

		// Open a crowdloan for Para 1 for slots 0-3
		assert_ok!(Crowdloan::create(
			signed(1),
			ParaId::from(2000),
			1_000_000,                    // Cap
			lease_period_index_start + 0, // First Slot
			lease_period_index_start + 3, // Last Slot
			200,                          // Block End
			None,
		));
		let fund = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
		let crowdloan_account = Crowdloan::fund_account_id(fund.fund_index);

		// Bunch of contributions
		let mut total = 0;
		for i in 10..20 {
			Balances::make_free_balance_be(&account_id(i), 1_000_000_000);
			assert_ok!(Crowdloan::contribute(signed(i), ParaId::from(2000), 900 - i, None));
			total += 900 - i;
		}
		assert!(total > 0);
		assert_eq!(Balances::free_balance(&crowdloan_account), total);

		// Bid for para 2 directly
		Balances::make_free_balance_be(&account_id(2), 1_000_000_000);
		assert_ok!(Auctions::bid(
			signed(2),
			ParaId::from(2001),
			1,                            // Auction Index
			lease_period_index_start + 0, // First Slot
			lease_period_index_start + 1, // Last slot
			900,                          // Amount
		));

		// Go to beginning of ending period
		run_to_block(ends_at);

		assert_eq!(Auctions::auction_status(ends_at), AuctionStatus::<u32>::EndingPeriod(0, 0));
		let mut winning = [(); SlotRange::SLOT_RANGE_COUNT].map(|_| None);

		winning[SlotRange::ZeroOne as u8 as usize] = Some((account_id(2), ParaId::from(2001), 900));
		winning[SlotRange::ZeroThree as u8 as usize] =
			Some((crowdloan_account.clone(), ParaId::from(2000), total));

		assert_eq!(auctions::Winning::<Test>::get(0), Some(winning));

		run_to_block(ends_at + 1);

		Balances::make_free_balance_be(&account_id(1234), 1_000_000_000);
		assert_ok!(Crowdloan::contribute(signed(1234), ParaId::from(2000), 900, None));

		// Data propagates correctly
		run_to_block(ends_at + 2);
		let mut winning = [(); SlotRange::SLOT_RANGE_COUNT].map(|_| None);
		winning[SlotRange::ZeroOne as u8 as usize] = Some((account_id(2), ParaId::from(2001), 900));
		winning[SlotRange::ZeroThree as u8 as usize] =
			Some((crowdloan_account.clone(), ParaId::from(2000), total + 900));
		assert_eq!(auctions::Winning::<Test>::get(2), Some(winning));
	})
}

#[test]
fn auction_bid_requires_registered_para() {
	new_test_ext().execute_with(|| {
		assert!(System::block_number().is_one()); /* So events are emitted */

		const START_SESSION_INDEX: SessionIndex = 1;
		run_to_session(START_SESSION_INDEX);

		// Start a new auction in the future
		let duration = 99u32;
		let lease_period_index_start = 4u32;
		assert_ok!(Auctions::new_auction(
			RuntimeOrigin::root(),
			duration,
			lease_period_index_start
		));

		// Can't bid with non-registered paras
		Balances::make_free_balance_be(&account_id(1), 1_000_000_000);
		assert_noop!(
			Auctions::bid(
				signed(1),
				ParaId::from(2000),
				1,                            // Auction Index
				lease_period_index_start + 0, // First Slot
				lease_period_index_start + 1, // Last slot
				900,                          // Amount
			),
			AuctionsError::<Test>::ParaNotRegistered
		);

		// Now we register the para
		let validation_code = test_validation_code(10);
		assert_ok!(Registrar::reserve(signed(1)));
		assert_ok!(Registrar::register(
			signed(1),
			ParaId::from(2000),
			test_genesis_head(10),
			validation_code.clone(),
		));
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		// Still can't bid until it is fully onboarded
		assert_noop!(
			Auctions::bid(
				signed(1),
				ParaId::from(2000),
				1,                            // Auction Index
				lease_period_index_start + 0, // First Slot
				lease_period_index_start + 1, // Last slot
				900,                          // Amount
			),
			AuctionsError::<Test>::ParaNotRegistered
		);

		// Onboarded on Session 2
		run_to_session(START_SESSION_INDEX + 2);

		// Success
		Balances::make_free_balance_be(&account_id(1), 1_000_000_000);
		assert_ok!(Auctions::bid(
			signed(1),
			ParaId::from(2000),
			1,                            // Auction Index
			lease_period_index_start + 0, // First Slot
			lease_period_index_start + 1, // Last slot
			900,                          // Amount
		));
	});
}

#[test]
fn gap_bids_work() {
	new_test_ext().execute_with(|| {
		assert!(System::block_number().is_one()); /* So events are emitted */

		const START_SESSION_INDEX: SessionIndex = 1;
		run_to_session(START_SESSION_INDEX);

		// Start a new auction in the future
		let duration = 99u32;
		let lease_period_index_start = 4u32;
		assert_ok!(Auctions::new_auction(
			RuntimeOrigin::root(),
			duration,
			lease_period_index_start
		));
		Balances::make_free_balance_be(&account_id(1), 1_000_000_000);
		Balances::make_free_balance_be(&account_id(2), 1_000_000_000);

		// Now register 2 paras
		let validation_code = test_validation_code(10);
		assert_ok!(Registrar::reserve(signed(1)));
		assert_ok!(Registrar::register(
			signed(1),
			ParaId::from(2000),
			test_genesis_head(10),
			validation_code.clone(),
		));
		assert_ok!(Registrar::reserve(signed(2)));
		assert_ok!(Registrar::register(
			signed(2),
			ParaId::from(2001),
			test_genesis_head(10),
			validation_code.clone(),
		));
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		// Onboarded on Session 2
		run_to_session(START_SESSION_INDEX + 2);

		// Make bids
		Balances::make_free_balance_be(&account_id(10), 1_000_000_000);
		Balances::make_free_balance_be(&account_id(20), 1_000_000_000);
		// Slot 1 for 100 from 10
		assert_ok!(Auctions::bid(
			signed(10),
			ParaId::from(2000),
			1,                            // Auction Index
			lease_period_index_start + 0, // First Slot
			lease_period_index_start + 0, // Last slot
			100,                          // Amount
		));
		// Slot 4 for 400 from 10
		assert_ok!(Auctions::bid(
			signed(10),
			ParaId::from(2000),
			1,                            // Auction Index
			lease_period_index_start + 3, // First Slot
			lease_period_index_start + 3, // Last slot
			400,                          // Amount
		));

		// A bid for another para is counted separately.
		assert_ok!(Auctions::bid(
			signed(10),
			ParaId::from(2001),
			1,                            // Auction Index
			lease_period_index_start + 1, // First Slot
			lease_period_index_start + 1, // Last slot
			555,                          // Amount
		));
		assert_eq!(Balances::reserved_balance(&account_id(10)), 400 + 555);

		// Slot 2 for 800 from 20, overtaking 10's bid
		assert_ok!(Auctions::bid(
			signed(20),
			ParaId::from(2000),
			1,                            // Auction Index
			lease_period_index_start + 1, // First Slot
			lease_period_index_start + 1, // Last slot
			800,                          // Amount
		));
		// Slot 3 for 200 from 20
		assert_ok!(Auctions::bid(
			signed(20),
			ParaId::from(2000),
			1,                            // Auction Index
			lease_period_index_start + 2, // First Slot
			lease_period_index_start + 2, // Last slot
			200,                          // Amount
		));

		// Finish the auction
		run_to_block(130 + LeaseOffset::get());

		// Should have won the lease periods
		assert_eq!(
			slots::Leases::<Test>::get(ParaId::from(2000)),
			vec![
				// LP 1
				None,
				// LP 2
				None,
				// LP 3
				None,
				// LP 4
				Some((account_id(10), 100)),
				// LP 5
				Some((account_id(20), 800)),
				// LP 6
				Some((account_id(20), 200)),
				// LP 7
				Some((account_id(10), 400))
			],
		);
		// Appropriate amount is reserved (largest of the values)
		assert_eq!(Balances::reserved_balance(&account_id(10)), 400);
		// Appropriate amount is reserved (largest of the values)
		assert_eq!(Balances::reserved_balance(&account_id(20)), 800);

		// Progress through the leases and note the correct amount of balance is reserved.

		add_blocks(300 + LeaseOffset::get());
		assert_eq!(
			slots::Leases::<Test>::get(ParaId::from(2000)),
			vec![
				// LP 4
				Some((account_id(10), 100)),
				// LP 5
				Some((account_id(20), 800)),
				// LP 6
				Some((account_id(20), 200)),
				// LP 7
				Some((account_id(10), 400))
			],
		);
		// Nothing changed.
		assert_eq!(Balances::reserved_balance(&account_id(10)), 400);
		assert_eq!(Balances::reserved_balance(&account_id(20)), 800);

		// Lease period 4 is done, but nothing is unreserved since user 1 has a debt on lease 7
		add_blocks(100);
		assert_eq!(
			slots::Leases::<Test>::get(ParaId::from(2000)),
			vec![
				// LP 5
				Some((account_id(20), 800)),
				// LP 6
				Some((account_id(20), 200)),
				// LP 7
				Some((account_id(10), 400))
			],
		);
		// Nothing changed.
		assert_eq!(Balances::reserved_balance(&account_id(10)), 400);
		assert_eq!(Balances::reserved_balance(&account_id(20)), 800);

		// Lease period 5 is done, and 20 will unreserve down to 200.
		add_blocks(100);
		assert_eq!(
			slots::Leases::<Test>::get(ParaId::from(2000)),
			// --------- 6 -------------- 7 -------
			vec![Some((account_id(20), 200)), Some((account_id(10), 400))],
		);
		assert_eq!(Balances::reserved_balance(&account_id(10)), 400);
		assert_eq!(Balances::reserved_balance(&account_id(20)), 200);

		// Lease period 6 is done, and 20 will unreserve everything.
		add_blocks(100);
		assert_eq!(
			slots::Leases::<Test>::get(ParaId::from(2000)),
			// --------- 7 -------
			vec![Some((account_id(10), 400))],
		);
		assert_eq!(Balances::reserved_balance(&account_id(10)), 400);
		assert_eq!(Balances::reserved_balance(&account_id(20)), 0);

		// All leases are done. Everything is unreserved.
		add_blocks(100);
		assert_eq!(slots::Leases::<Test>::get(ParaId::from(2000)), vec![]);
		assert_eq!(Balances::reserved_balance(&account_id(10)), 0);
		assert_eq!(Balances::reserved_balance(&account_id(20)), 0);
	});
}

// This test verifies that if a teyrchain already has won some lease periods, that it cannot bid for
// any of those same lease periods again.
#[test]
fn cant_bid_on_existing_lease_periods() {
	new_test_ext().execute_with(|| {
		assert!(System::block_number().is_one()); /* So events are emitted */

		const START_SESSION_INDEX: SessionIndex = 1;
		run_to_session(START_SESSION_INDEX);

		Balances::make_free_balance_be(&account_id(1), 1_000_000_000);
		// First register an on-demand teyrchain
		let validation_code = test_validation_code(10);
		assert_ok!(Registrar::reserve(signed(1)));
		assert_ok!(Registrar::register(
			signed(1),
			ParaId::from(2000),
			test_genesis_head(10),
			validation_code.clone(),
		));
		conclude_pvf_checking::<Test>(&validation_code, VALIDATORS, START_SESSION_INDEX);

		// Start a new auction in the future
		let starting_block = System::block_number();
		let duration = 99u32;
		let lease_period_index_start = 4u32;
		assert_ok!(Auctions::new_auction(
			RuntimeOrigin::root(),
			duration,
			lease_period_index_start
		));

		// 2 sessions later they are on-demand teyrchains
		run_to_session(START_SESSION_INDEX + 2);

		// Open a crowdloan for Para 1 for slots 0-3
		assert_ok!(Crowdloan::create(
			signed(1),
			ParaId::from(2000),
			1_000_000,                    // Cap
			lease_period_index_start + 0, // First Slot
			lease_period_index_start + 1, // Last Slot
			400,                          // Long block end
			None,
		));
		let fund = crowdloan::Funds::<Test>::get(ParaId::from(2000)).unwrap();
		let crowdloan_account = Crowdloan::fund_account_id(fund.fund_index);

		// Bunch of contributions
		let mut total = 0;
		for i in 10..20 {
			Balances::make_free_balance_be(&account_id(i), 1_000_000_000);
			assert_ok!(Crowdloan::contribute(signed(i), ParaId::from(2000), 900 - i, None));
			total += 900 - i;
		}
		assert!(total > 0);
		assert_eq!(Balances::free_balance(&crowdloan_account), total);

		// Finish the auction.
		run_to_block(starting_block + 110);

		// Appropriate Paras should have won slots
		assert_eq!(
			slots::Leases::<Test>::get(ParaId::from(2000)),
			// -- 1 --- 2 --- 3 ------------- 4 ------------------------ 5 -------------
			vec![
				None,
				None,
				None,
				Some((crowdloan_account.clone(), 8855)),
				Some((crowdloan_account.clone(), 8855))
			],
		);

		// Let's start another auction for the same range
		let starting_block = System::block_number();
		let duration = 99u32;
		let lease_period_index_start = 4u32;
		assert_ok!(Auctions::new_auction(
			RuntimeOrigin::root(),
			duration,
			lease_period_index_start
		));

		// Poke the crowdloan into `NewRaise`
		assert_ok!(Crowdloan::poke(signed(1), ParaId::from(2000)));
		assert_eq!(crowdloan::NewRaise::<Test>::get(), vec![ParaId::from(2000)]);

		// Beginning of ending block.
		run_to_block(starting_block + 100);

		// Bids cannot be made which intersect
		assert_noop!(
			Auctions::bid(
				RuntimeOrigin::signed(crowdloan_account.clone()),
				ParaId::from(2000),
				2,
				lease_period_index_start + 0,
				lease_period_index_start + 1,
				100,
			),
			AuctionsError::<Test>::AlreadyLeasedOut,
		);

		assert_noop!(
			Auctions::bid(
				RuntimeOrigin::signed(crowdloan_account.clone()),
				ParaId::from(2000),
				2,
				lease_period_index_start + 1,
				lease_period_index_start + 2,
				100,
			),
			AuctionsError::<Test>::AlreadyLeasedOut,
		);

		assert_noop!(
			Auctions::bid(
				RuntimeOrigin::signed(crowdloan_account.clone()),
				ParaId::from(2000),
				2,
				lease_period_index_start - 1,
				lease_period_index_start + 0,
				100,
			),
			AuctionsError::<Test>::AlreadyLeasedOut,
		);

		assert_noop!(
			Auctions::bid(
				RuntimeOrigin::signed(crowdloan_account.clone()),
				ParaId::from(2000),
				2,
				lease_period_index_start + 0,
				lease_period_index_start + 0,
				100,
			),
			AuctionsError::<Test>::AlreadyLeasedOut,
		);

		assert_noop!(
			Auctions::bid(
				RuntimeOrigin::signed(crowdloan_account.clone()),
				ParaId::from(2000),
				2,
				lease_period_index_start + 1,
				lease_period_index_start + 1,
				100,
			),
			AuctionsError::<Test>::AlreadyLeasedOut,
		);

		assert_noop!(
			Auctions::bid(
				RuntimeOrigin::signed(crowdloan_account.clone()),
				ParaId::from(2000),
				2,
				lease_period_index_start - 1,
				lease_period_index_start + 5,
				100,
			),
			AuctionsError::<Test>::AlreadyLeasedOut,
		);

		// Will work when not overlapping
		assert_ok!(Auctions::bid(
			RuntimeOrigin::signed(crowdloan_account.clone()),
			ParaId::from(2000),
			2,
			lease_period_index_start + 2,
			lease_period_index_start + 3,
			100,
		));
	});
}