astar_runtime/
xcm_config.rs

1// This file is part of Astar.
2
3// Copyright (C) Stake Technologies Pte.Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later
5
6// Astar is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// Astar is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with Astar. If not, see <http://www.gnu.org/licenses/>.
18
19use super::{
20    AccountId, AllPalletsWithSystem, AssetId, Assets, AstarAssetLocationIdConverter, Balance,
21    Balances, DealWithFees, MessageQueue, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime,
22    RuntimeCall, RuntimeEvent, RuntimeOrigin, TreasuryAccountId, XcAssetConfig, XcmWeightToFee,
23    XcmpQueue,
24};
25use crate::weights;
26use frame_support::{
27    parameter_types,
28    traits::{ConstU32, Contains, Everything, Nothing},
29    weights::Weight,
30};
31use frame_system::EnsureRoot;
32
33// Polkadot imports
34use cumulus_primitives_core::{AggregateMessageOrigin, ParaId};
35use frame_support::traits::{Disabled, TransformOrigin};
36use parachains_common::{
37    message_queue::ParaIdToSibling, xcm_config::ParentRelayOrSiblingParachains,
38};
39use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery;
40use xcm::latest::prelude::*;
41use xcm_builder::{
42    Account32Hash, AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
43    AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin,
44    FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, IsConcrete, NoChecking,
45    ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
46    SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
47    SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents,
48    WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
49};
50use xcm_executor::{
51    traits::{JustTry, WithOriginFilter},
52    XcmExecutor,
53};
54
55// Astar imports
56use astar_primitives::xcm::{FixedRateOfForeignAsset, ReserveAssetFilter, XcmFungibleFeeHandler};
57
58parameter_types! {
59    pub RelayNetwork: Option<NetworkId> = Some(NetworkId::Polkadot);
60    pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
61    pub UniversalLocation: InteriorLocation =
62    [GlobalConsensus(RelayNetwork::get().unwrap()), Parachain(ParachainInfo::parachain_id().into())].into();
63    pub AstarLocation: Location = Here.into_location();
64    pub DummyCheckingAccount: AccountId = PolkadotXcm::check_account();
65    pub TreasuryLocation: Location = Junction::AccountId32 { network: None, id: TreasuryAccountId::get().into() }.into();
66}
67
68/// Type for specifying how a `Location` can be converted into an `AccountId`. This is used
69/// when determining ownership of accounts for asset transacting and when attempting to use XCM
70/// `Transact` in order to determine the dispatch Origin.
71pub type LocationToAccountId = (
72    // The parent (Relay-chain) origin converts to the default `AccountId`.
73    ParentIsPreset<AccountId>,
74    // Sibling parachain origins convert to AccountId via the `ParaId::into`.
75    SiblingParachainConvertsVia<polkadot_parachain::primitives::Sibling, AccountId>,
76    // Straight up local `AccountId32` origins just alias directly to `AccountId`.
77    AccountId32Aliases<RelayNetwork, AccountId>,
78    // Derives a private `Account32` by hashing `("multiloc", received multilocation)`
79    Account32Hash<RelayNetwork, AccountId>,
80);
81
82/// Means for transacting the native currency on this chain.
83pub type CurrencyTransactor = FungibleAdapter<
84    // Use this currency:
85    Balances,
86    // Use this currency when it is a fungible asset matching the given location or name:
87    IsConcrete<AstarLocation>,
88    // Convert an XCM Location into a local account id:
89    LocationToAccountId,
90    // Our chain's account ID type (we can't get away without mentioning it explicitly):
91    AccountId,
92    // We don't track any teleports of `Balances`.
93    (),
94>;
95
96/// Means for transacting assets besides the native currency on this chain.
97pub type FungiblesTransactor = FungiblesAdapter<
98    // Use this fungibles implementation:
99    Assets,
100    // Use this currency when it is a fungible asset matching the given location or name:
101    ConvertedConcreteId<AssetId, Balance, AstarAssetLocationIdConverter, JustTry>,
102    // Convert an XCM Location into a local account id:
103    LocationToAccountId,
104    // Our chain's account ID type (we can't get away without mentioning it explicitly):
105    AccountId,
106    // We don't support teleport so no need to check any assets.
107    NoChecking,
108    // We don't support teleport so this is just a dummy account.
109    DummyCheckingAccount,
110>;
111
112/// Means for transacting assets on this chain.
113pub type AssetTransactors = (CurrencyTransactor, FungiblesTransactor);
114
115/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,
116/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can
117/// biases the kind of local `Origin` it will become.
118pub type XcmOriginToTransactDispatchOrigin = (
119    // Sovereign account converter; this attempts to derive an `AccountId` from the origin location
120    // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for
121    // foreign chains who want to have a local sovereign account on this chain which they control.
122    SovereignSignedViaLocation<LocationToAccountId, RuntimeOrigin>,
123    // Native converter for Relay-chain (Parent) location; will convert to a `Relay` origin when
124    // recognised.
125    RelayChainAsNative<RelayChainOrigin, RuntimeOrigin>,
126    // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when
127    // recognised.
128    SiblingParachainAsNative<cumulus_pallet_xcm::Origin, RuntimeOrigin>,
129    // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a
130    // transaction from the Root origin.
131    ParentAsSuperuser<RuntimeOrigin>,
132    // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.
133    pallet_xcm::XcmPassthrough<RuntimeOrigin>,
134    // Native signed account converter; this just converts an `AccountId32` origin into a normal
135    // `Origin::Signed` origin of the same 32-byte value.
136    SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
137);
138
139parameter_types! {
140    // One XCM operation is 1_000_000_000 weight - almost certainly a conservative estimate.
141    // For the PoV size, we estimate 4 kB per instruction. This will be changed when we benchmark the instructions.
142    pub UnitWeightCost: Weight = Weight::from_parts(1_000_000_000, 4 * 1024);
143    pub const MaxInstructions: u32 = 100;
144}
145
146pub struct ParentOrParentsPlurality;
147impl Contains<Location> for ParentOrParentsPlurality {
148    fn contains(location: &Location) -> bool {
149        matches!(location.unpack(), (1, []) | (1, [Plurality { .. }]))
150    }
151}
152
153/// A call filter for the XCM Transact instruction. This is a temporary measure until we properly
154/// account for proof size weights.
155pub struct SafeCallFilter;
156impl SafeCallFilter {
157    // 1. RuntimeCall::EVM(..) & RuntimeCall::Ethereum(..) have to be prohibited since we cannot measure PoV size properly
158
159    /// Checks whether the base (non-composite) call is allowed to be executed via `Transact` XCM instruction.
160    pub fn allow_base_call(call: &RuntimeCall) -> bool {
161        match call {
162            RuntimeCall::System(..)
163            | RuntimeCall::Identity(..)
164            | RuntimeCall::Balances(..)
165            | RuntimeCall::Vesting(..)
166            | RuntimeCall::DappStaking(..)
167            | RuntimeCall::Assets(..)
168            | RuntimeCall::Session(..)
169            | RuntimeCall::Proxy(
170                pallet_proxy::Call::add_proxy { .. }
171                | pallet_proxy::Call::remove_proxy { .. }
172                | pallet_proxy::Call::remove_proxies { .. }
173                | pallet_proxy::Call::create_pure { .. }
174                | pallet_proxy::Call::kill_pure { .. }
175                | pallet_proxy::Call::announce { .. }
176                | pallet_proxy::Call::remove_announcement { .. }
177                | pallet_proxy::Call::reject_announcement { .. },
178            )
179            | RuntimeCall::Multisig(
180                pallet_multisig::Call::approve_as_multi { .. }
181                | pallet_multisig::Call::cancel_as_multi { .. },
182            ) => true,
183            RuntimeCall::PolkadotXcm(call) => !matches!(
184                call,
185                pallet_xcm::Call::send { .. } | pallet_xcm::Call::execute { .. }
186            ),
187            _ => false,
188        }
189    }
190    /// Checks whether composite call is allowed to be executed via `Transact` XCM instruction.
191    ///
192    /// Each composite call's subcalls are checked against base call filter. No nesting of composite calls is allowed.
193    pub fn allow_composite_call(call: &RuntimeCall) -> bool {
194        match call {
195            RuntimeCall::Proxy(pallet_proxy::Call::proxy { call, .. }) => {
196                Self::allow_base_call(call)
197            }
198            RuntimeCall::Proxy(pallet_proxy::Call::proxy_announced { call, .. }) => {
199                Self::allow_base_call(call)
200            }
201            RuntimeCall::Utility(pallet_utility::Call::batch { calls, .. }) => {
202                calls.iter().all(|call| Self::allow_base_call(call))
203            }
204            RuntimeCall::Utility(pallet_utility::Call::batch_all { calls, .. }) => {
205                calls.iter().all(|call| Self::allow_base_call(call))
206            }
207            RuntimeCall::Utility(pallet_utility::Call::as_derivative { call, .. }) => {
208                Self::allow_base_call(call)
209            }
210            RuntimeCall::Multisig(pallet_multisig::Call::as_multi_threshold_1 { call, .. }) => {
211                Self::allow_base_call(call)
212            }
213            RuntimeCall::Multisig(pallet_multisig::Call::as_multi { call, .. }) => {
214                Self::allow_base_call(call)
215            }
216            _ => false,
217        }
218    }
219}
220
221impl Contains<RuntimeCall> for SafeCallFilter {
222    fn contains(call: &RuntimeCall) -> bool {
223        Self::allow_base_call(call) || Self::allow_composite_call(call)
224    }
225}
226
227pub type XcmBarrier = TrailingSetTopicAsId<(
228    TakeWeightCredit,
229    // Expected responses are OK.
230    AllowKnownQueryResponses<PolkadotXcm>,
231    // Allow XCMs with some computed origins to pass through.
232    WithComputedOrigin<
233        (
234            // If the message is one that immediately attempts to pay for execution, then allow it.
235            AllowTopLevelPaidExecutionFrom<Everything>,
236            // Subscriptions for version tracking are OK.
237            AllowSubscriptionsFrom<ParentRelayOrSiblingParachains>,
238        ),
239        UniversalLocation,
240        ConstU32<8>,
241    >,
242    // Parent and its plurality get free execution
243    AllowUnpaidExecutionFrom<ParentOrParentsPlurality>,
244)>;
245
246// Used to handle XCM fee deposit into treasury account
247pub type AstarXcmFungibleFeeHandler = XcmFungibleFeeHandler<AssetTransactors, TreasuryLocation>;
248
249pub struct XcmConfig;
250impl xcm_executor::Config for XcmConfig {
251    type RuntimeCall = RuntimeCall;
252    type XcmSender = XcmRouter;
253    type AssetTransactor = AssetTransactors;
254    type OriginConverter = XcmOriginToTransactDispatchOrigin;
255    type IsReserve = ReserveAssetFilter;
256    type IsTeleporter = ();
257    type UniversalLocation = UniversalLocation;
258    type Barrier = XcmBarrier;
259    type Weigher = Weigher;
260    type Trader = (
261        UsingComponents<XcmWeightToFee, AstarLocation, AccountId, Balances, DealWithFees>,
262        FixedRateOfForeignAsset<XcAssetConfig, AstarXcmFungibleFeeHandler>,
263    );
264    type ResponseHandler = PolkadotXcm;
265    type AssetTrap = PolkadotXcm;
266    type SubscriptionService = PolkadotXcm;
267
268    type PalletInstancesInfo = AllPalletsWithSystem;
269    type MaxAssetsIntoHolding = ConstU32<64>;
270    type AssetLocker = ();
271    type AssetExchanger = ();
272    type FeeManager = ();
273    type MessageExporter = ();
274    type UniversalAliases = Nothing;
275    type CallDispatcher = WithOriginFilter<SafeCallFilter>;
276    type SafeCallFilter = SafeCallFilter;
277    type Aliasers = Nothing;
278    type TransactionalProcessor = FrameTransactionalProcessor;
279
280    type HrmpNewChannelOpenRequestHandler = ();
281    type HrmpChannelAcceptedHandler = ();
282    type HrmpChannelClosingHandler = ();
283    type XcmRecorder = PolkadotXcm;
284    type XcmEventEmitter = PolkadotXcm;
285}
286
287/// Local origins on this chain are allowed to dispatch XCM sends/executions.
288pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
289
290/// The means for routing XCM messages which are not for local execution into the right message
291/// queues.
292pub type XcmRouter = WithUniqueTopic<(
293    // Two routers - use UMP to communicate with the relay chain:
294    cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
295    // ..and XCMP to communicate with the sibling chains.
296    XcmpQueue,
297)>;
298
299pub type Weigher =
300    WeightInfoBounds<weights::xcm::XcmWeight<Runtime, RuntimeCall>, RuntimeCall, MaxInstructions>;
301
302impl pallet_xcm::Config for Runtime {
303    const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
304
305    type RuntimeEvent = RuntimeEvent;
306    type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, ()>;
307    type XcmRouter = XcmRouter;
308    type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
309    type XcmExecuteFilter = Nothing;
310    type XcmExecutor = XcmExecutor<XcmConfig>;
311    type XcmTeleportFilter = Nothing;
312    type XcmReserveTransferFilter = Everything;
313    type Weigher = Weigher;
314    type UniversalLocation = UniversalLocation;
315    type RuntimeOrigin = RuntimeOrigin;
316    type RuntimeCall = RuntimeCall;
317    type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; // TODO:OR should we keep this at 2?
318
319    type Currency = Balances;
320    type CurrencyMatcher = ();
321    type TrustedLockers = ();
322    type SovereignAccountOf = LocationToAccountId;
323    type MaxLockers = ConstU32<0>;
324    type WeightInfo = weights::pallet_xcm::SubstrateWeight<Runtime>;
325    type MaxRemoteLockConsumers = ConstU32<0>;
326    type RemoteLockConsumerIdentifier = ();
327    type AdminOrigin = EnsureRoot<AccountId>;
328    type AuthorizedAliasConsideration = Disabled;
329}
330
331impl cumulus_pallet_xcm::Config for Runtime {
332    type RuntimeEvent = RuntimeEvent;
333    type XcmExecutor = XcmExecutor<XcmConfig>;
334}
335
336impl cumulus_pallet_xcmp_queue::Config for Runtime {
337    type RuntimeEvent = RuntimeEvent;
338    type ChannelInfo = ParachainSystem;
339    type VersionWrapper = PolkadotXcm;
340    type XcmpQueue = TransformOrigin<MessageQueue, AggregateMessageOrigin, ParaId, ParaIdToSibling>;
341    type MaxInboundSuspended = ConstU32<1_000>;
342    type MaxActiveOutboundChannels = ConstU32<128>;
343    type MaxPageSize = ConstU32<{ 128 * 1024 }>;
344    type ControllerOrigin = EnsureRoot<AccountId>;
345    type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
346    type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
347    type WeightInfo = cumulus_pallet_xcmp_queue::weights::SubstrateWeight<Runtime>;
348}