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
        snowbridge_outbound_token_transfer::{EthereumBlobExporter, SnowbrigeTokenTransferRouter},
51
        EthereumLocationsConverterFor,
52
    },
53
    tp_xcm_commons::{EthereumAssetReserve, NativeAssetReserve},
54
    xcm::{
55
        latest::prelude::{AssetId as XcmAssetId, *},
56
        opaque::latest::WESTEND_GENESIS_HASH,
57
    },
58
    xcm_builder::{
59
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
60
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
61
        ChildParachainConvertsVia, ConvertedConcreteId, DescribeAllTerminal, DescribeFamily,
62
        FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter,
63
        HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, NoChecking,
64
        OriginToPluralityVoice, SignedAccountId32AsNative, SignedToAccountId32,
65
        SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents,
66
        WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, 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 AssetHub: Location = Parachain(ASSET_HUB_ID).into_location();
165
    pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
166
    pub const MaxInstructions: u32 = 100;
167
    pub const MaxAssetsIntoHolding: u32 = 64;
168
}
169

            
170
pub struct OnlyParachains;
171
impl Contains<Location> for OnlyParachains {
172
    fn contains(loc: &Location) -> bool {
173
        matches!(loc.unpack(), (0, [Parachain(_)]))
174
    }
175
}
176

            
177
pub struct LocalPlurality;
178
impl Contains<Location> for LocalPlurality {
179
    fn contains(loc: &Location) -> bool {
180
        matches!(loc.unpack(), (0, [Plurality { .. }]))
181
    }
182
}
183

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

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

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

            
250
parameter_types! {
251
    pub const CollectiveBodyId: BodyId = BodyId::Unit;
252
    // StakingAdmin pluralistic body.
253
    pub const StakingAdminBodyId: BodyId = BodyId::Defense;
254
    // Fellows pluralistic body.
255
    pub const FellowsBodyId: BodyId = BodyId::Technical;
256
}
257

            
258
/// Type to convert an `Origin` type value into a `Location` value which represents an interior
259
/// location of this chain.
260
pub type LocalOriginToLocation = (
261
    // And a usual Signed origin to be used in XCM as a corresponding AccountId32
262
    SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
263
);
264

            
265
/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value.
266
pub type StakingAdminToPlurality =
267
    OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
268

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

            
272
/// Type to convert a pallet `Origin` type value into a `Location` value which represents an
273
/// interior location of this chain for a destination chain.
274
pub type LocalPalletOriginToLocation = (
275
    // StakingAdmin origin to be used in XCM as a corresponding Plurality `Location` value.
276
    StakingAdminToPlurality,
277
    // Fellows origin to be used in XCM as a corresponding Plurality `Location` value.
278
    FellowsToPlurality,
279
);
280

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

            
313
parameter_types! {
314
    // TODO: revisit these values in the future
315
    pub const ForeignAssetsAssetDeposit: Balance = 0;
316
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
317
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
318
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
319
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
320
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
321
    pub CheckingAccount: AccountId = XcmPallet::check_account();
322
}
323

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

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

            
361
impl pallet_foreign_asset_creator::Config for Runtime {
362
    type ForeignAsset = Location;
363
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
364
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
365
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
366
    type Fungibles = ForeignAssets;
367
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
368
    type OnForeignAssetCreated = ();
369
    type OnForeignAssetDestroyed = ();
370
}
371

            
372
parameter_types! {
373
    pub SnowbridgeChannelInfo: Option<(ChannelId, AgentId)> =
374
        pallet_ethereum_token_transfers::CurrentChannelInfo::<Runtime>::get()
375
58
            .map(|x| (x.channel_id, x.agent_id));
376
}
377

            
378
/// Exports message to the Ethereum Gateway contract.
379
pub type SnowbridgeExporter = EthereumBlobExporter<
380
    UniversalLocation,
381
    EthereumNetwork,
382
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
383
    EthereumSystem,
384
    SnowbridgeChannelInfo,
385
>;
386

            
387
/// Exports message to the Ethereum Gateway contract.
388
pub type ContainerToSnowbridgeMessageExporter = ContainerEthereumBlobExporter<
389
    UniversalLocation,
390
    EthereumNetwork,
391
    EthereumLocation,
392
    snowbridge_pallet_outbound_queue::Pallet<Runtime>,
393
    EthereumSystem,
394
    SnowbridgeChannelInfo,
395
>;