This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
/
lib.rs
1656 lines (1490 loc) · 55.3 KB
/
lib.rs
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
// Copyright (C) 2023 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Bridge Transfer Pallet
//!
//! Module which could help with different transfers through bridges,
//! e.g. move assets between different global consensus...
//!
//! ## Overview
//!
//! Pallet supports configuration for two independent scenarios:
//!
//! ### Transfer out
//!
//! * see (Config for transfer out) in the code
//! * if you want to allow initiate bridge transfer from runtime,
//! actually pallet supports asset transfer and ping with dedicated extrinsics `transfer_asset_via_bridge` / `ping_via_bridge`
//! * e.g. for asset transfer with correct configuration it sends `ReserveAssetDeposited` over bridge,
//! you can configure bridge location and allowed target location with `AllowedExporters`
//!
//! ### Transfer in
//!
//! * see (Config for transfer in) in the code
//! * e.g. if you want to allow process xcm `UniversalOrigin` instruction,
//! you can configure "allowed universal aliases" here and then use it for `xcm_executor::Config`:
//! `type UniversalAliases = AllowedUniversalAliasesOf<Runtime>;`
//! * e.g. if you want to allow process xcm `ReserveAssetDeposited` instruction,
//! you can configure "allowed reserve locations" here and then use it for `xcm_executor::Config`:
//! ```nocompile
//! type IsReserve = IsAllowedReserveOf<
//! Runtime,
//! IsDifferentGlobalConsensusConcreteAsset<UniversalLocationNetworkId>,
//! >;
//! ```
//!
//! Transfer in/out are independent so you can configure just to receive or just to send part.
//! All configuration is done by dedicated extrinsics under `AdminOrigin` so for example runtime can allow to change this configuration just by governance.
// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{transactional, BoundedBTreeSet};
use scale_info::TypeInfo;
use sp_runtime::RuntimeDebug;
use sp_std::boxed::Box;
pub use pallet::*;
use xcm::prelude::*;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub mod impls;
pub mod weights;
/// The log target of this pallet.
pub const LOG_TARGET: &str = "runtime::bridge-transfer";
#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]
pub struct BridgeConfig {
/// Contains location, which is able to bridge XCM messages to bridged network
pub bridge_location: MultiLocation,
/// Fee which could be needed to pay in `bridge_location`
/// `MultiAsset` is here from the point of view of `bridge_location`, e.g.: `MultiLocation::parent()` means relay chain token of `bridge_location`
pub bridge_location_fee: Option<MultiAsset>,
/// Contains target destination on bridged network. E.g.: MultiLocation of Statemine/t on different consensus
// TODO:check-parameter - lets start with 1..1, maybe later we could extend this with BoundedVec
// TODO: bridged bridge-hub should have router for this
pub allowed_target_location: MultiLocation,
// TODO:check-parameter - can we store Option<Weight> and then aviod using `Unlimited`?
/// If `None` then `UnpaidExecution` is used, else `Withdraw(target_location_fee)/BuyExecution(target_location_fee, Unlimited)`
/// `MultiAsset` is here from the point of view of `allowed_target_location`, e.g.: `MultiLocation::parent()` means relay chain token of `allowed_target_location`
pub max_target_location_fee: Option<MultiAsset>,
}
/// Trait for constructing ping message.
pub trait PingMessageBuilder {
fn try_build(
local_origin: &MultiLocation,
network: &NetworkId,
remote_destination: &MultiLocation,
) -> Option<Xcm<()>>;
}
impl PingMessageBuilder for () {
fn try_build(_: &MultiLocation, _: &NetworkId, _: &MultiLocation) -> Option<Xcm<()>> {
None
}
}
/// Builder creates xcm message just with `Trap` instruction.
pub struct UnpaidTrapMessageBuilder<TrapCode>(sp_std::marker::PhantomData<TrapCode>);
impl<TrapCode: frame_support::traits::Get<u64>> PingMessageBuilder
for UnpaidTrapMessageBuilder<TrapCode>
{
fn try_build(_: &MultiLocation, _: &NetworkId, _: &MultiLocation) -> Option<Xcm<()>> {
Some(Xcm(sp_std::vec![Trap(TrapCode::get())]))
}
}
#[frame_support::pallet]
pub mod pallet {
pub use crate::weights::WeightInfo;
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::{pallet_prelude::*, unique};
use xcm_executor::traits::TransactAsset;
#[pallet::pallet]
pub struct Pallet<T>(_);
/// Everything we need to run benchmarks.
#[cfg(feature = "runtime-benchmarks")]
pub trait BenchmarkHelper<RuntimeOrigin> {
/// Returns proper bridge configuration, supported by the runtime.
///
/// We expect that the XCM environment (`BridgeXcmSender`) has everything enabled
/// to support transfer to this destination **after** `prepare_asset_transfer` call.
fn bridge_config() -> Option<(NetworkId, BridgeConfig)> {
None
}
/// Prepare environment for assets transfer and return transfer origin and assets
/// to transfer. After this function is called, we expect `transfer_asset_via_bridge`
/// to succeed, so in proper environment, it should:
///
/// - deposit enough funds (fee from `bridge_config()` and transferred assets) to the sender account;
///
/// - ensure that the `BridgeXcmSender` is properly configured for the transfer;
///
/// - be close to the worst possible scenario - i.e. if some account may need to be created during
/// the assets transfer, it should be created. If there are multiple bridges, the "worst possible"
/// (in terms of performance) bridge must be selected for the transfer.
fn prepare_asset_transfer(
) -> Option<(RuntimeOrigin, VersionedMultiAssets, VersionedMultiLocation)> {
None
}
/// Prepare environment for ping transfer and return transfer origin and assets
/// to transfer. After this function is called, we expect `ping_via_bridge`
/// to succeed, so in proper environment, it should:
///
/// - deposit enough funds (fee from `bridge_config()`) to the sender account;
///
/// - ensure that the `BridgeXcmSender` is properly configured for the transfer;
///
/// - be close to the worst possible scenario - i.e. if some account may need to be created during
/// it should be created. If there are multiple bridges, the "worst possible"
/// (in terms of performance) bridge must be selected for the transfer.
fn prepare_ping_transfer() -> Option<(RuntimeOrigin, VersionedMultiLocation)> {
None
}
fn universal_alias() -> Option<(VersionedMultiLocation, Junction)> {
None
}
fn reserve_location() -> Option<VersionedMultiLocation> {
None
}
}
#[pallet::config]
pub trait Config: frame_system::Config {
/// The overarching event type.
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Runtime's universal location
type UniversalLocation: Get<InteriorMultiLocation>;
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
/// The configurable origin to allow bridges configuration management
type AdminOrigin: EnsureOrigin<Self::RuntimeOrigin>;
/// Max allowed universal aliases per one `MultiLocation`
/// (Config for transfer in)
type UniversalAliasesLimit: Get<u32>;
/// Max allowed reserve locations
/// (Config for transfer in)
type ReserveLocationsLimit: Get<u32>;
/// How to withdraw and deposit an asset for reserve.
/// (Config for transfer out)
type AssetTransactor: TransactAsset;
/// XCM sender which sends messages to the BridgeHub
/// (Config for transfer out)
type BridgeXcmSender: SendXcm;
/// Required origin for asset transfer. If successful, it resolves to `MultiLocation`.
/// (Config for transfer out)
type TransferAssetOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = MultiLocation>;
/// Max count of assets in one call
/// (Config for transfer out)
type MaxAssetsLimit: Get<u8>;
/// Required origin for ping transfer. If successful, it resolves to `MultiLocation`.
/// (Config for transfer out)
type TransferPingOrigin: EnsureOrigin<Self::RuntimeOrigin, Success = MultiLocation>;
/// Configurable ping message, `None` means no message will be transferred.
/// (Config for transfer out)
type PingMessageBuilder: PingMessageBuilder;
/// Benchmarks helper.
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper: BenchmarkHelper<Self::RuntimeOrigin>;
}
/// Details of configured bridges which are allowed for **transfer out**.
/// (Config for transfer out)
#[pallet::storage]
#[pallet::getter(fn allowed_exporters)]
pub(super) type AllowedExporters<T: Config> =
StorageMap<_, Blake2_128Concat, NetworkId, BridgeConfig>;
/// Holds allowed mappings `MultiLocation->Junction` for `UniversalAliases`
/// E.g:
/// BridgeHubMultiLocation1 -> NetworkId::Kusama
/// BridgeHubMultiLocation1 -> NetworkId::Polkadot
/// (Config for transfer in)
#[pallet::storage]
#[pallet::getter(fn allowed_universal_aliases)]
pub(super) type AllowedUniversalAliases<T: Config> = StorageMap<
_,
Blake2_128Concat,
MultiLocation,
BoundedBTreeSet<Junction, T::UniversalAliasesLimit>,
ValueQuery,
>;
/// Holds allowed mappings `MultiLocation` as trusted reserve locations
/// (Config for transfer in)
#[pallet::storage]
#[pallet::getter(fn allowed_reserve_locations)]
pub(super) type AllowedReserveLocations<T: Config> =
StorageValue<_, BoundedBTreeSet<MultiLocation, T::ReserveLocationsLimit>, ValueQuery>;
#[pallet::error]
#[cfg_attr(test, derive(PartialEq))]
pub enum Error<T> {
InvalidConfiguration,
UnavailableConfiguration,
ConfigurationAlreadyExists,
InvalidAssets,
MaxAssetsLimitReached,
UnsupportedDestination,
UnsupportedXcmVersion,
InvalidRemoteDestination,
BridgeCallError,
FailedToReserve,
UnsupportedPing,
}
#[pallet::event]
#[pallet::generate_deposit(pub (super) fn deposit_event)]
pub enum Event<T: Config> {
/// Transfer was successfully entered to the system (does not mean already delivered)
TransferInitiated {
/// `XcmHash` from `XcmContext` which is used for `AssetTransactor` processing and is related to the original message constructed here
message_id: XcmHash,
/// `XcmHash` from `SendXcm` (which is used for `ExportMessage` envelope)
forwarded_message_id: XcmHash,
/// `SendXcm` cost
sender_cost: MultiAssets,
},
/// Reserve asset passed
ReserveAssetsDeposited { from: MultiLocation, to: MultiLocation, assets: MultiAssets },
/// New bridge configuration was added
BridgeAdded,
/// Bridge configuration was removed
BridgeRemoved,
/// Bridge configuration was updated
BridgeUpdated,
/// New universal alias was added
UniversalAliasAdded,
/// New universal alias was removed
UniversalAliasRemoved,
/// New reserve location was added
ReserveLocationAdded,
/// New reserve location was removed
ReserveLocationRemoved,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Transfer asset via bridge to different global consensus
///
/// Parameters:
///
/// * `assets`:
/// * `destination`: Different consensus location, where the assets will be deposited, e.g. Polkadot's Statemint: `2, X2(GlobalConsensus(NetworkId::Polkadot), Parachain(1000))`
#[pallet::call_index(0)]
#[pallet::weight(T::WeightInfo::transfer_asset_via_bridge())]
pub fn transfer_asset_via_bridge(
origin: OriginFor<T>,
assets: Box<VersionedMultiAssets>,
destination: Box<VersionedMultiLocation>,
) -> DispatchResult {
// Check origin
let origin_location = T::TransferAssetOrigin::ensure_origin(origin)?;
// Check remote destination + bridge_config
let (_, bridge_config, remote_destination) =
Self::ensure_remote_destination(*destination)?;
// Check assets (lets leave others checks on `AssetTransactor`)
let assets: MultiAssets =
(*assets).try_into().map_err(|()| Error::<T>::InvalidAssets)?;
ensure!(
assets.len() <= T::MaxAssetsLimit::get() as usize,
Error::<T>::MaxAssetsLimitReached
);
// Do this in transaction (explicitly), the rollback should occur in case of any error and no assets will be trapped or lost
Self::do_reserve_and_send_in_transaction(
origin_location,
remote_destination,
assets,
bridge_config,
)
}
/// Transfer `ping` via bridge to different global consensus.
///
/// - can be used for testing purposes that bridge transfer is working and configured for `destination`
///
/// Parameters:
///
/// * `destination`: Different consensus location, e.g. Polkadot's Statemint: `2, X2(GlobalConsensus(NetworkId::Polkadot), Parachain(1000))`
#[pallet::call_index(4)]
#[pallet::weight(T::WeightInfo::ping_via_bridge())]
pub fn ping_via_bridge(
origin: OriginFor<T>,
destination: Box<VersionedMultiLocation>,
) -> DispatchResult {
let origin_location = T::TransferPingOrigin::ensure_origin(origin)?;
// Check remote destination + bridge_config
let (network, bridge_config, remote_destination) =
Self::ensure_remote_destination(*destination)?;
// Check reserve account - sovereign account of bridge
let allowed_target_location = bridge_config.allowed_target_location;
// Prepare `ping` message
let xcm: Xcm<()> =
T::PingMessageBuilder::try_build(&origin_location, &network, &remote_destination)
.ok_or(Error::<T>::UnsupportedPing)?;
// Initiate bridge transfer
Self::initiate_bridge_transfer(allowed_target_location, unique(&xcm), xcm)
.map_err(Into::into)
}
/// Adds new bridge configuration, which allows transfer to this `bridged_network`.
///
/// Parameters:
///
/// * `bridged_network`: Network where we want to allow transfer funds
/// * `bridge_config`: contains location for BridgeHub in our network + fee
#[pallet::call_index(1)]
#[pallet::weight(T::WeightInfo::add_exporter_config())]
pub fn add_exporter_config(
origin: OriginFor<T>,
bridged_network: NetworkId,
bridge_config: Box<BridgeConfig>,
) -> DispatchResult {
let _ = T::AdminOrigin::ensure_origin(origin)?;
ensure!(
!AllowedExporters::<T>::contains_key(bridged_network),
Error::<T>::ConfigurationAlreadyExists
);
let allowed_target_location_network = bridge_config
.allowed_target_location
.interior()
.global_consensus()
.map_err(|_| Error::<T>::InvalidConfiguration)?;
ensure!(
bridged_network == allowed_target_location_network,
Error::<T>::InvalidConfiguration
);
// bridged consensus must be different
let local_network = T::UniversalLocation::get()
.global_consensus()
.map_err(|_| Error::<T>::InvalidConfiguration)?;
ensure!(bridged_network != local_network, Error::<T>::InvalidConfiguration);
AllowedExporters::<T>::insert(bridged_network, bridge_config);
Self::deposit_event(Event::BridgeAdded);
Ok(())
}
/// Remove bridge configuration for specified `bridged_network`.
///
/// Parameters:
///
/// * `bridged_network`: Network where we want to remove
#[pallet::call_index(2)]
#[pallet::weight(T::WeightInfo::remove_exporter_config())]
pub fn remove_exporter_config(
origin: OriginFor<T>,
bridged_network: NetworkId,
) -> DispatchResult {
let _ = T::AdminOrigin::ensure_origin(origin)?;
ensure!(
AllowedExporters::<T>::contains_key(bridged_network),
Error::<T>::UnavailableConfiguration
);
AllowedExporters::<T>::remove(bridged_network);
Self::deposit_event(Event::BridgeRemoved);
Ok(())
}
/// Updates bridge configuration for specified `bridged_network`.
///
/// Parameters:
///
/// * `bridged_network`: Network where we want to remove
/// * `fee`: New fee to update
#[pallet::call_index(3)]
#[pallet::weight(T::WeightInfo::update_exporter_config())]
pub fn update_exporter_config(
origin: OriginFor<T>,
bridged_network: NetworkId,
bridge_location_fee: Option<Box<VersionedMultiAsset>>,
target_location_fee: Option<Box<VersionedMultiAsset>>,
) -> DispatchResult {
let _ = T::AdminOrigin::ensure_origin(origin)?;
AllowedExporters::<T>::try_mutate_exists(bridged_network, |maybe_bridge_config| {
let bridge_config =
maybe_bridge_config.as_mut().ok_or(Error::<T>::UnavailableConfiguration)?;
bridge_config.bridge_location_fee = bridge_location_fee
.map(|fee| MultiAsset::try_from(*fee))
.transpose()
.map_err(|_| Error::<T>::UnsupportedXcmVersion)?;
bridge_config.max_target_location_fee = target_location_fee
.map(|fee| MultiAsset::try_from(*fee))
.transpose()
.map_err(|_| Error::<T>::UnsupportedXcmVersion)?;
Self::deposit_event(Event::BridgeUpdated);
Ok(())
})
}
/// Add `(MultiLocation, Junction)` mapping to `AllowedUniversalAliases`
///
/// Parameters:
///
/// * `location`: key
/// * `junction`: value
#[pallet::call_index(5)]
#[pallet::weight(T::WeightInfo::add_universal_alias())]
pub fn add_universal_alias(
origin: OriginFor<T>,
location: Box<VersionedMultiLocation>,
junction: Junction,
) -> DispatchResult {
let _ = T::AdminOrigin::ensure_origin(origin)?;
let location: MultiLocation =
(*location).try_into().map_err(|_| Error::<T>::UnsupportedXcmVersion)?;
let added = AllowedUniversalAliases::<T>::try_mutate(location, |junctions| {
junctions.try_insert(junction)
})
.map_err(|_| Error::<T>::InvalidConfiguration)?;
if added {
Self::deposit_event(Event::UniversalAliasAdded);
}
Ok(())
}
/// Remove `(MultiLocation, Junction)` mapping from `AllowedUniversalAliases`
///
/// Parameters:
///
/// * `location`: key
/// * `junction`: value
#[pallet::call_index(6)]
#[pallet::weight(T::WeightInfo::remove_universal_alias())]
pub fn remove_universal_alias(
origin: OriginFor<T>,
location: Box<VersionedMultiLocation>,
junctions_to_remove: sp_std::prelude::Vec<Junction>,
) -> DispatchResult {
let _ = T::AdminOrigin::ensure_origin(origin)?;
let location: MultiLocation =
(*location).try_into().map_err(|_| Error::<T>::UnsupportedXcmVersion)?;
let removed = AllowedUniversalAliases::<T>::try_mutate(
location,
|junctions| -> Result<bool, Error<T>> {
let mut removed = false;
for jtr in junctions_to_remove {
removed |= junctions.remove(&jtr);
}
Ok(removed)
},
)?;
if removed {
Self::deposit_event(Event::UniversalAliasRemoved);
}
Ok(())
}
/// Add `MultiLocation` mapping to `AllowedReserveLocations`
///
/// Parameters:
///
/// * `location`: as reserve `MultiLocation`
#[pallet::call_index(7)]
#[pallet::weight(T::WeightInfo::add_reserve_location())]
pub fn add_reserve_location(
origin: OriginFor<T>,
location: Box<VersionedMultiLocation>,
) -> DispatchResult {
let _ = T::AdminOrigin::ensure_origin(origin)?;
let location: MultiLocation =
(*location).try_into().map_err(|_| Error::<T>::UnsupportedXcmVersion)?;
let added = AllowedReserveLocations::<T>::try_mutate(|locations| {
locations.try_insert(location)
})
.map_err(|_| Error::<T>::InvalidConfiguration)?;
if added {
Self::deposit_event(Event::ReserveLocationAdded);
}
Ok(())
}
/// Remove `MultiLocation` mapping from `AllowedReserveLocations`
///
/// Parameters:
///
/// * `location`: as reserve `MultiLocation`
#[pallet::call_index(8)]
#[pallet::weight(T::WeightInfo::remove_reserve_location())]
pub fn remove_reserve_location(
origin: OriginFor<T>,
locations_to_remove: sp_std::prelude::Vec<VersionedMultiLocation>,
) -> DispatchResult {
let _ = T::AdminOrigin::ensure_origin(origin)?;
let removed =
AllowedReserveLocations::<T>::try_mutate(|locations| -> Result<bool, Error<T>> {
let mut removed = false;
for ltr in locations_to_remove {
let ltr: MultiLocation =
ltr.try_into().map_err(|_| Error::<T>::UnsupportedXcmVersion)?;
removed |= locations.remove(<r);
}
Ok(removed)
})?;
if removed {
Self::deposit_event(Event::ReserveLocationRemoved);
}
Ok(())
}
}
impl<T: Config> Pallet<T> {
/// Validates destination and check if we support bridging to this remote global consensus
///
/// Returns: correct remote location, where we should be able to bridge
pub(crate) fn ensure_remote_destination(
remote_destination: VersionedMultiLocation,
) -> Result<(NetworkId, BridgeConfig, MultiLocation), Error<T>> {
match remote_destination {
VersionedMultiLocation::V3(remote_location) => {
ensure!(
remote_location.parent_count() == 2,
Error::<T>::UnsupportedDestination
);
let local_network = T::UniversalLocation::get()
.global_consensus()
.map_err(|_| Error::<T>::InvalidConfiguration)?;
let remote_network = remote_location
.interior()
.global_consensus()
.map_err(|_| Error::<T>::UnsupportedDestination)?;
ensure!(local_network != remote_network, Error::<T>::UnsupportedDestination);
match AllowedExporters::<T>::get(remote_network) {
Some(bridge_config) => {
ensure!(
// TODO:check-parameter - verify and prepare test for ETH scenario - https://github.com/paritytech/cumulus/pull/2013#discussion_r1094909290
remote_location.starts_with(&bridge_config.allowed_target_location),
Error::<T>::UnsupportedDestination
);
Ok((remote_network, bridge_config, remote_location))
},
None => return Err(Error::<T>::UnsupportedDestination),
}
},
_ => Err(Error::<T>::UnsupportedXcmVersion),
}
}
#[transactional]
fn do_reserve_and_send_in_transaction(
origin_location: MultiLocation,
remote_destination: MultiLocation,
assets: MultiAssets,
bridge_config: BridgeConfig,
) -> Result<(), DispatchError> {
// Resolve reserve account
let reserve_account =
Self::resolve_reserve_account(&bridge_config, &remote_destination);
// Resolve target destination
let target_destination = bridge_config.allowed_target_location;
// UniversalLocation as sovereign account location on target_location (as target_location sees UniversalLocation)
let universal_location_as_sovereign_account_on_target_location =
T::UniversalLocation::get()
.invert_target(&target_destination)
.map_err(|_| Error::<T>::InvalidConfiguration)?;
// Prepare some XcmContext
let xcm_context = XcmContext::with_message_id(unique(reserve_account));
// lets try to do a reserve for all assets
let mut reserved_assets = xcm_executor::Assets::new();
for asset in assets.into_inner() {
// TODO:check-parameter - verify this Joe's text
// Deposit assets into `AccountId` that corresponds to the bridge
// hub. In this way, Statemine acts as a reserve location to the
// bridge, such that it need not trust any consensus system from
// `./Parent/Parent/...`. (It may trust Polkadot, but would
// Polkadot trust Kusama with its DOT?)
// Move asset to reserve account
T::AssetTransactor::transfer_asset(
&asset,
&origin_location,
&reserve_account,
&xcm_context,
)
.and_then(|reserved_asset| {
Self::deposit_event(Event::ReserveAssetsDeposited {
from: origin_location,
to: reserve_account,
assets: reserved_asset.clone().into(),
});
reserved_assets.subsume_assets(reserved_asset);
Ok(())
})
.map_err(|e| {
log::error!(
target: LOG_TARGET,
"AssetTransactor failed to reserve assets from origin_location: {:?} to reserve_account: {:?} for assets: {:?}, error: {:?}",
origin_location,
reserve_account,
asset,
e
);
Error::<T>::FailedToReserve
})?;
}
// Prepare `ReserveAssetDeposited` msg to bridge to the other side.
// Reanchor stuff - we need to convert local asset id/MultiLocation to format that could be understood by different consensus and from their point-of-view
reserved_assets.reanchor(&target_destination, T::UniversalLocation::get(), None);
let remote_destination = remote_destination
.reanchored(&target_destination, T::UniversalLocation::get())
.map_err(|errored_dest| {
log::error!(
target: LOG_TARGET,
"Failed to reanchor remote_destination: {:?} for target_destination: {:?} and universal_location: {:?}",
errored_dest,
target_destination,
T::UniversalLocation::get()
);
Error::<T>::InvalidRemoteDestination
})?;
// prepare xcm message
// 1. buy execution (if needed) -> (we expect UniversalLocation's sovereign account should pay)
let (mut xcm_instructions, maybe_buy_execution) = match bridge_config
.max_target_location_fee
{
Some(target_location_fee) => (
sp_std::vec![
WithdrawAsset(target_location_fee.clone().into()),
BuyExecution { fees: target_location_fee.clone(), weight_limit: Unlimited },
],
Some(target_location_fee),
),
None => (
sp_std::vec![UnpaidExecution { check_origin: None, weight_limit: Unlimited }],
None,
),
};
// 2. add deposit reserved asset to destination account
xcm_instructions.extend(sp_std::vec![
ReserveAssetDeposited(reserved_assets.clone().into()),
DepositAsset {
assets: MultiAssetFilter::from(MultiAssets::from(reserved_assets)),
beneficiary: remote_destination
},
]);
// 3. add return unspent weight/asset back to the UniversalLocation's sovereign account on target
if let Some(target_location_fee) = maybe_buy_execution {
xcm_instructions.extend(sp_std::vec![
RefundSurplus,
DepositAsset {
assets: MultiAssetFilter::from(MultiAssets::from(target_location_fee)),
beneficiary: universal_location_as_sovereign_account_on_target_location
},
]);
}
Self::initiate_bridge_transfer(
target_destination,
xcm_context.message_id,
xcm_instructions.into(),
)
.map_err(Into::into)
}
fn initiate_bridge_transfer(
dest: MultiLocation,
message_id: XcmHash,
mut xcm: Xcm<()>,
) -> Result<(), Error<T>> {
// append message_id
xcm.0.extend(sp_std::vec![SetTopic(message_id.clone())]);
log::info!(
target: LOG_TARGET,
"[T::BridgeXcmSender] send to bridge, dest: {:?}, xcm: {:?}, message_id: {:?}",
dest,
xcm,
message_id,
);
// call bridge
// TODO: check-parameter - should we handle `sender_cost` somehow ?
let (forwarded_message_id, sender_cost) = send_xcm::<T::BridgeXcmSender>(dest, xcm)
.map_err(|e| {
log::error!(
target: LOG_TARGET,
"[T::BridgeXcmSender] SendError occurred, error: {:?}",
e
);
Error::<T>::BridgeCallError
})?;
// just fire event
Self::deposit_event(Event::TransferInitiated {
message_id,
forwarded_message_id,
sender_cost,
});
Ok(())
}
/// Resolve (sovereign) account which will be used as reserve account
fn resolve_reserve_account(
bridge_conig: &BridgeConfig,
_remote_destination: &MultiLocation,
) -> MultiLocation {
// lets start with target_location
bridge_conig.allowed_target_location.clone()
}
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate as bridge_transfer;
use frame_support::traits::{ConstU32, Contains, ContainsPair, Currency, Everything};
use crate::impls::{AllowedUniversalAliasesOf, IsAllowedReserveOf};
use frame_support::{
assert_noop, assert_ok, dispatch::DispatchError, parameter_types, sp_io, sp_tracing,
};
use frame_system::EnsureRoot;
use polkadot_parachain::primitives::Sibling;
use sp_runtime::{
testing::{Header, H256},
traits::{BlakeTwo256, IdentityLookup},
AccountId32, ModuleError,
};
use sp_version::RuntimeVersion;
use xcm_builder::{
AccountId32Aliases, CurrencyAdapter, EnsureXcmOrigin, ExporterFor, IsConcrete,
SiblingParachainConvertsVia, SignedToAccountId32, UnpaidRemoteExporter,
};
use xcm_executor::traits::Convert;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<TestRuntime>;
type Block = frame_system::mocking::MockBlock<TestRuntime>;
frame_support::construct_runtime!(
pub enum TestRuntime where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
BridgeTransfer: bridge_transfer::{Pallet, Call, Event<T>} = 52,
}
);
parameter_types! {
pub const BlockHashCount: u64 = 250;
pub Version: RuntimeVersion = RuntimeVersion {
spec_name: sp_version::create_runtime_str!("test"),
impl_name: sp_version::create_runtime_str!("system-test"),
authoring_version: 1,
spec_version: 1,
impl_version: 1,
apis: sp_version::create_apis_vec!([]),
transaction_version: 1,
state_version: 1,
};
}
pub type AccountId = AccountId32;
impl frame_system::Config for TestRuntime {
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount;
type BlockLength = ();
type BlockWeights = ();
type Version = Version;
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<u64>;
type OnNewAccount = ();
type OnKilledAccount = ();
type DbWeight = ();
type BaseCallFilter = frame_support::traits::Everything;
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
parameter_types! {
pub const ExistentialDeposit: u64 = 5;
pub const MaxReserves: u32 = 50;
}
impl pallet_balances::Config for TestRuntime {
type Balance = u64;
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type WeightInfo = ();
type MaxLocks = ();
type MaxReserves = MaxReserves;
type ReserveIdentifier = [u8; 8];
type HoldIdentifier = ();
type FreezeIdentifier = ();
type MaxHolds = ConstU32<0>;
type MaxFreezes = ConstU32<0>;
}
parameter_types! {
// UniversalLocation as statemine
pub const RelayNetwork: NetworkId = NetworkId::ByGenesis([9; 32]);
pub UniversalLocation: InteriorMultiLocation = X2(GlobalConsensus(RelayNetwork::get()), Parachain(1000));
// Test bridge cfg
pub TestBridgeTable: sp_std::prelude::Vec<(NetworkId, MultiLocation, Option<MultiAsset>)> = sp_std::vec![
(NetworkId::Wococo, (Parent, Parachain(1013)).into(), None),
(NetworkId::Polkadot, (Parent, Parachain(1002)).into(), None),
];
// Relay chain currency/balance location (e.g. KsmLocation, DotLocation, ..)
pub const RelayLocation: MultiLocation = MultiLocation::parent();
}
std::thread_local! {
static ROUTED_MESSAGE: std::cell::RefCell<Option<Xcm<()>>> = std::cell::RefCell::new(None);
}
pub struct ThreadLocalXcmRouter;
impl SendXcm for ThreadLocalXcmRouter {
type Ticket = Option<Xcm<()>>;
fn validate(
destination: &mut Option<MultiLocation>,
message: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
log::info!(
target: super::LOG_TARGET,
"[ThreadLocalXcmRouter]: destination: {:?}, message: {:?}",
destination,
message
);
Ok((message.take(), MultiAssets::default()))
}
fn deliver(ticket: Self::Ticket) -> Result<XcmHash, SendError> {
match ticket {
Some(msg) => {
ROUTED_MESSAGE.with(|rm| *rm.borrow_mut() = Some(msg));
Ok([0u8; 32])
},
None => Err(SendError::MissingArgument),
}
}
}
pub struct NotApplicableOrFailOnParachain2222XcmRouter;
impl SendXcm for NotApplicableOrFailOnParachain2222XcmRouter {
type Ticket = Option<Xcm<()>>;
fn validate(
destination: &mut Option<MultiLocation>,
message: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
log::info!(
target: super::LOG_TARGET,
"[NotApplicableOrFailOnParachain2222XcmRouter]: destination: {:?}, message: {:?}",
destination,
message
);
if matches!(
destination,
Some(MultiLocation { interior: X1(Parachain(2222)), parents: 1 })
) {
Err(SendError::Transport("Simulate what ever error"))
} else {
Err(SendError::NotApplicable)
}
}
fn deliver(ticket: Self::Ticket) -> Result<XcmHash, SendError> {
unimplemented!("We should not come here, ticket: {:?}", ticket)
}
}
pub type XcmRouter = (NotApplicableOrFailOnParachain2222XcmRouter, ThreadLocalXcmRouter);
/// Bridge router, which wraps and sends xcm to BridgeHub to be delivered to the different GlobalConsensus
pub type TestBridgeXcmSender =
UnpaidRemoteExporter<BridgeTransfer, XcmRouter, UniversalLocation>;
/// No local origins on this chain are allowed to dispatch XCM sends/executions.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
pub type LocationToAccountId = (
// Sibling parachain origins convert to AccountId via the `ParaId::into`.
SiblingParachainConvertsVia<Sibling, AccountId>,
// Straight up local `AccountId32` origins just alias directly to `AccountId`.
AccountId32Aliases<RelayNetwork, AccountId>,
);
/// Means for transacting the native currency on this chain.
pub type CurrencyTransactor = CurrencyAdapter<
// Use this currency:
Balances,
// Use this currency when it is a fungible asset matching the given location or name:
IsConcrete<RelayLocation>,
// Convert an XCM MultiLocation into a local account id:
LocationToAccountId,
// Our chain's account ID type (we can't get away without mentioning it explicitly):
AccountId,
// We don't track any teleports of `Balances`.
(),
>;
/// Bridge configuration we use in our tests.
fn test_bridge_config() -> (NetworkId, BridgeConfig) {
(
Wococo,
BridgeConfig {
bridge_location: (Parent, Parachain(1013)).into(),
bridge_location_fee: None,