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, weights, weights::xcm::XcmWeight, AccountId, AllPalletsWithSystem,
22
        Balances, Dmp, Fellows, ParaId, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin,
23
        TransactionByteFee, Treasury, WeightToFee, XcmPallet,
24
    },
25
    crate::governance::StakingAdmin,
26
    dancelight_runtime_constants::{currency::CENTS, system_parachain::*},
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
    tp_bridge::EthereumLocationsConverterFor,
39
    tp_xcm_commons::NativeAssetReserve,
40
    xcm::latest::prelude::*,
41
    xcm_builder::{
42
        AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
43
        AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
44
        ChildParachainConvertsVia, DescribeAllTerminal, DescribeFamily, FixedWeightBounds,
45
        FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsChildSystemParachain,
46
        IsConcrete, MintLocation, OriginToPluralityVoice, SendXcmFeeToAccount,
47
        SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation,
48
        TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds,
49
        WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents,
50
    },
51
    xcm_executor::XcmExecutor,
52
};
53

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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