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, ParaId,
24
        Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, TransactionByteFee, Treasury,
25
        WeightToFee, XcmPallet,
26
    },
27
    crate::governance::StakingAdmin,
28
    dancelight_runtime_constants::{currency::CENTS, system_parachain::*},
29
    frame_support::{
30
        parameter_types,
31
        traits::{Contains, Equals, Everything, Nothing},
32
        weights::Weight,
33
    },
34
    frame_system::EnsureRoot,
35
    runtime_common::{
36
        xcm_sender::{ChildParachainRouter, ExponentialPrice},
37
        ToAuthor,
38
    },
39
    sp_core::ConstU32,
40
    tp_bridge::EthereumLocationsConverterFor,
41
    tp_xcm_commons::NativeAssetReserve,
42
    xcm::{
43
        latest::prelude::{AssetId as XcmAssetId, *},
44
        opaque::latest::{ROCOCO_GENESIS_HASH, WESTEND_GENESIS_HASH},
45
    },
46
    xcm_builder::{
47
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
48
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
49
        ChildParachainConvertsVia, DescribeAllTerminal, DescribeFamily, FixedWeightBounds,
50
        FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsChildSystemParachain,
51
        IsConcrete, MintLocation, OriginToPluralityVoice, SendXcmFeeToAccount,
52
        SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation,
53
        TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds,
54
        WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents,
55
    },
56
    xcm_executor::XcmExecutor,
57
};
58

            
59
parameter_types! {
60
    pub TokenLocation: Location = Here.into_location();
61
    pub RootLocation: Location = Location::here();
62
    pub const ThisNetwork: NetworkId = NetworkId::ByGenesis(ROCOCO_GENESIS_HASH); // FIXME: Change to Dancelight
63
    pub UniversalLocation: InteriorLocation = ThisNetwork::get().into();
64
    pub CheckAccount: AccountId = XcmPallet::check_account();
65
    pub LocalCheckAccount: (AccountId, MintLocation) = (CheckAccount::get(), MintLocation::Local);
66
    pub TreasuryAccount: AccountId = Treasury::account_id();
67
}
68

            
69
#[cfg(feature = "runtime-benchmarks")]
70
parameter_types! {
71
    // Universal location for benchmarks that need to run through a para-id scenario
72
    pub UniversalLocationForParaIdBenchmarks: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(2000u32)].into();
73
}
74

            
75
pub type LocationConverter = (
76
    // We can convert a child parachain using the standard `AccountId` conversion.
77
    ChildParachainConvertsVia<ParaId, AccountId>,
78
    // We can directly alias an `AccountId32` into a local account.
79
    AccountId32Aliases<ThisNetwork, AccountId>,
80
    // Foreign locations alias into accounts according to a hash of their standard description.
81
    HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
82
    // Ethereum contract sovereign account.
83
    // (Used to convert ethereum contract locations to sovereign account)
84
    EthereumLocationsConverterFor<AccountId>,
85
);
86

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

            
104
/// The means that we convert an the XCM message origin location into a local dispatch origin.
105
type LocalOriginConverter = (
106
    // A `Signed` origin of the sovereign account that the original location controls.
107
    SovereignSignedViaLocation<LocationConverter, RuntimeOrigin>,
108
    // A child parachain, natively expressed, has the `Parachain` origin.
109
    ChildParachainAsNative<parachains_origin::Origin, RuntimeOrigin>,
110
    // The AccountId32 location type can be expressed natively as a `Signed` origin.
111
    SignedAccountId32AsNative<ThisNetwork, RuntimeOrigin>,
112
);
113

            
114
parameter_types! {
115
    /// The amount of weight an XCM operation takes. This is a safe overestimate.
116
    pub const BaseXcmWeight: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
117
    /// The asset ID for the asset that we use to pay for message delivery fees.
118
    pub FeeAssetId: XcmAssetId = XcmAssetId(TokenLocation::get());
119
    /// The base fee for the message delivery fees.
120
    pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
121
}
122

            
123
pub type PriceForChildParachainDelivery =
124
    ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, Dmp>;
125

            
126
/// The XCM router. When we want to send an XCM message, we use this type. It amalgamates all of our
127
/// individual routers.
128
pub type XcmRouter = WithUniqueTopic<
129
    // Only one router so far - use DMP to communicate with child parachains.
130
    ChildParachainRouter<Runtime, XcmPallet, PriceForChildParachainDelivery>,
131
>;
132

            
133
parameter_types! {
134
    pub Star: AssetFilter = Wild(AllOf { fun: WildFungible, id: XcmAssetId(TokenLocation::get()) });
135
    pub AssetHub: Location = Parachain(ASSET_HUB_ID).into_location();
136
    pub Contracts: Location = Parachain(CONTRACTS_ID).into_location();
137
    pub Encointer: Location = Parachain(ENCOINTER_ID).into_location();
138
    pub BridgeHub: Location = Parachain(BRIDGE_HUB_ID).into_location();
139
    pub People: Location = Parachain(PEOPLE_ID).into_location();
140
    pub Broker: Location = Parachain(BROKER_ID).into_location();
141
    pub Tick: Location = Parachain(100).into_location();
142
    pub Trick: Location = Parachain(110).into_location();
143
    pub Track: Location = Parachain(120).into_location();
144
    pub StarForTick: (AssetFilter, Location) = (Star::get(), Tick::get());
145
    pub StarForTrick: (AssetFilter, Location) = (Star::get(), Trick::get());
146
    pub StarForTrack: (AssetFilter, Location) = (Star::get(), Track::get());
147
    pub StarForAssetHub: (AssetFilter, Location) = (Star::get(), AssetHub::get());
148
    pub StarForContracts: (AssetFilter, Location) = (Star::get(), Contracts::get());
149
    pub StarForEncointer: (AssetFilter, Location) = (Star::get(), Encointer::get());
150
    pub StarForBridgeHub: (AssetFilter, Location) = (Star::get(), BridgeHub::get());
151
    pub StarForPeople: (AssetFilter, Location) = (Star::get(), People::get());
152
    pub StarForBroker: (AssetFilter, Location) = (Star::get(), Broker::get());
153
    pub const RelayNetwork: NetworkId = NetworkId::ByGenesis(WESTEND_GENESIS_HASH);
154
    pub const MaxInstructions: u32 = 100;
155
    pub const MaxAssetsIntoHolding: u32 = 64;
156
}
157

            
158
pub struct OnlyParachains;
159
impl Contains<Location> for OnlyParachains {
160
    fn contains(loc: &Location) -> bool {
161
        matches!(loc.unpack(), (0, [Parachain(_)]))
162
    }
163
}
164

            
165
pub struct LocalPlurality;
166
impl Contains<Location> for LocalPlurality {
167
    fn contains(loc: &Location) -> bool {
168
        matches!(loc.unpack(), (0, [Plurality { .. }]))
169
    }
170
}
171

            
172
/// The barriers one of which must be passed for an XCM message to be executed.
173
pub type Barrier = TrailingSetTopicAsId<(
174
    // Weight that is paid for may be consumed.
175
    TakeWeightCredit,
176
    // Expected responses are OK.
177
    AllowKnownQueryResponses<XcmPallet>,
178
    WithComputedOrigin<
179
        (
180
            // If the message is one that immediately attempts to pay for execution, then allow it.
181
            AllowTopLevelPaidExecutionFrom<Everything>,
182
            // Messages coming from system parachains need not pay for execution.
183
            AllowExplicitUnpaidExecutionFrom<IsChildSystemParachain<ParaId>>,
184
            // Subscriptions for version tracking are OK.
185
            AllowSubscriptionsFrom<OnlyParachains>,
186
        ),
187
        UniversalLocation,
188
        ConstU32<8>,
189
    >,
190
)>;
191

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

            
197
pub struct XcmConfig;
198
impl xcm_executor::Config for XcmConfig {
199
    type RuntimeCall = RuntimeCall;
200
    type XcmSender = XcmRouter;
201
    type AssetTransactor = LocalAssetTransactor;
202
    type OriginConverter = LocalOriginConverter;
203
    type IsReserve = NativeAssetReserve;
204
    type IsTeleporter = ();
205
    type UniversalLocation = UniversalLocation;
206
    type Barrier = Barrier;
207
    type Weigher = XcmWeigher;
208
    type Trader =
209
        UsingComponents<WeightToFee, TokenLocation, AccountId, Balances, ToAuthor<Runtime>>;
210
    type ResponseHandler = XcmPallet;
211
    type AssetTrap = XcmPallet;
212
    type AssetLocker = ();
213
    type AssetExchanger = ();
214
    type AssetClaims = XcmPallet;
215
    type SubscriptionService = XcmPallet;
216
    type PalletInstancesInfo = AllPalletsWithSystem;
217
    type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
218
    type FeeManager = XcmFeeManagerFromComponents<
219
        WaivedLocations,
220
        SendXcmFeeToAccount<Self::AssetTransactor, TreasuryAccount>,
221
    >;
222
    type MessageExporter = ();
223
    type UniversalAliases = Nothing;
224
    type CallDispatcher = RuntimeCall;
225
    type SafeCallFilter = Everything;
226
    type Aliasers = Nothing;
227
    type TransactionalProcessor = FrameTransactionalProcessor;
228
    type HrmpNewChannelOpenRequestHandler = ();
229
    type HrmpChannelAcceptedHandler = ();
230
    type HrmpChannelClosingHandler = ();
231
    type XcmRecorder = ();
232
}
233

            
234
parameter_types! {
235
    pub const CollectiveBodyId: BodyId = BodyId::Unit;
236
    // StakingAdmin pluralistic body.
237
    pub const StakingAdminBodyId: BodyId = BodyId::Defense;
238
    // Fellows pluralistic body.
239
    pub const FellowsBodyId: BodyId = BodyId::Technical;
240
}
241

            
242
/// Type to convert an `Origin` type value into a `Location` value which represents an interior
243
/// location of this chain.
244
pub type LocalOriginToLocation = (
245
    // And a usual Signed origin to be used in XCM as a corresponding AccountId32
246
    SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
247
);
248

            
249
/// Type to convert the `StakingAdmin` origin to a Plurality `Location` value.
250
pub type StakingAdminToPlurality =
251
    OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
252

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

            
256
/// Type to convert a pallet `Origin` type value into a `Location` value which represents an
257
/// interior location of this chain for a destination chain.
258
pub type LocalPalletOriginToLocation = (
259
    // StakingAdmin origin to be used in XCM as a corresponding Plurality `Location` value.
260
    StakingAdminToPlurality,
261
    // Fellows origin to be used in XCM as a corresponding Plurality `Location` value.
262
    FellowsToPlurality,
263
);
264

            
265
impl pallet_xcm::Config for Runtime {
266
    type RuntimeEvent = RuntimeEvent;
267
    // Note that this configuration of `SendXcmOrigin` is different from the one present in
268
    // production.
269
    type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
270
    type XcmRouter = XcmRouter;
271
    // Anyone can execute XCM messages locally.
272
    type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
273
    type XcmExecuteFilter = Everything;
274
    type XcmExecutor = XcmExecutor<XcmConfig>;
275
    type XcmTeleportFilter = Nothing;
276
    // Anyone is able to use reserve transfers regardless of who they are and what they want to
277
    // transfer.
278
    type XcmReserveTransferFilter = Everything;
279
    type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
280
    type UniversalLocation = UniversalLocation;
281
    type RuntimeOrigin = RuntimeOrigin;
282
    type RuntimeCall = RuntimeCall;
283
    const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
284
    type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
285
    type Currency = Balances;
286
    type CurrencyMatcher = IsConcrete<TokenLocation>;
287
    type TrustedLockers = ();
288
    type SovereignAccountOf = LocationConverter;
289
    type MaxLockers = ConstU32<8>;
290
    type MaxRemoteLockConsumers = ConstU32<0>;
291
    type RemoteLockConsumerIdentifier = ();
292
    type WeightInfo = weights::pallet_xcm::SubstrateWeight<Runtime>;
293
    type AdminOrigin = EnsureRoot<AccountId>;
294
}
295

            
296
parameter_types! {
297
    // TODO: revisit these values in the future
298
    pub const ForeignAssetsAssetDeposit: Balance = 0;
299
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
300
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
301
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
302
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
303
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
304
    pub CheckingAccount: AccountId = XcmPallet::check_account();
305
}
306

            
307
#[cfg(feature = "runtime-benchmarks")]
308
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
309
pub struct ForeignAssetBenchmarkHelper;
310
#[cfg(feature = "runtime-benchmarks")]
311
impl pallet_assets::BenchmarkHelper<AssetId> for ForeignAssetBenchmarkHelper {
312
    fn create_asset_id_parameter(id: u32) -> AssetId {
313
        id.try_into()
314
            .expect("number too large to create benchmarks")
315
    }
316
}
317

            
318
pub type AssetId = u16;
319
pub type ForeignAssetsInstance = pallet_assets::Instance1;
320
impl pallet_assets::Config<ForeignAssetsInstance> for Runtime {
321
    type RuntimeEvent = RuntimeEvent;
322
    type Balance = Balance;
323
    type AssetId = AssetId;
324
    type AssetIdParameter = AssetId;
325
    type Currency = Balances;
326
    type CreateOrigin = frame_support::traits::NeverEnsureOrigin<AccountId>;
327
    type ForceOrigin = EnsureRoot<AccountId>;
328
    type AssetDeposit = ForeignAssetsAssetDeposit;
329
    type MetadataDepositBase = ForeignAssetsMetadataDepositBase;
330
    type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte;
331
    type ApprovalDeposit = ForeignAssetsApprovalDeposit;
332
    type StringLimit = ForeignAssetsAssetsStringLimit;
333
    type Freezer = ();
334
    type Extra = ();
335
    type WeightInfo = weights::pallet_assets::SubstrateWeight<Runtime>;
336
    type CallbackHandle = ();
337
    type AssetAccountDeposit = ForeignAssetsAssetAccountDeposit;
338
    type RemoveItemsLimit = frame_support::traits::ConstU32<1000>;
339
    #[cfg(feature = "runtime-benchmarks")]
340
    type BenchmarkHelper = ForeignAssetBenchmarkHelper;
341
}
342

            
343
impl pallet_foreign_asset_creator::Config for Runtime {
344
    type RuntimeEvent = RuntimeEvent;
345
    type ForeignAsset = Location;
346
    type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
347
    type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
348
    type ForeignAssetDestroyerOrigin = EnsureRoot<AccountId>;
349
    type Fungibles = ForeignAssets;
350
    type WeightInfo = weights::pallet_foreign_asset_creator::SubstrateWeight<Runtime>;
351
    type OnForeignAssetCreated = ();
352
    type OnForeignAssetDestroyed = ();
353
}