#![cfg_attr(not(feature = "std"), no_std)] // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. #![recursion_limit = "256"] extern crate alloc; // Make the WASM binary available. #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use fp_rpc::TransactionStatus; use frame_system::{ limits::{BlockLength, BlockWeights}, EnsureRoot, EnsureSigned, EnsureWithSuccess, }; use sp_core::crypto::AccountId32; use address_unification::CallKillEVMLinkAccount; use inflation_manager::types::{InflationConfiguration, InflationParameters}; use address_unification::EVMAddressMapping; use cumulus_primitives_core::AggregateMessageOrigin; use pallet_ethereum::{Call::transact, PostLogContent, Transaction as EthereumTransaction}; use pallet_evm::{ Account as EVMAccount, EnsureAddressTruncated, FeeCalculator, GasWeightMapping, HashedAddressMapping, Runner, }; use parity_scale_codec::Encode; use peaq_pallet_did::{did::Did, structs::Attribute as DidAttribute}; use peaq_pallet_rbac::{ error::RbacError, rbac::{Group, Permission, Rbac, Result as RbacResult, Role}, structs::{ Entity as RbacEntity, Permission2Role as RbacPermission2Role, Role2Group as RbacRole2Group, Role2User as RbacRole2User, User2Group as RbacUser2Group, }, }; use peaq_pallet_storage::traits::Storage; use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; use sp_runtime::{generic::Preamble, traits::IdentityLookup}; use frame_support::traits::{ tokens::{fungible::HoldConsideration, PayFromAccount, UnityAssetBalanceConversion}, EqualPrivilegeOnly, LinearStoragePrice, }; use smallvec::smallvec; use sp_api::impl_runtime_apis; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H160, H256, U256}; use sp_runtime::{ generic, impl_opaque_keys, traits::{ AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, Convert, ConvertInto, DispatchInfoOf, Dispatchable, OpaqueKeys, PostDispatchInfoOf, SaturatedConversion, UniqueSaturatedInto, }, transaction_validity::{ InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError, }, ApplyExtrinsicResult, FixedPointNumber, Perbill, Percent, Permill, }; use sp_std::{borrow::Cow, marker::PhantomData, prelude::*, vec, vec::Vec}; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; use zenlink_protocol::{AssetBalance, MultiAssetsHandler, PairInfo, ZenlinkMultiAssets}; mod weights; pub mod xcm_config; // A few exports that help ease life for downstream crates. #[cfg(feature = "std")] pub use fp_evm::GenesisAccount; pub use frame_support::{ construct_runtime, dispatch::{DispatchClass, GetDispatchInfo}, parameter_types, traits::{ AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, Contains, Currency, EitherOfDiverse, EnsureOrigin, ExistenceRequirement, FindAuthor, Imbalance, KeyOwnerProofSystem, Nothing, OnFinalize, OnUnbalanced, Randomness, StorageInfo, WithdrawReasons, }, weights::{ constants::{ BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND, }, ConstantMultiplier, IdentityFee, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }, ConsensusEngineId, PalletId, StorageValue, }; pub use pallet_balances::Call as BalancesCall; pub use pallet_timestamp::Call as TimestampCall; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; mod precompiles; pub use precompiles::PeaqPrecompiles; pub type Precompiles = PeaqPrecompiles; use peaq_primitives_xcm::{ xcm::AssetLocationIdConverter, Address, AssetId as PeaqAssetId, AssetIdToEVMAddress, AssetIdToZenlinkId, Balance, EvmRevertCodeHandler, Header, Moment, Nonce, RbacEntityId, StorageAssetId, NATIVE_ASSET_ID, }; use peaq_rpc_primitives_txpool::TxPoolResponse; use zenlink_protocol::AssetId as ZenlinkAssetId; pub use peaq_pallet_did; pub use peaq_pallet_rbac; pub use peaq_pallet_storage; pub use peaq_pallet_transaction; // For Zenlink-DEX-Module use peaq_primitives_xcm::EVMAddressToAssetId; pub use precompiles::EVMAssetPrefix; use runtime_common::{ LocalAssetAdaptor, OnChargeEVMTransaction, OperationalFeeMultiplier, PeaqAssetZenlinkLpGenerate, PeaqMultiCurrenciesOnChargeTransaction, PeaqMultiCurrenciesPaymentConvert, PeaqMultiCurrenciesWrapper, PeaqNativeCurrencyWrapper, TransactionByteFee, CENTS, DOLLARS, MAX_POV_SIZE, MILLICENTS, }; /// An index to a block. type BlockNumber = peaq_primitives_xcm::BlockNumber; /// Alias to 512-bit hash when used in the context of a transaction signature on the chain. pub type Signature = peaq_primitives_xcm::Signature; /// Some way of identifying an account on the chain. We intentionally make it equivalent /// to the public key of our transaction signing scheme. pub type AccountId = peaq_primitives_xcm::AccountId; /// The type for looking up accounts. We don't expect more than 4 billion of them, but you /// never know... // type AccountIndex = peaq_primitives_xcm::AccountIndex; /// A hash of some data used by the chain. type Hash = peaq_primitives_xcm::Hash; /// Block type as expected by this runtime. /// Note: this is really wild! You can define it here, but not in peaq_primitives_xcm...?! pub type Block = generic::Block; /// Maximum number of blocks simultaneously accepted by the Runtime, not yet included into the /// relay chain. pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3; /// How many parachain blocks are processed by the relay chain per parent. Limits the number of /// blocks authored per slot. pub const BLOCK_PROCESSING_VELOCITY: u32 = 1; /// Relay chain slot duration, in milliseconds. pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000; pub type PeaqAssetLocationIdConverter = AssetLocationIdConverter; // Implementation from Moonbeam /// peaq, the native token, uses 18 decimals of precision. pub mod currency { use super::Balance; // Provide a common factor between runtimes based on a supply of 10_000_000 tokens. pub const SUPPLY_FACTOR: Balance = 100; pub const WEI: Balance = 1; pub const KILOWEI: Balance = 1_000; pub const MEGAWEI: Balance = 1_000_000; pub const GIGAWEI: Balance = 1_000_000_000; pub const MICROPEAQ: Balance = 1_000_000_000_000; pub const MILLIPEAQ: Balance = 1_000_000_000_000_000; pub const PEAQ: Balance = 1_000_000_000_000_000_000; pub const KILOPEAQ: Balance = 1_000_000_000_000_000_000_000; pub const TRANSACTION_BYTE_FEE: Balance = GIGAWEI * SUPPLY_FACTOR; pub const STORAGE_BYTE_FEE: Balance = 100 * MICROPEAQ * SUPPLY_FACTOR; pub const WEIGHT_FEE: Balance = 400 * KILOWEI * SUPPLY_FACTOR; // pub const fn deposit(items: u32, bytes: u32) -> Balance { // items as Balance * 100 * MILLIPEAQ * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE // } } /// Opaque types. These are used by the CLI to instantiate machinery that don't need to know /// the specifics of the runtime. They can then be made to be agnostic over specific formats /// of data like extrinsics, allowing for them to continue syncing the network through upgrades /// to even the core data structures. pub mod opaque { use super::*; impl_opaque_keys! { pub struct SessionKeys { pub aura: Aura, } } } // To learn more about runtime versioning and what each of the following value means: // https://docs.substrate.io/v3/runtime/origins#runtime-versioning #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: Cow::Borrowed("peaq-node"), impl_name: Cow::Borrowed("peaq-node"), authoring_version: 1, // The version of the runtime specification. A full node will not attempt to use its native // runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`, // `spec_version`, and `authoring_version` are the same between Wasm and native. // This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use // the compatible custom types. spec_version: 113, impl_version: 1, apis: RUNTIME_API_VERSIONS, transaction_version: 2, system_version: 1, }; /// This determines the average expected block time that we are targeting. /// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`. /// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked /// up by `pallet_aura` to implement `fn slot_duration()`. /// /// Change this to adjust the block time. pub const MILLISECS_PER_BLOCK: u64 = 6000; // NOTE: Currently it is not possible to change the slot duration after the chain has started. // Attempting to do so will brick block production. pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; // Time is measured by number of blocks. pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); pub const HOURS: BlockNumber = MINUTES * 60; pub const DAYS: BlockNumber = HOURS * 24; /// Charge fee for stored bytes and items as part of `pallet-contracts`. /// /// The slight difference to general `deposit` function is because there is fixed bound on how large /// the DB key can grow so it doesn't make sense to have as high deposit per item as in the general /// approach. const fn contracts_deposit(items: u32, bytes: u32) -> Balance { items as Balance * 40 * MILLICENTS + (bytes as Balance) * MILLICENTS } /// The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } } /// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is /// used to limit the maximal weight of a single extrinsic. const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5); /// We allow `Normal` extrinsics to fill up the block up to 90%, the rest can be used by /// `Operational` extrinsics. const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(90); /// We allow for 0.5 of a second of compute with a 12 second average block time. const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2_u64), MAX_POV_SIZE as u64); /// Base Deposit for occupying storage - 0.01 PEAQ const STORAGE_DEPOSIT_BASE: Balance = CENTS; /// Deposit per byte for occupying storage - 0.001 PEAQ const STORAGE_DEPOSIT_PER_BYTE: Balance = CENTS / 10; parameter_types! { pub const Version: RuntimeVersion = VERSION; // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`. // The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize // the lazy contract deletion. pub RuntimeBlockLength: BlockLength = BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() // Explicit setup the block weights for the runtime. .base_block(BlockExecutionWeight::get()) .for_class(DispatchClass::all(), |weights| { weights.base_extrinsic = ExtrinsicBaseWeight::get(); }) .for_class(DispatchClass::Normal, |weights| { weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); }) .for_class(DispatchClass::Operational, |weights| { weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); // Operational transactions have some extra reserved space, so that they // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. weights.reserved = Some( MAXIMUM_BLOCK_WEIGHT - (NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT) ); }) .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) .build_or_panic(); pub const SS58Prefix: u16 = 42; pub const StorageDepositBase: Balance = STORAGE_DEPOSIT_BASE; pub const StorageDepositPerByte: Balance = STORAGE_DEPOSIT_PER_BYTE; } pub struct BaseFilter; impl Contains for BaseFilter { fn contains(call: &RuntimeCall) -> bool { match call { // Filter permission-less assets creation/destroying. // Custom asset's `id` should fit in `u32` as not to mix with service assets. RuntimeCall::Assets(pallet_assets::Call::create { id, .. }) => match >::try_into(*id) { Ok(id) => id.is_allow_to_create(), Err(_) => false, }, // These modules are not allowed to be called by transactions: // To leave collator just shutdown it, next session funds will be released // Other modules should works: _ => true, } } } // Configure FRAME pallets to include in runtime. impl frame_system::Config for Runtime { type Nonce = Nonce; type Block = Block; /// The basic call filter to use in dispatchable. type BaseCallFilter = BaseFilter; /// Block & extrinsics weights: base values and limits. type BlockWeights = RuntimeBlockWeights; /// The maximum length of a block (in bytes). type BlockLength = RuntimeBlockLength; /// The identifier used to distinguish between accounts. type AccountId = AccountId; /// The aggregated dispatch type that is available for extrinsics. type RuntimeCall = RuntimeCall; /// The lookup mechanism to get account ID from whatever is passed in dispatchers. type Lookup = (AccountIdLookup, AddressUnification); /// The type for hashing blocks and tries. type Hash = Hash; /// The hashing algorithm used. type Hashing = BlakeTwo256; /// The ubiquitous event type. type RuntimeEvent = RuntimeEvent; /// The ubiquitous origin type. type RuntimeOrigin = RuntimeOrigin; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; /// The weight of database operations that the runtime can invoke. type DbWeight = RocksDbWeight; /// Version of the runtime. type Version = Version; /// Converts a module to the index of the module in `construct_runtime!`. /// /// This type is being generated by `construct_runtime!`. type PalletInfo = PalletInfo; /// What to do if a new account is created. type OnNewAccount = (); /// What to do if an account is fully reaped from the system. type OnKilledAccount = (CallKillEVMLinkAccount,); /// The data to be stored in an account. type AccountData = pallet_balances::AccountData; /// Weight information for the extrinsics of this pallet. type SystemWeightInfo = (); /// This is used as an identifier of the chain. 42 is the generic substrate prefix. type SS58Prefix = SS58Prefix; type MaxConsumers = frame_support::traits::ConstU32<16>; type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; type RuntimeTask = RuntimeTask; type ExtensionsWeightInfo = (); type MultiBlockMigrator = (); type SingleBlockMigrations = (); type PostInherents = (); type PreInherents = (); type PostTransactions = (); } impl pallet_aura::Config for Runtime { type AuthorityId = AuraId; type DisabledValidators = (); type MaxAuthorities = staking::MaxCollatorCandidates; // Should be only enabled (`true`) when async backing is enabled // otherwise set to `false` type AllowMultipleBlocksPerSlot = ConstBool; type SlotDuration = ConstU64; } // For ink parameter_types! { pub const DepositPerItem: Balance = contracts_deposit(1, 0); pub const DepositPerByte: Balance = contracts_deposit(0, 1); pub const DefaultDepositLimit: Balance = contracts_deposit(16, 16 * 1024); pub const MaxValueSize: u32 = 16 * 1024; // The lazy deletion runs inside on_initialize. pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO * RuntimeBlockWeights::get().max_block; pub const DeletionQueueDepth: u32 = 128; pub Schedule: pallet_contracts::Schedule = pallet_contracts::Schedule { limits: pallet_contracts::Limits { payload_len: 12 * 1024, // Reduced from 16KB to 12KB to meet storage limit with 90% dispatch ratio ..Default::default() }, ..Default::default() }; pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(30); // TODO: re-vist to make sure values are appropriate pub const MaxDelegateDependencies: u32 = 32; } impl pallet_contracts::Config for Runtime { type Time = Timestamp; type Randomness = RandomnessCollectiveFlip; type Currency = Balances; type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; /// The safest default is to allow no calls at all. /// /// Runtimes should whitelist dispatchables that are allowed to be called from contracts /// and make sure they are stable. Dispatchables exposed to contracts are not allowed to /// change because that would break already deployed contracts. The `Call` structure itself /// is not allowed to change the indices of existing pallets, too. type CallFilter = Nothing; type DepositPerItem = DepositPerItem; type DepositPerByte = DepositPerByte; type WeightPrice = pallet_transaction_payment::Pallet; type WeightInfo = pallet_contracts::weights::SubstrateWeight; type ChainExtension = (); type Schedule = Schedule; type CallStack = [pallet_contracts::Frame; 5]; type AddressGenerator = pallet_contracts::DefaultAddressGenerator; type MaxStorageKeyLen = ConstU32<128>; type MaxCodeLen = ConstU32<{ 123 * 1024 }>; type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>; type UnsafeUnstableInterface = ConstBool; type DefaultDepositLimit = DefaultDepositLimit; type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; type MaxDelegateDependencies = MaxDelegateDependencies; type RuntimeHoldReason = RuntimeHoldReason; type Migrations = (pallet_contracts::migration::v16::Migration,); type Debug = (); type Environment = (); type Xcm = (); type ApiVersion = (); type InstantiateOrigin = EnsureSigned<::AccountId>; type MaxTransientStorageSize = ConstU32<{ 1024 * 1024 }>; type UploadOrigin = EnsureSigned<::AccountId>; } parameter_types! { pub const MinimumPeriod: u64 = SLOT_DURATION / 2; } impl pallet_timestamp::Config for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = Moment; type MinimumPeriod = ConstU64<0>; type WeightInfo = (); type OnTimestampSet = (Aura, BlockReward); } parameter_types! { pub const ExistentialDeposit: u128 = 0; pub const MaxLocks: u32 = 50; pub const MaxReserves: u32 = 50; pub const DIDReserveIdentifier: [u8; 8] = [b'p', b'e', b'a', b'q', b'_', b'd', b'i', b'd']; pub const StorageReserveIdentifier: [u8; 8] = [b'p', b'e', b'a', b'q', b's', b't', b'o', b'r']; pub const RBACReserveIdentifier: [u8; 8] = [b'p', b'e', b'a', b'q', b'r', b'b', b'a', b'c']; } impl pallet_balances::Config for Runtime { type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; /// The type for recording an account's balance. type Balance = Balance; /// The ubiquitous event type. type RuntimeEvent = RuntimeEvent; type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; type WeightInfo = (); type FreezeIdentifier = (); type MaxFreezes = (); type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type DoneSlashHandler = (); } parameter_types! { pub const WeightFeeFactor: Balance = 1_745_500_000_000_000; // Around 0.002 peaq per unit of ref time. pub const EoTFeeFactor: Perbill = Perbill::from_percent(0); } /// Handles converting a weight scalar to a fee value, based on the scale and granularity of the /// node's balance type. /// /// This should typically create a mapping between the following ranges: /// - `[0, MAXIMUM_BLOCK_WEIGHT]` /// - `[Balance::min, Balance::max]` /// /// Yet, it can be used for any other sort of change to weight-fee. Some examples being: /// - Setting it to `0` will essentially disable the weight fee. /// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged. pub struct WeightToFee; impl WeightToFeePolynomial for WeightToFee { type Balance = Balance; fn polynomial() -> WeightToFeeCoefficients { let p = WeightFeeFactor::get(); let q = Balance::from(ExtrinsicBaseWeight::get().ref_time()); smallvec![WeightToFeeCoefficient { degree: 1, negative: false, coeff_frac: Perbill::from_rational(p % q, q), coeff_integer: p / q, }] } } type NegativeImbalance = >::NegativeImbalance; parameter_types! { // [TODO] Should have a way to increase it without doing runtime upgrade pub PcpcLocalAccepted: Vec = vec![ PeaqAssetId::Token(1).try_into().unwrap(), ]; } pub struct PeaqCPC; impl PeaqMultiCurrenciesPaymentConvert for PeaqCPC { type AccountId = AccountId; type Currency = Balances; type MultiCurrency = PeaqMultiCurrencies; type DexOperator = ZenlinkProtocol; type ExistentialDeposit = ExistentialDeposit; type NativeAssetId = GetNativeAssetId; type LocalAcceptedIds = PcpcLocalAccepted; type AssetId = StorageAssetId; type AssetIdToZenlinkId = AssetIdToZenlinkId; } impl pallet_transaction_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; type OnChargeTransaction = PeaqMultiCurrenciesOnChargeTransaction; type OperationalFeeMultiplier = OperationalFeeMultiplier; type WeightToFee = WeightToFee; type LengthToFee = ConstantMultiplier; type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; type WeightInfo = (); } impl pallet_sudo::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type WeightInfo = pallet_sudo::weights::SubstrateWeight; } parameter_types! { pub const DidStorageDepositBase: Balance = MILLICENTS * 500; pub const DidStorageDepositPerByte: Balance = 0; } /// Config the did in pallets/did impl peaq_pallet_did::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Time = pallet_timestamp::Pallet; type WeightInfo = peaq_pallet_did::weights::WeightInfo; type Currency = Balances; type StorageDepositBase = DidStorageDepositBase; type StorageDepositPerByte = DidStorageDepositPerByte; type ReserveIdentifier = DIDReserveIdentifier; } /// Config the utility in pallets/utility impl pallet_utility::Config for Runtime { type RuntimeCall = RuntimeCall; type RuntimeEvent = RuntimeEvent; type PalletsOrigin = OriginCaller; type WeightInfo = (); } parameter_types! { pub const CouncilMotionDuration: BlockNumber = 5 * DAYS; pub const CouncilMaxProposals: u32 = 100; pub const CouncilMaxMembers: u32 = 100; pub MaxProposalWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block; } type CouncilCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = CouncilMotionDuration; type MaxProposals = CouncilMaxProposals; type MaxMembers = CouncilMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type WeightInfo = pallet_collective::weights::SubstrateWeight; type SetMembersOrigin = EnsureRoot; type MaxProposalWeight = MaxProposalWeight; type DisapproveOrigin = EnsureRoot; type Consideration = (); type KillOrigin = EnsureRoot; } // Config the treasyry in pallets/treasury parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub const ProposalBondMinimum: Balance = DOLLARS; pub const SpendPeriod: BlockNumber = DAYS; pub const Burn: Permill = Permill::from_percent(0); pub const TipCountdown: BlockNumber = DAYS; pub const TipFindersFee: Percent = Percent::from_percent(20); pub const TipReportDepositBase: Balance = DOLLARS; pub const DataDepositPerByte: Balance = CENTS; pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub const MaximumReasonLength: u32 = 300; pub const MaxApprovals: u32 = 100; pub const MaxBalance: Balance = Balance::MAX; } type RootOrTreasuryCouncilOrigin = EitherOfDiverse< EnsureRoot, pallet_collective::EnsureProportionMoreThan, >; // Treasury spends require root or a council 3/5 supermajority. The stable2503 // base gated this at council >1/2; deliberately tightened to 3/5 here. // RejectOrigin is intentionally left at the looser >1/2. type RootOrTreasuryCouncilSpendOrigin = EitherOfDiverse< EnsureRoot, pallet_collective::EnsureProportionAtLeast, >; impl pallet_treasury::Config for Runtime { type PalletId = TreasuryPalletId; type Currency = Balances; type RejectOrigin = RootOrTreasuryCouncilOrigin; type SpendPeriod = SpendPeriod; type Burn = Burn; type BurnDestination = (); type SpendFunds = (); type WeightInfo = pallet_treasury::weights::SubstrateWeight; type MaxApprovals = MaxApprovals; type SpendOrigin = EnsureWithSuccess; type RuntimeEvent = RuntimeEvent; type AssetKind = (); type Beneficiary = AccountId; type BeneficiaryLookup = IdentityLookup; type Paymaster = PayFromAccount; type BalanceConverter = UnityAssetBalanceConversion; type PayoutPeriod = ConstU32<{ 30 * DAYS }>; type BlockNumberProvider = System; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } // Pallet EVM pub struct FindAuthorTruncated(PhantomData); impl> FindAuthor for FindAuthorTruncated { fn find_author<'a, I>(digests: I) -> Option where I: 'a + IntoIterator, { if let Some(author_index) = F::find_author(digests) { let authority_id = pallet_aura::Authorities::::get()[author_index as usize].clone(); let encoded = authority_id.encode(); let bytes: [u8; 32] = encoded.try_into().expect("Encoded authority_id should be exactly 32 bytes"); let sub_addr = AccountId32::from(bytes); let evm_addr = AddressUnification::get_evm_address_or_default(&sub_addr); if AddressUnification::is_linked(&sub_addr, &evm_addr) { return Some(evm_addr); } else { // Return withdrawable addr return Some(H160::from_slice(&sub_addr.encode()[0..20])); } } None } } /// Current approximation of the gas/s consumption considering /// EVM execution over compiled WASM (on 4.4Ghz CPU). /// Given the 2s Weight, from which 90% only are used for transactions, /// the total EVM execution gas limit is: GAS_PER_SECOND * 2.0 * 0.90 ~= 72_000_000. pub const GAS_PER_SECOND: u64 = 40_000_000; /// Approximate ratio of the amount of Weight per Gas. /// u64 works for approximations because Weight is a very small unit compared to gas. pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND.saturating_div(GAS_PER_SECOND); parameter_types! { pub const EvmChainId: u64 = 3338; pub BlockGasLimit: U256 = U256::from( NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS ); pub PrecompilesValue: PeaqPrecompiles = PeaqPrecompiles::<_>::new(); pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0); /// The amount of gas per pov. A ratio of 4 if we convert ref_time to gas and we compare /// it with the pov_size for a block. E.g. /// ceil( /// (max_extrinsic.ref_time() / max_extrinsic.proof_size()) / WEIGHT_PER_GAS /// ) /// = ceil(max_gas_limit / max_extrinsic.proof_size()) /// = ceil(BlockGasLimit / (NORMAL_DISPATCH_RATIO * MAX_POV_SIZE)) /// = 4 pub const GasLimitPovSizeRatio: u64 = 4; /// In moonbeam, they setup as 366 and follow below formula: /// The amount of gas per storage (in bytes): BLOCK_GAS_LIMIT / BLOCK_STORAGE_LIMIT /// (15_000_000 / 40kb) /// However, let us setup the value as 1 for now because we also has the did/storage bridge /// [TODO] Need to check pub GasLimitStorageGrowthRatio: u64 = 1; } pub struct TransactionPaymentAsGasPrice; impl FeeCalculator for TransactionPaymentAsGasPrice { fn min_gas_price() -> (U256, Weight) { // note: transaction-payment differs from EIP-1559 in that its tip and length fees are not // scaled by the multiplier, which means its multiplier will be overstated when // applied to an ethereum transaction // note: transaction-payment uses both a congestion modifier (next_fee_multiplier, which is // updated once per block in on_finalize) and a 'WeightToFee' implementation. Our // runtime implements this as a 'ConstantModifier', so we can get away with a simple // multiplication here. // It is imperative that `saturating_mul_int` be performed as late as possible in the // expression since it involves fixed point multiplication with a division by a fixed // divisor. This leads to truncation and subsequent precision loss if performed too early. // This can lead to min_gas_price being same across blocks even if the multiplier changes. // There's still some precision loss when the final `gas_price` (used_gas * min_gas_price) // is computed in frontier, but that's currently unavoidable. let min_gas_price = TransactionPayment::next_fee_multiplier() .saturating_mul_int(currency::WEIGHT_FEE.saturating_mul(WEIGHT_PER_GAS as u128)); (min_gas_price.into(), ::DbWeight::get().reads(1)) } } impl pallet_evm::Config for Runtime { type FeeCalculator = TransactionPaymentAsGasPrice; type WeightPerGas = WeightPerGas; type GasWeightMapping = pallet_evm::FixedGasWeightMapping; type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping; type CallOrigin = EnsureAddressTruncated; type WithdrawOrigin = EnsureAddressTruncated; type AddressMapping = AddressUnification; type Currency = Balances; type RuntimeEvent = RuntimeEvent; type Runner = pallet_evm::runner::stack::Runner; type PrecompilesType = Precompiles; type PrecompilesValue = PrecompilesValue; type ChainId = EvmChainId; type BlockGasLimit = BlockGasLimit; type OnChargeTransaction = OnChargeEVMTransaction; type OnCreate = (); type FindAuthor = FindAuthorTruncated; type GasLimitPovSizeRatio = GasLimitPovSizeRatio; type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio; type Timestamp = Timestamp; type WeightInfo = crate::weights::pallet_evm::WeightInfo; type AccountProvider = pallet_evm::FrameSystemAccountProvider; type CreateInnerOriginFilter = (); type CreateOriginFilter = (); } parameter_types! { pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; } impl pallet_ethereum::Config for Runtime { type RuntimeEvent = RuntimeEvent; type StateRoot = pallet_ethereum::IntermediateStateRoot<::Version>; type PostLogContent = PostBlockAndTxnHashes; type ExtraDataLength = ConstU32<30>; } impl pallet_insecure_randomness_collective_flip::Config for Runtime {} // Parachain parameter_types! { pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4_u64); pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4_u64); pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; } impl cumulus_pallet_parachain_system::Config for Runtime { type RuntimeEvent = RuntimeEvent; type OnSystemEvent = (); type SelfParaId = parachain_info::Pallet; type OutboundXcmpMessageSource = XcmpQueue; type DmpQueue = frame_support::traits::EnqueueWithOrigin; type ReservedDmpWeight = ReservedDmpWeight; type XcmpMessageHandler = XcmpQueue; type ReservedXcmpWeight = ReservedXcmpWeight; type ConsensusHook = ConsensusHook; type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases; type WeightInfo = (); type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector; } type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< Runtime, RELAY_CHAIN_SLOT_DURATION_MILLIS, BLOCK_PROCESSING_VELOCITY, UNINCLUDED_SEGMENT_CAPACITY, >; impl parachain_info::Config for Runtime {} impl cumulus_pallet_aura_ext::Config for Runtime {} parameter_types! { pub const AssetAdminId: PalletId = PalletId(*b"AssetAdm"); pub const PotStakeId: PalletId = PalletId(*b"PotStake"); pub const PotTreasuryId: PalletId = TreasuryPalletId::get(); pub const PotCoretimeId: PalletId = PalletId(*b"PotCoret"); pub const PotSubsidizationId: PalletId = PalletId(*b"PotSubsi"); pub const PotDepinStakingId: PalletId = PalletId(*b"PotDPStk"); pub const PotDepinIncentivisationId: PalletId = PalletId(*b"PotDPInc"); } impl pallet_authorship::Config for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex; type EventHandler = ParachainStaking; } impl pallet_session::Config for Runtime { type RuntimeEvent = RuntimeEvent; type ValidatorId = ::AccountId; type ValidatorIdOf = ConvertInto; type ShouldEndSession = ParachainStaking; type NextSessionRotation = ParachainStaking; type SessionManager = ParachainStaking; type SessionHandler = ::KeyTypeIdProviders; type Keys = opaque::SessionKeys; type WeightInfo = pallet_session::weights::SubstrateWeight; type DisablingStrategy = (); } pub mod staking { use super::*; pub const MAX_COLLATOR_STAKE: Balance = 10_000 * MinCollatorStake::get(); parameter_types! { /// Minimum round length is 1 hour pub const MinBlocksPerRound: BlockNumber = HOURS; /// Default length of a round/session is 4 hours pub const DefaultBlocksPerRound: BlockNumber = 4 * HOURS; /// Unstaked balance can be unlocked after 7 days pub const StakeDuration: BlockNumber = 14 * DAYS; /// Collator exit requests are delayed by 4 hours (2 rounds/sessions) pub const ExitQueueDelay: u32 = 2; /// Minimum 4 collators selected per round, default at genesis and minimum forever after pub const MinCollators: u32 = 4; /// At least 4 candidates which cannot leave the network if there are no other candidates. pub const MinRequiredCollators: u32 = 4; /// We only allow one delegation per round. pub const MaxDelegationsPerRound: u32 = 1; /// Maximum number of delegators per collator at launch #[derive(Debug, PartialEq, Eq)] pub const MaxDelegatorsPerCollator: u32 = 100; /// Maximum 8 collators per delegator at launch, will be increased later #[derive(Debug, PartialEq, Eq)] pub const MaxCollatorsPerDelegator: u32 = 8; /// Minimum stake required to be reserved to be a collator is 50_000 * DOLLARS pub const MinCollatorStake: Balance = 50_000 * DOLLARS; /// Minimum stake required to be reserved to be a delegator is 100 * DOLLARS pub const MinDelegatorStake: Balance = 100 * DOLLARS; /// Maximum number of collator candidates #[derive(Debug, PartialEq, Eq)] pub const MaxCollatorCandidates: u32 = 64; /// Maximum number of concurrent requests to unlock unstaked balance pub const MaxUnstakeRequests: u32 = 10; } } impl parachain_staking::Config for Runtime { type PotId = PotStakeId; type RuntimeEvent = RuntimeEvent; type Currency = Balances; type CurrencyBalance = Balance; type MinBlocksPerRound = staking::MinBlocksPerRound; type DefaultBlocksPerRound = staking::DefaultBlocksPerRound; type StakeDuration = staking::StakeDuration; type ExitQueueDelay = staking::ExitQueueDelay; type MinCollators = staking::MinCollators; type MinRequiredCollators = staking::MinRequiredCollators; type MaxDelegationsPerRound = staking::MaxDelegationsPerRound; type MaxDelegatorsPerCollator = staking::MaxDelegatorsPerCollator; type MaxCollatorsPerDelegator = staking::MaxCollatorsPerDelegator; type MinCollatorStake = staking::MinCollatorStake; type MinCollatorCandidateStake = staking::MinCollatorStake; type MaxTopCandidates = staking::MaxCollatorCandidates; type MinDelegation = staking::MinDelegatorStake; type MinDelegatorStake = staking::MinDelegatorStake; type MaxUnstakeRequests = staking::MaxUnstakeRequests; type WeightInfo = parachain_staking::weights::WeightInfo; } /// Sinks adopted by `migrations::v3::MigrateToV3x` when it finds the legacy, /// pre-Sinks fixed distribution config on chain, and the default genesis sinks for /// fresh `--chain peaq-local` networks (see `node/src/parachain/peaq_chain_spec.rs`). /// Only treasury and parachain-staking survive the migration here, with a new split /// -- everything the legacy config used to send to coretime/subsidization/DePIN /// pots now goes to treasury instead. /// /// A `const` array (not a `parameter_types!` `Vec` literal) so the 100%-sum /// invariant can be, and is, checked at compile time below. const BLOCK_REWARD_SINKS: [pallet_block_reward::Sink; 2] = [ pallet_block_reward::block_reward_sink!(PotTreasuryId, 70), pallet_block_reward::block_reward_sink!(PotStakeId, 30), ]; const _: () = assert!( pallet_block_reward::is_complete_distribution(&BLOCK_REWARD_SINKS), "BLOCK_REWARD_SINKS must sum to exactly 100% with no zero shares" ); parameter_types! { /// Upper bound on the number of configurable block-reward token sinks. pub const MaxBlockRewardSinks: u32 = 8; pub BlockRewardMigrationSinks: sp_std::vec::Vec = BLOCK_REWARD_SINKS.to_vec(); } /// Maps an EVM address to a Substrate `AccountId`, reusing the same hashing scheme /// already used to unify EVM and native accounts elsewhere in this runtime. pub struct BlockRewardAddressMapping; impl pallet_block_reward::AddressMapping for BlockRewardAddressMapping { fn into_account_id(address: H160) -> AccountId { as pallet_evm::AddressMapping>::into_account_id( address, ) } } impl pallet_block_reward::Config for Runtime { type AddressMapping = BlockRewardAddressMapping; type Currency = Balances; type MaxSinks = MaxBlockRewardSinks; type MigrationSinks = BlockRewardMigrationSinks; type RuntimeEvent = RuntimeEvent; type WeightInfo = pallet_block_reward::weights::WeightInfo; } parameter_types! { pub const GetNativeAssetId: StorageAssetId = NATIVE_ASSET_ID; } pub fn get_all_module_accounts() -> Vec { vec![ PotStakeId::get().into_account_truncating(), PotTreasuryId::get().into_account_truncating(), PotCoretimeId::get().into_account_truncating(), PotSubsidizationId::get().into_account_truncating(), PotDepinStakingId::get().into_account_truncating(), PotDepinIncentivisationId::get().into_account_truncating(), ] } pub struct DustRemovalWhitelist; impl Contains for DustRemovalWhitelist { fn contains(a: &AccountId) -> bool { get_all_module_accounts().contains(a) } } parameter_types! { pub PeaqAssetAdm: AccountId = AssetAdminId::get().into_account_truncating(); pub PeaqPotAccount: AccountId = PotStakeId::get().into_account_truncating(); pub PeaqTreasuryAccount: AccountId = TreasuryPalletId::get().into_account_truncating(); pub PeaqCoretimeAccount: AccountId = PotCoretimeId::get().into_account_truncating(); pub PeaqSubsidizationAccount: AccountId = PotSubsidizationId::get().into_account_truncating(); pub PeaqDepinStakingAccount: AccountId = PotDepinStakingId::get().into_account_truncating(); pub PeaqDepinIncentivisationAccount: AccountId = PotDepinIncentivisationId::get().into_account_truncating(); } parameter_types! { pub const RBACStorageDepositBase: Balance = MILLICENTS * 500; pub const RBACStorageDepositPerByte: Balance = 0; } impl peaq_pallet_rbac::Config for Runtime { type RuntimeEvent = RuntimeEvent; type EntityId = RbacEntityId; type BoundedDataLen = ConstU32<262144>; type WeightInfo = peaq_pallet_rbac::weights::WeightInfo; type Currency = Balances; type StorageDepositBase = RBACStorageDepositBase; type StorageDepositPerByte = RBACStorageDepositPerByte; type ReserveIdentifier = RBACReserveIdentifier; } parameter_types! { pub const StorageStorageDepositBase: Balance = MILLICENTS * 500; pub const StorageStorageDepositPerByte: Balance = 0; } // Config the storage in pallets/storage impl peaq_pallet_storage::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = peaq_pallet_storage::weights::WeightInfo; type BoundedDataLen = ConstU32<256>; type Currency = Balances; type StorageDepositBase = StorageStorageDepositBase; type StorageDepositPerByte = StorageStorageDepositPerByte; type ReserveIdentifier = StorageReserveIdentifier; } // Zenlink-DEX Parameter definitions parameter_types! { pub SelfParaId: u32 = ParachainInfo::parachain_id().into(); pub const ZenlinkDexPalletId: PalletId = PalletId(*b"zenlkpro"); } type PeaqMultiCurrencies = PeaqMultiCurrenciesWrapper< Runtime, Assets, PeaqNativeCurrencyWrapper, GetNativeAssetId, >; /// Short form for our individual configuration of Zenlink's MultiAssets. pub type MultiAssets = ZenlinkMultiAssets< ZenlinkProtocol, Balances, LocalAssetAdaptor, >; impl zenlink_protocol::Config for Runtime { type RuntimeEvent = RuntimeEvent; type MultiAssetsHandler = MultiAssets; type PalletId = ZenlinkDexPalletId; type AssetId = ZenlinkAssetId; type LpGenerate = PeaqAssetZenlinkLpGenerate; type TargetChains = (); type SelfParaId = SelfParaId; type WeightInfo = (); type ControlOrigin = EnsureRoot; } parameter_types! { pub const InfaltionPot: PalletId = PalletId(*b"inflapot"); pub const DefaultTotalIssuanceNum: Balance = 4_200_000_000 * DOLLARS; pub const DefaultInflationConfiguration: InflationConfiguration = InflationConfiguration { inflation_parameters: InflationParameters { inflation_rate: Perbill::from_perthousand(35u32), disinflation_rate: Perbill::from_percent(10), }, inflation_stagnation_rate: Perbill::from_percent(1), inflation_stagnation_year: 13, }; pub const InitializeInflationAt: BlockNumber = 0; pub const BlockRewardBeforeInitialize: Balance = 0; } impl inflation_manager::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type BoundedDataLen = ConstU32<262144>; type PotId = InfaltionPot; type DefaultTotalIssuanceNum = DefaultTotalIssuanceNum; type DefaultInflationConfiguration = DefaultInflationConfiguration; type WeightInfo = inflation_manager::weights::WeightInfo; type DoInitializeAt = InitializeInflationAt; type BlockRewardBeforeInitialize = BlockRewardBeforeInitialize; } parameter_types! { pub MaximumSchedulerWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block; } impl pallet_scheduler::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeOrigin = RuntimeOrigin; type PalletsOrigin = OriginCaller; type RuntimeCall = RuntimeCall; type MaximumWeight = MaximumSchedulerWeight; type ScheduleOrigin = EnsureRoot; type MaxScheduledPerBlock = ConstU32<50>; type WeightInfo = pallet_scheduler::weights::SubstrateWeight; type OriginPrivilegeCmp = EqualPrivilegeOnly; type Preimages = Preimage; type BlockNumberProvider = System; } parameter_types! { pub const PreimageBaseDeposit: Balance = DOLLARS / 10; pub const PreimageByteDeposit: Balance = DOLLARS; pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage); } impl pallet_preimage::Config for Runtime { type WeightInfo = pallet_preimage::weights::SubstrateWeight; type RuntimeEvent = RuntimeEvent; type Currency = Balances; type ManagerOrigin = EnsureRoot; type Consideration = HoldConsideration< AccountId, Balances, PreimageHoldReason, LinearStoragePrice, >; } // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( pub enum Runtime { System: frame_system = 0, RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip::{Pallet, Storage} = 1, Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 2, Aura: pallet_aura::{Pallet, Storage, Config} = 3, Balances: pallet_balances = 4, TransactionPayment: pallet_transaction_payment::{Pallet, Storage, Event} = 5, Sudo: pallet_sudo::{Pallet, Call, Config, Storage, Event} = 6, Contracts: pallet_contracts = 7, Utility: pallet_utility::{Pallet, Call, Event} = 8, Treasury: pallet_treasury = 9, Council: pallet_collective:: = 10, // EVM Ethereum: pallet_ethereum = 11, EVM: pallet_evm = 12, // DynamicFee: pallet_dynamic_fee = 13, // BaseFee: pallet_base_fee::{Pallet, Call, Storage, Config, Event} = 14, // Parachain InflationManager: inflation_manager::{Pallet, Call, Storage, Config, Event} = 15, Authorship: pallet_authorship::{Pallet, Storage} = 20, Session: pallet_session::{Pallet, Call, Storage, Event, Config} = 21, AuraExt: cumulus_pallet_aura_ext = 22, ParachainStaking: parachain_staking = 23, ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event} = 24, ParachainInfo: parachain_info = 25, BlockReward: pallet_block_reward::{Pallet, Call, Storage, Config, Event} = 26, // Remove StakingCoefficientRewardCalculator: 27 // // Governance stuff Scheduler: pallet_scheduler::{Pallet, Storage, Event, Call} = 27, Preimage: pallet_preimage::{Pallet, Call, Storage, Event, HoldReason} = 28, // XCM helpers. XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 30, PolkadotXcm: pallet_xcm = 31, CumulusXcm: cumulus_pallet_xcm::{Pallet, Event, Origin} = 32, // Remove the DmpQueue, 33, from the runtime. XTokens: orml_xtokens::{Pallet, Storage, Call, Event} = 36, ZenlinkProtocol: zenlink_protocol::{Pallet, Call, Storage, Event} = 38, Assets: pallet_assets = 39, XcAssetConfig: xc_asset_config::{Pallet, Call, Storage, Event} = 40, AddressUnification: address_unification::{Pallet, Call, Storage, Event} = 41, MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event} = 42, Vesting: pallet_vesting = 50, // Include the custom pallets PeaqDid: peaq_pallet_did::{Pallet, Call, Storage, Event} = 100, Transaction: peaq_pallet_transaction::{Pallet, Call, Storage, Event} = 101, Multisig: pallet_multisig::{Pallet, Call, Storage, Event} = 102, PeaqRbac: peaq_pallet_rbac::{Pallet, Call, Storage, Event} = 103, PeaqStorage: peaq_pallet_storage::{Pallet, Call, Storage, Event} = 104, } ); /// The SignedExtension to the basic transaction logic. pub type SignedExtra = cumulus_pallet_weight_reclaim::StorageWeightReclaim< Runtime, ( frame_system::CheckNonZeroSender, frame_system::CheckSpecVersion, frame_system::CheckTxVersion, frame_system::CheckGenesis, frame_system::CheckEra, frame_system::CheckNonce, frame_system::CheckWeight, pallet_transaction_payment::ChargeTransactionPayment, frame_metadata_hash_extension::CheckMetadataHash, ), >; type EventRecord = frame_system::EventRecord< ::RuntimeEvent, ::Hash, >; /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = fp_self_contained::UncheckedExtrinsic; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic; // Migrations to apply on runtime upgrade pub type Migrations = ( pallet_session::migrations::v1::MigrateV0ToV1< Runtime, pallet_session::migrations::v1::InitOffenceSeverity, >, pallet_contracts::Migration, cumulus_pallet_xcmp_queue::migration::v5::MigrateV4ToV5, // permanent pallet_xcm::migration::MigrateToLatestXcmVersion, cumulus_pallet_aura_ext::migration::MigrateV0ToV1, ); /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< Runtime, Block, frame_system::ChainContext, Runtime, AllPalletsWithSystem, Migrations, >; #[cfg(feature = "runtime-benchmarks")] #[macro_use] extern crate frame_benchmarking; #[cfg(feature = "runtime-benchmarks")] mod benches { define_benchmarks!( [frame_benchmarking, BaselineBench::] [frame_system, SystemBench::] [pallet_balances, Balances] [pallet_timestamp, Timestamp] [pallet_multisig, Multisig] [cumulus_pallet_xcmp_queue, XcmpQueue] [parachain_staking, ParachainStaking] [pallet_block_reward, BlockReward] [peaq_pallet_transaction, Transaction] [peaq_pallet_did, PeaqDid] [peaq_pallet_rbac, PeaqRbac] [peaq_pallet_storage, PeaqStorage] [pallet_evm, EVM] // [pallet_xcm, PalletXcmExtrinsicsBenchmark::] [pallet_assets, Assets] [xc_asset_config, XcAssetConfig] [address_unification, AddressUnification] [inflation_manager, InflationManager] ); } impl fp_self_contained::SelfContainedCall for RuntimeCall { type SignedInfo = H160; fn is_self_contained(&self) -> bool { match self { RuntimeCall::Ethereum(call) => call.is_self_contained(), _ => false, } } fn check_self_contained(&self) -> Option> { match self { RuntimeCall::Ethereum(call) => call.check_self_contained(), _ => None, } } fn validate_self_contained( &self, signed_info: &Self::SignedInfo, dispatch_info: &DispatchInfoOf, len: usize, ) -> Option { match self { RuntimeCall::Ethereum(call) => call.validate_self_contained(signed_info, dispatch_info, len), _ => None, } } fn pre_dispatch_self_contained( &self, info: &Self::SignedInfo, dispatch_info: &DispatchInfoOf, len: usize, ) -> Option> { match self { RuntimeCall::Ethereum(call) => call.pre_dispatch_self_contained(info, dispatch_info, len), _ => None, } } fn apply_self_contained( self, info: Self::SignedInfo, ) -> Option>> { match self { call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), ))), _ => None, } } } impl_runtime_apis! { impl sp_api::Core for Runtime { fn version() -> RuntimeVersion { VERSION } fn execute_block(block: Block) { Executive::execute_block(block) } fn initialize_block(header: &::Header) -> sp_runtime::ExtrinsicInclusionMode { Executive::initialize_block(header) } } impl sp_api::Metadata for Runtime { fn metadata() -> OpaqueMetadata { OpaqueMetadata::new(Runtime::metadata().into()) } fn metadata_at_version(version: u32) -> Option { Runtime::metadata_at_version(version) } fn metadata_versions() -> Vec { Runtime::metadata_versions() } } impl sp_block_builder::BlockBuilder for Runtime { fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { Executive::apply_extrinsic(extrinsic) } fn finalize_block() -> ::Header { Executive::finalize_block() } fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { data.create_extrinsics() } fn check_inherents( block: Block, data: sp_inherents::InherentData, ) -> sp_inherents::CheckInherentsResult { data.check_extrinsics(&block) } } impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { fn validate_transaction( source: TransactionSource, xt: ::Extrinsic, block_hash: ::Hash, ) -> TransactionValidity { // Filtered calls should not enter the tx pool as they'll fail if inserted. // If this call is not allowed, we return early. if !::BaseCallFilter::contains(&xt.0.function) { return InvalidTransaction::Call.into(); } // This runtime uses Substrate's pallet transaction payment. This // makes the chain feel like a standard Substrate chain when submitting // frame transactions and using Substrate ecosystem tools. It has the downside that // transaction are not prioritized by gas_price. The following code reprioritizes // transactions to overcome this. // // A more elegant, ethereum-first solution is // a pallet that replaces pallet transaction payment, and allows users // to directly specify a gas price rather than computing an effective one. // #HopefullySomeday // First we pass the transactions to the standard FRAME executive. This calculates all the // necessary tags, longevity and other properties that we will leave unchanged. // This also assigns some priority that we don't care about and will overwrite next. let mut intermediate_valid = Executive::validate_transaction(source, xt.clone(), block_hash)?; let dispatch_info = xt.get_dispatch_info(); // If this is a pallet ethereum transaction, then its priority is already set // according to gas price from pallet ethereum. If it is any other kind of transaction, // we modify its priority. Ok(match &xt.0.function { RuntimeCall::Ethereum(transact { .. }) => intermediate_valid, _ if dispatch_info.class != DispatchClass::Normal => intermediate_valid, _ => { let tip = match &xt.0.preamble { Preamble::Bare(_) => 0, Preamble::Signed(_, _, signed_extra) => { // Yuck, this depends on the index of ChargeTransactionPayment in SignedExtra // Get the 7th item from the tuple let charge_transaction_payment = &signed_extra.0.7; charge_transaction_payment.tip() }, Preamble::General(_, _) => 0, }; // Calculate the fee that will be taken by pallet transaction payment let fee: u64 = TransactionPayment::compute_fee( xt.encode().len() as u32, &dispatch_info, tip, ).saturated_into(); // Calculate how much gas this effectively uses according to the existing mapping let effective_gas = ::GasWeightMapping::weight_to_gas( dispatch_info.total_weight() ); // Here we calculate an ethereum-style effective gas price using the // current fee of the transaction. Because the weight -> gas conversion is // lossy, we have to handle the case where a very low weight maps to zero gas. let effective_gas_price = if effective_gas > 0 { fee / effective_gas } else { // If the effective gas was zero, we just act like it was 1. fee }; // Overwrite the original prioritization with this ethereum one intermediate_valid.priority = effective_gas_price; intermediate_valid } }) } } impl sp_offchain::OffchainWorkerApi for Runtime { fn offchain_worker(header: &::Header) { Executive::offchain_worker(header) } } impl sp_consensus_aura::AuraApi for Runtime { fn slot_duration() -> sp_consensus_aura::SlotDuration { sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION) } fn authorities() -> Vec { pallet_aura::Authorities::::get().to_vec() } } impl cumulus_primitives_aura::AuraUnincludedSegmentApi for Runtime { fn can_build_upon( included_hash: ::Hash, slot: cumulus_primitives_aura::Slot, ) -> bool { ConsensusHook::can_build_upon(included_hash, slot) } } impl cumulus_primitives_core::GetCoreSelectorApi for Runtime { fn core_selector() -> (cumulus_primitives_core::CoreSelector, cumulus_primitives_core::ClaimQueueOffset) { ParachainSystem::core_selector() } } impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { fn account_nonce(account: AccountId) -> Nonce { System::account_nonce(account) } } impl peaq_rpc_primitives_debug::DebugRuntimeApi for Runtime { #[cfg(feature = "evm-tracing")] fn trace_transaction( extrinsics: Vec<::Extrinsic>, traced_transaction: &EthereumTransaction, header: &::Header, ) -> Result< (), sp_runtime::DispatchError, > { { use peaq_evm_tracer::tracer::EvmTracer; // We need to follow the order when replaying the transactions. // Block initialize happens first then apply_extrinsic. Executive::initialize_block(header); // Apply the a subset of extrinsics: all the substrate-specific or ethereum // transactions that preceded the requested transaction. for ext in extrinsics.into_iter() { let _ = match &ext.0.function { RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => { if transaction == traced_transaction { EvmTracer::new().trace(|| Executive::apply_extrinsic(ext)); return Ok(()); } else { Executive::apply_extrinsic(ext) } } _ => Executive::apply_extrinsic(ext), }; } Err(sp_runtime::DispatchError::Other( "Failed to find Ethereum transaction among the extrinsics.", )) } } #[cfg(not(feature = "evm-tracing"))] fn trace_transaction( _extrinsics: Vec<::Extrinsic>, _traced_transaction: &EthereumTransaction, _header: &::Header, ) -> Result< (), sp_runtime::DispatchError, > { Err(sp_runtime::DispatchError::Other( "Missing `evm-tracing` compile time feature flag.", )) } #[cfg(feature = "evm-tracing")] fn trace_block( extrinsics: Vec<::Extrinsic>, known_transactions: Vec, header: &::Header, ) -> Result< (), sp_runtime::DispatchError, > { { use peaq_evm_tracer::tracer::EvmTracer; // We need to follow the order when replaying the transactions. // Block initialize happens first then apply_extrinsic. Executive::initialize_block(header); // Apply all extrinsics. Ethereum extrinsics are traced. for ext in extrinsics.into_iter() { match &ext.0.function { RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => { if known_transactions.contains(&transaction.hash()) { // Each known extrinsic is a new call stack. EvmTracer::emit_new(); EvmTracer::new().trace(|| Executive::apply_extrinsic(ext)); } else { let _ = Executive::apply_extrinsic(ext); } } _ => { let _ = Executive::apply_extrinsic(ext); } }; } Ok(()) } } #[cfg(not(feature = "evm-tracing"))] fn trace_block( _extrinsics: Vec<::Extrinsic>, _known_transactions: Vec, _header: &::Header, ) -> Result< (), sp_runtime::DispatchError, > { Err(sp_runtime::DispatchError::Other( "Missing `evm-tracing` compile time feature flag.", )) } #[cfg(feature = "evm-tracing")] fn trace_call( header: &::Header, from: H160, to: H160, data: Vec, value: U256, gas_limit: U256, max_fee_per_gas: Option, max_priority_fee_per_gas: Option, nonce: Option, access_list: Option)>>, ) -> Result<(), sp_runtime::DispatchError> { use peaq_evm_tracer::tracer::EvmTracer; // Initialize block: calls the "on_initialize" hook on every pallet // in AllPalletsWithSystem. Executive::initialize_block(header); EvmTracer::new().trace(|| { let is_transactional = false; let validate = true; let transaction_data = pallet_ethereum::TransactionData::new( pallet_ethereum::TransactionAction::Call(to), data.clone(), nonce.unwrap_or_default(), gas_limit, None, max_fee_per_gas.or(Some(U256::default())), max_priority_fee_per_gas.or(Some(U256::default())), value, Some(::ChainId::get()), access_list.clone().unwrap_or_default(), ); let gas_limit = gas_limit.min(u64::MAX.into()).low_u64(); let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::::transaction_weight(&transaction_data); let _ = ::Runner::call( from, to, data, value, gas_limit, max_fee_per_gas, max_priority_fee_per_gas, nonce, access_list.unwrap_or_default(), is_transactional, validate, weight_limit, proof_size_base_cost, ::config(), ); }); Ok(()) } #[cfg(not(feature = "evm-tracing"))] fn trace_call( _header: &::Header, _from: H160, _to: H160, _data: Vec, _value: U256, _gas_limit: U256, _max_fee_per_gas: Option, _max_priority_fee_per_gas: Option, _nonce: Option, _access_list: Option)>>, ) -> Result<(), sp_runtime::DispatchError> { Err(sp_runtime::DispatchError::Other( "Missing `evm-tracing` compile time feature flag.", )) } } impl peaq_rpc_primitives_txpool::TxPoolRuntimeApi for Runtime { fn extrinsic_filter( xts_ready: Vec<::Extrinsic>, xts_future: Vec<::Extrinsic>, ) -> TxPoolResponse { TxPoolResponse { ready: xts_ready .into_iter() .filter_map(|xt| match xt.0.function { RuntimeCall::Ethereum(transact { transaction }) => Some(transaction), _ => None, }) .collect(), future: xts_future .into_iter() .filter_map(|xt| match xt.0.function { RuntimeCall::Ethereum(transact { transaction }) => Some(transaction), _ => None, }) .collect(), } } } impl fp_rpc::EthereumRuntimeRPCApi for Runtime { fn chain_id() -> u64 { ::ChainId::get() } fn account_basic(address: H160) -> EVMAccount { let (account, _) = EVM::account_basic(&address); account } fn gas_price() -> U256 { let (gas_price, _) = ::FeeCalculator::min_gas_price(); gas_price } fn account_code_at(address: H160) -> Vec { pallet_evm::AccountCodes::::get(address) } fn author() -> H160 { >::find_author() } fn storage_at(address: H160, index: U256) -> H256 { pallet_evm::AccountStorages::::get(address, H256::from_slice(&index.to_big_endian())) } fn call( from: H160, to: H160, data: Vec, value: U256, gas_limit: U256, max_fee_per_gas: Option, max_priority_fee_per_gas: Option, nonce: Option, estimate: bool, access_list: Option)>>, ) -> Result { let config = if estimate { let mut config = ::config().clone(); config.estimate = true; Some(config) } else { None }; let is_transactional = false; let validate = true; // Estimated encoded transaction size must be based on the heaviest transaction // type (EIP1559Transaction) to be compatible with all transaction types. let mut estimated_transaction_len = data.len() + // pallet ethereum index: 1 // transact call index: 1 // Transaction enum variant: 1 // chain_id 8 bytes // nonce: 32 // max_priority_fee_per_gas: 32 // max_fee_per_gas: 32 // gas_limit: 32 // action: 21 (enum varianrt + call address) // value: 32 // access_list: 1 (empty vec size) // 65 bytes signature 258; if access_list.is_some() { estimated_transaction_len += access_list.encoded_size(); } let gas_limit = gas_limit.min(u64::MAX.into()).low_u64(); let without_base_extrinsic_weight = true; let (weight_limit, proof_size_base_cost) = match ::GasWeightMapping::gas_to_weight( gas_limit, without_base_extrinsic_weight ) { weight_limit if weight_limit.proof_size() > 0 => { (Some(weight_limit), Some(estimated_transaction_len as u64)) } _ => (None, None), }; ::Runner::call( from, to, data, value, gas_limit.unique_saturated_into(), max_fee_per_gas, max_priority_fee_per_gas, nonce, access_list.unwrap_or_default(), is_transactional, validate, weight_limit, proof_size_base_cost, config.as_ref().unwrap_or_else(|| ::config()), ).map_err(|err| err.error.into()) } fn create( from: H160, data: Vec, value: U256, gas_limit: U256, max_fee_per_gas: Option, max_priority_fee_per_gas: Option, nonce: Option, estimate: bool, access_list: Option)>>, ) -> Result { let config = if estimate { let mut config = ::config().clone(); config.estimate = true; Some(config) } else { None }; let is_transactional = false; let validate = true; // Reused approach from Moonbeam since Frontier implementation doesn't support this let mut estimated_transaction_len = data.len() + // from: 20 // value: 32 // gas_limit: 32 // nonce: 32 // 1 byte transaction action variant // chain id 8 bytes // 65 bytes signature 190; if max_fee_per_gas.is_some() { estimated_transaction_len += 32; } if max_priority_fee_per_gas.is_some() { estimated_transaction_len += 32; } if access_list.is_some() { estimated_transaction_len += access_list.encoded_size(); } let gas_limit = gas_limit.min(u64::MAX.into()).low_u64(); let without_base_extrinsic_weight = true; let (weight_limit, proof_size_base_cost) = match ::GasWeightMapping::gas_to_weight( gas_limit, without_base_extrinsic_weight ) { weight_limit if weight_limit.proof_size() > 0 => { (Some(weight_limit), Some(estimated_transaction_len as u64)) } _ => (None, None), }; #[allow(clippy::or_fun_call)] // suggestion not helpful here ::Runner::create( from, data, value, gas_limit.unique_saturated_into(), max_fee_per_gas, max_priority_fee_per_gas, nonce, access_list.unwrap_or_default(), is_transactional, validate, weight_limit, proof_size_base_cost, config.as_ref().unwrap_or(::config()), ).map_err(|err| err.error.into()) } fn current_transaction_statuses() -> Option> { pallet_ethereum::CurrentTransactionStatuses::::get() } fn current_block() -> Option { pallet_ethereum::CurrentBlock::::get() } fn current_receipts() -> Option> { pallet_ethereum::CurrentReceipts::::get() } fn current_all() -> ( Option, Option>, Option> ) { ( Self::current_block(), Self::current_receipts(), Self::current_transaction_statuses() ) } fn extrinsic_filter( xts: Vec<::Extrinsic>, ) -> Vec { xts.into_iter().filter_map(|xt| match xt.0.function { RuntimeCall::Ethereum(transact { transaction }) => Some(transaction), _ => None }).collect::>() } fn elasticity() -> Option { None } fn gas_limit_multiplier_support() {} fn pending_block( xts: Vec<::Extrinsic>, ) -> (Option, Option>) { for ext in xts.into_iter() { let _ = Executive::apply_extrinsic(ext); } Ethereum::on_finalize(System::block_number() + 1); ( pallet_ethereum::CurrentBlock::::get(), pallet_ethereum::CurrentTransactionStatuses::::get() ) } fn initialize_pending_block(header: &::Header) { Executive::initialize_block(header); } } impl fp_rpc::ConvertTransactionRuntimeApi for Runtime { fn convert_transaction( transaction: pallet_ethereum::Transaction ) -> ::Extrinsic { UncheckedExtrinsic::new_bare( pallet_ethereum::Call::::transact { transaction }.into(), ) } } impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi< Block, Balance, > for Runtime { fn query_info( uxt: ::Extrinsic, len: u32 ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { TransactionPayment::query_info(uxt, len) } fn query_fee_details( uxt: ::Extrinsic, len: u32, ) -> pallet_transaction_payment::FeeDetails { TransactionPayment::query_fee_details(uxt, len) } fn query_weight_to_fee(weight: Weight) -> Balance { TransactionPayment::weight_to_fee(weight) } fn query_length_to_fee(length: u32) -> Balance { TransactionPayment::length_to_fee(length) } } impl pallet_contracts::ContractsApi for Runtime { fn call( origin: AccountId, dest: AccountId, value: Balance, gas_limit: Option, storage_deposit_limit: Option, input_data: Vec, ) -> pallet_contracts::ContractExecResult { let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); Contracts::bare_call( origin, dest, value, gas_limit, storage_deposit_limit, input_data, pallet_contracts::DebugInfo::UnsafeDebug, pallet_contracts::CollectEvents::UnsafeCollect, pallet_contracts::Determinism::Enforced, ) } fn instantiate( origin: AccountId, value: Balance, gas_limit: Option, storage_deposit_limit: Option, code: pallet_contracts::Code, data: Vec, salt: Vec, ) -> pallet_contracts::ContractInstantiateResult { let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); Contracts::bare_instantiate( origin, value, gas_limit, storage_deposit_limit, code, data, salt, pallet_contracts::DebugInfo::UnsafeDebug, pallet_contracts::CollectEvents::UnsafeCollect, ) } fn upload_code( origin: AccountId, code: Vec, storage_deposit_limit: Option, determinism: pallet_contracts::Determinism, ) -> pallet_contracts::CodeUploadResult { Contracts::bare_upload_code(origin, code, storage_deposit_limit, determinism) } fn get_storage( address: AccountId, key: Vec, ) -> pallet_contracts::GetStorageResult { Contracts::get_storage(address, key) } } impl peaq_pallet_did_runtime_api::PeaqDIDApi for Runtime { fn read(did_account: AccountId, name: Vec) -> Option< DidAttribute> { PeaqDid::read(&did_account, &name) } } impl peaq_pallet_rbac_runtime_api::PeaqRBACRuntimeApi for Runtime { fn fetch_role( account: AccountId, entity: RbacEntityId ) -> RbacResult, RbacError> { PeaqRbac::get_role(&account, entity) } fn fetch_roles( owner: AccountId ) -> RbacResult>, RbacError> { PeaqRbac::get_roles(&owner) } fn fetch_user_roles( owner: AccountId, user_id: RbacEntityId ) -> RbacResult>, RbacError> { PeaqRbac::get_user_roles(&owner, user_id) } fn fetch_permission( owner: AccountId, permission_id: RbacEntityId ) -> RbacResult, RbacError> { PeaqRbac::get_permission(&owner, permission_id) } fn fetch_permissions( owner: AccountId ) -> RbacResult>, RbacError> { PeaqRbac::get_permissions(&owner) } fn fetch_role_permissions( owner: AccountId, role_id: RbacEntityId ) -> RbacResult>, RbacError> { PeaqRbac::get_role_permissions(&owner, role_id) } fn fetch_group( owner: AccountId, group_id: RbacEntityId ) -> RbacResult, RbacError> { PeaqRbac::get_group(&owner, group_id) } fn fetch_groups( owner: AccountId ) -> RbacResult>, RbacError> { PeaqRbac::get_groups(&owner) } fn fetch_group_roles( owner: AccountId, group_id: RbacEntityId ) -> RbacResult>, RbacError> { PeaqRbac::get_group_roles(&owner, group_id) } fn fetch_user_groups( owner: AccountId, user_id: RbacEntityId ) -> RbacResult>, RbacError> { PeaqRbac::get_user_groups(&owner, user_id) } fn fetch_user_permissions( owner: AccountId, user_id: RbacEntityId ) -> RbacResult>, RbacError> { PeaqRbac::get_user_permissions(&owner, user_id) } fn fetch_group_permissions( owner: AccountId, group_id: RbacEntityId ) -> RbacResult>, RbacError> { PeaqRbac::get_group_permissions(&owner, group_id) } } impl sp_session::SessionKeys for Runtime { fn generate_session_keys(seed: Option>) -> Vec { opaque::SessionKeys::generate(seed) } fn decode_session_keys( encoded: Vec, ) -> Option, KeyTypeId)>> { opaque::SessionKeys::decode_into_raw_public_keys(&encoded) } } impl sp_genesis_builder::GenesisBuilder for Runtime { fn build_state(config: Vec) -> sp_genesis_builder::Result { frame_support::genesis_builder_helper::build_state::(config) } fn get_preset(id: &Option) -> Option> { frame_support::genesis_builder_helper::get_preset::(id, |_| None) } fn preset_names() -> Vec { vec![] } } impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) } } impl peaq_pallet_storage_runtime_api::PeaqStorageApi for Runtime{ fn read(did_account: AccountId, item_type: Vec) -> Option>{ PeaqStorage::read(&did_account, &item_type) } } impl zenlink_protocol_runtime_api::ZenlinkProtocolApi for Runtime { fn get_balance(asset_id: ZenlinkAssetId, owner: AccountId) -> AssetBalance { ::MultiAssetsHandler::balance_of(asset_id, &owner) } fn get_pair_by_asset_id( asset_0: ZenlinkAssetId, asset_1: ZenlinkAssetId ) -> Option> { ZenlinkProtocol::get_pair_by_asset_id(asset_0, asset_1) } fn get_amount_in_price(supply: AssetBalance, path: Vec) -> AssetBalance { ZenlinkProtocol::desired_in_amount(supply, path) } fn get_amount_out_price(supply: AssetBalance, path: Vec) -> AssetBalance { ZenlinkProtocol::supply_out_amount(supply, path) } fn get_estimate_lptoken( asset_0: ZenlinkAssetId, asset_1: ZenlinkAssetId, amount_0_desired: AssetBalance, amount_1_desired: AssetBalance, amount_0_min: AssetBalance, amount_1_min: AssetBalance, ) -> AssetBalance { ZenlinkProtocol::get_estimate_lptoken(asset_0, asset_1, amount_0_desired, amount_1_desired, amount_0_min, amount_1_min) } fn calculate_remove_liquidity( asset_0: ZenlinkAssetId, asset_1: ZenlinkAssetId, amount: AssetBalance, ) -> Option<(AssetBalance, AssetBalance)> { ZenlinkProtocol::calculate_remove_liquidity(asset_0, asset_1, amount) } } #[cfg(feature = "runtime-benchmarks")] impl frame_benchmarking::Benchmark for Runtime { fn benchmark_metadata(extra: bool) -> ( Vec, Vec, ) { use frame_benchmarking::{baseline, BenchmarkList}; use frame_support::traits::StorageInfoTrait; use frame_system_benchmarking::Pallet as SystemBench; use baseline::Pallet as BaselineBench; let mut list = Vec::::new(); list_benchmarks!(list, extra); let storage_info = AllPalletsWithSystem::storage_info(); (list, storage_info) } fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig ) -> Result, alloc::string::String> { use frame_benchmarking::{baseline, BenchmarkBatch}; use frame_support::traits::TrackedStorageKey; use frame_system_benchmarking::Pallet as SystemBench; use baseline::Pallet as BaselineBench; impl frame_system_benchmarking::Config for Runtime {} impl baseline::Config for Runtime {} use frame_support::traits::WhitelistedStorageKeys; let whitelist: Vec = AllPalletsWithSystem::whitelisted_storage_keys(); let mut batches = Vec::::new(); let params = (&config, &whitelist); add_benchmarks!(params, batches); if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } Ok(batches) } } #[cfg(feature = "try-runtime")] impl frame_try_runtime::TryRuntime for Runtime { fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { log::info!("try-runtime::on_runtime_upgrade polkadot."); let weight = Executive::try_runtime_upgrade(checks).unwrap(); (weight, RuntimeBlockWeights::get().max_block) } fn execute_block( block: Block, state_root_check: bool, signature_check: bool, select: frame_try_runtime::TryStateSelect, ) -> Weight { // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to // have a backtrace here. Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() } } } impl peaq_pallet_transaction::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type WeightInfo = peaq_pallet_transaction::weights::WeightInfo; } parameter_types! { pub const DepositBase: Balance = 6 * CENTS; pub const DepositFactor: Balance = 10 * CENTS; pub const MaxSignatories: u16 = 20; } impl pallet_multisig::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type Currency = Balances; type DepositBase = DepositBase; type DepositFactor = DepositFactor; type MaxSignatories = MaxSignatories; type WeightInfo = (); type BlockNumberProvider = System; } cumulus_pallet_parachain_system::register_validate_block! { Runtime = Runtime, BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, } parameter_types! { pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE); } impl pallet_vesting::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type BlockNumberToBalance = ConvertInto; type MinVestedTransfer = ConstU128<0>; type WeightInfo = pallet_vesting::weights::SubstrateWeight; const MAX_VESTING_SCHEDULES: u32 = 28; type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; type BlockNumberProvider = System; } parameter_types! { pub const AssetDeposit: Balance = DOLLARS; pub const AssetApprovalDeposit: Balance = 100 * MILLICENTS; pub const AssetsStringLimit: u32 = 50; /// Key = 32 bytes, Value = 36 bytes (32+1+1+1+1) // https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271 pub const MetadataDepositBase: Balance = CENTS; pub const MetadataDepositPerByte: Balance = 100 * MILLICENTS; pub const AssetAccountDeposit: Balance = CENTS; } impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; type AssetId = StorageAssetId; type Currency = Balances; type CreateOrigin = AsEnsureOriginWithArg>; type ForceOrigin = EnsureRoot; type AssetDeposit = AssetDeposit; type MetadataDepositBase = MetadataDepositBase; type MetadataDepositPerByte = MetadataDepositPerByte; type AssetAccountDeposit = AssetAccountDeposit; type ApprovalDeposit = AssetApprovalDeposit; type StringLimit = AssetsStringLimit; type Freezer = (); type Extra = (); type WeightInfo = (); type RemoveItemsLimit = ConstU32<1000>; type AssetIdParameter = StorageAssetId; type CallbackHandle = EvmRevertCodeHandler; type Holder = (); #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } impl address_unification::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type OriginAddressMapping = HashedAddressMapping; type ChainId = EvmChainId; type WeightInfo = address_unification::weights::WeightInfo; } impl EVMAddressToAssetId for Runtime { fn address_to_asset_id(address: H160) -> Option { match AssetIdToEVMAddress::::convert(address) { Some(asset_id) => asset_id.try_into().ok(), None => None, } } fn asset_id_to_address(asset_id: StorageAssetId) -> Option { let asset_id = asset_id.try_into().ok()?; Some(AssetIdToEVMAddress::::convert(asset_id)) } } impl cumulus_pallet_weight_reclaim::Config for Runtime { type WeightInfo = (); }