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, SnowbridgeFeesAccount},
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
    tanssi_runtime_common::relay::ExporterFeeHandler,
48
    tp_bridge::{
49
        container_token_to_ethereum_message_exporter::ContainerEthereumBlobExporter,
50
        container_token_to_ethereum_message_exporter_v2::ContainerEthereumBlobExporterV2,
51
        snowbridge_outbound_token_transfer::{EthereumBlobExporter, SnowbrigeTokenTransferRouter},
52
        snowbridge_outbound_token_transfer_v2::EthereumBlobExporterV2,
53
        EthereumLocationsConverterFor,
54
    },
55
    tp_xcm_commons::{EthereumAssetReserve, NativeAssetReserve},
56
    xcm::{
57
        latest::prelude::{AssetId as XcmAssetId, *},
58
        opaque::latest::WESTEND_GENESIS_HASH,
59
    },
60
    xcm_builder::{
61
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
62
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
63
        ChildParachainConvertsVia, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily,
64
        FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter,
65
        HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, NoChecking,
66
        OriginToPluralityVoice, SendXcmFeeToAccount, SignedAccountId32AsNative,
67
        SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
68
        UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
69
        XcmFeeManagerFromComponents,
70
    },
71
    xcm_executor::XcmExecutor,
72
};
73

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

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

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

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

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

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

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

            
154
pub type PriceForChildParachainDelivery =
155
    ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, Dmp>;
156

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

            
168
parameter_types! {
169
    pub AssetHub: Location = Parachain(ASSET_HUB_ID).into_location();
170
    pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
171
    pub const MaxInstructions: u32 = 100;
172
    pub const MaxAssetsIntoHolding: u32 = 64;
173
}
174

            
175
pub struct OnlyParachains;
176
impl Contains<Location> for OnlyParachains {
177
    fn contains(loc: &Location) -> bool {
178
        matches!(loc.unpack(), (0, [Parachain(_)]))
179
    }
180
}
181

            
182
pub struct LocalPlurality;
183
impl Contains<Location> for LocalPlurality {
184
    fn contains(loc: &Location) -> bool {
185
        matches!(loc.unpack(), (0, [Plurality { .. }]))
186
    }
187
}
188

            
189
/// The barriers one of which must be passed for an XCM message to be executed.
190
pub type Barrier = TrailingSetTopicAsId<(
191
    // Weight that is paid for may be consumed.
192
    TakeWeightCredit,
193
    // Expected responses are OK.
194
    AllowKnownQueryResponses<XcmPallet>,
195
    WithComputedOrigin<
196
        (
197
            // If the message is one that immediately attempts to pay for execution, then allow it.
198
            AllowTopLevelPaidExecutionFrom<Everything>,
199
            // Messages coming from system parachains need not pay for execution.
200
            AllowExplicitUnpaidExecutionFrom<IsChildSystemParachain<ParaId>>,
201
            // Subscriptions for version tracking are OK.
202
            AllowSubscriptionsFrom<OnlyParachains>,
203
        ),
204
        UniversalLocation,
205
        ConstU32<8>,
206
    >,
207
)>;
208

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

            
214
pub struct XcmConfig;
215
impl xcm_executor::Config for XcmConfig {
216
    type RuntimeCall = RuntimeCall;
217
    type XcmSender = XcmRouter;
218
    type AssetTransactor = (LocalAssetTransactor, ForeignFungiblesTransactor);
219
    type OriginConverter = LocalOriginConverter;
220
    type IsReserve = (
221
        NativeAssetReserve,
222
        EthereumAssetReserve<EthereumLocation, EthereumNetwork>,
223
    );
224
    type IsTeleporter = ();
225
    type UniversalLocation = UniversalLocation;
226
    type Barrier = Barrier;
227
    type Weigher = XcmWeigher;
228
    type Trader =
229
        UsingComponents<WeightToFee, TokenLocation, AccountId, Balances, ToAuthor<Runtime>>;
230
    type ResponseHandler = XcmPallet;
231
    type AssetTrap = XcmPallet;
232
    type AssetLocker = ();
233
    type AssetExchanger = ();
234
    type AssetClaims = XcmPallet;
235
    type SubscriptionService = XcmPallet;
236
    type PalletInstancesInfo = AllPalletsWithSystem;
237
    type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
238
    type FeeManager = XcmFeeManagerFromComponents<
239
        WaivedLocations,
240
        ExporterFeeHandler<Self::AssetTransactor, SnowbridgeFeesAccount, TreasuryAccount>,
241
    >;
242
    type MessageExporter = (
243
        ContainerToSnowbridgeMessageExporterV2,
244
        ContainerToSnowbridgeMessageExporter,
245
    );
246
    type UniversalAliases = Nothing;
247
    type CallDispatcher = RuntimeCall;
248
    type SafeCallFilter = Everything;
249
    type Aliasers = Nothing;
250
    type TransactionalProcessor = FrameTransactionalProcessor;
251
    type HrmpNewChannelOpenRequestHandler = ();
252
    type HrmpChannelAcceptedHandler = ();
253
    type HrmpChannelClosingHandler = ();
254
    type XcmRecorder = ();
255
    type XcmEventEmitter = XcmPallet;
256
}
257

            
258
parameter_types! {
259
    pub const CollectiveBodyId: BodyId = BodyId::Unit;
260
    // StakingAdmin pluralistic body.
261
    pub const StakingAdminBodyId: BodyId = BodyId::Defense;
262
    // Fellows pluralistic body.
263
    pub const FellowsBodyId: BodyId = BodyId::Technical;
264
}
265

            
266
/// Type to convert an `Origin` type value into a `Location` value which represents an interior
267
/// location of this chain.
268
pub type LocalOriginToLocation = (
269
    // And a usual Signed origin to be used in XCM as a corresponding AccountId32
270
    SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
271
);
272

            
273
/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value.
274
pub type StakingAdminToPlurality =
275
    OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
276

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

            
280
/// Type to convert a pallet `Origin` type value into a `Location` value which represents an
281
/// interior location of this chain for a destination chain.
282
pub type LocalPalletOriginToLocation = (
283
    // StakingAdmin origin to be used in XCM as a corresponding Plurality `Location` value.
284
    StakingAdminToPlurality,
285
    // Fellows origin to be used in XCM as a corresponding Plurality `Location` value.
286
    FellowsToPlurality,
287
);
288

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

            
321
parameter_types! {
322
    // TODO: revisit these values in the future
323
    pub const ForeignAssetsAssetDeposit: Balance = 0;
324
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
325
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
326
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
327
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
328
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
329
    pub CheckingAccount: AccountId = XcmPallet::check_account();
330
}
331

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

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

            
369
impl pallet_foreign_asset_creator::Config for Runtime {
370
    type ForeignAsset = Location;
371
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
372
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
373
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
374
    type Fungibles = ForeignAssets;
375
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
376
    type OnForeignAssetCreated = ();
377
    type OnForeignAssetDestroyed = ();
378
}
379

            
380
parameter_types! {
381
    pub SnowbridgeChannelInfo: Option<(ChannelId, AgentId)> =
382
        pallet_ethereum_token_transfers::CurrentChannelInfo::<Runtime>::get()
383
64
            .map(|x| (x.channel_id, x.agent_id));
384

            
385
    pub const MinV2Reward: u128 = 1u128;
386
    pub MinSnowbridgeV2Reward: Asset = (TokenLocation::get(), MinV2Reward::get()).into();
387
}
388

            
389
/// Exports message to the Ethereum Gateway contract.
390
pub type SnowbridgeExporter = EthereumBlobExporter<
391
    UniversalLocation,
392
    EthereumNetwork,
393
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
394
    EthereumSystem,
395
    SnowbridgeChannelInfo,
396
>;
397

            
398
/// Exports message to the Ethereum Gateway contract.
399
pub type SnowbridgeExporterv2 = EthereumBlobExporterV2<
400
    UniversalLocation,
401
    EthereumNetwork,
402
    snowbridge_pallet_outbound_queue_v2::Pallet<Runtime>,
403
    EthereumSystem,
404
    MinSnowbridgeV2Reward,
405
    SendXcmFeeToAccount<LocalAssetTransactor, SnowbridgeFeesAccount>,
406
>;
407

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

            
418
/// Exports message to the Ethereum Gateway contract using Snowbridge V2.
419
pub type ContainerToSnowbridgeMessageExporterV2 = ContainerEthereumBlobExporterV2<
420
    UniversalLocation,
421
    EthereumNetwork,
422
    EthereumLocation,
423
    snowbridge_pallet_outbound_queue_v2::Pallet<Runtime>,
424
    EthereumSystem,
425
    MinSnowbridgeV2Reward,
426
>;