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::*, TANSSI_GENESIS_HASH},
39
    tp_bridge::EthereumLocationsConverterFor,
40
    tp_xcm_commons::NativeAssetReserve,
41
    xcm::{latest::prelude::*, opaque::latest::WESTEND_GENESIS_HASH},
42
    xcm_builder::{
43
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
44
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
45
        ChildParachainConvertsVia, DescribeAllTerminal, DescribeFamily, FixedWeightBounds,
46
        FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsChildSystemParachain,
47
        IsConcrete, MintLocation, OriginToPluralityVoice, SendXcmFeeToAccount,
48
        SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation,
49
        TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds,
50
        WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents,
51
    },
52
    xcm_executor::XcmExecutor,
53
};
54

            
55
parameter_types! {
56
    pub TokenLocation: Location = Here.into_location();
57
    pub RootLocation: Location = Location::here();
58
    pub const ThisNetwork: NetworkId = NetworkId::ByGenesis(TANSSI_GENESIS_HASH);
59
    pub UniversalLocation: InteriorLocation = ThisNetwork::get().into();
60
    pub CheckAccount: AccountId = XcmPallet::check_account();
61
    pub LocalCheckAccount: (AccountId, MintLocation) = (CheckAccount::get(), MintLocation::Local);
62
    pub TreasuryAccount: AccountId = Treasury::account_id();
63
}
64

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

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

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

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

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

            
119
pub type PriceForChildParachainDelivery =
120
    ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, Dmp>;
121

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

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

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

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

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

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

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

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

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

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

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

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

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