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
//! XCM configuration for Dancelight.
18

            
19
use {
20
    super::{
21
        parachains_origin,
22
        weights::{self, xcm::XcmWeight},
23
        AccountId, AllPalletsWithSystem, Balance, Balances, Dmp, Fellows, ForeignAssets,
24
        ForeignAssetsCreator, ParaId, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
25
        TransactionByteFee, Treasury, WeightToFee, XcmPallet,
26
    },
27
    crate::{governance::StakingAdmin, EthereumSystem},
28
    dancelight_runtime_constants::{
29
        currency::CENTS,
30
        snowbridge::{EthereumLocation, EthereumNetwork},
31
        system_parachain::*,
32
        DANCELIGHT_GENESIS_HASH,
33
    },
34
    frame_support::{
35
        parameter_types,
36
        traits::{Contains, Disabled, Equals, Everything, Nothing},
37
        weights::Weight,
38
    },
39
    frame_system::EnsureRoot,
40
    runtime_common::{
41
        xcm_sender::{ChildParachainRouter, ExponentialPrice},
42
        ToAuthor,
43
    },
44
    snowbridge_core::{AgentId, ChannelId},
45
    sp_core::ConstU32,
46
    sp_runtime::traits::TryConvertInto,
47
    tp_bridge::{
48
        container_token_to_ethereum_message_exporter::ContainerEthereumBlobExporter,
49
        snowbridge_outbound_token_transfer::{EthereumBlobExporter, SnowbrigeTokenTransferRouter},
50
        EthereumLocationsConverterFor,
51
    },
52
    tp_xcm_commons::{EthereumAssetReserve, NativeAssetReserve},
53
    xcm::{
54
        latest::prelude::{AssetId as XcmAssetId, *},
55
        opaque::latest::WESTEND_GENESIS_HASH,
56
    },
57
    xcm_builder::{
58
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
59
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
60
        ChildParachainConvertsVia, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily,
61
        FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter,
62
        HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, NoChecking,
63
        OriginToPluralityVoice, SendXcmFeeToAccount, SignedAccountId32AsNative,
64
        SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
65
        UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
66
        XcmFeeManagerFromComponents,
67
    },
68
    xcm_executor::XcmExecutor,
69
};
70

            
71
parameter_types! {
72
    pub TokenLocation: Location = Here.into_location();
73
    pub RootLocation: Location = Location::here();
74
    pub const ThisNetwork: NetworkId = NetworkId::ByGenesis(DANCELIGHT_GENESIS_HASH);
75
    pub UniversalLocation: InteriorLocation = ThisNetwork::get().into();
76
    pub CheckAccount: AccountId = XcmPallet::check_account();
77
    pub LocalCheckAccount: (AccountId, MintLocation) = (CheckAccount::get(), MintLocation::Local);
78
    pub TreasuryAccount: AccountId = Treasury::account_id();
79
}
80

            
81
#[cfg(feature = "runtime-benchmarks")]
82
parameter_types! {
83
    // Universal location for benchmarks that need to run through a para-id scenario
84
    pub UniversalLocationForParaIdBenchmarks: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(2000u32)].into();
85
}
86

            
87
pub type LocationConverter = (
88
    // We can convert a child parachain using the standard `AccountId` conversion.
89
    ChildParachainConvertsVia<ParaId, AccountId>,
90
    // We can directly alias an `AccountId32` into a local account.
91
    AccountId32Aliases<ThisNetwork, AccountId>,
92
    // Foreign locations alias into accounts according to a hash of their standard description.
93
    HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
94
    // Ethereum contract sovereign account.
95
    // (Used to convert ethereum contract locations to sovereign account)
96
    EthereumLocationsConverterFor<AccountId>,
97
);
98

            
99
/// Our asset transactor. This is what allows us to interest with the runtime facilities from the
100
/// point of view of XCM-only concepts like `Location` and `Asset`.
101
///
102
/// Ours is only aware of the Balances pallet, which is mapped to `StarLocation`.
103
pub type LocalAssetTransactor = FungibleAdapter<
104
    // Use this currency:
105
    Balances,
106
    // Use this currency when it is a fungible asset matching the given location or name:
107
    IsConcrete<TokenLocation>,
108
    // We can convert the Locations with our converter above:
109
    LocationConverter,
110
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
111
    AccountId,
112
    // We track our teleports in/out to keep total issuance correct.
113
    LocalCheckAccount,
114
>;
115

            
116
/// Means for transacting foreign assets from different global consensus.
117
pub type ForeignFungiblesTransactor = FungiblesAdapter<
118
    // Use this fungibles implementation:
119
    ForeignAssets,
120
    // Use this currency when it is a fungible asset matching the given location or name:
121
    (ConvertedConcreteId<AssetId, Balance, ForeignAssetsCreator, TryConvertInto>,),
122
    // Convert an XCM Location into a local account id:
123
    LocationConverter,
124
    // Our chain's account ID type (we can't get away without mentioning it explicitly):
125
    AccountId,
126
    // We dont need to check teleports here.
127
    NoChecking,
128
    // The account to use for tracking teleports.
129
    CheckingAccount,
130
>;
131

            
132
/// The means that we convert an the XCM message origin location into a local dispatch origin.
133
type LocalOriginConverter = (
134
    // A `Signed` origin of the sovereign account that the original location controls.
135
    SovereignSignedViaLocation<LocationConverter, RuntimeOrigin>,
136
    // A child parachain, natively expressed, has the `Parachain` origin.
137
    ChildParachainAsNative<parachains_origin::Origin, RuntimeOrigin>,
138
    // The AccountId32 location type can be expressed natively as a `Signed` origin.
139
    SignedAccountId32AsNative<ThisNetwork, RuntimeOrigin>,
140
);
141

            
142
parameter_types! {
143
    /// The amount of weight an XCM operation takes. This is a safe overestimate.
144
    pub const BaseXcmWeight: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
145
    /// The asset ID for the asset that we use to pay for message delivery fees.
146
    pub FeeAssetId: XcmAssetId = XcmAssetId(TokenLocation::get());
147
    /// The base fee for the message delivery fees.
148
    pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
149
}
150

            
151
pub type PriceForChildParachainDelivery =
152
    ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, Dmp>;
153

            
154
/// The XCM router. When we want to send an XCM message, we use this type. It amalgamates all of our
155
/// individual routers.
156
pub type XcmRouter = WithUniqueTopic<(
157
    // Use DMP to communicate with child parachains.
158
    ChildParachainRouter<Runtime, XcmPallet, PriceForChildParachainDelivery>,
159
    // Send Ethereum-native tokens back to Ethereum.
160
    SnowbrigeTokenTransferRouter<SnowbridgeExporter, UniversalLocation>,
161
)>;
162

            
163
parameter_types! {
164
    pub Star: AssetFilter = Wild(AllOf { fun: WildFungible, id: XcmAssetId(TokenLocation::get()) });
165
    pub AssetHub: Location = Parachain(ASSET_HUB_ID).into_location();
166
    pub Contracts: Location = Parachain(CONTRACTS_ID).into_location();
167
    pub Encointer: Location = Parachain(ENCOINTER_ID).into_location();
168
    pub BridgeHub: Location = Parachain(BRIDGE_HUB_ID).into_location();
169
    pub People: Location = Parachain(PEOPLE_ID).into_location();
170
    pub Broker: Location = Parachain(BROKER_ID).into_location();
171
    pub Tick: Location = Parachain(100).into_location();
172
    pub Trick: Location = Parachain(110).into_location();
173
    pub Track: Location = Parachain(120).into_location();
174
    pub StarForTick: (AssetFilter, Location) = (Star::get(), Tick::get());
175
    pub StarForTrick: (AssetFilter, Location) = (Star::get(), Trick::get());
176
    pub StarForTrack: (AssetFilter, Location) = (Star::get(), Track::get());
177
    pub StarForAssetHub: (AssetFilter, Location) = (Star::get(), AssetHub::get());
178
    pub StarForContracts: (AssetFilter, Location) = (Star::get(), Contracts::get());
179
    pub StarForEncointer: (AssetFilter, Location) = (Star::get(), Encointer::get());
180
    pub StarForBridgeHub: (AssetFilter, Location) = (Star::get(), BridgeHub::get());
181
    pub StarForPeople: (AssetFilter, Location) = (Star::get(), People::get());
182
    pub StarForBroker: (AssetFilter, Location) = (Star::get(), Broker::get());
183
    pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
184
    pub const MaxInstructions: u32 = 100;
185
    pub const MaxAssetsIntoHolding: u32 = 64;
186
}
187

            
188
pub struct OnlyParachains;
189
impl Contains<Location> for OnlyParachains {
190
    fn contains(loc: &Location) -> bool {
191
        matches!(loc.unpack(), (0, [Parachain(_)]))
192
    }
193
}
194

            
195
pub struct LocalPlurality;
196
impl Contains<Location> for LocalPlurality {
197
    fn contains(loc: &Location) -> bool {
198
        matches!(loc.unpack(), (0, [Plurality { .. }]))
199
    }
200
}
201

            
202
/// The barriers one of which must be passed for an XCM message to be executed.
203
pub type Barrier = TrailingSetTopicAsId<(
204
    // Weight that is paid for may be consumed.
205
    TakeWeightCredit,
206
    // Expected responses are OK.
207
    AllowKnownQueryResponses<XcmPallet>,
208
    WithComputedOrigin<
209
        (
210
            // If the message is one that immediately attempts to pay for execution, then allow it.
211
            AllowTopLevelPaidExecutionFrom<Everything>,
212
            // Messages coming from system parachains need not pay for execution.
213
            AllowExplicitUnpaidExecutionFrom<IsChildSystemParachain<ParaId>>,
214
            // Subscriptions for version tracking are OK.
215
            AllowSubscriptionsFrom<OnlyParachains>,
216
        ),
217
        UniversalLocation,
218
        ConstU32<8>,
219
    >,
220
)>;
221

            
222
/// Locations that will not be charged fees in the executor, neither for execution nor delivery.
223
/// We only waive fees for system functions, which these locations represent.
224
pub type WaivedLocations = Equals<RootLocation>;
225
pub type XcmWeigher = WeightInfoBounds<XcmWeight<RuntimeCall>, RuntimeCall, MaxInstructions>;
226

            
227
pub struct XcmConfig;
228
impl xcm_executor::Config for XcmConfig {
229
    type RuntimeCall = RuntimeCall;
230
    type XcmSender = XcmRouter;
231
    type AssetTransactor = (LocalAssetTransactor, ForeignFungiblesTransactor);
232
    type OriginConverter = LocalOriginConverter;
233
    type IsReserve = (
234
        NativeAssetReserve,
235
        EthereumAssetReserve<EthereumLocation, EthereumNetwork>,
236
    );
237
    type IsTeleporter = ();
238
    type UniversalLocation = UniversalLocation;
239
    type Barrier = Barrier;
240
    type Weigher = XcmWeigher;
241
    type Trader =
242
        UsingComponents<WeightToFee, TokenLocation, AccountId, Balances, ToAuthor<Runtime>>;
243
    type ResponseHandler = XcmPallet;
244
    type AssetTrap = XcmPallet;
245
    type AssetLocker = ();
246
    type AssetExchanger = ();
247
    type AssetClaims = XcmPallet;
248
    type SubscriptionService = XcmPallet;
249
    type PalletInstancesInfo = AllPalletsWithSystem;
250
    type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
251
    type FeeManager = XcmFeeManagerFromComponents<
252
        WaivedLocations,
253
        SendXcmFeeToAccount<Self::AssetTransactor, TreasuryAccount>,
254
    >;
255
    type MessageExporter = ContainerToSnowbridgeMessageExporter;
256
    type UniversalAliases = Nothing;
257
    type CallDispatcher = RuntimeCall;
258
    type SafeCallFilter = Everything;
259
    type Aliasers = Nothing;
260
    type TransactionalProcessor = FrameTransactionalProcessor;
261
    type HrmpNewChannelOpenRequestHandler = ();
262
    type HrmpChannelAcceptedHandler = ();
263
    type HrmpChannelClosingHandler = ();
264
    type XcmRecorder = ();
265
    type XcmEventEmitter = XcmPallet;
266
}
267

            
268
parameter_types! {
269
    pub const CollectiveBodyId: BodyId = BodyId::Unit;
270
    // StakingAdmin pluralistic body.
271
    pub const StakingAdminBodyId: BodyId = BodyId::Defense;
272
    // Fellows pluralistic body.
273
    pub const FellowsBodyId: BodyId = BodyId::Technical;
274
}
275

            
276
/// Type to convert an `Origin` type value into a `Location` value which represents an interior
277
/// location of this chain.
278
pub type LocalOriginToLocation = (
279
    // And a usual Signed origin to be used in XCM as a corresponding AccountId32
280
    SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
281
);
282

            
283
/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value.
284
pub type StakingAdminToPlurality =
285
    OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
286

            
287
/// Type to convert the Fellows origin to a Plurality `Location` value.
288
pub type FellowsToPlurality = OriginToPluralityVoice<RuntimeOrigin, Fellows, FellowsBodyId>;
289

            
290
/// Type to convert a pallet `Origin` type value into a `Location` value which represents an
291
/// interior location of this chain for a destination chain.
292
pub type LocalPalletOriginToLocation = (
293
    // StakingAdmin origin to be used in XCM as a corresponding Plurality `Location` value.
294
    StakingAdminToPlurality,
295
    // Fellows origin to be used in XCM as a corresponding Plurality `Location` value.
296
    FellowsToPlurality,
297
);
298

            
299
impl pallet_xcm::Config for Runtime {
300
    type RuntimeEvent = RuntimeEvent;
301
    // Note that this configuration of `SendXcmOrigin` is different from the one present in
302
    // production.
303
    type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
304
    type XcmRouter = XcmRouter;
305
    // Anyone can execute XCM messages locally.
306
    type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
307
    type XcmExecuteFilter = Everything;
308
    type XcmExecutor = XcmExecutor<XcmConfig>;
309
    type XcmTeleportFilter = Nothing;
310
    // Anyone is able to use reserve transfers regardless of who they are and what they want to
311
    // transfer.
312
    type XcmReserveTransferFilter = Everything;
313
    type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
314
    type UniversalLocation = UniversalLocation;
315
    type RuntimeOrigin = RuntimeOrigin;
316
    type RuntimeCall = RuntimeCall;
317
    const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
318
    type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
319
    type Currency = Balances;
320
    type CurrencyMatcher = IsConcrete<TokenLocation>;
321
    type TrustedLockers = ();
322
    type SovereignAccountOf = LocationConverter;
323
    type MaxLockers = ConstU32<8>;
324
    type MaxRemoteLockConsumers = ConstU32<0>;
325
    type RemoteLockConsumerIdentifier = ();
326
    type WeightInfo = weights::pallet_xcm::SubstrateWeight<Runtime>;
327
    type AdminOrigin = EnsureRoot<AccountId>;
328
    type AuthorizedAliasConsideration = Disabled;
329
}
330

            
331
parameter_types! {
332
    // TODO: revisit these values in the future
333
    pub const ForeignAssetsAssetDeposit: Balance = 0;
334
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
335
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
336
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
337
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
338
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
339
    pub CheckingAccount: AccountId = XcmPallet::check_account();
340
}
341

            
342
#[cfg(feature = "runtime-benchmarks")]
343
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
344
pub struct ForeignAssetBenchmarkHelper;
345
#[cfg(feature = "runtime-benchmarks")]
346
impl pallet_assets::BenchmarkHelper<AssetId> for ForeignAssetBenchmarkHelper {
347
    fn create_asset_id_parameter(id: u32) -> AssetId {
348
        id.try_into()
349
            .expect("number too large to create benchmarks")
350
    }
351
}
352

            
353
pub type AssetId = u16;
354
pub type ForeignAssetsInstance = pallet_assets::Instance1;
355
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
356
    type RuntimeEvent = RuntimeEvent;
357
    type Balance = Balance;
358
    type AssetId = AssetId;
359
    type AssetIdParameter = AssetId;
360
    type Currency = Balances;
361
    type CreateOrigin = frame_support::traits::NeverEnsureOrigin<AccountId>;
362
    type ForceOrigin = EnsureRoot<AccountId>;
363
    type AssetDeposit = ForeignAssetsAssetDeposit;
364
    type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
365
    type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
366
    type ApprovalDeposit = ForeignAssetsApprovalDeposit;
367
    type StringLimit = ForeignAssetsAssetsStringLimit;
368
    type Freezer = ();
369
    type Extra = ();
370
    type WeightInfo = weights::pallet_assets::SubstrateWeight<Runtime>;
371
    type CallbackHandle = ();
372
    type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
373
    type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
374
    type Holder = ();
375
    #[cfg(feature = "runtime-benchmarks")]
376
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
377
}
378

            
379
impl pallet_foreign_asset_creator::Config for Runtime {
380
    type RuntimeEvent = RuntimeEvent;
381
    type ForeignAsset = Location;
382
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
383
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
384
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
385
    type Fungibles = ForeignAssets;
386
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
387
    type OnForeignAssetCreated = ();
388
    type OnForeignAssetDestroyed = ();
389
}
390

            
391
parameter_types! {
392
    pub SnowbridgeChannelInfo: Option<(ChannelId, AgentId)> =
393
        pallet_ethereum_token_transfers::CurrentChannelInfo::<Runtime>::get()
394
4
            .map(|x| (x.channel_id, x.agent_id));
395
}
396

            
397
/// Exports message to the Ethereum Gateway contract.
398
pub type SnowbridgeExporter = EthereumBlobExporter<
399
    UniversalLocation,
400
    EthereumNetwork,
401
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
402
    EthereumSystem,
403
    SnowbridgeChannelInfo,
404
>;
405

            
406
/// Exports message to the Ethereum Gateway contract.
407
pub type ContainerToSnowbridgeMessageExporter = ContainerEthereumBlobExporter<
408
    UniversalLocation,
409
    EthereumNetwork,
410
    EthereumLocation,
411
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
412
    EthereumSystem,
413
    SnowbridgeChannelInfo,
414
>;