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

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

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

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

            
17
use {
18
    super::{
19
        currency::MICROUNIT,
20
        precompiles::FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX,
21
        weights::{self, xcm::XcmWeight as XcmGenericWeights},
22
        AccountId, AllPalletsWithSystem, AssetRate, Balance, Balances, ForeignAssetsCreator,
23
        MaintenanceMode, MessageQueue, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime,
24
        RuntimeBlockWeights, RuntimeCall, RuntimeEvent, RuntimeOrigin, TransactionByteFee,
25
        WeightToFee, XcmpQueue,
26
    },
27
    ccp_xcm::SignedToAccountKey20,
28
    cumulus_primitives_core::{AggregateMessageOrigin, ParaId},
29
    frame_support::{
30
        parameter_types,
31
        traits::{Everything, Nothing, PalletInfoAccess, TransformOrigin},
32
        weights::Weight,
33
    },
34
    frame_system::EnsureRoot,
35
    pallet_foreign_asset_creator::{
36
        AssetBalance, AssetId as AssetIdOf, ForeignAssetCreatedHook, ForeignAssetDestroyedHook,
37
    },
38
    pallet_xcm::XcmPassthrough,
39
    pallet_xcm_executor_utils::{
40
        filters::{IsReserveFilter, IsTeleportFilter},
41
        DefaultTrustPolicy,
42
    },
43
    parachains_common::{
44
        message_queue::{NarrowOriginToSibling, ParaIdToSibling},
45
        xcm_config::AssetFeeAsExistentialDepositMultiplier,
46
    },
47
    polkadot_runtime_common::xcm_sender::ExponentialPrice,
48
    sp_core::{ConstU32, H160},
49
    sp_runtime::Perbill,
50
    sp_std::vec::Vec,
51
    staging_xcm::latest::prelude::*,
52
    staging_xcm_builder::{
53
        AccountKey20Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
54
        AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, FungibleAdapter,
55
        IsConcrete, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
56
        SiblingParachainConvertsVia, SignedAccountKey20AsNative, SovereignSignedViaLocation,
57
        TakeWeightCredit, UsingComponents, WeightInfoBounds, WithComputedOrigin,
58
    },
59
    staging_xcm_executor::XcmExecutor,
60
    xcm_primitives::AccountIdAssetIdConversion,
61
};
62
parameter_types! {
63
    // Self Reserve location, defines the multilocation identifiying the self-reserve currency
64
    // This is used to match it also against our Balances pallet when we receive such
65
    // a Location: (Self Balances pallet index)
66
    // We use the RELATIVE multilocation
67
    pub SelfReserve: Location = Location {
68
        parents:0,
69
        interior: [
70
            PalletInstance(<Balances as PalletInfoAccess>::index() as u8)
71
        ].into()
72
    };
73

            
74
    // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate.
75
    pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
76

            
77
    // TODO: revisit
78
    pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
79

            
80
    // The relay chain Origin type
81
    pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
82

            
83
    pub const MaxAssetsIntoHolding: u32 = 64;
84

            
85
    /// Maximum number of instructions in a single XCM fragment. A sanity check against
86
    /// weight caculations getting too crazy.
87
    pub MaxInstructions: u32 = 100;
88

            
89
    // The universal location within the global consensus system
90
    pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into())].into();
91

            
92

            
93
    pub const BaseDeliveryFee: u128 = 100 * MICROUNIT;
94
}
95

            
96
#[cfg(feature = "runtime-benchmarks")]
97
parameter_types! {
98
    pub ReachableDest: Option<Location> = Some(Parent.into());
99
}
100

            
101
pub type XcmBarrier = (
102
    // Weight that is paid for may be consumed.
103
    TakeWeightCredit,
104
    // Expected responses are OK.
105
    AllowKnownQueryResponses<PolkadotXcm>,
106
    WithComputedOrigin<
107
        (
108
            // If the message is one that immediately attemps to pay for execution, then allow it.
109
            AllowTopLevelPaidExecutionFrom<Everything>,
110
            // Subscriptions for version tracking are OK.
111
            AllowSubscriptionsFrom<Everything>,
112
        ),
113
        UniversalLocation,
114
        ConstU32<8>,
115
    >,
116
);
117

            
118
// For benchmarking, we cannot use the describeFamily
119
// the benchmark is written to be able to convert an AccountId32, but describeFamily prevents this
120
#[cfg(not(feature = "runtime-benchmarks"))]
121
type Descriptor = staging_xcm_builder::DescribeFamily<staging_xcm_builder::DescribeAllTerminal>;
122
#[cfg(feature = "runtime-benchmarks")]
123
type Descriptor = staging_xcm_builder::DescribeAllTerminal;
124

            
125
/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
126
/// when determining ownership of accounts for asset transacting and when attempting to use XCM
127
/// `Transact` in order to determine the dispatch Origin.
128
pub type LocationToAccountId = (
129
    // The parent (Relay-chain) origin converts to the default `AccountId`.
130
    ParentIsPreset<AccountId>,
131
    // Sibling parachain origins convert to AccountId via the `ParaId::into`.
132
    SiblingParachainConvertsVia<polkadot_parachain_primitives::primitives::Sibling, AccountId>,
133
    // If we receive a Location of type AccountKey20, just generate a native account
134
    AccountKey20Aliases<RelayNetwork, AccountId>,
135
    // Generate remote accounts according to polkadot standards
136
    staging_xcm_builder::HashedDescription<AccountId, Descriptor>,
137
);
138

            
139
/// Local origins on this chain are allowed to dispatch XCM sends/executions.
140
pub type LocalOriginToLocation = SignedToAccountKey20<RuntimeOrigin, AccountId, RelayNetwork>;
141

            
142
/// Means for transacting the native currency on this chain.
143
pub type CurrencyTransactor = FungibleAdapter<
144
    // Use this currency:
145
    Balances,
146
    // Use this currency when it is a fungible asset matching the given location or name:
147
    IsConcrete<SelfReserve>,
148
    // Convert an XCM Location into a local account id:
149
    LocationToAccountId,
150
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
151
    AccountId,
152
    // We don't track any teleports of `Balances`.
153
    (),
154
>;
155

            
156
/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
157
/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
158
/// biases the kind of local `Origin` it will become.
159
pub type XcmOriginToTransactDispatchOrigin = (
160
    // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
161
    // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
162
    // foreign chains who want to have a local sovereign account on this chain which they control.
163
    SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
164
    // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
165
    // recognised.
166
    RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
167
    // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
168
    // recognised.
169
    SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
170
    // Native signed account converter; this just converts an `AccountId32` origin into a normal
171
    // `RuntimeOrigin::Signed` origin of the same 32-byte value.
172
    SignedAccountKey20AsNative<RelayNetwork, RuntimeOrigin>,
173
    // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
174
    XcmPassthrough<RuntimeOrigin>,
175
);
176

            
177
/// Means for transacting assets on this chain.
178
pub type AssetTransactors = (CurrencyTransactor, ForeignFungiblesTransactor);
179
pub type XcmWeigher =
180
    WeightInfoBounds<XcmGenericWeights<RuntimeCall>, RuntimeCall, MaxInstructions>;
181

            
182
/// The means for routing XCM messages which are not for local execution into the right message
183
/// queues.
184
pub type XcmRouter = (
185
    // Two routers - use UMP to communicate with the relay chain:
186
    cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
187
    // ..and XCMP to communicate with the sibling chains.
188
    XcmpQueue,
189
);
190

            
191
pub struct XcmConfig;
192
impl staging_xcm_executor::Config for XcmConfig {
193
    type RuntimeCall = RuntimeCall;
194
    type XcmSender = XcmRouter;
195
    type AssetTransactor = AssetTransactors;
196
    type OriginConverter = XcmOriginToTransactDispatchOrigin;
197
    type IsReserve = IsReserveFilter<Runtime>;
198
    type IsTeleporter = IsTeleportFilter<Runtime>;
199
    type UniversalLocation = UniversalLocation;
200
    type Barrier = XcmBarrier;
201
    type Weigher = XcmWeigher;
202
    type Trader = (
203
        UsingComponents<WeightToFee, SelfReserve, AccountId, Balances, ()>,
204
        cumulus_primitives_utility::TakeFirstAssetTrader<
205
            AccountId,
206
            AssetRateAsMultiplier,
207
            // Use this currency when it is a fungible asset matching the given location or name:
208
            (ConvertedConcreteId<AssetId, Balance, ForeignAssetsCreator, JustTry>,),
209
            ForeignAssets,
210
            (),
211
        >,
212
    );
213
    type ResponseHandler = PolkadotXcm;
214
    type AssetTrap = PolkadotXcm;
215
    type AssetClaims = PolkadotXcm;
216
    type SubscriptionService = PolkadotXcm;
217
    type PalletInstancesInfo = AllPalletsWithSystem;
218
    type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
219
    type AssetLocker = ();
220
    type AssetExchanger = ();
221
    type FeeManager = ();
222
    type MessageExporter = ();
223
    type UniversalAliases = Nothing;
224
    type CallDispatcher = RuntimeCall;
225
    type SafeCallFilter = Everything;
226
    type Aliasers = Nothing;
227
    type TransactionalProcessor = staging_xcm_builder::FrameTransactionalProcessor;
228
    type HrmpNewChannelOpenRequestHandler = ();
229
    type HrmpChannelAcceptedHandler = ();
230
    type HrmpChannelClosingHandler = ();
231
    type XcmRecorder = ();
232
}
233

            
234
impl pallet_xcm::Config for Runtime {
235
    type RuntimeEvent = RuntimeEvent;
236
    type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
237
    type XcmRouter = XcmRouter;
238
    type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
239
    type XcmExecuteFilter = Everything;
240
    type XcmExecutor = XcmExecutor<XcmConfig>;
241
    type XcmTeleportFilter = Nothing;
242
    type XcmReserveTransferFilter = Everything;
243
    type Weigher = XcmWeigher;
244
    type UniversalLocation = UniversalLocation;
245
    type RuntimeOrigin = RuntimeOrigin;
246
    type RuntimeCall = RuntimeCall;
247
    const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
248
    type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
249
    type Currency = Balances;
250
    type CurrencyMatcher = ();
251
    type TrustedLockers = ();
252
    type SovereignAccountOf = LocationToAccountId;
253
    type MaxLockers = ConstU32<8>;
254
    type MaxRemoteLockConsumers = ConstU32<0>;
255
    type RemoteLockConsumerIdentifier = ();
256
    // TODO pallet-xcm weights
257
    type WeightInfo = weights::pallet_xcm::SubstrateWeight<Runtime>;
258
    type AdminOrigin = EnsureRoot<AccountId>;
259
}
260

            
261
pub type PriceForSiblingParachainDelivery =
262
    ExponentialPrice<SelfReserve, BaseDeliveryFee, TransactionByteFee, XcmpQueue>;
263

            
264
pub type PriceForParentDelivery =
265
    ExponentialPrice<SelfReserve, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
266

            
267
impl cumulus_pallet_xcmp_queue::Config for Runtime {
268
    type RuntimeEvent = RuntimeEvent;
269
    type ChannelInfo = ParachainSystem;
270
    type VersionWrapper = PolkadotXcm;
271
    type ControllerOrigin = EnsureRoot<AccountId>;
272
    type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
273
    type WeightInfo = weights::cumulus_pallet_xcmp_queue::SubstrateWeight<Runtime>;
274
    type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
275
    type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
276
    type MaxInboundSuspended = sp_core::ConstU32<1_000>;
277
    type MaxActiveOutboundChannels = ConstU32<128>;
278
    type MaxPageSize = ConstU32<{ 103 * 1024 }>;
279
}
280

            
281
impl cumulus_pallet_xcm::Config for Runtime {
282
    type RuntimeEvent = RuntimeEvent;
283
    type XcmExecutor = XcmExecutor<XcmConfig>;
284
}
285

            
286
parameter_types! {
287
    pub MessageQueueServiceWeight: Weight = Perbill::from_percent(25) * RuntimeBlockWeights::get().max_block;
288
}
289

            
290
impl pallet_message_queue::Config for Runtime {
291
    type RuntimeEvent = RuntimeEvent;
292
    type WeightInfo = weights::pallet_message_queue::SubstrateWeight<Self>;
293
    #[cfg(feature = "runtime-benchmarks")]
294
    type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor<
295
        cumulus_primitives_core::AggregateMessageOrigin,
296
    >;
297
    #[cfg(not(feature = "runtime-benchmarks"))]
298
    type MessageProcessor = staging_xcm_builder::ProcessXcmMessage<
299
        AggregateMessageOrigin,
300
        XcmExecutor<XcmConfig>,
301
        RuntimeCall,
302
    >;
303
    type Size = u32;
304
    // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
305
    type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
306
    // NarrowOriginToSibling calls XcmpQueue's is_pause if Origin is sibling. Allows all other origins
307
    type QueuePausedQuery = (MaintenanceMode, NarrowOriginToSibling<XcmpQueue>);
308
    // TODO verify values
309
    type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>;
310
    type MaxStale = sp_core::ConstU32<8>;
311
    type ServiceWeight = MessageQueueServiceWeight;
312
    type IdleMaxServiceWeight = MessageQueueServiceWeight;
313
}
314

            
315
parameter_types! {
316
    // we just reuse the same deposits
317
    pub const ForeignAssetsAssetDeposit: Balance = 0;
318
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
319
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
320
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
321
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
322
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
323
    pub CheckingAccount: AccountId = PolkadotXcm::check_account();
324
}
325

            
326
#[cfg(feature = "runtime-benchmarks")]
327
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
328
pub struct ForeignAssetBenchmarkHelper;
329
#[cfg(feature = "runtime-benchmarks")]
330
impl pallet_assets::BenchmarkHelper<AssetId> for ForeignAssetBenchmarkHelper {
331
    fn create_asset_id_parameter(id: u32) -> AssetId {
332
        id.try_into()
333
            .expect("number too large to create benchmarks")
334
    }
335
}
336
#[cfg(feature = "runtime-benchmarks")]
337
impl pallet_asset_rate::AssetKindFactory<AssetId> for ForeignAssetBenchmarkHelper {
338
    fn create_asset_kind(id: u32) -> AssetId {
339
        id.try_into()
340
            .expect("number too large to create benchmarks")
341
    }
342
}
343

            
344
// Instruct how to go from an H160 to an AssetID
345
// We just take the lowest 2 bytes
346
impl AccountIdAssetIdConversion<AccountId, AssetId> for Runtime {
347
    /// The way to convert an account to assetId is by ensuring that the prefix is [0xFF, 18]
348
    /// and by taking the lowest 2 bytes as the assetId
349
    fn account_to_asset_id(account: AccountId) -> Option<(Vec<u8>, AssetId)> {
350
        let h160_account: H160 = account.into();
351
        let mut data = [0u8; 2];
352
        let (prefix_part, id_part) = h160_account.as_fixed_bytes().split_at(18);
353
        if prefix_part == FOREIGN_ASSET_PRECOMPILE_ADDRESS_PREFIX {
354
            data.copy_from_slice(id_part);
355
            let asset_id: AssetId = u16::from_be_bytes(data);
356
            Some((prefix_part.to_vec(), asset_id))
357
        } else {
358
            None
359
        }
360
    }
361

            
362
    // The opposite conversion
363
11
    fn asset_id_to_account(prefix: &[u8], asset_id: AssetId) -> AccountId {
364
11
        let mut data = [0u8; 20];
365
11
        data[0..18].copy_from_slice(prefix);
366
11
        data[18..20].copy_from_slice(&asset_id.to_be_bytes());
367
11
        AccountId::from(data)
368
11
    }
369
}
370

            
371
pub type AssetId = u16;
372
pub type ForeignAssetsInstance = pallet_assets::Instance1;
373
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
374
    type RuntimeEvent = RuntimeEvent;
375
    type Balance = Balance;
376
    type AssetId = AssetId;
377
    type AssetIdParameter = AssetId;
378
    type Currency = Balances;
379
    type CreateOrigin = frame_support::traits::NeverEnsureOrigin<AccountId>;
380
    type ForceOrigin = EnsureRoot<AccountId>;
381
    type AssetDeposit = ForeignAssetsAssetDeposit;
382
    type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
383
    type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
384
    type ApprovalDeposit = ForeignAssetsApprovalDeposit;
385
    type StringLimit = ForeignAssetsAssetsStringLimit;
386
    type Freezer = ();
387
    type Extra = ();
388
    type WeightInfo = weights::pallet_assets::SubstrateWeight<Runtime>;
389
    type CallbackHandle = ();
390
    type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
391
    type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
392
    #[cfg(feature = "runtime-benchmarks")]
393
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
394
}
395

            
396
pub struct RevertCodePrecompileHook;
397

            
398
impl ForeignAssetCreatedHook<Location, AssetIdOf<Runtime>, AssetBalance<Runtime>>
399
    for RevertCodePrecompileHook
400
{
401
6
    fn on_asset_created(
402
6
        _foreign_asset: &Location,
403
6
        asset_id: &AssetIdOf<Runtime>,
404
6
        _min_balance: &AssetBalance<Runtime>,
405
6
    ) {
406
6
        let revert_bytecode = [0x60, 0x00, 0x60, 0x00, 0xFD].to_vec();
407
6
        let prefix_slice = [255u8; 18];
408
6
        let account_id = Runtime::asset_id_to_account(prefix_slice.as_slice(), *asset_id);
409
6

            
410
6
        let _ = pallet_evm::Pallet::<Runtime>::create_account(
411
6
            account_id.into(),
412
6
            revert_bytecode.clone(),
413
6
            None,
414
6
        );
415
6
    }
416
}
417

            
418
impl ForeignAssetDestroyedHook<Location, AssetIdOf<Runtime>> for RevertCodePrecompileHook {
419
    fn on_asset_destroyed(_foreign_asset: &Location, asset_id: &AssetIdOf<Runtime>) {
420
        let prefix_slice = [255u8; 18];
421
        let account_id = Runtime::asset_id_to_account(prefix_slice.as_slice(), *asset_id);
422

            
423
        pallet_evm::Pallet::<Runtime>::remove_account(&account_id.into());
424
    }
425
}
426

            
427
impl pallet_foreign_asset_creator::Config for Runtime {
428
    type RuntimeEvent = RuntimeEvent;
429
    type ForeignAsset = Location;
430
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
431
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
432
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
433
    type Fungibles = ForeignAssets;
434
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
435
    type OnForeignAssetCreated = RevertCodePrecompileHook;
436
    type OnForeignAssetDestroyed = RevertCodePrecompileHook;
437
}
438

            
439
impl pallet_asset_rate::Config for Runtime {
440
    type CreateOrigin = EnsureRoot<AccountId>;
441
    type RemoveOrigin = EnsureRoot<AccountId>;
442
    type UpdateOrigin = EnsureRoot<AccountId>;
443
    type Currency = Balances;
444
    type AssetKind = AssetId;
445
    type RuntimeEvent = RuntimeEvent;
446
    type WeightInfo = weights::pallet_asset_rate::SubstrateWeight<Runtime>;
447
    #[cfg(feature = "runtime-benchmarks")]
448
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
449
}
450

            
451
parameter_types! {
452
    pub const TrustPolicyMaxAssets: u32 = 1000;
453
    pub const AllNativeTrustPolicy: DefaultTrustPolicy = DefaultTrustPolicy::AllNative;
454
    pub const AllNeverTrustPolicy: DefaultTrustPolicy = DefaultTrustPolicy::Never;
455
}
456
impl pallet_xcm_executor_utils::Config for Runtime {
457
    type RuntimeEvent = RuntimeEvent;
458
    type TrustPolicyMaxAssets = TrustPolicyMaxAssets;
459
    type ReserveDefaultTrustPolicy = AllNativeTrustPolicy;
460
    type SetReserveTrustOrigin = EnsureRoot<AccountId>;
461
    type TeleportDefaultTrustPolicy = AllNeverTrustPolicy;
462
    type SetTeleportTrustOrigin = EnsureRoot<AccountId>;
463
    type WeightInfo = weights::pallet_xcm_executor_utils::SubstrateWeight<Runtime>;
464
}
465

            
466
use {
467
    crate::ForeignAssets,
468
    staging_xcm_builder::{FungiblesAdapter, NoChecking},
469
    staging_xcm_executor::traits::JustTry,
470
};
471

            
472
/// Means for transacting foreign assets from different global consensus.
473
pub type ForeignFungiblesTransactor = FungiblesAdapter<
474
    // Use this fungibles implementation:
475
    ForeignAssets,
476
    // Use this currency when it is a fungible asset matching the given location or name:
477
    (ConvertedConcreteId<AssetId, Balance, ForeignAssetsCreator, JustTry>,),
478
    // Convert an XCM Location into a local account id:
479
    LocationToAccountId,
480
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
481
    AccountId,
482
    // We dont need to check teleports here.
483
    NoChecking,
484
    // The account to use for tracking teleports.
485
    CheckingAccount,
486
>;
487

            
488
/// Multiplier used for dedicated `TakeFirstAssetTrader` with `ForeignAssets` instance.
489
pub type AssetRateAsMultiplier =
490
    AssetFeeAsExistentialDepositMultiplier<Runtime, WeightToFee, AssetRate, ForeignAssetsInstance>;
491

            
492
#[test]
493
1
fn test_asset_id_to_account_conversion() {
494
1
    let prefix_slice = [255u8].repeat(18);
495
1
    let asset_ids_to_check = vec![0u16, 123u16, 3453u16, 10000u16, 65535u16];
496
6
    for current_asset_id in asset_ids_to_check {
497
5
        let account_id = Runtime::asset_id_to_account(prefix_slice.as_slice(), current_asset_id);
498
5
        assert_eq!(
499
5
            account_id.to_string().to_lowercase(),
500
5
            String::from("0xffffffffffffffffffffffffffffffffffff")
501
5
                + format!("{:04x}", current_asset_id).as_str()
502
5
        );
503
    }
504
1
}