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 Starlight.
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
    frame_support::{
29
        parameter_types,
30
        traits::{Contains, Disabled, Equals, Everything, Nothing},
31
        weights::Weight,
32
    },
33
    frame_system::EnsureRoot,
34
    runtime_common::{
35
        xcm_sender::{ChildParachainRouter, ExponentialPrice},
36
        ToAuthor,
37
    },
38
    sp_core::ConstU32,
39
    starlight_runtime_constants::{currency::CENTS, system_parachain::*, TANSSI_GENESIS_HASH},
40
    tp_bridge::EthereumLocationsConverterFor,
41
    tp_xcm_commons::NativeAssetReserve,
42
    xcm::{
43
        latest::prelude::{AssetId as XcmAssetId, *},
44
        opaque::latest::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(TANSSI_GENESIS_HASH);
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
    type XcmEventEmitter = XcmPallet;
233
}
234

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

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

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

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

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

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

            
298
parameter_types! {
299
    pub const ForeignAssetsAssetDeposit: Balance = 0;
300
    pub const ForeignAssetsAssetAccountDeposit: Balance = 0;
301
    pub const ForeignAssetsApprovalDeposit: Balance = 0;
302
    pub const ForeignAssetsAssetsStringLimit: u32 = 50;
303
    pub const ForeignAssetsMetadataDepositBase: Balance = 0;
304
    pub const ForeignAssetsMetadataDepositPerByte: Balance = 0;
305
    pub CheckingAccount: AccountId = XcmPallet::check_account();
306
}
307

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

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

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