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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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