referrerpolicy=no-referrer-when-downgrade
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
// Copyright 2019-2021 Parity Technologies (UK) Ltd.
// This file is part of Parity Bridges Common.

// Parity Bridges Common 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.

// Parity Bridges Common 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 Parity Bridges Common.  If not, see <http://www.gnu.org/licenses/>.

//! Module that adds XCM support to bridge pallets. The pallet allows to dynamically
//! open and close bridges between local (to this pallet location) and remote XCM
//! destinations.
//!
//! The `pallet_xcm_bridge_hub` pallet is used to manage (open, close) bridges between chains from
//! different consensuses. The new extrinsics `fn open_bridge` and `fn close_bridge` are introduced.
//! Other chains can manage channels with different bridged global consensuses.
//!
//! # Concept of `lane` and `LaneId`
//!
//! There is another `pallet_bridge_messages` pallet that handles inbound/outbound lanes for
//! messages. Each lane is a unique connection between two chains from different consensuses and is
//! identified by `LaneId`. `LaneId` is generated once when a new bridge is requested by `fn
//! open_bridge`. It is generated by `BridgeLocations::calculate_lane_id` based on the following
//! parameters:
//! - Source `bridge_origin_universal_location` (latest XCM)
//! - Destination `bridge_destination_universal_location` (latest XCM)
//! - XCM version (both sides of the bridge must use the same parameters to generate the same
//!   `LaneId`)
//!   - `bridge_origin_universal_location`, `bridge_destination_universal_location` is converted to
//!     the `Versioned*` structs
//!
//! `LaneId` is expected to never change because:
//! - We need the same `LaneId` on both sides of the bridge, as `LaneId` is part of the message key
//!   proofs.
//! - Runtime upgrades are entirely asynchronous.
//! - We already have a running production Polkadot/Kusama bridge that uses `LaneId([0, 0, 0, 0])`.
//!
//! `LaneId` is backward compatible, meaning it can be encoded/decoded from the older format `[u8;
//! 4]` used for static lanes, as well as the new format `H256` generated by
//! `BridgeLocations::calculate_lane_id`.
//!
//! # Concept of `bridge` and `BridgeId`
//!
//! The `pallet_xcm_bridge_hub` pallet needs to store some metadata about opened bridges. The bridge
//! (or bridge metadata) is stored under the `BridgeId` key.
//!
//! `BridgeId` is generated from `bridge_origin_relative_location` and
//! `bridge_origin_universal_location` using the `latest` XCM structs. `BridgeId` is not transferred
//! over the bridge; it is only important for local consensus. It essentially serves as an index/key
//! to bridge metadata. All the XCM infrastructure around `XcmExecutor`, `SendXcm`, `ExportXcm` use
//! the `latest` XCM, so `BridgeId` must remain compatible with the `latest` XCM. For example, we
//! have an `ExportXcm` implementation in `exporter.rs` that handles the `ExportMessage` instruction
//! with `universal_source` and `destination` (latest XCM), so we need to create `BridgeId` and the
//! corresponding `LaneId`.
//!
//! # Migrations and State
//!
//! This pallet implements `try_state`, ensuring compatibility and checking everything so we know if
//! any migration is needed. `do_try_state` checks for `BridgeId` compatibility, which is
//! recalculated on runtime upgrade. Upgrading to a new XCM version should not break anything,
//! except removing older XCM versions. In such cases, we need to add migration for `BridgeId` and
//! stored `Versioned*` structs and update `LaneToBridge` mapping, but this won't affect `LaneId`
//! over the bridge.
//!
//! # How to Open a Bridge?
//!
//! The `pallet_xcm_bridge_hub` pallet has the extrinsic `fn open_bridge` and an important
//! configuration `pallet_xcm_bridge_hub::Config::OpenBridgeOrigin`, which translates the call's
//! origin to the XCM `Location` and converts it to the `bridge_origin_universal_location`. With the
//! current setup, this origin/location is expected to be either the relay chain or a sibling
//! parachain as one side of the bridge. Another parameter is
//! `bridge_destination_universal_location`, which is the other side of the bridge from a different
//! global consensus.
//!
//! Every bridge between two XCM locations has a dedicated lane in associated
//! messages pallet. Assuming that this pallet is deployed at the bridge hub
//! parachain and there's a similar pallet at the bridged network, the dynamic
//! bridge lifetime is as follows:
//!
//! 1) the sibling parachain opens a XCMP channel with this bridge hub;
//!
//! 2) the sibling parachain funds its sovereign parachain account at this bridge hub. It shall hold
//!    enough funds to pay for the bridge (see `BridgeDeposit`);
//!
//! 3) the sibling parachain opens the bridge by sending XCM `Transact` instruction with the
//!    `open_bridge` call. The `BridgeDeposit` amount is reserved on the sovereign account of
//!    sibling parachain;
//!
//! 4) at the other side of the bridge, the same thing (1, 2, 3) happens. Parachains that need to
//!    connect over the bridge need to coordinate the moment when they start sending messages over
//!    the bridge. Otherwise they may lose messages and/or bundled assets;
//!
//! 5) when either side wants to close the bridge, it sends the XCM `Transact` with the
//!    `close_bridge` call. The bridge is closed immediately if there are no queued messages.
//!    Otherwise, the owner must repeat the `close_bridge` call to prune all queued messages first.
//!
//! The pallet doesn't provide any mechanism for graceful closure, because it always involves
//! some contract between two connected chains and the bridge hub knows nothing about that. It
//! is the task for the connected chains to make sure that all required actions are completed
//! before the closure. In the end, the bridge hub can't even guarantee that all messages that
//! are delivered to the destination, are processed in the way their sender expects. So if we
//! can't guarantee that, we shall not care about more complex procedures and leave it to the
//! participating parties.
//!
//! # Example
//!
//! Example of opening a bridge between some random parachains from Polkadot and Kusama:
//!
//! 0. Let's have:
//! 	- BridgeHubPolkadot with `UniversalLocation` = `[GlobalConsensus(Polkadot), Parachain(1002)]`
//! 	- BridgeHubKusama with `UniversalLocation` = `[GlobalConsensus(Kusama), Parachain(1002)]`
//! 1. The Polkadot local sibling parachain `Location::new(1, Parachain(1234))` must send some DOTs
//!    to its sovereign account on BridgeHubPolkadot to cover `BridgeDeposit`, fees for `Transact`,
//!    and the existential deposit.
//! 2. Send a call to the BridgeHubPolkadot from the local sibling parachain: `Location::new(1,
//!    Parachain(1234))` ``` xcm::Transact( origin_kind: OriginKind::Xcm,
//!    XcmOverBridgeHubKusama::open_bridge( VersionedInteriorLocation::V4([GlobalConsensus(Kusama),
//!    Parachain(4567)].into()), ); ) ```
//! 3. Check the stored bridge metadata and generated `LaneId`.
//! 4. The Kusama local sibling parachain `Location::new(1, Parachain(4567))` must send some KSMs to
//!    its sovereign account
//! on BridgeHubKusama to cover `BridgeDeposit`, fees for `Transact`, and the existential deposit.
//! 5. Send a call to the BridgeHubKusama from the local sibling parachain: `Location::new(1,
//!    Parachain(4567))` ``` xcm::Transact( origin_kind: OriginKind::Xcm,
//!    XcmOverBridgeHubKusama::open_bridge(
//!    VersionedInteriorLocation::V4([GlobalConsensus(Polkadot), Parachain(1234)].into()), ); ) ```
//! 6. Check the stored bridge metadata and generated `LaneId`.
//! 7. Both `LaneId`s from steps 3 and 6 must be the same (see above _Concept of `lane` and
//!    `LaneId`_).
//! 8. Run the bridge messages relayer for `LaneId`.
//! 9. Send messages from both sides.
//!
//! The opening bridge holds the configured `BridgeDeposit` from the origin's sovereign account, but
//! this deposit is returned when the bridge is closed with `fn close_bridge`.

#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]

use bp_messages::{LaneState, MessageNonce};
use bp_runtime::{AccountIdOf, BalanceOf, RangeInclusiveExt};
pub use bp_xcm_bridge_hub::{Bridge, BridgeId, BridgeState};
use bp_xcm_bridge_hub::{BridgeLocations, BridgeLocationsError, LocalXcmChannelManager};
use frame_support::{traits::fungible::MutateHold, DefaultNoBound};
use frame_system::Config as SystemConfig;
use pallet_bridge_messages::{Config as BridgeMessagesConfig, LanesManagerError};
use sp_runtime::traits::Zero;
use sp_std::{boxed::Box, vec::Vec};
use xcm::prelude::*;
use xcm_builder::DispatchBlob;
use xcm_executor::traits::ConvertLocation;

pub use bp_xcm_bridge_hub::XcmAsPlainPayload;
pub use dispatcher::XcmBlobMessageDispatchResult;
pub use exporter::PalletAsHaulBlobExporter;
pub use pallet::*;

mod dispatcher;
mod exporter;
pub mod migration;
mod mock;

/// The target that will be used when publishing logs related to this pallet.
pub const LOG_TARGET: &str = "runtime::bridge-xcm";

#[frame_support::pallet]
pub mod pallet {
	use super::*;
	use frame_support::{
		pallet_prelude::*,
		traits::{tokens::Precision, Contains},
	};
	use frame_system::pallet_prelude::{BlockNumberFor, *};

	/// The reason for this pallet placing a hold on funds.
	#[pallet::composite_enum]
	pub enum HoldReason<I: 'static = ()> {
		/// The funds are held as a deposit for opened bridge.
		#[codec(index = 0)]
		BridgeDeposit,
	}

	#[pallet::config]
	#[pallet::disable_frame_system_supertrait_check]
	pub trait Config<I: 'static = ()>:
		BridgeMessagesConfig<Self::BridgeMessagesPalletInstance>
	{
		/// The overarching event type.
		type RuntimeEvent: From<Event<Self, I>>
			+ IsType<<Self as frame_system::Config>::RuntimeEvent>;

		/// Runtime's universal location.
		type UniversalLocation: Get<InteriorLocation>;
		// TODO: https://github.com/paritytech/parity-bridges-common/issues/1666 remove `ChainId` and
		// replace it with the `NetworkId` - then we'll be able to use
		// `T as pallet_bridge_messages::Config<T::BridgeMessagesPalletInstance>::BridgedChain::NetworkId`
		/// Bridged network as relative location of bridged `GlobalConsensus`.
		#[pallet::constant]
		type BridgedNetwork: Get<Location>;
		/// Associated messages pallet instance that bridges us with the
		/// `BridgedNetworkId` consensus.
		type BridgeMessagesPalletInstance: 'static;

		/// Price of single message export to the bridged consensus (`Self::BridgedNetwork`).
		type MessageExportPrice: Get<Assets>;
		/// Checks the XCM version for the destination.
		type DestinationVersion: GetVersion;

		/// The origin that is allowed to call privileged operations on the pallet, e.g. open/close
		/// bridge for locations.
		type ForceOrigin: EnsureOrigin<<Self as SystemConfig>::RuntimeOrigin>;
		/// A set of XCM locations within local consensus system that are allowed to open
		/// bridges with remote destinations.
		type OpenBridgeOrigin: EnsureOrigin<
			<Self as SystemConfig>::RuntimeOrigin,
			Success = Location,
		>;
		/// A converter between a location and a sovereign account.
		type BridgeOriginAccountIdConverter: ConvertLocation<AccountIdOf<ThisChainOf<Self, I>>>;

		/// Amount of this chain native tokens that is reserved on the sibling parachain account
		/// when bridge open request is registered.
		#[pallet::constant]
		type BridgeDeposit: Get<BalanceOf<ThisChainOf<Self, I>>>;
		/// Currency used to pay for bridge registration.
		type Currency: MutateHold<
			AccountIdOf<ThisChainOf<Self, I>>,
			Balance = BalanceOf<ThisChainOf<Self, I>>,
			Reason = Self::RuntimeHoldReason,
		>;
		/// The overarching runtime hold reason.
		type RuntimeHoldReason: From<HoldReason<I>>;
		/// Do not hold `Self::BridgeDeposit` for the location of `Self::OpenBridgeOrigin`.
		/// For example, it is possible to make an exception for a system parachain or relay.
		type AllowWithoutBridgeDeposit: Contains<Location>;

		/// Local XCM channel manager.
		type LocalXcmChannelManager: LocalXcmChannelManager;
		/// XCM-level dispatcher for inbound bridge messages.
		type BlobDispatcher: DispatchBlob;
	}

	/// An alias for the bridge metadata.
	pub type BridgeOf<T, I> = Bridge<ThisChainOf<T, I>, LaneIdOf<T, I>>;
	/// An alias for this chain.
	pub type ThisChainOf<T, I> =
		pallet_bridge_messages::ThisChainOf<T, <T as Config<I>>::BridgeMessagesPalletInstance>;
	/// An alias for lane identifier type.
	pub type LaneIdOf<T, I> =
		<T as BridgeMessagesConfig<<T as Config<I>>::BridgeMessagesPalletInstance>>::LaneId;
	/// An alias for the associated lanes manager.
	pub type LanesManagerOf<T, I> =
		pallet_bridge_messages::LanesManager<T, <T as Config<I>>::BridgeMessagesPalletInstance>;

	#[pallet::pallet]
	#[pallet::storage_version(migration::STORAGE_VERSION)]
	pub struct Pallet<T, I = ()>(PhantomData<(T, I)>);

	#[pallet::hooks]
	impl<T: Config<I>, I: 'static> Hooks<BlockNumberFor<T>> for Pallet<T, I> {
		fn integrity_test() {
			assert!(
				Self::bridged_network_id().is_ok(),
				"Configured `T::BridgedNetwork`: {:?} does not contain `GlobalConsensus` junction with `NetworkId`",
				T::BridgedNetwork::get()
			)
		}

		#[cfg(feature = "try-runtime")]
		fn try_state(_n: BlockNumberFor<T>) -> Result<(), sp_runtime::TryRuntimeError> {
			Self::do_try_state()
		}
	}

	#[pallet::call]
	impl<T: Config<I>, I: 'static> Pallet<T, I> {
		/// Open a bridge between two locations.
		///
		/// The caller must be within the `T::OpenBridgeOrigin` filter (presumably: a sibling
		/// parachain or a parent relay chain). The `bridge_destination_universal_location` must be
		/// a destination within the consensus of the `T::BridgedNetwork` network.
		///
		/// The `BridgeDeposit` amount is reserved on the caller account. This deposit
		/// is unreserved after bridge is closed.
		///
		/// The states after this call: bridge is `Opened`, outbound lane is `Opened`, inbound lane
		/// is `Opened`.
		#[pallet::call_index(0)]
		#[pallet::weight(Weight::zero())] // TODO:(bridges-v2) - https://github.com/paritytech/parity-bridges-common/issues/3046 - add benchmarks impl
		pub fn open_bridge(
			origin: OriginFor<T>,
			bridge_destination_universal_location: Box<VersionedInteriorLocation>,
		) -> DispatchResult {
			// check and compute required bridge locations and laneId
			let xcm_version = bridge_destination_universal_location.identify_version();
			let locations =
				Self::bridge_locations_from_origin(origin, bridge_destination_universal_location)?;
			let lane_id = locations.calculate_lane_id(xcm_version).map_err(|e| {
				log::trace!(
					target: LOG_TARGET,
					"calculate_lane_id error: {e:?}",
				);
				Error::<T, I>::BridgeLocations(e)
			})?;

			Self::do_open_bridge(locations, lane_id, true)
		}

		/// Try to close the bridge.
		///
		/// Can only be called by the "owner" of this side of the bridge, meaning that the
		/// inbound XCM channel with the local origin chain is working.
		///
		/// Closed bridge is a bridge without any traces in the runtime storage. So this method
		/// first tries to prune all queued messages at the outbound lane. When there are no
		/// outbound messages left, outbound and inbound lanes are purged. After that, funds
		/// are returned back to the owner of this side of the bridge.
		///
		/// The number of messages that we may prune in a single call is limited by the
		/// `may_prune_messages` argument. If there are more messages in the queue, the method
		/// prunes exactly `may_prune_messages` and exits early. The caller may call it again
		/// until outbound queue is depleted and get his funds back.
		///
		/// The states after this call: everything is either `Closed`, or purged from the
		/// runtime storage.
		#[pallet::call_index(1)]
		#[pallet::weight(Weight::zero())] // TODO:(bridges-v2) - https://github.com/paritytech/parity-bridges-common/issues/3046 - add benchmarks impl
		pub fn close_bridge(
			origin: OriginFor<T>,
			bridge_destination_universal_location: Box<VersionedInteriorLocation>,
			may_prune_messages: MessageNonce,
		) -> DispatchResult {
			// compute required bridge locations
			let locations =
				Self::bridge_locations_from_origin(origin, bridge_destination_universal_location)?;

			// TODO: https://github.com/paritytech/parity-bridges-common/issues/1760 - may do refund here, if
			// bridge/lanes are already closed + for messages that are not pruned

			// update bridge metadata - this also guarantees that the bridge is in the proper state
			let bridge =
				Bridges::<T, I>::try_mutate_exists(locations.bridge_id(), |bridge| match bridge {
					Some(bridge) => {
						bridge.state = BridgeState::Closed;
						Ok(bridge.clone())
					},
					None => Err(Error::<T, I>::UnknownBridge),
				})?;

			// close inbound and outbound lanes
			let lanes_manager = LanesManagerOf::<T, I>::new();
			let mut inbound_lane = lanes_manager
				.any_state_inbound_lane(bridge.lane_id)
				.map_err(Error::<T, I>::LanesManager)?;
			let mut outbound_lane = lanes_manager
				.any_state_outbound_lane(bridge.lane_id)
				.map_err(Error::<T, I>::LanesManager)?;

			// now prune queued messages
			let mut pruned_messages = 0;
			for _ in outbound_lane.queued_messages() {
				if pruned_messages == may_prune_messages {
					break
				}

				outbound_lane.remove_oldest_unpruned_message();
				pruned_messages += 1;
			}

			// if there are outbound messages in the queue, just update states and early exit
			if !outbound_lane.queued_messages().is_empty() {
				// update lanes state. Under normal circumstances, following calls shall never fail
				inbound_lane.set_state(LaneState::Closed);
				outbound_lane.set_state(LaneState::Closed);

				// write something to log
				let enqueued_messages = outbound_lane.queued_messages().saturating_len();
				log::trace!(
					target: LOG_TARGET,
					"Bridge {:?} between {:?} and {:?} is closing lane_id: {:?}. {} messages remaining",
					locations.bridge_id(),
					locations.bridge_origin_universal_location(),
					locations.bridge_destination_universal_location(),
					bridge.lane_id,
					enqueued_messages,
				);

				// deposit the `ClosingBridge` event
				Self::deposit_event(Event::<T, I>::ClosingBridge {
					bridge_id: *locations.bridge_id(),
					lane_id: bridge.lane_id.into(),
					pruned_messages,
					enqueued_messages,
				});

				return Ok(())
			}

			// else we have pruned all messages, so lanes and the bridge itself may gone
			inbound_lane.purge();
			outbound_lane.purge();
			Bridges::<T, I>::remove(locations.bridge_id());
			LaneToBridge::<T, I>::remove(bridge.lane_id);

			// return deposit
			let released_deposit = T::Currency::release(
				&HoldReason::BridgeDeposit.into(),
				&bridge.bridge_owner_account,
				bridge.deposit,
				Precision::BestEffort,
			)
			.inspect_err(|e| {
				// we can't do anything here - looks like funds have been (partially) unreserved
				// before by someone else. Let's not fail, though - it'll be worse for the caller
				log::error!(
					target: LOG_TARGET,
					"Failed to unreserve during the bridge {:?} closure with error: {e:?}",
					locations.bridge_id(),
				);
			})
			.ok()
			.unwrap_or(BalanceOf::<ThisChainOf<T, I>>::zero());

			// write something to log
			log::trace!(
				target: LOG_TARGET,
				"Bridge {:?} between {:?} and {:?} has closed lane_id: {:?}, the bridge deposit {released_deposit:?} was returned",
				locations.bridge_id(),
				bridge.lane_id,
				locations.bridge_origin_universal_location(),
				locations.bridge_destination_universal_location(),
			);

			// deposit the `BridgePruned` event
			Self::deposit_event(Event::<T, I>::BridgePruned {
				bridge_id: *locations.bridge_id(),
				lane_id: bridge.lane_id.into(),
				bridge_deposit: released_deposit,
				pruned_messages,
			});

			Ok(())
		}
	}

	impl<T: Config<I>, I: 'static> Pallet<T, I> {
		/// Open bridge for lane.
		pub fn do_open_bridge(
			locations: Box<BridgeLocations>,
			lane_id: T::LaneId,
			create_lanes: bool,
		) -> Result<(), DispatchError> {
			// reserve balance on the origin's sovereign account (if needed)
			let bridge_owner_account = T::BridgeOriginAccountIdConverter::convert_location(
				locations.bridge_origin_relative_location(),
			)
			.ok_or(Error::<T, I>::InvalidBridgeOriginAccount)?;
			let deposit = if T::AllowWithoutBridgeDeposit::contains(
				locations.bridge_origin_relative_location(),
			) {
				BalanceOf::<ThisChainOf<T, I>>::zero()
			} else {
				let deposit = T::BridgeDeposit::get();
				T::Currency::hold(
					&HoldReason::BridgeDeposit.into(),
					&bridge_owner_account,
					deposit,
				)
				.map_err(|e| {
					log::error!(
						target: LOG_TARGET,
						"Failed to hold bridge deposit: {deposit:?} \
						from bridge_owner_account: {bridge_owner_account:?} derived from \
						bridge_origin_relative_location: {:?} with error: {e:?}",
						locations.bridge_origin_relative_location(),
					);
					Error::<T, I>::FailedToReserveBridgeDeposit
				})?;
				deposit
			};

			// save bridge metadata
			Bridges::<T, I>::try_mutate(locations.bridge_id(), |bridge| match bridge {
				Some(_) => Err(Error::<T, I>::BridgeAlreadyExists),
				None => {
					*bridge = Some(BridgeOf::<T, I> {
						bridge_origin_relative_location: Box::new(
							locations.bridge_origin_relative_location().clone().into(),
						),
						bridge_origin_universal_location: Box::new(
							locations.bridge_origin_universal_location().clone().into(),
						),
						bridge_destination_universal_location: Box::new(
							locations.bridge_destination_universal_location().clone().into(),
						),
						state: BridgeState::Opened,
						bridge_owner_account,
						deposit,
						lane_id,
					});
					Ok(())
				},
			})?;
			// save lane to bridge mapping
			LaneToBridge::<T, I>::try_mutate(lane_id, |bridge| match bridge {
				Some(_) => Err(Error::<T, I>::BridgeAlreadyExists),
				None => {
					*bridge = Some(*locations.bridge_id());
					Ok(())
				},
			})?;

			if create_lanes {
				// create new lanes. Under normal circumstances, following calls shall never fail
				let lanes_manager = LanesManagerOf::<T, I>::new();
				lanes_manager
					.create_inbound_lane(lane_id)
					.map_err(Error::<T, I>::LanesManager)?;
				lanes_manager
					.create_outbound_lane(lane_id)
					.map_err(Error::<T, I>::LanesManager)?;
			}

			// write something to log
			log::trace!(
				target: LOG_TARGET,
				"Bridge {:?} between {:?} and {:?} has been opened using lane_id: {lane_id:?}",
				locations.bridge_id(),
				locations.bridge_origin_universal_location(),
				locations.bridge_destination_universal_location(),
			);

			// deposit `BridgeOpened` event
			Self::deposit_event(Event::<T, I>::BridgeOpened {
				bridge_id: *locations.bridge_id(),
				bridge_deposit: deposit,
				local_endpoint: Box::new(locations.bridge_origin_universal_location().clone()),
				remote_endpoint: Box::new(
					locations.bridge_destination_universal_location().clone(),
				),
				lane_id: lane_id.into(),
			});

			Ok(())
		}
	}

	impl<T: Config<I>, I: 'static> Pallet<T, I> {
		/// Return bridge endpoint locations and dedicated lane identifier. This method converts
		/// runtime `origin` argument to relative `Location` using the `T::OpenBridgeOrigin`
		/// converter.
		pub fn bridge_locations_from_origin(
			origin: OriginFor<T>,
			bridge_destination_universal_location: Box<VersionedInteriorLocation>,
		) -> Result<Box<BridgeLocations>, sp_runtime::DispatchError> {
			Self::bridge_locations(
				T::OpenBridgeOrigin::ensure_origin(origin)?,
				(*bridge_destination_universal_location)
					.try_into()
					.map_err(|_| Error::<T, I>::UnsupportedXcmVersion)?,
			)
		}

		/// Return bridge endpoint locations and dedicated **bridge** identifier (`BridgeId`).
		pub fn bridge_locations(
			bridge_origin_relative_location: Location,
			bridge_destination_universal_location: InteriorLocation,
		) -> Result<Box<BridgeLocations>, sp_runtime::DispatchError> {
			BridgeLocations::bridge_locations(
				T::UniversalLocation::get(),
				bridge_origin_relative_location,
				bridge_destination_universal_location,
				Self::bridged_network_id()?,
			)
			.map_err(|e| {
				log::trace!(
					target: LOG_TARGET,
					"bridge_locations error: {e:?}",
				);
				Error::<T, I>::BridgeLocations(e).into()
			})
		}

		/// Return bridge metadata by bridge_id
		pub fn bridge(bridge_id: &BridgeId) -> Option<BridgeOf<T, I>> {
			Bridges::<T, I>::get(bridge_id)
		}

		/// Return bridge metadata by lane_id
		pub fn bridge_by_lane_id(lane_id: &T::LaneId) -> Option<(BridgeId, BridgeOf<T, I>)> {
			LaneToBridge::<T, I>::get(lane_id)
				.and_then(|bridge_id| Self::bridge(&bridge_id).map(|bridge| (bridge_id, bridge)))
		}
	}

	impl<T: Config<I>, I: 'static> Pallet<T, I> {
		/// Returns some `NetworkId` if contains `GlobalConsensus` junction.
		fn bridged_network_id() -> Result<NetworkId, sp_runtime::DispatchError> {
			match T::BridgedNetwork::get().take_first_interior() {
				Some(GlobalConsensus(network)) => Ok(network),
				_ => Err(Error::<T, I>::BridgeLocations(
					BridgeLocationsError::InvalidBridgeDestination,
				)
				.into()),
			}
		}
	}

	#[cfg(any(test, feature = "try-runtime", feature = "std"))]
	impl<T: Config<I>, I: 'static> Pallet<T, I> {
		/// Ensure the correctness of the state of this pallet.
		pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
			use sp_std::collections::btree_set::BTreeSet;

			let mut lanes = BTreeSet::new();

			// check all known bridge configurations
			for (bridge_id, bridge) in Bridges::<T, I>::iter() {
				lanes.insert(Self::do_try_state_for_bridge(bridge_id, bridge)?);
			}
			ensure!(
				lanes.len() == Bridges::<T, I>::iter().count(),
				"Invalid `Bridges` configuration, probably two bridges handle the same laneId!"
			);
			ensure!(
				lanes.len() == LaneToBridge::<T, I>::iter().count(),
				"Invalid `LaneToBridge` configuration, probably missing or not removed laneId!"
			);

			// check connected `pallet_bridge_messages` state.
			Self::do_try_state_for_messages()
		}

		/// Ensure the correctness of the state of the bridge.
		pub fn do_try_state_for_bridge(
			bridge_id: BridgeId,
			bridge: BridgeOf<T, I>,
		) -> Result<T::LaneId, sp_runtime::TryRuntimeError> {
			log::info!(target: LOG_TARGET, "Checking `do_try_state_for_bridge` for bridge_id: {bridge_id:?} and bridge: {bridge:?}");

			// check `BridgeId` points to the same `LaneId` and vice versa.
			ensure!(
				Some(bridge_id) == LaneToBridge::<T, I>::get(bridge.lane_id),
				"Found `LaneToBridge` inconsistency for bridge_id - missing mapping!"
			);

			// check `pallet_bridge_messages` state for that `LaneId`.
			let lanes_manager = LanesManagerOf::<T, I>::new();
			ensure!(
				lanes_manager.any_state_inbound_lane(bridge.lane_id).is_ok(),
				"Inbound lane not found!",
			);
			ensure!(
				lanes_manager.any_state_outbound_lane(bridge.lane_id).is_ok(),
				"Outbound lane not found!",
			);

			// check that `locations` are convertible to the `latest` XCM.
			let bridge_origin_relative_location_as_latest: &Location =
				bridge.bridge_origin_relative_location.try_as().map_err(|_| {
					"`bridge.bridge_origin_relative_location` cannot be converted to the `latest` XCM, needs migration!"
				})?;
			let bridge_origin_universal_location_as_latest: &InteriorLocation = bridge.bridge_origin_universal_location
				.try_as()
				.map_err(|_| "`bridge.bridge_origin_universal_location` cannot be converted to the `latest` XCM, needs migration!")?;
			let bridge_destination_universal_location_as_latest: &InteriorLocation = bridge.bridge_destination_universal_location
				.try_as()
				.map_err(|_| "`bridge.bridge_destination_universal_location` cannot be converted to the `latest` XCM, needs migration!")?;

			// check `BridgeId` does not change
			ensure!(
				bridge_id == BridgeId::new(bridge_origin_universal_location_as_latest, bridge_destination_universal_location_as_latest),
				"`bridge_id` is different than calculated from `bridge_origin_universal_location_as_latest` and `bridge_destination_universal_location_as_latest`, needs migration!"
			);

			// check bridge account owner
			ensure!(
				T::BridgeOriginAccountIdConverter::convert_location(bridge_origin_relative_location_as_latest) == Some(bridge.bridge_owner_account),
				"`bridge.bridge_owner_account` is different than calculated from `bridge.bridge_origin_relative_location`, needs migration!"
			);

			Ok(bridge.lane_id)
		}

		/// Ensure the correctness of the state of the connected `pallet_bridge_messages` instance.
		pub fn do_try_state_for_messages() -> Result<(), sp_runtime::TryRuntimeError> {
			// check that all `InboundLanes` laneIds have mapping to some bridge.
			for lane_id in pallet_bridge_messages::InboundLanes::<T, T::BridgeMessagesPalletInstance>::iter_keys() {
				log::info!(target: LOG_TARGET, "Checking `do_try_state_for_messages` for `InboundLanes`'s lane_id: {lane_id:?}...");
				ensure!(
					LaneToBridge::<T, I>::get(lane_id).is_some(),
					"Found `LaneToBridge` inconsistency for `InboundLanes`'s lane_id - missing mapping!"
				);
			}

			// check that all `OutboundLanes` laneIds have mapping to some bridge.
			for lane_id in pallet_bridge_messages::OutboundLanes::<T, T::BridgeMessagesPalletInstance>::iter_keys() {
				log::info!(target: LOG_TARGET, "Checking `do_try_state_for_messages` for `OutboundLanes`'s lane_id: {lane_id:?}...");
				ensure!(
					LaneToBridge::<T, I>::get(lane_id).is_some(),
					"Found `LaneToBridge` inconsistency for `OutboundLanes`'s lane_id - missing mapping!"
				);
			}

			Ok(())
		}
	}

	/// All registered bridges.
	#[pallet::storage]
	pub type Bridges<T: Config<I>, I: 'static = ()> =
		StorageMap<_, Identity, BridgeId, BridgeOf<T, I>>;
	/// All registered `lane_id` and `bridge_id` mappings.
	#[pallet::storage]
	pub type LaneToBridge<T: Config<I>, I: 'static = ()> =
		StorageMap<_, Identity, T::LaneId, BridgeId>;

	#[pallet::genesis_config]
	#[derive(DefaultNoBound)]
	pub struct GenesisConfig<T: Config<I>, I: 'static = ()> {
		/// Opened bridges.
		///
		/// Keep in mind that we are **NOT** reserving any amount for the bridges opened at
		/// genesis. We are **NOT** opening lanes, used by this bridge. It all must be done using
		/// other pallets genesis configuration or some other means.
		pub opened_bridges: Vec<(Location, InteriorLocation, Option<T::LaneId>)>,
		/// Dummy marker.
		#[serde(skip)]
		pub _phantom: sp_std::marker::PhantomData<(T, I)>,
	}

	#[pallet::genesis_build]
	impl<T: Config<I>, I: 'static> BuildGenesisConfig for GenesisConfig<T, I>
	where
		T: frame_system::Config<AccountId = AccountIdOf<ThisChainOf<T, I>>>,
	{
		fn build(&self) {
			for (
				bridge_origin_relative_location,
				bridge_destination_universal_location,
				maybe_lane_id,
			) in &self.opened_bridges
			{
				let locations = Pallet::<T, I>::bridge_locations(
					bridge_origin_relative_location.clone(),
					bridge_destination_universal_location.clone().into(),
				)
				.expect("Invalid genesis configuration");

				let lane_id = match maybe_lane_id {
					Some(lane_id) => *lane_id,
					None =>
						locations.calculate_lane_id(xcm::latest::VERSION).expect("Valid locations"),
				};

				Pallet::<T, I>::do_open_bridge(locations, lane_id, true)
					.expect("Valid opened bridge!");
			}
		}
	}

	#[pallet::event]
	#[pallet::generate_deposit(pub(super) fn deposit_event)]
	pub enum Event<T: Config<I>, I: 'static = ()> {
		/// The bridge between two locations has been opened.
		BridgeOpened {
			/// Bridge identifier.
			bridge_id: BridgeId,
			/// Amount of deposit held.
			bridge_deposit: BalanceOf<ThisChainOf<T, I>>,

			/// Universal location of local bridge endpoint.
			local_endpoint: Box<InteriorLocation>,
			/// Universal location of remote bridge endpoint.
			remote_endpoint: Box<InteriorLocation>,
			/// Lane identifier.
			lane_id: T::LaneId,
		},
		/// Bridge is going to be closed, but not yet fully pruned from the runtime storage.
		ClosingBridge {
			/// Bridge identifier.
			bridge_id: BridgeId,
			/// Lane identifier.
			lane_id: T::LaneId,
			/// Number of pruned messages during the close call.
			pruned_messages: MessageNonce,
			/// Number of enqueued messages that need to be pruned in follow up calls.
			enqueued_messages: MessageNonce,
		},
		/// Bridge has been closed and pruned from the runtime storage. It now may be reopened
		/// again by any participant.
		BridgePruned {
			/// Bridge identifier.
			bridge_id: BridgeId,
			/// Lane identifier.
			lane_id: T::LaneId,
			/// Amount of deposit released.
			bridge_deposit: BalanceOf<ThisChainOf<T, I>>,
			/// Number of pruned messages during the close call.
			pruned_messages: MessageNonce,
		},
	}

	#[pallet::error]
	pub enum Error<T, I = ()> {
		/// Bridge locations error.
		BridgeLocations(BridgeLocationsError),
		/// Invalid local bridge origin account.
		InvalidBridgeOriginAccount,
		/// The bridge is already registered in this pallet.
		BridgeAlreadyExists,
		/// The local origin already owns a maximal number of bridges.
		TooManyBridgesForLocalOrigin,
		/// Trying to close already closed bridge.
		BridgeAlreadyClosed,
		/// Lanes manager error.
		LanesManager(LanesManagerError),
		/// Trying to access unknown bridge.
		UnknownBridge,
		/// The bridge origin can't pay the required amount for opening the bridge.
		FailedToReserveBridgeDeposit,
		/// The version of XCM location argument is unsupported.
		UnsupportedXcmVersion,
	}
}

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

	use frame_support::{assert_err, assert_noop, assert_ok, traits::fungible::Mutate, BoundedVec};
	use frame_system::{EventRecord, Phase};
	use sp_runtime::TryRuntimeError;

	fn fund_origin_sovereign_account(locations: &BridgeLocations, balance: Balance) -> AccountId {
		let bridge_owner_account =
			LocationToAccountId::convert_location(locations.bridge_origin_relative_location())
				.unwrap();
		assert_ok!(Balances::mint_into(&bridge_owner_account, balance));
		bridge_owner_account
	}

	fn mock_open_bridge_from_with(
		origin: RuntimeOrigin,
		deposit: Balance,
		with: InteriorLocation,
	) -> (BridgeOf<TestRuntime, ()>, BridgeLocations) {
		let locations =
			XcmOverBridge::bridge_locations_from_origin(origin, Box::new(with.into())).unwrap();
		let lane_id = locations.calculate_lane_id(xcm::latest::VERSION).unwrap();
		let bridge_owner_account =
			fund_origin_sovereign_account(&locations, deposit + ExistentialDeposit::get());
		Balances::hold(&HoldReason::BridgeDeposit.into(), &bridge_owner_account, deposit).unwrap();

		let bridge = Bridge {
			bridge_origin_relative_location: Box::new(
				locations.bridge_origin_relative_location().clone().into(),
			),
			bridge_origin_universal_location: Box::new(
				locations.bridge_origin_universal_location().clone().into(),
			),
			bridge_destination_universal_location: Box::new(
				locations.bridge_destination_universal_location().clone().into(),
			),
			state: BridgeState::Opened,
			bridge_owner_account,
			deposit,
			lane_id,
		};
		Bridges::<TestRuntime, ()>::insert(locations.bridge_id(), bridge.clone());
		LaneToBridge::<TestRuntime, ()>::insert(bridge.lane_id, locations.bridge_id());

		let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
		lanes_manager.create_inbound_lane(bridge.lane_id).unwrap();
		lanes_manager.create_outbound_lane(bridge.lane_id).unwrap();

		assert_ok!(XcmOverBridge::do_try_state());

		(bridge, *locations)
	}

	fn mock_open_bridge_from(
		origin: RuntimeOrigin,
		deposit: Balance,
	) -> (BridgeOf<TestRuntime, ()>, BridgeLocations) {
		mock_open_bridge_from_with(origin, deposit, bridged_asset_hub_universal_location())
	}

	fn enqueue_message(lane: TestLaneIdType) {
		let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
		lanes_manager
			.active_outbound_lane(lane)
			.unwrap()
			.send_message(BoundedVec::try_from(vec![42]).expect("We craft valid messages"));
	}

	#[test]
	fn open_bridge_fails_if_origin_is_not_allowed() {
		run_test(|| {
			assert_noop!(
				XcmOverBridge::open_bridge(
					OpenBridgeOrigin::disallowed_origin(),
					Box::new(bridged_asset_hub_universal_location().into()),
				),
				sp_runtime::DispatchError::BadOrigin,
			);
		})
	}

	#[test]
	fn open_bridge_fails_if_origin_is_not_relative() {
		run_test(|| {
			assert_noop!(
				XcmOverBridge::open_bridge(
					OpenBridgeOrigin::parent_relay_chain_universal_origin(),
					Box::new(bridged_asset_hub_universal_location().into()),
				),
				Error::<TestRuntime, ()>::BridgeLocations(
					BridgeLocationsError::InvalidBridgeOrigin
				),
			);

			assert_noop!(
				XcmOverBridge::open_bridge(
					OpenBridgeOrigin::sibling_parachain_universal_origin(),
					Box::new(bridged_asset_hub_universal_location().into()),
				),
				Error::<TestRuntime, ()>::BridgeLocations(
					BridgeLocationsError::InvalidBridgeOrigin
				),
			);
		})
	}

	#[test]
	fn open_bridge_fails_if_destination_is_not_remote() {
		run_test(|| {
			assert_noop!(
				XcmOverBridge::open_bridge(
					OpenBridgeOrigin::parent_relay_chain_origin(),
					Box::new(
						[GlobalConsensus(RelayNetwork::get()), Parachain(BRIDGED_ASSET_HUB_ID)]
							.into()
					),
				),
				Error::<TestRuntime, ()>::BridgeLocations(BridgeLocationsError::DestinationIsLocal),
			);
		});
	}

	#[test]
	fn open_bridge_fails_if_outside_of_bridged_consensus() {
		run_test(|| {
			assert_noop!(
				XcmOverBridge::open_bridge(
					OpenBridgeOrigin::parent_relay_chain_origin(),
					Box::new(
						[
							GlobalConsensus(NonBridgedRelayNetwork::get()),
							Parachain(BRIDGED_ASSET_HUB_ID)
						]
						.into()
					),
				),
				Error::<TestRuntime, ()>::BridgeLocations(
					BridgeLocationsError::UnreachableDestination
				),
			);
		});
	}

	#[test]
	fn open_bridge_fails_if_origin_has_no_sovereign_account() {
		run_test(|| {
			assert_noop!(
				XcmOverBridge::open_bridge(
					OpenBridgeOrigin::origin_without_sovereign_account(),
					Box::new(bridged_asset_hub_universal_location().into()),
				),
				Error::<TestRuntime, ()>::InvalidBridgeOriginAccount,
			);
		});
	}

	#[test]
	fn open_bridge_fails_if_origin_sovereign_account_has_no_enough_funds() {
		run_test(|| {
			assert_noop!(
				XcmOverBridge::open_bridge(
					OpenBridgeOrigin::sibling_parachain_origin(),
					Box::new(bridged_asset_hub_universal_location().into()),
				),
				Error::<TestRuntime, ()>::FailedToReserveBridgeDeposit,
			);
		});
	}

	#[test]
	fn open_bridge_fails_if_it_already_exists() {
		run_test(|| {
			let origin = OpenBridgeOrigin::parent_relay_chain_origin();
			let locations = XcmOverBridge::bridge_locations_from_origin(
				origin.clone(),
				Box::new(bridged_asset_hub_universal_location().into()),
			)
			.unwrap();
			let lane_id = locations.calculate_lane_id(xcm::latest::VERSION).unwrap();
			fund_origin_sovereign_account(
				&locations,
				BridgeDeposit::get() + ExistentialDeposit::get(),
			);

			Bridges::<TestRuntime, ()>::insert(
				locations.bridge_id(),
				Bridge {
					bridge_origin_relative_location: Box::new(
						locations.bridge_origin_relative_location().clone().into(),
					),
					bridge_origin_universal_location: Box::new(
						locations.bridge_origin_universal_location().clone().into(),
					),
					bridge_destination_universal_location: Box::new(
						locations.bridge_destination_universal_location().clone().into(),
					),
					state: BridgeState::Opened,
					bridge_owner_account: [0u8; 32].into(),
					deposit: 0,
					lane_id,
				},
			);

			assert_noop!(
				XcmOverBridge::open_bridge(
					origin,
					Box::new(bridged_asset_hub_universal_location().into()),
				),
				Error::<TestRuntime, ()>::BridgeAlreadyExists,
			);
		})
	}

	#[test]
	fn open_bridge_fails_if_its_lanes_already_exists() {
		run_test(|| {
			let origin = OpenBridgeOrigin::parent_relay_chain_origin();
			let locations = XcmOverBridge::bridge_locations_from_origin(
				origin.clone(),
				Box::new(bridged_asset_hub_universal_location().into()),
			)
			.unwrap();
			let lane_id = locations.calculate_lane_id(xcm::latest::VERSION).unwrap();
			fund_origin_sovereign_account(
				&locations,
				BridgeDeposit::get() + ExistentialDeposit::get(),
			);

			let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();

			lanes_manager.create_inbound_lane(lane_id).unwrap();
			assert_noop!(
				XcmOverBridge::open_bridge(
					origin.clone(),
					Box::new(bridged_asset_hub_universal_location().into()),
				),
				Error::<TestRuntime, ()>::LanesManager(LanesManagerError::InboundLaneAlreadyExists),
			);

			lanes_manager.active_inbound_lane(lane_id).unwrap().purge();
			lanes_manager.create_outbound_lane(lane_id).unwrap();
			assert_noop!(
				XcmOverBridge::open_bridge(
					origin,
					Box::new(bridged_asset_hub_universal_location().into()),
				),
				Error::<TestRuntime, ()>::LanesManager(
					LanesManagerError::OutboundLaneAlreadyExists
				),
			);
		})
	}

	#[test]
	fn open_bridge_works() {
		run_test(|| {
			// in our test runtime, we expect that bridge may be opened by parent relay chain
			// and any sibling parachain
			let origins = [
				(OpenBridgeOrigin::parent_relay_chain_origin(), 0),
				(OpenBridgeOrigin::sibling_parachain_origin(), BridgeDeposit::get()),
			];

			// check that every origin may open the bridge
			let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
			let existential_deposit = ExistentialDeposit::get();
			for (origin, expected_deposit) in origins {
				// reset events
				System::set_block_number(1);
				System::reset_events();

				// compute all other locations
				let xcm_version = xcm::latest::VERSION;
				let locations = XcmOverBridge::bridge_locations_from_origin(
					origin.clone(),
					Box::new(
						VersionedInteriorLocation::from(bridged_asset_hub_universal_location())
							.into_version(xcm_version)
							.expect("valid conversion"),
					),
				)
				.unwrap();
				let lane_id = locations.calculate_lane_id(xcm_version).unwrap();

				// ensure that there's no bridge and lanes in the storage
				assert_eq!(Bridges::<TestRuntime, ()>::get(locations.bridge_id()), None);
				assert_eq!(
					lanes_manager.active_inbound_lane(lane_id).map(drop),
					Err(LanesManagerError::UnknownInboundLane)
				);
				assert_eq!(
					lanes_manager.active_outbound_lane(lane_id).map(drop),
					Err(LanesManagerError::UnknownOutboundLane)
				);
				assert_eq!(LaneToBridge::<TestRuntime, ()>::get(lane_id), None);

				// give enough funds to the sovereign account of the bridge origin
				let bridge_owner_account = fund_origin_sovereign_account(
					&locations,
					expected_deposit + existential_deposit,
				);
				assert_eq!(
					Balances::free_balance(&bridge_owner_account),
					expected_deposit + existential_deposit
				);
				assert_eq!(Balances::reserved_balance(&bridge_owner_account), 0);

				// now open the bridge
				assert_ok!(XcmOverBridge::open_bridge(
					origin,
					Box::new(locations.bridge_destination_universal_location().clone().into()),
				));

				// ensure that everything has been set up in the runtime storage
				assert_eq!(
					Bridges::<TestRuntime, ()>::get(locations.bridge_id()),
					Some(Bridge {
						bridge_origin_relative_location: Box::new(
							locations.bridge_origin_relative_location().clone().into()
						),
						bridge_origin_universal_location: Box::new(
							locations.bridge_origin_universal_location().clone().into(),
						),
						bridge_destination_universal_location: Box::new(
							locations.bridge_destination_universal_location().clone().into(),
						),
						state: BridgeState::Opened,
						bridge_owner_account: bridge_owner_account.clone(),
						deposit: expected_deposit,
						lane_id
					}),
				);
				assert_eq!(
					lanes_manager.active_inbound_lane(lane_id).map(|l| l.state()),
					Ok(LaneState::Opened)
				);
				assert_eq!(
					lanes_manager.active_outbound_lane(lane_id).map(|l| l.state()),
					Ok(LaneState::Opened)
				);
				assert_eq!(
					LaneToBridge::<TestRuntime, ()>::get(lane_id),
					Some(*locations.bridge_id())
				);
				assert_eq!(Balances::free_balance(&bridge_owner_account), existential_deposit);
				assert_eq!(Balances::reserved_balance(&bridge_owner_account), expected_deposit);

				// ensure that the proper event is deposited
				assert_eq!(
					System::events().last(),
					Some(&EventRecord {
						phase: Phase::Initialization,
						event: RuntimeEvent::XcmOverBridge(Event::BridgeOpened {
							bridge_id: *locations.bridge_id(),
							bridge_deposit: expected_deposit,
							local_endpoint: Box::new(
								locations.bridge_origin_universal_location().clone()
							),
							remote_endpoint: Box::new(
								locations.bridge_destination_universal_location().clone()
							),
							lane_id: lane_id.into()
						}),
						topics: vec![],
					}),
				);

				// check state
				assert_ok!(XcmOverBridge::do_try_state());
			}
		});
	}

	#[test]
	fn close_bridge_fails_if_origin_is_not_allowed() {
		run_test(|| {
			assert_noop!(
				XcmOverBridge::close_bridge(
					OpenBridgeOrigin::disallowed_origin(),
					Box::new(bridged_asset_hub_universal_location().into()),
					0,
				),
				sp_runtime::DispatchError::BadOrigin,
			);
		})
	}

	#[test]
	fn close_bridge_fails_if_origin_is_not_relative() {
		run_test(|| {
			assert_noop!(
				XcmOverBridge::close_bridge(
					OpenBridgeOrigin::parent_relay_chain_universal_origin(),
					Box::new(bridged_asset_hub_universal_location().into()),
					0,
				),
				Error::<TestRuntime, ()>::BridgeLocations(
					BridgeLocationsError::InvalidBridgeOrigin
				),
			);

			assert_noop!(
				XcmOverBridge::close_bridge(
					OpenBridgeOrigin::sibling_parachain_universal_origin(),
					Box::new(bridged_asset_hub_universal_location().into()),
					0,
				),
				Error::<TestRuntime, ()>::BridgeLocations(
					BridgeLocationsError::InvalidBridgeOrigin
				),
			);
		})
	}

	#[test]
	fn close_bridge_fails_if_its_lanes_are_unknown() {
		run_test(|| {
			let origin = OpenBridgeOrigin::parent_relay_chain_origin();
			let (bridge, locations) = mock_open_bridge_from(origin.clone(), 0);

			let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
			lanes_manager.any_state_inbound_lane(bridge.lane_id).unwrap().purge();
			assert_noop!(
				XcmOverBridge::close_bridge(
					origin.clone(),
					Box::new(locations.bridge_destination_universal_location().clone().into()),
					0,
				),
				Error::<TestRuntime, ()>::LanesManager(LanesManagerError::UnknownInboundLane),
			);
			lanes_manager.any_state_outbound_lane(bridge.lane_id).unwrap().purge();

			let (_, locations) = mock_open_bridge_from(origin.clone(), 0);
			lanes_manager.any_state_outbound_lane(bridge.lane_id).unwrap().purge();
			assert_noop!(
				XcmOverBridge::close_bridge(
					origin,
					Box::new(locations.bridge_destination_universal_location().clone().into()),
					0,
				),
				Error::<TestRuntime, ()>::LanesManager(LanesManagerError::UnknownOutboundLane),
			);
		});
	}

	#[test]
	fn close_bridge_works() {
		run_test(|| {
			let origin = OpenBridgeOrigin::parent_relay_chain_origin();
			let expected_deposit = BridgeDeposit::get();
			let (bridge, locations) = mock_open_bridge_from(origin.clone(), expected_deposit);
			System::set_block_number(1);

			// remember owner balances
			let free_balance = Balances::free_balance(&bridge.bridge_owner_account);
			let reserved_balance = Balances::reserved_balance(&bridge.bridge_owner_account);

			// enqueue some messages
			for _ in 0..32 {
				enqueue_message(bridge.lane_id);
			}

			// now call the `close_bridge`, which will only partially prune messages
			assert_ok!(XcmOverBridge::close_bridge(
				origin.clone(),
				Box::new(locations.bridge_destination_universal_location().clone().into()),
				16,
			),);

			// as a result, the bridge and lanes are switched to the `Closed` state, some messages
			// are pruned, but funds are not unreserved
			let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
			assert_eq!(
				Bridges::<TestRuntime, ()>::get(locations.bridge_id()).map(|b| b.state),
				Some(BridgeState::Closed)
			);
			assert_eq!(
				lanes_manager.any_state_inbound_lane(bridge.lane_id).unwrap().state(),
				LaneState::Closed
			);
			assert_eq!(
				lanes_manager.any_state_outbound_lane(bridge.lane_id).unwrap().state(),
				LaneState::Closed
			);
			assert_eq!(
				lanes_manager
					.any_state_outbound_lane(bridge.lane_id)
					.unwrap()
					.queued_messages()
					.checked_len(),
				Some(16)
			);
			assert_eq!(
				LaneToBridge::<TestRuntime, ()>::get(bridge.lane_id),
				Some(*locations.bridge_id())
			);
			assert_eq!(Balances::free_balance(&bridge.bridge_owner_account), free_balance);
			assert_eq!(Balances::reserved_balance(&bridge.bridge_owner_account), reserved_balance);
			assert_eq!(
				System::events().last(),
				Some(&EventRecord {
					phase: Phase::Initialization,
					event: RuntimeEvent::XcmOverBridge(Event::ClosingBridge {
						bridge_id: *locations.bridge_id(),
						lane_id: bridge.lane_id.into(),
						pruned_messages: 16,
						enqueued_messages: 16,
					}),
					topics: vec![],
				}),
			);

			// now call the `close_bridge` again, which will only partially prune messages
			assert_ok!(XcmOverBridge::close_bridge(
				origin.clone(),
				Box::new(locations.bridge_destination_universal_location().clone().into()),
				8,
			),);

			// nothing is changed (apart from the pruned messages)
			assert_eq!(
				Bridges::<TestRuntime, ()>::get(locations.bridge_id()).map(|b| b.state),
				Some(BridgeState::Closed)
			);
			assert_eq!(
				lanes_manager.any_state_inbound_lane(bridge.lane_id).unwrap().state(),
				LaneState::Closed
			);
			assert_eq!(
				lanes_manager.any_state_outbound_lane(bridge.lane_id).unwrap().state(),
				LaneState::Closed
			);
			assert_eq!(
				lanes_manager
					.any_state_outbound_lane(bridge.lane_id)
					.unwrap()
					.queued_messages()
					.checked_len(),
				Some(8)
			);
			assert_eq!(
				LaneToBridge::<TestRuntime, ()>::get(bridge.lane_id),
				Some(*locations.bridge_id())
			);
			assert_eq!(Balances::free_balance(&bridge.bridge_owner_account), free_balance);
			assert_eq!(Balances::reserved_balance(&bridge.bridge_owner_account), reserved_balance);
			assert_eq!(
				System::events().last(),
				Some(&EventRecord {
					phase: Phase::Initialization,
					event: RuntimeEvent::XcmOverBridge(Event::ClosingBridge {
						bridge_id: *locations.bridge_id(),
						lane_id: bridge.lane_id.into(),
						pruned_messages: 8,
						enqueued_messages: 8,
					}),
					topics: vec![],
				}),
			);

			// now call the `close_bridge` again that will prune all remaining messages and the
			// bridge
			assert_ok!(XcmOverBridge::close_bridge(
				origin,
				Box::new(locations.bridge_destination_universal_location().clone().into()),
				9,
			),);

			// there's no traces of bridge in the runtime storage and funds are unreserved
			assert_eq!(
				Bridges::<TestRuntime, ()>::get(locations.bridge_id()).map(|b| b.state),
				None
			);
			assert_eq!(
				lanes_manager.any_state_inbound_lane(bridge.lane_id).map(drop),
				Err(LanesManagerError::UnknownInboundLane)
			);
			assert_eq!(
				lanes_manager.any_state_outbound_lane(bridge.lane_id).map(drop),
				Err(LanesManagerError::UnknownOutboundLane)
			);
			assert_eq!(LaneToBridge::<TestRuntime, ()>::get(bridge.lane_id), None);
			assert_eq!(
				Balances::free_balance(&bridge.bridge_owner_account),
				free_balance + reserved_balance
			);
			assert_eq!(Balances::reserved_balance(&bridge.bridge_owner_account), 0);
			assert_eq!(
				System::events().last(),
				Some(&EventRecord {
					phase: Phase::Initialization,
					event: RuntimeEvent::XcmOverBridge(Event::BridgePruned {
						bridge_id: *locations.bridge_id(),
						lane_id: bridge.lane_id.into(),
						bridge_deposit: expected_deposit,
						pruned_messages: 8,
					}),
					topics: vec![],
				}),
			);
		});
	}

	#[test]
	fn do_try_state_works() {
		let bridge_origin_relative_location = SiblingLocation::get();
		let bridge_origin_universal_location = SiblingUniversalLocation::get();
		let bridge_destination_universal_location = BridgedUniversalDestination::get();
		let bridge_owner_account =
			LocationToAccountId::convert_location(&bridge_origin_relative_location)
				.expect("valid accountId");
		let bridge_owner_account_mismatch =
			LocationToAccountId::convert_location(&Location::parent()).expect("valid accountId");
		let bridge_id = BridgeId::new(
			&bridge_origin_universal_location,
			&bridge_destination_universal_location,
		);
		let bridge_id_mismatch = BridgeId::new(&InteriorLocation::Here, &InteriorLocation::Here);
		let lane_id = TestLaneIdType::try_new(1, 2).unwrap();
		let lane_id_mismatch = TestLaneIdType::try_new(3, 4).unwrap();

		let test_bridge_state =
			|id,
			 bridge,
			 (lane_id, bridge_id),
			 (inbound_lane_id, outbound_lane_id),
			 expected_error: Option<TryRuntimeError>| {
				Bridges::<TestRuntime, ()>::insert(id, bridge);
				LaneToBridge::<TestRuntime, ()>::insert(lane_id, bridge_id);

				let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
				lanes_manager.create_inbound_lane(inbound_lane_id).unwrap();
				lanes_manager.create_outbound_lane(outbound_lane_id).unwrap();

				let result = XcmOverBridge::do_try_state();
				if let Some(e) = expected_error {
					assert_err!(result, e);
				} else {
					assert_ok!(result);
				}
			};
		let cleanup = |bridge_id, lane_ids| {
			Bridges::<TestRuntime, ()>::remove(bridge_id);
			for lane_id in lane_ids {
				LaneToBridge::<TestRuntime, ()>::remove(lane_id);
				let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
				if let Ok(lane) = lanes_manager.any_state_inbound_lane(lane_id) {
					lane.purge();
				}
				if let Ok(lane) = lanes_manager.any_state_outbound_lane(lane_id) {
					lane.purge();
				}
			}
			assert_ok!(XcmOverBridge::do_try_state());
		};

		run_test(|| {
			// ok state
			test_bridge_state(
				bridge_id,
				Bridge {
					bridge_origin_relative_location: Box::new(VersionedLocation::from(
						bridge_origin_relative_location.clone(),
					)),
					bridge_origin_universal_location: Box::new(VersionedInteriorLocation::from(
						bridge_origin_universal_location.clone(),
					)),
					bridge_destination_universal_location: Box::new(
						VersionedInteriorLocation::from(
							bridge_destination_universal_location.clone(),
						),
					),
					state: BridgeState::Opened,
					bridge_owner_account: bridge_owner_account.clone(),
					deposit: Zero::zero(),
					lane_id,
				},
				(lane_id, bridge_id),
				(lane_id, lane_id),
				None,
			);
			cleanup(bridge_id, vec![lane_id]);

			// error - missing `LaneToBridge` mapping
			test_bridge_state(
				bridge_id,
				Bridge {
					bridge_origin_relative_location: Box::new(VersionedLocation::from(
						bridge_origin_relative_location.clone(),
					)),
					bridge_origin_universal_location: Box::new(VersionedInteriorLocation::from(
						bridge_origin_universal_location.clone(),
					)),
					bridge_destination_universal_location: Box::new(
						VersionedInteriorLocation::from(
							bridge_destination_universal_location.clone(),
						),
					),
					state: BridgeState::Opened,
					bridge_owner_account: bridge_owner_account.clone(),
					deposit: Zero::zero(),
					lane_id,
				},
				(lane_id, bridge_id_mismatch),
				(lane_id, lane_id),
				Some(TryRuntimeError::Other(
					"Found `LaneToBridge` inconsistency for bridge_id - missing mapping!",
				)),
			);
			cleanup(bridge_id, vec![lane_id]);

			// error bridge owner account cannot be calculated
			test_bridge_state(
				bridge_id,
				Bridge {
					bridge_origin_relative_location: Box::new(VersionedLocation::from(
						bridge_origin_relative_location.clone(),
					)),
					bridge_origin_universal_location: Box::new(VersionedInteriorLocation::from(
						bridge_origin_universal_location.clone(),
					)),
					bridge_destination_universal_location: Box::new(VersionedInteriorLocation::from(
						bridge_destination_universal_location.clone(),
					)),
					state: BridgeState::Opened,
					bridge_owner_account: bridge_owner_account_mismatch.clone(),
					deposit: Zero::zero(),
					lane_id,
				},
				(lane_id, bridge_id),
				(lane_id, lane_id),
				Some(TryRuntimeError::Other("`bridge.bridge_owner_account` is different than calculated from `bridge.bridge_origin_relative_location`, needs migration!")),
			);
			cleanup(bridge_id, vec![lane_id]);

			// error when (bridge_origin_universal_location + bridge_destination_universal_location)
			// produces different `BridgeId`
			test_bridge_state(
				bridge_id_mismatch,
				Bridge {
					bridge_origin_relative_location: Box::new(VersionedLocation::from(
						bridge_origin_relative_location.clone(),
					)),
					bridge_origin_universal_location: Box::new(VersionedInteriorLocation::from(
						bridge_origin_universal_location.clone(),
					)),
					bridge_destination_universal_location: Box::new(VersionedInteriorLocation::from(
						bridge_destination_universal_location.clone(),
					)),
					state: BridgeState::Opened,
					bridge_owner_account: bridge_owner_account_mismatch.clone(),
					deposit: Zero::zero(),
					lane_id,
				},
				(lane_id, bridge_id_mismatch),
				(lane_id, lane_id),
				Some(TryRuntimeError::Other("`bridge_id` is different than calculated from `bridge_origin_universal_location_as_latest` and `bridge_destination_universal_location_as_latest`, needs migration!")),
			);
			cleanup(bridge_id_mismatch, vec![lane_id]);

			// missing inbound lane for a bridge
			test_bridge_state(
				bridge_id,
				Bridge {
					bridge_origin_relative_location: Box::new(VersionedLocation::from(
						bridge_origin_relative_location.clone(),
					)),
					bridge_origin_universal_location: Box::new(VersionedInteriorLocation::from(
						bridge_origin_universal_location.clone(),
					)),
					bridge_destination_universal_location: Box::new(
						VersionedInteriorLocation::from(
							bridge_destination_universal_location.clone(),
						),
					),
					state: BridgeState::Opened,
					bridge_owner_account: bridge_owner_account.clone(),
					deposit: Zero::zero(),
					lane_id,
				},
				(lane_id, bridge_id),
				(lane_id_mismatch, lane_id),
				Some(TryRuntimeError::Other("Inbound lane not found!")),
			);
			cleanup(bridge_id, vec![lane_id, lane_id_mismatch]);

			// missing outbound lane for a bridge
			test_bridge_state(
				bridge_id,
				Bridge {
					bridge_origin_relative_location: Box::new(VersionedLocation::from(
						bridge_origin_relative_location.clone(),
					)),
					bridge_origin_universal_location: Box::new(VersionedInteriorLocation::from(
						bridge_origin_universal_location.clone(),
					)),
					bridge_destination_universal_location: Box::new(
						VersionedInteriorLocation::from(
							bridge_destination_universal_location.clone(),
						),
					),
					state: BridgeState::Opened,
					bridge_owner_account: bridge_owner_account.clone(),
					deposit: Zero::zero(),
					lane_id,
				},
				(lane_id, bridge_id),
				(lane_id, lane_id_mismatch),
				Some(TryRuntimeError::Other("Outbound lane not found!")),
			);
			cleanup(bridge_id, vec![lane_id, lane_id_mismatch]);

			// missing bridge for inbound lane
			let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
			assert!(lanes_manager.create_inbound_lane(lane_id).is_ok());
			assert_err!(XcmOverBridge::do_try_state(), TryRuntimeError::Other("Found `LaneToBridge` inconsistency for `InboundLanes`'s lane_id - missing mapping!"));
			cleanup(bridge_id, vec![lane_id]);

			// missing bridge for outbound lane
			let lanes_manager = LanesManagerOf::<TestRuntime, ()>::new();
			assert!(lanes_manager.create_outbound_lane(lane_id).is_ok());
			assert_err!(XcmOverBridge::do_try_state(), TryRuntimeError::Other("Found `LaneToBridge` inconsistency for `OutboundLanes`'s lane_id - missing mapping!"));
			cleanup(bridge_id, vec![lane_id]);
		});
	}

	#[test]
	fn ensure_encoding_compatibility() {
		use codec::Encode;

		let bridge_destination_universal_location = BridgedUniversalDestination::get();
		let may_prune_messages = 13;

		assert_eq!(
			bp_xcm_bridge_hub::XcmBridgeHubCall::open_bridge {
				bridge_destination_universal_location: Box::new(
					bridge_destination_universal_location.clone().into()
				)
			}
			.encode(),
			Call::<TestRuntime, ()>::open_bridge {
				bridge_destination_universal_location: Box::new(
					bridge_destination_universal_location.clone().into()
				)
			}
			.encode()
		);
		assert_eq!(
			bp_xcm_bridge_hub::XcmBridgeHubCall::close_bridge {
				bridge_destination_universal_location: Box::new(
					bridge_destination_universal_location.clone().into()
				),
				may_prune_messages,
			}
			.encode(),
			Call::<TestRuntime, ()>::close_bridge {
				bridge_destination_universal_location: Box::new(
					bridge_destination_universal_location.clone().into()
				),
				may_prune_messages,
			}
			.encode()
		);
	}
}