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
    xcm::latest::prelude::*,
52
    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
    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 = xcm_builder::DescribeFamily<xcm_builder::DescribeAllTerminal>;
122
#[cfg(feature = "runtime-benchmarks")]
123
type Descriptor = 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
    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 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 = 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 =
299
        xcm_builder::ProcessXcmMessage<AggregateMessageOrigin, XcmExecutor<XcmConfig>, RuntimeCall>;
300
    type Size = u32;
301
    // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin:
302
    type QueueChangeHandler = NarrowOriginToSibling<XcmpQueue>;
303
    // NarrowOriginToSibling calls XcmpQueue's is_pause if Origin is sibling. Allows all other origins
304
    type QueuePausedQuery = (MaintenanceMode, NarrowOriginToSibling<XcmpQueue>);
305
    // TODO verify values
306
    type HeapSize = sp_core::ConstU32<{ 64 * 1024 }>;
307
    type MaxStale = sp_core::ConstU32<8>;
308
    type ServiceWeight = MessageQueueServiceWeight;
309
    type IdleMaxServiceWeight = MessageQueueServiceWeight;
310
}
311

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

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

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

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

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

            
393
pub struct RevertCodePrecompileHook;
394

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

            
407
33
        let _ = pallet_evm::Pallet::<Runtime>::create_account(
408
33
            account_id.into(),
409
33
            revert_bytecode.clone(),
410
33
            None,
411
33
        );
412
33
    }
413
}
414

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

            
420
        pallet_evm::Pallet::<Runtime>::remove_account(&account_id.into());
421
    }
422
}
423

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

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

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

            
463
use {
464
    crate::ForeignAssets,
465
    xcm_builder::{FungiblesAdapter, NoChecking},
466
    xcm_executor::traits::JustTry,
467
};
468

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

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

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