git.delta.rocks / unique-network / refs/commits / aa49f021671b

difftreelog

feat use pallet-configuration

Yaroslav Bolyukin2022-08-15parent: #a7efb3e.patch.diff
in: master

11 files changed

addedpallets/configuration/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/pallets/configuration/Cargo.toml
@@ -0,0 +1,33 @@
+[package]
+name = "pallet-configuration"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
+parity-scale-codec = { version = "3.1.5", features = [
+	"derive",
+], default-features = false }
+scale-info = { version = "2.0.1", default-features = false, features = [
+	"derive",
+] }
+frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+sp-runtime = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+sp-std = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+sp-core = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+sp-arithmetic = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.24" }
+fp-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.24" }
+smallvec = "1.6.1"
+
+[features]
+default = ["std"]
+std = [
+	"parity-scale-codec/std",
+	"frame-support/std",
+	"frame-system/std",
+	"sp-runtime/std",
+	"sp-std/std",
+	"sp-core/std",
+	"sp-arithmetic/std",
+	"fp-evm/std",
+]
addedpallets/configuration/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/configuration/src/lib.rs
@@ -0,0 +1,124 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use core::marker::PhantomData;
+
+use frame_support::{
+	pallet,
+	weights::{WeightToFeePolynomial, WeightToFeeCoefficients, WeightToFeeCoefficient},
+	traits::Get,
+};
+use sp_arithmetic::traits::{BaseArithmetic, Unsigned};
+use smallvec::smallvec;
+
+pub use pallet::*;
+use sp_core::U256;
+use sp_runtime::Perbill;
+
+#[pallet]
+mod pallet {
+	use super::*;
+	use frame_support::{
+		traits::Get,
+		pallet_prelude::{StorageValue, ValueQuery, DispatchResult},
+	};
+	use frame_system::{pallet_prelude::OriginFor, ensure_root};
+
+	#[pallet::config]
+	pub trait Config: frame_system::Config {
+		#[pallet::constant]
+		type DefaultWeightToFeeCoefficient: Get<u32>;
+		#[pallet::constant]
+		type DefaultMinGasPrice: Get<u64>;
+	}
+
+	#[pallet::storage]
+	pub type WeightToFeeCoefficientOverride<T: Config> = StorageValue<
+		Value = u32,
+		QueryKind = ValueQuery,
+		OnEmpty = T::DefaultWeightToFeeCoefficient,
+	>;
+
+	#[pallet::storage]
+	pub type MinGasPriceOverride<T: Config> =
+		StorageValue<Value = u64, QueryKind = ValueQuery, OnEmpty = T::DefaultMinGasPrice>;
+
+	#[pallet::call]
+	impl<T: Config> Pallet<T> {
+		#[pallet::weight(T::DbWeight::get().writes(1))]
+		pub fn set_weight_to_fee_coefficient_override(
+			origin: OriginFor<T>,
+			coeff: Option<u32>,
+		) -> DispatchResult {
+			let _sender = ensure_root(origin)?;
+			if let Some(coeff) = coeff {
+				<WeightToFeeCoefficientOverride<T>>::set(coeff);
+			} else {
+				<WeightToFeeCoefficientOverride<T>>::kill();
+			}
+			Ok(())
+		}
+
+		#[pallet::weight(T::DbWeight::get().writes(1))]
+		pub fn set_min_gas_price_override(
+			origin: OriginFor<T>,
+			coeff: Option<u64>,
+		) -> DispatchResult {
+			let _sender = ensure_root(origin)?;
+			if let Some(coeff) = coeff {
+				<MinGasPriceOverride<T>>::set(coeff);
+			} else {
+				<MinGasPriceOverride<T>>::kill();
+			}
+			Ok(())
+		}
+	}
+
+	#[pallet::pallet]
+	#[pallet::generate_store(pub(super) trait Store)]
+	pub struct Pallet<T>(_);
+}
+
+pub struct WeightToFee<T, B>(PhantomData<(T, B)>);
+
+impl<T, B> WeightToFeePolynomial for WeightToFee<T, B>
+where
+	T: Config,
+	B: BaseArithmetic + From<u32> + Copy + Unsigned,
+{
+	type Balance = B;
+
+	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
+		smallvec!(WeightToFeeCoefficient {
+			coeff_integer: <WeightToFeeCoefficientOverride<T>>::get().into(),
+			coeff_frac: Perbill::zero(),
+			negative: false,
+			degree: 1,
+		})
+	}
+}
+
+pub struct FeeCalculator<T>(PhantomData<T>);
+impl<T: Config> fp_evm::FeeCalculator for FeeCalculator<T> {
+	fn min_gas_price() -> (U256, u64) {
+		(
+			<MinGasPriceOverride<T>>::get().into(),
+			T::DbWeight::get().reads(1),
+		)
+	}
+}
modifiedprimitives/common/src/constants.rsdiffbeforeafterboth
--- a/primitives/common/src/constants.rs
+++ b/primitives/common/src/constants.rs
@@ -36,10 +36,10 @@
 pub const UNIQUE: Balance = 100 * CENTIUNIQUE;
 
 // Targeting 0.1 UNQ per transfer
-pub const WEIGHT_TO_FEE_COEFF: u32 = 207_890_902;
+pub const WEIGHT_TO_FEE_COEFF: u32 = /*<weight2fee>*/207_890_902/*</weight2fee>*/;
 
 // Targeting 0.15 UNQ per transfer via ETH
-pub const MIN_GAS_PRICE: u64 = 1_019_493_469_850;
+pub const MIN_GAS_PRICE: u64 = /*<mingasprice>*/1_019_493_469_850/*</mingasprice>*/;
 
 /// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.
 /// This is used to limit the maximal weight of a single extrinsic.
modifiedruntime/common/config/ethereum.rsdiffbeforeafterboth
--- a/runtime/common/config/ethereum.rs
+++ b/runtime/common/config/ethereum.rs
@@ -50,13 +50,6 @@
 	}
 }
 
-pub struct FixedFee;
-impl pallet_evm::FeeCalculator for FixedFee {
-	fn min_gas_price() -> (U256, u64) {
-		(MIN_GAS_PRICE.into(), 0)
-	}
-}
-
 pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);
 impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {
 	fn find_author<'a, I>(digests: I) -> Option<H160>
@@ -73,7 +66,7 @@
 
 impl pallet_evm::Config for Runtime {
 	type BlockGasLimit = BlockGasLimit;
-	type FeeCalculator = FixedFee;
+	type FeeCalculator = pallet_configuration::FeeCalculator<Self>;
 	type GasWeightMapping = FixedGasWeightMapping;
 	type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
 	type CallOrigin = EnsureAddressTruncated<Self>;
modifiedruntime/common/config/pallets/mod.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -25,6 +25,7 @@
 	},
 	Runtime, Event, Call, Balances,
 };
+use frame_support::traits::{ConstU32, ConstU64};
 use up_common::{
 	types::{AccountId, Balance, BlockNumber},
 	constants::*,
@@ -91,3 +92,8 @@
 	type CommonWeightInfo = CommonWeights<Self>;
 	type RefungibleExtensionsWeightInfo = CommonWeights<Self>;
 }
+
+impl pallet_configuration::Config for Runtime {
+	type DefaultWeightToFeeCoefficient = ConstU32<{ up_common::constants::WEIGHT_TO_FEE_COEFF }>;
+	type DefaultMinGasPrice = ConstU64<{ up_common::constants::MIN_GAS_PRICE }>;
+}
modifiedruntime/common/config/substrate.rsdiffbeforeafterboth
--- a/runtime/common/config/substrate.rs
+++ b/runtime/common/config/substrate.rs
@@ -18,8 +18,7 @@
 	traits::{Everything, ConstU32},
 	weights::{
 		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight},
-		DispatchClass, WeightToFeePolynomial, WeightToFeeCoefficients, ConstantMultiplier,
-		WeightToFeeCoefficient,
+		DispatchClass, ConstantMultiplier,
 	},
 	parameter_types, PalletId,
 };
@@ -32,8 +31,6 @@
 	limits::{BlockLength, BlockWeights},
 	EnsureRoot,
 };
-use sp_arithmetic::traits::{BaseArithmetic, Unsigned};
-use smallvec::smallvec;
 use crate::{
 	runtime_common::DealWithFees, Runtime, Event, Call, Origin, PalletInfo, System, Balances,
 	Treasury, SS58Prefix, Version,
@@ -154,32 +151,13 @@
 	/// This value increases the priority of `Operational` transactions by adding
 	/// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.
 	pub const OperationalFeeMultiplier: u8 = 5;
-}
-
-/// Linear implementor of `WeightToFeePolynomial`
-pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);
-
-impl<T> WeightToFeePolynomial for LinearFee<T>
-where
-	T: BaseArithmetic + From<u32> + Copy + Unsigned,
-{
-	type Balance = T;
-
-	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
-		smallvec!(WeightToFeeCoefficient {
-			coeff_integer: WEIGHT_TO_FEE_COEFF.into(),
-			coeff_frac: Perbill::zero(),
-			negative: false,
-			degree: 1,
-		})
-	}
 }
 
 impl pallet_transaction_payment::Config for Runtime {
 	type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;
 	type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
 	type OperationalFeeMultiplier = OperationalFeeMultiplier;
-	type WeightToFee = LinearFee<Balance>;
+	type WeightToFee = pallet_configuration::WeightToFee<Self, Balance>;
 	type FeeMultiplierUpdate = ();
 }
 
modifiedruntime/common/config/xcm.rsdiffbeforeafterboth
before · runtime/common/config/xcm.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use frame_support::{18	traits::{19		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get, Everything,20	},21	weights::{Weight, WeightToFeePolynomial, WeightToFee},22	parameter_types, match_types,23};24use frame_system::EnsureRoot;25use sp_runtime::{26	traits::{Saturating, CheckedConversion, Zero},27	SaturatedConversion,28};29use pallet_xcm::XcmPassthrough;30use polkadot_parachain::primitives::Sibling;31use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};32use xcm::latest::{33	AssetId::{Concrete},34	Fungibility::Fungible as XcmFungible,35	MultiAsset, Error as XcmError,36};37use xcm_executor::traits::{MatchesFungible, WeightTrader};38use xcm_builder::{39	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,40	FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser, RelayChainAsNative,41	SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,42	SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, ParentIsPreset,43};44use xcm_executor::{Config, XcmExecutor, Assets};45use sp_std::marker::PhantomData;46use crate::{47	runtime_common::config::substrate::LinearFee, Runtime, Call, Event, Origin, Balances,48	ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,49};50use up_common::{51	types::{AccountId, Balance},52	constants::*,53};5455parameter_types! {56	pub const RelayLocation: MultiLocation = MultiLocation::parent();57	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;58	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();59	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();60}6162/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used63/// when determining ownership of accounts for asset transacting and when attempting to use XCM64/// `Transact` in order to determine the dispatch Origin.65pub type LocationToAccountId = (66	// The parent (Relay-chain) origin converts to the default `AccountId`.67	ParentIsPreset<AccountId>,68	// Sibling parachain origins convert to AccountId via the `ParaId::into`.69	SiblingParachainConvertsVia<Sibling, AccountId>,70	// Straight up local `AccountId32` origins just alias directly to `AccountId`.71	AccountId32Aliases<RelayNetwork, AccountId>,72);7374pub struct OnlySelfCurrency;75impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {76	fn matches_fungible(a: &MultiAsset) -> Option<B> {77		match (&a.id, &a.fun) {78			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),79			_ => None,80		}81	}82}8384/// Means for transacting assets on this chain.85pub type LocalAssetTransactor = CurrencyAdapter<86	// Use this currency:87	Balances,88	// Use this currency when it is a fungible asset matching the given location or name:89	OnlySelfCurrency,90	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:91	LocationToAccountId,92	// Our chain's account ID type (we can't get away without mentioning it explicitly):93	AccountId,94	// We don't track any teleports.95	(),96>;9798/// No local origins on this chain are allowed to dispatch XCM sends/executions.99pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);100101/// The means for routing XCM messages which are not for local execution into the right message102/// queues.103pub type XcmRouter = (104	// Two routers - use UMP to communicate with the relay chain:105	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,106	// ..and XCMP to communicate with the sibling chains.107	XcmpQueue,108);109110/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,111/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can112/// biases the kind of local `Origin` it will become.113pub type XcmOriginToTransactDispatchOrigin = (114	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location115	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for116	// foreign chains who want to have a local sovereign account on this chain which they control.117	SovereignSignedViaLocation<LocationToAccountId, Origin>,118	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when119	// recognised.120	RelayChainAsNative<RelayOrigin, Origin>,121	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when122	// recognised.123	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,124	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a125	// transaction from the Root origin.126	ParentAsSuperuser<Origin>,127	// Native signed account converter; this just converts an `AccountId32` origin into a normal128	// `Origin::Signed` origin of the same 32-byte value.129	SignedAccountId32AsNative<RelayNetwork, Origin>,130	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.131	XcmPassthrough<Origin>,132);133134parameter_types! {135	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.136	pub UnitWeightCost: Weight = 1_000_000;137	// 1200 UNIQUEs buy 1 second of weight.138	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);139	pub const MaxInstructions: u32 = 100;140}141142match_types! {143	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {144		MultiLocation { parents: 1, interior: Here } |145		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }146	};147}148149pub type Barrier = (150	TakeWeightCredit,151	AllowTopLevelPaidExecutionFrom<Everything>,152	// ^^^ Parent & its unit plurality gets free execution153);154155pub struct UsingOnlySelfCurrencyComponents<156	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,157	AssetId: Get<MultiLocation>,158	AccountId,159	Currency: CurrencyT<AccountId>,160	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,161>(162	Weight,163	Currency::Balance,164	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,165);166impl<167		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,168		AssetId: Get<MultiLocation>,169		AccountId,170		Currency: CurrencyT<AccountId>,171		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,172	> WeightTrader173	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>174{175	fn new() -> Self {176		Self(0, Zero::zero(), PhantomData)177	}178179	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {180		let amount = WeightToFee::weight_to_fee(&weight);181		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;182183		// location to this parachain through relay chain184		let option1: xcm::v1::AssetId = Concrete(MultiLocation {185			parents: 1,186			interior: X1(Parachain(ParachainInfo::parachain_id().into())),187		});188		// direct location189		let option2: xcm::v1::AssetId = Concrete(MultiLocation {190			parents: 0,191			interior: Here,192		});193194		let required = if payment.fungible.contains_key(&option1) {195			(option1, u128_amount).into()196		} else if payment.fungible.contains_key(&option2) {197			(option2, u128_amount).into()198		} else {199			(Concrete(MultiLocation::default()), u128_amount).into()200		};201202		let unused = payment203			.checked_sub(required)204			.map_err(|_| XcmError::TooExpensive)?;205		self.0 = self.0.saturating_add(weight);206		self.1 = self.1.saturating_add(amount);207		Ok(unused)208	}209210	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {211		let weight = weight.min(self.0);212		let amount = WeightToFee::weight_to_fee(&weight);213		self.0 -= weight;214		self.1 = self.1.saturating_sub(amount);215		let amount: u128 = amount.saturated_into();216		if amount > 0 {217			Some((AssetId::get(), amount).into())218		} else {219			None220		}221	}222}223impl<224		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,225		AssetId: Get<MultiLocation>,226		AccountId,227		Currency: CurrencyT<AccountId>,228		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,229	> Drop230	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>231{232	fn drop(&mut self) {233		OnUnbalanced::on_unbalanced(Currency::issue(self.1));234	}235}236237pub struct XcmConfig;238impl Config for XcmConfig {239	type Call = Call;240	type XcmSender = XcmRouter;241	// How to withdraw and deposit an asset.242	type AssetTransactor = LocalAssetTransactor;243	type OriginConverter = XcmOriginToTransactDispatchOrigin;244	type IsReserve = NativeAsset;245	type IsTeleporter = (); // Teleportation is disabled246	type LocationInverter = LocationInverter<Ancestry>;247	type Barrier = Barrier;248	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;249	type Trader =250		UsingOnlySelfCurrencyComponents<LinearFee<Balance>, RelayLocation, AccountId, Balances, ()>;251	type ResponseHandler = (); // Don't handle responses for now.252	type SubscriptionService = PolkadotXcm;253254	type AssetTrap = PolkadotXcm;255	type AssetClaims = PolkadotXcm;256}257258impl pallet_xcm::Config for Runtime {259	type Event = Event;260	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;261	type XcmRouter = XcmRouter;262	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;263	type XcmExecuteFilter = Everything;264	type XcmExecutor = XcmExecutor<XcmConfig>;265	type XcmTeleportFilter = Everything;266	type XcmReserveTransferFilter = Everything;267	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;268	type LocationInverter = LocationInverter<Ancestry>;269	type Origin = Origin;270	type Call = Call;271	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;272	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;273}274275impl cumulus_pallet_xcm::Config for Runtime {276	type Event = Event;277	type XcmExecutor = XcmExecutor<XcmConfig>;278}279280impl cumulus_pallet_xcmp_queue::Config for Runtime {281	type WeightInfo = ();282	type Event = Event;283	type XcmExecutor = XcmExecutor<XcmConfig>;284	type ChannelInfo = ParachainSystem;285	type VersionWrapper = ();286	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;287	type ControllerOrigin = EnsureRoot<AccountId>;288	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;289}290291impl cumulus_pallet_dmp_queue::Config for Runtime {292	type Event = Event;293	type XcmExecutor = XcmExecutor<XcmConfig>;294	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;295}
after · runtime/common/config/xcm.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use frame_support::{18	traits::{19		tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Get, Everything,20	},21	weights::{Weight, WeightToFeePolynomial, WeightToFee},22	parameter_types, match_types,23};24use frame_system::EnsureRoot;25use sp_runtime::{26	traits::{Saturating, CheckedConversion, Zero},27	SaturatedConversion,28};29use pallet_xcm::XcmPassthrough;30use polkadot_parachain::primitives::Sibling;31use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};32use xcm::latest::{33	AssetId::{Concrete},34	Fungibility::Fungible as XcmFungible,35	MultiAsset, Error as XcmError,36};37use xcm_executor::traits::{MatchesFungible, WeightTrader};38use xcm_builder::{39	AccountId32Aliases, AllowTopLevelPaidExecutionFrom, CurrencyAdapter, EnsureXcmOrigin,40	FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser, RelayChainAsNative,41	SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative,42	SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, ParentIsPreset,43};44use xcm_executor::{Config, XcmExecutor, Assets};45use sp_std::marker::PhantomData;46use crate::{47	Runtime, Call, Event, Origin, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, XcmpQueue,48};49use up_common::{50	types::{AccountId, Balance},51	constants::*,52};5354parameter_types! {55	pub const RelayLocation: MultiLocation = MultiLocation::parent();56	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;57	pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();58	pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();59}6061/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used62/// when determining ownership of accounts for asset transacting and when attempting to use XCM63/// `Transact` in order to determine the dispatch Origin.64pub type LocationToAccountId = (65	// The parent (Relay-chain) origin converts to the default `AccountId`.66	ParentIsPreset<AccountId>,67	// Sibling parachain origins convert to AccountId via the `ParaId::into`.68	SiblingParachainConvertsVia<Sibling, AccountId>,69	// Straight up local `AccountId32` origins just alias directly to `AccountId`.70	AccountId32Aliases<RelayNetwork, AccountId>,71);7273pub struct OnlySelfCurrency;74impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {75	fn matches_fungible(a: &MultiAsset) -> Option<B> {76		match (&a.id, &a.fun) {77			(Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),78			_ => None,79		}80	}81}8283/// Means for transacting assets on this chain.84pub type LocalAssetTransactor = CurrencyAdapter<85	// Use this currency:86	Balances,87	// Use this currency when it is a fungible asset matching the given location or name:88	OnlySelfCurrency,89	// Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:90	LocationToAccountId,91	// Our chain's account ID type (we can't get away without mentioning it explicitly):92	AccountId,93	// We don't track any teleports.94	(),95>;9697/// No local origins on this chain are allowed to dispatch XCM sends/executions.98pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);99100/// The means for routing XCM messages which are not for local execution into the right message101/// queues.102pub type XcmRouter = (103	// Two routers - use UMP to communicate with the relay chain:104	cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,105	// ..and XCMP to communicate with the sibling chains.106	XcmpQueue,107);108109/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,110/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can111/// biases the kind of local `Origin` it will become.112pub type XcmOriginToTransactDispatchOrigin = (113	// Sovereign account converter; this attempts to derive an `AccountId` from the origin location114	// using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for115	// foreign chains who want to have a local sovereign account on this chain which they control.116	SovereignSignedViaLocation<LocationToAccountId, Origin>,117	// Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when118	// recognised.119	RelayChainAsNative<RelayOrigin, Origin>,120	// Native converter for sibling Parachains; will convert to a `SiblingPara` origin when121	// recognised.122	SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,123	// Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a124	// transaction from the Root origin.125	ParentAsSuperuser<Origin>,126	// Native signed account converter; this just converts an `AccountId32` origin into a normal127	// `Origin::Signed` origin of the same 32-byte value.128	SignedAccountId32AsNative<RelayNetwork, Origin>,129	// Xcm origins can be represented natively under the Xcm pallet's Xcm origin.130	XcmPassthrough<Origin>,131);132133parameter_types! {134	// One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.135	pub UnitWeightCost: Weight = 1_000_000;136	// 1200 UNIQUEs buy 1 second of weight.137	pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);138	pub const MaxInstructions: u32 = 100;139}140141match_types! {142	pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {143		MultiLocation { parents: 1, interior: Here } |144		MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }145	};146}147148pub type Barrier = (149	TakeWeightCredit,150	AllowTopLevelPaidExecutionFrom<Everything>,151	// ^^^ Parent & its unit plurality gets free execution152);153154pub struct UsingOnlySelfCurrencyComponents<155	WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,156	AssetId: Get<MultiLocation>,157	AccountId,158	Currency: CurrencyT<AccountId>,159	OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,160>(161	Weight,162	Currency::Balance,163	PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,164);165impl<166		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,167		AssetId: Get<MultiLocation>,168		AccountId,169		Currency: CurrencyT<AccountId>,170		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,171	> WeightTrader172	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>173{174	fn new() -> Self {175		Self(0, Zero::zero(), PhantomData)176	}177178	fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {179		let amount = WeightToFee::weight_to_fee(&weight);180		let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;181182		// location to this parachain through relay chain183		let option1: xcm::v1::AssetId = Concrete(MultiLocation {184			parents: 1,185			interior: X1(Parachain(ParachainInfo::parachain_id().into())),186		});187		// direct location188		let option2: xcm::v1::AssetId = Concrete(MultiLocation {189			parents: 0,190			interior: Here,191		});192193		let required = if payment.fungible.contains_key(&option1) {194			(option1, u128_amount).into()195		} else if payment.fungible.contains_key(&option2) {196			(option2, u128_amount).into()197		} else {198			(Concrete(MultiLocation::default()), u128_amount).into()199		};200201		let unused = payment202			.checked_sub(required)203			.map_err(|_| XcmError::TooExpensive)?;204		self.0 = self.0.saturating_add(weight);205		self.1 = self.1.saturating_add(amount);206		Ok(unused)207	}208209	fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {210		let weight = weight.min(self.0);211		let amount = WeightToFee::weight_to_fee(&weight);212		self.0 -= weight;213		self.1 = self.1.saturating_sub(amount);214		let amount: u128 = amount.saturated_into();215		if amount > 0 {216			Some((AssetId::get(), amount).into())217		} else {218			None219		}220	}221}222impl<223		WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,224		AssetId: Get<MultiLocation>,225		AccountId,226		Currency: CurrencyT<AccountId>,227		OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,228	> Drop229	for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>230{231	fn drop(&mut self) {232		OnUnbalanced::on_unbalanced(Currency::issue(self.1));233	}234}235236pub struct XcmConfig<T>(PhantomData<T>);237impl<T> Config for XcmConfig<T>238where239	T: pallet_configuration::Config,240{241	type Call = Call;242	type XcmSender = XcmRouter;243	// How to withdraw and deposit an asset.244	type AssetTransactor = LocalAssetTransactor;245	type OriginConverter = XcmOriginToTransactDispatchOrigin;246	type IsReserve = NativeAsset;247	type IsTeleporter = (); // Teleportation is disabled248	type LocationInverter = LocationInverter<Ancestry>;249	type Barrier = Barrier;250	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;251	type Trader = UsingOnlySelfCurrencyComponents<252		pallet_configuration::WeightToFee<T, Balance>,253		RelayLocation,254		AccountId,255		Balances,256		(),257	>;258	type ResponseHandler = (); // Don't handle responses for now.259	type SubscriptionService = PolkadotXcm;260261	type AssetTrap = PolkadotXcm;262	type AssetClaims = PolkadotXcm;263}264265impl pallet_xcm::Config for Runtime {266	type Event = Event;267	type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;268	type XcmRouter = XcmRouter;269	type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;270	type XcmExecuteFilter = Everything;271	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;272	type XcmTeleportFilter = Everything;273	type XcmReserveTransferFilter = Everything;274	type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;275	type LocationInverter = LocationInverter<Ancestry>;276	type Origin = Origin;277	type Call = Call;278	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;279	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;280}281282impl cumulus_pallet_xcm::Config for Runtime {283	type Event = Event;284	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;285}286287impl cumulus_pallet_xcmp_queue::Config for Runtime {288	type WeightInfo = ();289	type Event = Event;290	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;291	type ChannelInfo = ParachainSystem;292	type VersionWrapper = ();293	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;294	type ControllerOrigin = EnsureRoot<AccountId>;295	type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;296}297298impl cumulus_pallet_dmp_queue::Config for Runtime {299	type Event = Event;300	type XcmExecutor = XcmExecutor<XcmConfig<Self>>;301	type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;302}
modifiedruntime/common/construct_runtime/mod.rsdiffbeforeafterboth
--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -57,7 +57,7 @@
                 #[runtimes(opal)]
                 Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
 
-                // free = 63
+                Configuration: pallet_configuration::{Pallet, Call, Storage} = 63,
 
                 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,
                 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,
modifiedruntime/opal/Cargo.tomldiffbeforeafterboth
--- a/runtime/opal/Cargo.toml
+++ b/runtime/opal/Cargo.toml
@@ -87,6 +87,7 @@
     'parachain-info/std',
     'serde',
     'pallet-inflation/std',
+    'pallet-configuration/std',
     'pallet-common/std',
     'pallet-structure/std',
     'pallet-fungible/std',
@@ -414,6 +415,7 @@
 fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.24" }
 pallet-inflation = { path = '../../pallets/inflation', default-features = false }
 up-data-structs = { path = '../../primitives/data-structs', default-features = false }
+pallet-configuration = { default-features = false, path = "../../pallets/configuration" }
 pallet-common = { default-features = false, path = "../../pallets/common" }
 pallet-structure = { default-features = false, path = "../../pallets/structure" }
 pallet-fungible = { default-features = false, path = "../../pallets/fungible" }
modifiedruntime/quartz/Cargo.tomldiffbeforeafterboth
--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -87,6 +87,7 @@
     'parachain-info/std',
     'serde',
     'pallet-inflation/std',
+    'pallet-configuration/std',
     'pallet-common/std',
     'pallet-structure/std',
     'pallet-fungible/std',
@@ -418,6 +419,7 @@
 fp-evm-mapping = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.24" }
 pallet-inflation = { path = '../../pallets/inflation', default-features = false }
 up-data-structs = { path = '../../primitives/data-structs', default-features = false }
+pallet-configuration = { default-features = false, path = "../../pallets/configuration" }
 pallet-common = { default-features = false, path = "../../pallets/common" }
 pallet-structure = { default-features = false, path = "../../pallets/structure" }
 pallet-fungible = { default-features = false, path = "../../pallets/fungible" }
modifiedruntime/unique/Cargo.tomldiffbeforeafterboth
--- a/runtime/unique/Cargo.toml
+++ b/runtime/unique/Cargo.toml
@@ -88,6 +88,7 @@
     'parachain-info/std',
     'serde',
     'pallet-inflation/std',
+    'pallet-configuration/std',
     'pallet-common/std',
     'pallet-structure/std',
     'pallet-fungible/std',
@@ -411,6 +412,7 @@
 rmrk-rpc = { path = "../../primitives/rmrk-rpc", default-features = false }
 pallet-inflation = { path = '../../pallets/inflation', default-features = false }
 up-data-structs = { path = '../../primitives/data-structs', default-features = false }
+pallet-configuration = { default-features = false, path = "../../pallets/configuration" }
 pallet-common = { default-features = false, path = "../../pallets/common" }
 pallet-structure = { default-features = false, path = "../../pallets/structure" }
 pallet-fungible = { default-features = false, path = "../../pallets/fungible" }