difftreelog
fix clippy warnings
in: master
9 files changed
client/rpc/src/lib.rsdiffbeforeafterboth--- a/client/rpc/src/lib.rs
+++ b/client/rpc/src/lib.rs
@@ -328,7 +328,7 @@
macro_rules! pass_method {
(
$method_name:ident(
- $($(#[map(|$map_arg:ident| $map:expr)])? $name:ident: $ty:ty),* $(,)?
+ $($(#[map = $map:expr])? $name:ident: $ty:ty),* $(,)?
) -> $result:ty $(=> $mapper:expr)?,
//$runtime_name:ident $(<$($lt: tt),+>)*
$runtime_api_macro:ident
@@ -355,7 +355,7 @@
let result = $(if _api_version < $ver {
api.$changed_method_name(at, $($changed_name),*).map(|r| r.and_then($fixer))
} else)*
- { api.$method_name(at, $($((|$map_arg: $ty| $map))? ($name)),*) };
+ { api.$method_name(at, $($($map)? ($name)),*) };
Ok(result
.map_err(|e| anyhow!("unable to query: {e}"))?
@@ -413,7 +413,7 @@
pass_method!(collection_properties(
collection: CollectionId,
- #[map(|keys| string_keys_to_bytes_keys(keys))]
+ #[map = string_keys_to_bytes_keys]
keys: Option<Vec<String>>
) -> Vec<Property>, unique_api);
@@ -421,14 +421,14 @@
collection: CollectionId,
token_id: TokenId,
- #[map(|keys| string_keys_to_bytes_keys(keys))]
+ #[map = string_keys_to_bytes_keys]
keys: Option<Vec<String>>
) -> Vec<Property>, unique_api);
pass_method!(property_permissions(
collection: CollectionId,
- #[map(|keys| string_keys_to_bytes_keys(keys))]
+ #[map = string_keys_to_bytes_keys]
keys: Option<Vec<String>>
) -> Vec<PropertyKeyPermission>, unique_api);
@@ -437,7 +437,7 @@
collection: CollectionId,
token_id: TokenId,
- #[map(|keys| string_keys_to_bytes_keys(keys))]
+ #[map = string_keys_to_bytes_keys]
keys: Option<Vec<String>>,
) -> TokenData<CrossAccountId>, unique_api;
changed_in 3, token_data_before_version_3(collection, token_id, string_keys_to_bytes_keys(keys)) => |value| Ok(value.into())
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -531,7 +531,11 @@
debug!("Parachain genesis block: {:?}", block);
info!(
"Is collating: {}",
- config.role.is_authority().then_some("yes").unwrap_or("no")
+ if config.role.is_authority() {
+ "yes"
+ } else {
+ "no"
+ }
);
start_node_using_chain_runtime! {
pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -30,11 +30,11 @@
//!
//!
//! ## Interface
-//! The pallet provides interfaces for funds, collection/contract operations (see [types] module).
+//! The pallet provides interfaces for funds, collection/contract operations (see [types] module).
//!
//! ### Dispatchable Functions
-//! - [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.
+//! - [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.
//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.
//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.
//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -73,7 +73,7 @@
//!
//! - [`WithRecorder`](pallet_evm_coder_substrate::WithRecorder): Trait for EVM support
//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing with collections
-//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight
+//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight
//! - [`CommonEvmHandler`](pallet_common::erc::CommonEvmHandler): Function for handling EVM runtime calls
#![cfg_attr(not(feature = "std"), no_std)]
@@ -728,7 +728,7 @@
/// Transfer fungible tokens from one account to another.
/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.
/// The owner should set allowance for the spender to transfer pieces.
- /// See [`set_allowance`][`Pallet::set_allowance`] for more details.
+ /// See [`set_allowance`][`Pallet::set_allowance`] for more details.
pub fn transfer_from(
collection: &FungibleHandle<T>,
spender: &T::CrossAccountId,
@@ -778,7 +778,7 @@
Ok(())
}
- /// Creates fungible token.
+ /// Creates fungible token.
///
/// The sender should be the owner/admin of the collection or collection should be configured
/// to allow public minting.
@@ -799,7 +799,7 @@
)
}
- /// Creates fungible token.
+ /// Creates fungible token.
///
/// - `data`: Contains user who will become the owners of the tokens and amount
/// of tokens he will receive.
pallets/identity/src/lib.rsdiffbeforeafterboth--- a/pallets/identity/src/lib.rs
+++ b/pallets/identity/src/lib.rs
@@ -95,8 +95,13 @@
mod types;
pub mod weights;
-use frame_support::traits::{BalanceStatus, Currency, OnUnbalanced, ReservableCurrency};
-use sp_runtime::traits::{AppendZerosInput, Hash, Saturating, StaticLookup, Zero};
+use frame_support::{
+ traits::{BalanceStatus, Currency, OnUnbalanced, ReservableCurrency},
+};
+use sp_runtime::{
+ BoundedVec,
+ traits::{AppendZerosInput, Hash, Saturating, StaticLookup, Zero},
+};
use sp_std::prelude::*;
pub use weights::WeightInfo;
@@ -112,6 +117,18 @@
<T as frame_system::Config>::AccountId,
>>::NegativeImbalance;
type AccountIdLookupOf<T> = <<T as frame_system::Config>::Lookup as StaticLookup>::Source;
+type RegistrarInfoOf<T> = RegistrarInfo<BalanceOf<T>, <T as frame_system::Config>::AccountId>;
+type RegistrationOf<T> =
+ Registration<BalanceOf<T>, <T as Config>::MaxRegistrars, <T as Config>::MaxAdditionalFields>;
+type SubAccounts<T> =
+ sp_runtime::BoundedVec<<T as frame_system::Config>::AccountId, <T as Config>::MaxSubAccounts>;
+type SubAccountsByAccountId<T> = (
+ <T as frame_system::Config>::AccountId,
+ (
+ BalanceOf<T>,
+ BoundedVec<(<T as frame_system::Config>::AccountId, Data), <T as Config>::MaxSubAccounts>,
+ ),
+);
#[frame_support::pallet]
pub mod pallet {
@@ -198,13 +215,8 @@
/// TWOX-NOTE: OK ― `AccountId` is a secure hash.
#[pallet::storage]
#[pallet::getter(fn subs_of)]
- pub(super) type SubsOf<T: Config> = StorageMap<
- _,
- Twox64Concat,
- T::AccountId,
- (BalanceOf<T>, BoundedVec<T::AccountId, T::MaxSubAccounts>),
- ValueQuery,
- >;
+ pub(super) type SubsOf<T: Config> =
+ StorageMap<_, Twox64Concat, T::AccountId, (BalanceOf<T>, SubAccounts<T>), ValueQuery>;
/// The set of registrars. Not expected to get very big as can only be added through a
/// special origin (likely a council motion).
@@ -212,11 +224,8 @@
/// The index into this can be cast to `RegistrarIndex` to get a valid value.
#[pallet::storage]
#[pallet::getter(fn registrars)]
- pub(super) type Registrars<T: Config> = StorageValue<
- _,
- BoundedVec<Option<RegistrarInfo<BalanceOf<T>, T::AccountId>>, T::MaxRegistrars>,
- ValueQuery,
- >;
+ pub(super) type Registrars<T: Config> =
+ StorageValue<_, BoundedVec<Option<RegistrarInfoOf<T>>, T::MaxRegistrars>, ValueQuery>;
#[pallet::error]
pub enum Error<T> {
@@ -482,18 +491,21 @@
.all(|i| i.0 == sender);
ensure!(not_other_sub, Error::<T>::AlreadyClaimed);
- if old_deposit < new_deposit {
- T::Currency::reserve(&sender, new_deposit - old_deposit)?;
- } else if old_deposit > new_deposit {
- let err_amount = T::Currency::unreserve(&sender, old_deposit - new_deposit);
- debug_assert!(err_amount.is_zero());
+ match old_deposit.cmp(&new_deposit) {
+ core::cmp::Ordering::Less => {
+ T::Currency::reserve(&sender, new_deposit - old_deposit)?
+ }
+ core::cmp::Ordering::Equal => { /* do nothing if they're equal. */ }
+ core::cmp::Ordering::Greater => {
+ let err_amount = T::Currency::unreserve(&sender, old_deposit - new_deposit);
+ debug_assert!(err_amount.is_zero());
+ }
}
- // do nothing if they're equal.
for s in old_ids.iter() {
<SuperOf<T>>::remove(s);
}
- let mut ids = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();
+ let mut ids = <SubAccounts<T>>::default();
for (id, name) in subs {
<SuperOf<T>>::insert(&id, (sender.clone(), name));
ids.try_push(id)
@@ -1107,10 +1119,7 @@
))]
pub fn force_insert_identities(
origin: OriginFor<T>,
- identities: Vec<(
- T::AccountId,
- Registration<BalanceOf<T>, T::MaxRegistrars, T::MaxAdditionalFields>,
- )>,
+ identities: Vec<(T::AccountId, RegistrationOf<T>)>,
) -> DispatchResult {
T::ForceOrigin::ensure_origin(origin)?;
for identity in identities.clone() {
@@ -1162,13 +1171,7 @@
))]
pub fn force_set_subs(
origin: OriginFor<T>,
- subs: Vec<(
- T::AccountId,
- (
- BalanceOf<T>,
- BoundedVec<(T::AccountId, Data), T::MaxSubAccounts>,
- ),
- )>,
+ subs: Vec<SubAccountsByAccountId<T>>,
) -> DispatchResult {
T::ForceOrigin::ensure_origin(origin)?;
for identity in subs.clone() {
@@ -1178,7 +1181,7 @@
<SuperOf<T>>::remove(old_sub);
}
- let mut ids = BoundedVec::<T::AccountId, T::MaxSubAccounts>::default();
+ let mut ids = <SubAccounts<T>>::default();
for (id, name) in identity.1 .1 {
<SuperOf<T>>::insert(&id, (account.clone(), name));
ids.try_push(id)
pallets/inflation/src/lib.rsdiffbeforeafterboth--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -26,7 +26,7 @@
//!
//! * `start_inflation` - This method sets the inflation start date. Can be only called once.
//! Inflation start block can be backdated and will catch up. The method will create Treasury
-//! account if it does not exist and perform the first inflation deposit.
+//! account if it does not exist and perform the first inflation deposit.
// #![recursion_limit = "1024"]
#![cfg_attr(not(feature = "std"), no_std)]
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -90,7 +90,7 @@
use crate::erc_token::ERC20Events;
use crate::erc::ERC721Events;
-use core::ops::Deref;
+use core::{ops::Deref, cmp::Ordering};
use evm_coder::ToLog;
use frame_support::{ensure, storage::with_transaction, transactional};
use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
@@ -1266,44 +1266,48 @@
<Balance<T>>::insert((collection.id, token, owner), amount);
<TotalSupply<T>>::insert((collection.id, token), amount);
- if amount > total_pieces {
- let mint_amount = amount - total_pieces;
- <PalletEvm<T>>::deposit_log(
- ERC20Events::Transfer {
- from: H160::default(),
- to: *owner.as_eth(),
- value: mint_amount.into(),
- }
- .to_log(T::EvmTokenAddressMapping::token_to_address(
+ match total_pieces.cmp(&amount) {
+ Ordering::Less => {
+ let mint_amount = amount - total_pieces;
+ <PalletEvm<T>>::deposit_log(
+ ERC20Events::Transfer {
+ from: H160::default(),
+ to: *owner.as_eth(),
+ value: mint_amount.into(),
+ }
+ .to_log(T::EvmTokenAddressMapping::token_to_address(
+ collection.id,
+ token,
+ )),
+ );
+ <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
collection.id,
token,
- )),
- );
- <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(
- collection.id,
- token,
- owner.clone(),
- mint_amount,
- ));
- } else if total_pieces > amount {
- let burn_amount = total_pieces - amount;
- <PalletEvm<T>>::deposit_log(
- ERC20Events::Transfer {
- from: *owner.as_eth(),
- to: H160::default(),
- value: burn_amount.into(),
- }
- .to_log(T::EvmTokenAddressMapping::token_to_address(
+ owner.clone(),
+ mint_amount,
+ ));
+ }
+ Ordering::Greater => {
+ let burn_amount = total_pieces - amount;
+ <PalletEvm<T>>::deposit_log(
+ ERC20Events::Transfer {
+ from: *owner.as_eth(),
+ to: H160::default(),
+ value: burn_amount.into(),
+ }
+ .to_log(T::EvmTokenAddressMapping::token_to_address(
+ collection.id,
+ token,
+ )),
+ );
+ <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
collection.id,
token,
- )),
- );
- <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(
- collection.id,
- token,
- owner.clone(),
- burn_amount,
- ));
+ owner.clone(),
+ burn_amount,
+ ));
+ }
+ Ordering::Equal => {}
}
Ok(())
runtime/common/ethereum/precompiles/utils/macro/src/lib.rsdiffbeforeafterboth--- a/runtime/common/ethereum/precompiles/utils/macro/src/lib.rs
+++ b/runtime/common/ethereum/precompiles/utils/macro/src/lib.rs
@@ -35,8 +35,8 @@
/// ```ignore
/// #[generate_function_selector]
/// enum Action {
-/// Toto = "toto()",
-/// Tata = "tata()",
+/// Toto = "toto()",
+/// Tata = "tata()",
/// }
/// ```
///
@@ -45,8 +45,8 @@
/// ```rust
/// #[repr(u32)]
/// enum Action {
-/// Toto = 119097542u32,
-/// Tata = 1414311903u32,
+/// Toto = 119097542u32,
+/// Tata = 1414311903u32,
/// }
/// ```
///
runtime/common/runtime_apis.rsdiffbeforeafterboth1// 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/>.1617#[macro_export]18macro_rules! dispatch_unique_runtime {19 ($collection:ident.$method:ident($($name:ident),*) $($rest:tt)*) => {{20 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch($collection)?;21 let dispatch = collection.as_dyn();2223 Ok::<_, DispatchError>(dispatch.$method($($name),*) $($rest)*)24 }};25}2627#[macro_export]28macro_rules! impl_common_runtime_apis {29 (30 $(31 #![custom_apis]3233 $($custom_apis:tt)+34 )?35 ) => {36 use sp_std::prelude::*;37 use sp_api::impl_runtime_apis;38 use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};39 use sp_runtime::{40 Permill,41 traits::Block as BlockT,42 transaction_validity::{TransactionSource, TransactionValidity},43 ApplyExtrinsicResult, DispatchError,44 };45 use frame_support::pallet_prelude::Weight;46 use fp_rpc::TransactionStatus;47 use pallet_transaction_payment::{48 FeeDetails, RuntimeDispatchInfo,49 };50 use pallet_evm::{51 Runner, account::CrossAccountId as _,52 Account as EVMAccount, FeeCalculator,53 };54 use runtime_common::{55 sponsoring::{SponsorshipPredict, UniqueSponsorshipPredict},56 dispatch::CollectionDispatch,57 config::ethereum::CrossAccountId,58 };59 use up_data_structs::*;606162 impl_runtime_apis! {63 $($($custom_apis)+)?6465 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {66 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {67 dispatch_unique_runtime!(collection.account_tokens(account))68 }69 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {70 dispatch_unique_runtime!(collection.collection_tokens())71 }72 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {73 dispatch_unique_runtime!(collection.token_exists(token))74 }7576 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {77 dispatch_unique_runtime!(collection.token_owner(token).ok())78 }7980 fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError> {81 dispatch_unique_runtime!(collection.token_owners(token))82 }8384 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {85 let budget = up_data_structs::budget::Value::new(10);8687 <pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)88 }89 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {90 Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))91 }92 fn collection_properties(93 collection: CollectionId,94 keys: Option<Vec<Vec<u8>>>95 ) -> Result<Vec<Property>, DispatchError> {96 let keys = keys.map(97 |keys| Common::bytes_keys_to_property_keys(keys)98 ).transpose()?;99100 Common::filter_collection_properties(collection, keys)101 }102103 fn token_properties(104 collection: CollectionId,105 token_id: TokenId,106 keys: Option<Vec<Vec<u8>>>107 ) -> Result<Vec<Property>, DispatchError> {108 let keys = keys.map(109 |keys| Common::bytes_keys_to_property_keys(keys)110 ).transpose()?;111112 dispatch_unique_runtime!(collection.token_properties(token_id, keys))113 }114115 fn property_permissions(116 collection: CollectionId,117 keys: Option<Vec<Vec<u8>>>118 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {119 let keys = keys.map(120 |keys| Common::bytes_keys_to_property_keys(keys)121 ).transpose()?;122123 Common::filter_property_permissions(collection, keys)124 }125126 fn token_data(127 collection: CollectionId,128 token_id: TokenId,129 keys: Option<Vec<Vec<u8>>>130 ) -> Result<TokenData<CrossAccountId>, DispatchError> {131 let token_data = TokenData {132 properties: Self::token_properties(collection, token_id, keys)?,133 owner: Self::token_owner(collection, token_id)?,134 pieces: Self::total_pieces(collection, token_id)?.unwrap_or(0),135 };136137 Ok(token_data)138 }139140 fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {141 dispatch_unique_runtime!(collection.total_supply())142 }143 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {144 dispatch_unique_runtime!(collection.account_balance(account))145 }146 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {147 dispatch_unique_runtime!(collection.balance(account, token))148 }149 fn allowance(150 collection: CollectionId,151 sender: CrossAccountId,152 spender: CrossAccountId,153 token: TokenId,154 ) -> Result<u128, DispatchError> {155 dispatch_unique_runtime!(collection.allowance(sender, spender, token))156 }157158 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {159 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))160 }161 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {162 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))163 }164 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {165 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))166 }167 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {168 dispatch_unique_runtime!(collection.last_token_id())169 }170 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {171 Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))172 }173 fn collection_stats() -> Result<CollectionStats, DispatchError> {174 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())175 }176 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {177 Ok(<UniqueSponsorshipPredict<Runtime> as SponsorshipPredict<Runtime>>::predict(178 collection,179 account,180 token181 ))182 }183184 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {185 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))186 }187188 fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {189 dispatch_unique_runtime!(collection.total_pieces(token_id))190 }191192 fn allowance_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> Result<bool, DispatchError> {193 dispatch_unique_runtime!(collection.allowance_for_all(owner, operator))194 }195 }196197 impl app_promotion_rpc::AppPromotionApi<Block, BlockNumber, CrossAccountId, AccountId> for Runtime {198 #[allow(unused_variables)]199 fn total_staked(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {200 #[cfg(not(feature = "app-promotion"))]201 return unsupported!();202203 #[cfg(feature = "app-promotion")]204 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default());205 }206207 #[allow(unused_variables)]208 fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {209 #[cfg(not(feature = "app-promotion"))]210 return unsupported!();211212 #[cfg(feature = "app-promotion")]213 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker));214 }215216 #[allow(unused_variables)]217 fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {218 #[cfg(not(feature = "app-promotion"))]219 return unsupported!();220221 #[cfg(feature = "app-promotion")]222 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker));223 }224225 #[allow(unused_variables)]226 fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {227 #[cfg(not(feature = "app-promotion"))]228 return unsupported!();229230 #[cfg(feature = "app-promotion")]231 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))232 }233 }234235 impl sp_api::Core<Block> for Runtime {236 fn version() -> RuntimeVersion {237 VERSION238 }239240 fn execute_block(block: Block) {241 Executive::execute_block(block)242 }243244 fn initialize_block(header: &<Block as BlockT>::Header) {245 Executive::initialize_block(header)246 }247 }248249 impl sp_api::Metadata<Block> for Runtime {250 fn metadata() -> OpaqueMetadata {251 OpaqueMetadata::new(Runtime::metadata().into())252 }253254 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {255 Runtime::metadata_at_version(version)256 }257258 fn metadata_versions() -> sp_std::vec::Vec<u32> {259 Runtime::metadata_versions()260 }261 }262263 impl sp_block_builder::BlockBuilder<Block> for Runtime {264 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {265 Executive::apply_extrinsic(extrinsic)266 }267268 fn finalize_block() -> <Block as BlockT>::Header {269 Executive::finalize_block()270 }271272 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {273 data.create_extrinsics()274 }275276 fn check_inherents(277 block: Block,278 data: sp_inherents::InherentData,279 ) -> sp_inherents::CheckInherentsResult {280 data.check_extrinsics(&block)281 }282283 // fn random_seed() -> <Block as BlockT>::Hash {284 // RandomnessCollectiveFlip::random_seed().0285 // }286 }287288 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {289 fn validate_transaction(290 source: TransactionSource,291 tx: <Block as BlockT>::Extrinsic,292 hash: <Block as BlockT>::Hash,293 ) -> TransactionValidity {294 Executive::validate_transaction(source, tx, hash)295 }296 }297298 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {299 fn offchain_worker(header: &<Block as BlockT>::Header) {300 Executive::offchain_worker(header)301 }302 }303304 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {305 fn chain_id() -> u64 {306 <Runtime as pallet_evm::Config>::ChainId::get()307 }308309 fn account_basic(address: H160) -> EVMAccount {310 let (account, _) = EVM::account_basic(&address);311 account312 }313314 fn gas_price() -> U256 {315 let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();316 price317 }318319 fn account_code_at(address: H160) -> Vec<u8> {320 use pallet_evm::OnMethodCall;321 <Runtime as pallet_evm::Config>::OnMethodCall::get_code(&address)322 .unwrap_or_else(|| pallet_evm::AccountCodes::<Runtime>::get(address))323 }324325 fn author() -> H160 {326 <pallet_evm::Pallet<Runtime>>::find_author()327 }328329 fn storage_at(address: H160, index: U256) -> H256 {330 let mut tmp = [0u8; 32];331 index.to_big_endian(&mut tmp);332 pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))333 }334335 #[allow(clippy::redundant_closure)]336 fn call(337 from: H160,338 to: H160,339 data: Vec<u8>,340 value: U256,341 gas_limit: U256,342 max_fee_per_gas: Option<U256>,343 max_priority_fee_per_gas: Option<U256>,344 nonce: Option<U256>,345 estimate: bool,346 access_list: Option<Vec<(H160, Vec<H256>)>>,347 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {348 let config = if estimate {349 let mut config = <Runtime as pallet_evm::Config>::config().clone();350 config.estimate = true;351 Some(config)352 } else {353 None354 };355356 let is_transactional = false;357 let validate = false;358 <Runtime as pallet_evm::Config>::Runner::call(359 CrossAccountId::from_eth(from),360 to,361 data,362 value,363 gas_limit.low_u64(),364 max_fee_per_gas,365 max_priority_fee_per_gas,366 nonce,367 access_list.unwrap_or_default(),368 is_transactional,369 validate,370 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),371 ).map_err(|err| err.error.into())372 }373374 #[allow(clippy::redundant_closure)]375 fn create(376 from: H160,377 data: Vec<u8>,378 value: U256,379 gas_limit: U256,380 max_fee_per_gas: Option<U256>,381 max_priority_fee_per_gas: Option<U256>,382 nonce: Option<U256>,383 estimate: bool,384 access_list: Option<Vec<(H160, Vec<H256>)>>,385 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {386 let config = if estimate {387 let mut config = <Runtime as pallet_evm::Config>::config().clone();388 config.estimate = true;389 Some(config)390 } else {391 None392 };393394 let is_transactional = false;395 let validate = false;396 <Runtime as pallet_evm::Config>::Runner::create(397 CrossAccountId::from_eth(from),398 data,399 value,400 gas_limit.low_u64(),401 max_fee_per_gas,402 max_priority_fee_per_gas,403 nonce,404 access_list.unwrap_or_default(),405 is_transactional,406 validate,407 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),408 ).map_err(|err| err.error.into())409 }410411 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {412 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()413 }414415 fn current_block() -> Option<pallet_ethereum::Block> {416 pallet_ethereum::CurrentBlock::<Runtime>::get()417 }418419 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {420 pallet_ethereum::CurrentReceipts::<Runtime>::get()421 }422423 fn current_all() -> (424 Option<pallet_ethereum::Block>,425 Option<Vec<pallet_ethereum::Receipt>>,426 Option<Vec<TransactionStatus>>427 ) {428 (429 pallet_ethereum::CurrentBlock::<Runtime>::get(),430 pallet_ethereum::CurrentReceipts::<Runtime>::get(),431 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()432 )433 }434435 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {436 xts.into_iter().filter_map(|xt| match xt.0.function {437 RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),438 _ => None439 }).collect()440 }441442 fn elasticity() -> Option<Permill> {443 None444 }445446 fn gas_limit_multiplier_support() {}447 }448449 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {450 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {451 UncheckedExtrinsic::new_unsigned(452 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),453 )454 }455 }456457 impl sp_session::SessionKeys<Block> for Runtime {458 fn decode_session_keys(459 encoded: Vec<u8>,460 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {461 SessionKeys::decode_into_raw_public_keys(&encoded)462 }463464 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {465 SessionKeys::generate(seed)466 }467 }468469 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {470 fn slot_duration() -> sp_consensus_aura::SlotDuration {471 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())472 }473474 fn authorities() -> Vec<AuraId> {475 Aura::authorities().to_vec()476 }477 }478479 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {480 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {481 ParachainSystem::collect_collation_info(header)482 }483 }484485 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {486 fn account_nonce(account: AccountId) -> Index {487 System::account_nonce(account)488 }489 }490491 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {492 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {493 TransactionPayment::query_info(uxt, len)494 }495 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {496 TransactionPayment::query_fee_details(uxt, len)497 }498 fn query_weight_to_fee(weight: Weight) -> Balance {499 TransactionPayment::weight_to_fee(weight)500 }501 fn query_length_to_fee(length: u32) -> Balance {502 TransactionPayment::length_to_fee(length)503 }504 }505506 /*507 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>508 for Runtime509 {510 fn call(511 origin: AccountId,512 dest: AccountId,513 value: Balance,514 gas_limit: u64,515 input_data: Vec<u8>,516 ) -> pallet_contracts_primitives::ContractExecResult {517 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)518 }519520 fn instantiate(521 origin: AccountId,522 endowment: Balance,523 gas_limit: u64,524 code: pallet_contracts_primitives::Code<Hash>,525 data: Vec<u8>,526 salt: Vec<u8>,527 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>528 {529 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)530 }531532 fn get_storage(533 address: AccountId,534 key: [u8; 32],535 ) -> pallet_contracts_primitives::GetStorageResult {536 Contracts::get_storage(address, key)537 }538539 fn rent_projection(540 address: AccountId,541 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {542 Contracts::rent_projection(address)543 }544 }545 */546547 #[cfg(feature = "runtime-benchmarks")]548 impl frame_benchmarking::Benchmark<Block> for Runtime {549 fn benchmark_metadata(extra: bool) -> (550 Vec<frame_benchmarking::BenchmarkList>,551 Vec<frame_support::traits::StorageInfo>,552 ) {553 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};554 use frame_support::traits::StorageInfoTrait;555556 let mut list = Vec::<BenchmarkList>::new();557 list_benchmark!(list, extra, pallet_xcm, PolkadotXcm);558559 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);560 list_benchmark!(list, extra, pallet_common, Common);561 list_benchmark!(list, extra, pallet_unique, Unique);562 list_benchmark!(list, extra, pallet_structure, Structure);563 list_benchmark!(list, extra, pallet_inflation, Inflation);564 list_benchmark!(list, extra, pallet_configuration, Configuration);565566 #[cfg(feature = "app-promotion")]567 list_benchmark!(list, extra, pallet_app_promotion, AppPromotion);568569 list_benchmark!(list, extra, pallet_fungible, Fungible);570 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);571572 #[cfg(feature = "refungible")]573 list_benchmark!(list, extra, pallet_refungible, Refungible);574575 #[cfg(feature = "scheduler")]576 list_benchmark!(list, extra, pallet_unique_scheduler_v2, Scheduler);577578 #[cfg(feature = "collator-selection")]579 list_benchmark!(list, extra, pallet_collator_selection, CollatorSelection);580581 #[cfg(feature = "collator-selection")]582 list_benchmark!(list, extra, pallet_identity, Identity);583584 #[cfg(feature = "foreign-assets")]585 list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);586587 list_benchmark!(list, extra, pallet_maintenance, Maintenance);588589 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);590591 let storage_info = AllPalletsWithSystem::storage_info();592593 return (list, storage_info)594 }595596 fn dispatch_benchmark(597 config: frame_benchmarking::BenchmarkConfig598 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {599 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};600601 let allowlist: Vec<TrackedStorageKey> = vec![602 // Total Issuance603 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),604605 // Block Number606 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),607 // Execution Phase608 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),609 // Event Count610 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),611 // System Events612 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),613614 // Evm CurrentLogs615 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),616617 // Transactional depth618 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),619 ];620621 let mut batches = Vec::<BenchmarkBatch>::new();622 let params = (&config, &allowlist);623 add_benchmark!(params, batches, pallet_xcm, PolkadotXcm);624625 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);626 add_benchmark!(params, batches, pallet_common, Common);627 add_benchmark!(params, batches, pallet_unique, Unique);628 add_benchmark!(params, batches, pallet_structure, Structure);629 add_benchmark!(params, batches, pallet_inflation, Inflation);630 add_benchmark!(params, batches, pallet_configuration, Configuration);631632 #[cfg(feature = "app-promotion")]633 add_benchmark!(params, batches, pallet_app_promotion, AppPromotion);634635 add_benchmark!(params, batches, pallet_fungible, Fungible);636 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);637638 #[cfg(feature = "refungible")]639 add_benchmark!(params, batches, pallet_refungible, Refungible);640641 #[cfg(feature = "scheduler")]642 add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);643644 #[cfg(feature = "collator-selection")]645 add_benchmark!(params, batches, pallet_collator_selection, CollatorSelection);646647 #[cfg(feature = "collator-selection")]648 add_benchmark!(params, batches, pallet_identity, Identity);649650 #[cfg(feature = "foreign-assets")]651 add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);652653 add_benchmark!(params, batches, pallet_maintenance, Maintenance);654655 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);656657 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }658 Ok(batches)659 }660 }661662 impl up_pov_estimate_rpc::PovEstimateApi<Block> for Runtime {663 #[allow(unused_variables)]664 fn pov_estimate(uxt: Vec<u8>) -> ApplyExtrinsicResult {665 #[cfg(feature = "pov-estimate")]666 {667 use codec::Decode;668669 let uxt_decode = <<Block as BlockT>::Extrinsic as Decode>::decode(&mut &uxt)670 .map_err(|_| DispatchError::Other("failed to decode the extrinsic"));671672 let uxt = match uxt_decode {673 Ok(uxt) => uxt,674 Err(err) => return Ok(err.into()),675 };676677 Executive::apply_extrinsic(uxt)678 }679680 #[cfg(not(feature = "pov-estimate"))]681 return Ok(unsupported!());682 }683 }684685 #[cfg(feature = "try-runtime")]686 impl frame_try_runtime::TryRuntime<Block> for Runtime {687 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {688 log::info!("try-runtime::on_runtime_upgrade unique-chain.");689 let weight = Executive::try_runtime_upgrade(checks).unwrap();690 (weight, crate::config::substrate::RuntimeBlockWeights::get().max_block)691 }692693 fn execute_block(694 block: Block,695 state_root_check: bool,696 signature_check: bool,697 select: frame_try_runtime::TryStateSelect698 ) -> Weight {699 log::info!(700 target: "node-runtime",701 "try-runtime: executing block {:?} / root checks: {:?} / try-state-select: {:?}",702 block.header.hash(),703 state_root_check,704 select,705 );706707 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()708 }709 }710 }711 }712}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/>.1617#[macro_export]18macro_rules! dispatch_unique_runtime {19 ($collection:ident.$method:ident($($name:ident),*) $($rest:tt)*) => {{20 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch($collection)?;21 let dispatch = collection.as_dyn();2223 Ok::<_, DispatchError>(dispatch.$method($($name),*) $($rest)*)24 }};25}2627#[macro_export]28macro_rules! impl_common_runtime_apis {29 (30 $(31 #![custom_apis]3233 $($custom_apis:tt)+34 )?35 ) => {36 use sp_std::prelude::*;37 use sp_api::impl_runtime_apis;38 use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};39 use sp_runtime::{40 Permill,41 traits::Block as BlockT,42 transaction_validity::{TransactionSource, TransactionValidity},43 ApplyExtrinsicResult, DispatchError,44 };45 use frame_support::pallet_prelude::Weight;46 use fp_rpc::TransactionStatus;47 use pallet_transaction_payment::{48 FeeDetails, RuntimeDispatchInfo,49 };50 use pallet_evm::{51 Runner, account::CrossAccountId as _,52 Account as EVMAccount, FeeCalculator,53 };54 use runtime_common::{55 sponsoring::{SponsorshipPredict, UniqueSponsorshipPredict},56 dispatch::CollectionDispatch,57 config::ethereum::CrossAccountId,58 };59 use up_data_structs::*;606162 impl_runtime_apis! {63 $($($custom_apis)+)?6465 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId> for Runtime {66 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {67 dispatch_unique_runtime!(collection.account_tokens(account))68 }69 fn collection_tokens(collection: CollectionId) -> Result<Vec<TokenId>, DispatchError> {70 dispatch_unique_runtime!(collection.collection_tokens())71 }72 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {73 dispatch_unique_runtime!(collection.token_exists(token))74 }7576 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {77 dispatch_unique_runtime!(collection.token_owner(token).ok())78 }7980 fn token_owners(collection: CollectionId, token: TokenId) -> Result<Vec::<CrossAccountId>, DispatchError> {81 dispatch_unique_runtime!(collection.token_owners(token))82 }8384 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {85 let budget = up_data_structs::budget::Value::new(10);8687 <pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)88 }89 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {90 Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))91 }92 fn collection_properties(93 collection: CollectionId,94 keys: Option<Vec<Vec<u8>>>95 ) -> Result<Vec<Property>, DispatchError> {96 let keys = keys.map(97 |keys| Common::bytes_keys_to_property_keys(keys)98 ).transpose()?;99100 Common::filter_collection_properties(collection, keys)101 }102103 fn token_properties(104 collection: CollectionId,105 token_id: TokenId,106 keys: Option<Vec<Vec<u8>>>107 ) -> Result<Vec<Property>, DispatchError> {108 let keys = keys.map(109 |keys| Common::bytes_keys_to_property_keys(keys)110 ).transpose()?;111112 dispatch_unique_runtime!(collection.token_properties(token_id, keys))113 }114115 fn property_permissions(116 collection: CollectionId,117 keys: Option<Vec<Vec<u8>>>118 ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {119 let keys = keys.map(120 |keys| Common::bytes_keys_to_property_keys(keys)121 ).transpose()?;122123 Common::filter_property_permissions(collection, keys)124 }125126 fn token_data(127 collection: CollectionId,128 token_id: TokenId,129 keys: Option<Vec<Vec<u8>>>130 ) -> Result<TokenData<CrossAccountId>, DispatchError> {131 let token_data = TokenData {132 properties: Self::token_properties(collection, token_id, keys)?,133 owner: Self::token_owner(collection, token_id)?,134 pieces: Self::total_pieces(collection, token_id)?.unwrap_or(0),135 };136137 Ok(token_data)138 }139140 fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {141 dispatch_unique_runtime!(collection.total_supply())142 }143 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {144 dispatch_unique_runtime!(collection.account_balance(account))145 }146 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {147 dispatch_unique_runtime!(collection.balance(account, token))148 }149 fn allowance(150 collection: CollectionId,151 sender: CrossAccountId,152 spender: CrossAccountId,153 token: TokenId,154 ) -> Result<u128, DispatchError> {155 dispatch_unique_runtime!(collection.allowance(sender, spender, token))156 }157158 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {159 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))160 }161 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {162 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))163 }164 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {165 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))166 }167 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {168 dispatch_unique_runtime!(collection.last_token_id())169 }170 fn collection_by_id(collection: CollectionId) -> Result<Option<RpcCollection<AccountId>>, DispatchError> {171 Ok(<pallet_common::Pallet<Runtime>>::rpc_collection(collection))172 }173 fn collection_stats() -> Result<CollectionStats, DispatchError> {174 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())175 }176 fn next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<Option<u64>, DispatchError> {177 Ok(<UniqueSponsorshipPredict<Runtime> as SponsorshipPredict<Runtime>>::predict(178 collection,179 account,180 token181 ))182 }183184 fn effective_collection_limits(collection: CollectionId) -> Result<Option<CollectionLimits>, DispatchError> {185 Ok(<pallet_common::Pallet<Runtime>>::effective_collection_limits(collection))186 }187188 fn total_pieces(collection: CollectionId, token_id: TokenId) -> Result<Option<u128>, DispatchError> {189 dispatch_unique_runtime!(collection.total_pieces(token_id))190 }191192 fn allowance_for_all(collection: CollectionId, owner: CrossAccountId, operator: CrossAccountId) -> Result<bool, DispatchError> {193 dispatch_unique_runtime!(collection.allowance_for_all(owner, operator))194 }195 }196197 impl app_promotion_rpc::AppPromotionApi<Block, BlockNumber, CrossAccountId, AccountId> for Runtime {198 #[allow(unused_variables)]199 fn total_staked(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {200 #[cfg(not(feature = "app-promotion"))]201 return unsupported!();202203 #[cfg(feature = "app-promotion")]204 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default());205 }206207 #[allow(unused_variables)]208 fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {209 #[cfg(not(feature = "app-promotion"))]210 return unsupported!();211212 #[cfg(feature = "app-promotion")]213 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker));214 }215216 #[allow(unused_variables)]217 fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {218 #[cfg(not(feature = "app-promotion"))]219 return unsupported!();220221 #[cfg(feature = "app-promotion")]222 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker));223 }224225 #[allow(unused_variables)]226 fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {227 #[cfg(not(feature = "app-promotion"))]228 return unsupported!();229230 #[cfg(feature = "app-promotion")]231 return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))232 }233 }234235 impl sp_api::Core<Block> for Runtime {236 fn version() -> RuntimeVersion {237 VERSION238 }239240 fn execute_block(block: Block) {241 Executive::execute_block(block)242 }243244 fn initialize_block(header: &<Block as BlockT>::Header) {245 Executive::initialize_block(header)246 }247 }248249 impl sp_api::Metadata<Block> for Runtime {250 fn metadata() -> OpaqueMetadata {251 OpaqueMetadata::new(Runtime::metadata().into())252 }253254 fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {255 Runtime::metadata_at_version(version)256 }257258 fn metadata_versions() -> sp_std::vec::Vec<u32> {259 Runtime::metadata_versions()260 }261 }262263 impl sp_block_builder::BlockBuilder<Block> for Runtime {264 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {265 Executive::apply_extrinsic(extrinsic)266 }267268 fn finalize_block() -> <Block as BlockT>::Header {269 Executive::finalize_block()270 }271272 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {273 data.create_extrinsics()274 }275276 fn check_inherents(277 block: Block,278 data: sp_inherents::InherentData,279 ) -> sp_inherents::CheckInherentsResult {280 data.check_extrinsics(&block)281 }282283 // fn random_seed() -> <Block as BlockT>::Hash {284 // RandomnessCollectiveFlip::random_seed().0285 // }286 }287288 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {289 fn validate_transaction(290 source: TransactionSource,291 tx: <Block as BlockT>::Extrinsic,292 hash: <Block as BlockT>::Hash,293 ) -> TransactionValidity {294 Executive::validate_transaction(source, tx, hash)295 }296 }297298 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {299 fn offchain_worker(header: &<Block as BlockT>::Header) {300 Executive::offchain_worker(header)301 }302 }303304 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {305 fn chain_id() -> u64 {306 <Runtime as pallet_evm::Config>::ChainId::get()307 }308309 fn account_basic(address: H160) -> EVMAccount {310 let (account, _) = EVM::account_basic(&address);311 account312 }313314 fn gas_price() -> U256 {315 let (price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();316 price317 }318319 fn account_code_at(address: H160) -> Vec<u8> {320 use pallet_evm::OnMethodCall;321 <Runtime as pallet_evm::Config>::OnMethodCall::get_code(&address)322 .unwrap_or_else(|| pallet_evm::AccountCodes::<Runtime>::get(address))323 }324325 fn author() -> H160 {326 <pallet_evm::Pallet<Runtime>>::find_author()327 }328329 fn storage_at(address: H160, index: U256) -> H256 {330 let mut tmp = [0u8; 32];331 index.to_big_endian(&mut tmp);332 pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))333 }334335 #[allow(clippy::redundant_closure)]336 fn call(337 from: H160,338 to: H160,339 data: Vec<u8>,340 value: U256,341 gas_limit: U256,342 max_fee_per_gas: Option<U256>,343 max_priority_fee_per_gas: Option<U256>,344 nonce: Option<U256>,345 estimate: bool,346 access_list: Option<Vec<(H160, Vec<H256>)>>,347 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {348 let config = if estimate {349 let mut config = <Runtime as pallet_evm::Config>::config().clone();350 config.estimate = true;351 Some(config)352 } else {353 None354 };355356 let is_transactional = false;357 let validate = false;358 <Runtime as pallet_evm::Config>::Runner::call(359 CrossAccountId::from_eth(from),360 to,361 data,362 value,363 gas_limit.low_u64(),364 max_fee_per_gas,365 max_priority_fee_per_gas,366 nonce,367 access_list.unwrap_or_default(),368 is_transactional,369 validate,370 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),371 ).map_err(|err| err.error.into())372 }373374 #[allow(clippy::redundant_closure)]375 fn create(376 from: H160,377 data: Vec<u8>,378 value: U256,379 gas_limit: U256,380 max_fee_per_gas: Option<U256>,381 max_priority_fee_per_gas: Option<U256>,382 nonce: Option<U256>,383 estimate: bool,384 access_list: Option<Vec<(H160, Vec<H256>)>>,385 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {386 let config = if estimate {387 let mut config = <Runtime as pallet_evm::Config>::config().clone();388 config.estimate = true;389 Some(config)390 } else {391 None392 };393394 let is_transactional = false;395 let validate = false;396 <Runtime as pallet_evm::Config>::Runner::create(397 CrossAccountId::from_eth(from),398 data,399 value,400 gas_limit.low_u64(),401 max_fee_per_gas,402 max_priority_fee_per_gas,403 nonce,404 access_list.unwrap_or_default(),405 is_transactional,406 validate,407 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),408 ).map_err(|err| err.error.into())409 }410411 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {412 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()413 }414415 fn current_block() -> Option<pallet_ethereum::Block> {416 pallet_ethereum::CurrentBlock::<Runtime>::get()417 }418419 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {420 pallet_ethereum::CurrentReceipts::<Runtime>::get()421 }422423 fn current_all() -> (424 Option<pallet_ethereum::Block>,425 Option<Vec<pallet_ethereum::Receipt>>,426 Option<Vec<TransactionStatus>>427 ) {428 (429 pallet_ethereum::CurrentBlock::<Runtime>::get(),430 pallet_ethereum::CurrentReceipts::<Runtime>::get(),431 pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()432 )433 }434435 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {436 xts.into_iter().filter_map(|xt| match xt.0.function {437 RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),438 _ => None439 }).collect()440 }441442 fn elasticity() -> Option<Permill> {443 None444 }445446 fn gas_limit_multiplier_support() {}447 }448449 impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {450 fn convert_transaction(transaction: pallet_ethereum::Transaction) -> <Block as BlockT>::Extrinsic {451 UncheckedExtrinsic::new_unsigned(452 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),453 )454 }455 }456457 impl sp_session::SessionKeys<Block> for Runtime {458 fn decode_session_keys(459 encoded: Vec<u8>,460 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {461 SessionKeys::decode_into_raw_public_keys(&encoded)462 }463464 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {465 SessionKeys::generate(seed)466 }467 }468469 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {470 fn slot_duration() -> sp_consensus_aura::SlotDuration {471 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())472 }473474 fn authorities() -> Vec<AuraId> {475 Aura::authorities().to_vec()476 }477 }478479 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {480 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {481 ParachainSystem::collect_collation_info(header)482 }483 }484485 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {486 fn account_nonce(account: AccountId) -> Index {487 System::account_nonce(account)488 }489 }490491 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {492 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {493 TransactionPayment::query_info(uxt, len)494 }495 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {496 TransactionPayment::query_fee_details(uxt, len)497 }498 fn query_weight_to_fee(weight: Weight) -> Balance {499 TransactionPayment::weight_to_fee(weight)500 }501 fn query_length_to_fee(length: u32) -> Balance {502 TransactionPayment::length_to_fee(length)503 }504 }505506 /*507 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>508 for Runtime509 {510 fn call(511 origin: AccountId,512 dest: AccountId,513 value: Balance,514 gas_limit: u64,515 input_data: Vec<u8>,516 ) -> pallet_contracts_primitives::ContractExecResult {517 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)518 }519520 fn instantiate(521 origin: AccountId,522 endowment: Balance,523 gas_limit: u64,524 code: pallet_contracts_primitives::Code<Hash>,525 data: Vec<u8>,526 salt: Vec<u8>,527 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>528 {529 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)530 }531532 fn get_storage(533 address: AccountId,534 key: [u8; 32],535 ) -> pallet_contracts_primitives::GetStorageResult {536 Contracts::get_storage(address, key)537 }538539 fn rent_projection(540 address: AccountId,541 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {542 Contracts::rent_projection(address)543 }544 }545 */546547 #[cfg(feature = "runtime-benchmarks")]548 impl frame_benchmarking::Benchmark<Block> for Runtime {549 fn benchmark_metadata(extra: bool) -> (550 Vec<frame_benchmarking::BenchmarkList>,551 Vec<frame_support::traits::StorageInfo>,552 ) {553 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};554 use frame_support::traits::StorageInfoTrait;555556 let mut list = Vec::<BenchmarkList>::new();557 list_benchmark!(list, extra, pallet_xcm, PolkadotXcm);558559 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);560 list_benchmark!(list, extra, pallet_common, Common);561 list_benchmark!(list, extra, pallet_unique, Unique);562 list_benchmark!(list, extra, pallet_structure, Structure);563 list_benchmark!(list, extra, pallet_inflation, Inflation);564 list_benchmark!(list, extra, pallet_configuration, Configuration);565566 #[cfg(feature = "app-promotion")]567 list_benchmark!(list, extra, pallet_app_promotion, AppPromotion);568569 list_benchmark!(list, extra, pallet_fungible, Fungible);570 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);571572 #[cfg(feature = "refungible")]573 list_benchmark!(list, extra, pallet_refungible, Refungible);574575 #[cfg(feature = "scheduler")]576 list_benchmark!(list, extra, pallet_unique_scheduler_v2, Scheduler);577578 #[cfg(feature = "collator-selection")]579 list_benchmark!(list, extra, pallet_collator_selection, CollatorSelection);580581 #[cfg(feature = "collator-selection")]582 list_benchmark!(list, extra, pallet_identity, Identity);583584 #[cfg(feature = "foreign-assets")]585 list_benchmark!(list, extra, pallet_foreign_assets, ForeignAssets);586587 list_benchmark!(list, extra, pallet_maintenance, Maintenance);588589 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);590591 let storage_info = AllPalletsWithSystem::storage_info();592593 return (list, storage_info)594 }595596 fn dispatch_benchmark(597 config: frame_benchmarking::BenchmarkConfig598 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {599 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};600601 let allowlist: Vec<TrackedStorageKey> = vec![602 // Total Issuance603 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),604605 // Block Number606 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),607 // Execution Phase608 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),609 // Event Count610 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),611 // System Events612 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),613614 // Evm CurrentLogs615 hex_literal::hex!("1da53b775b270400e7e61ed5cbc5a146547f210cec367e9af919603343b9cb56").to_vec().into(),616617 // Transactional depth618 hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a").to_vec().into(),619 ];620621 let mut batches = Vec::<BenchmarkBatch>::new();622 let params = (&config, &allowlist);623 add_benchmark!(params, batches, pallet_xcm, PolkadotXcm);624625 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);626 add_benchmark!(params, batches, pallet_common, Common);627 add_benchmark!(params, batches, pallet_unique, Unique);628 add_benchmark!(params, batches, pallet_structure, Structure);629 add_benchmark!(params, batches, pallet_inflation, Inflation);630 add_benchmark!(params, batches, pallet_configuration, Configuration);631632 #[cfg(feature = "app-promotion")]633 add_benchmark!(params, batches, pallet_app_promotion, AppPromotion);634635 add_benchmark!(params, batches, pallet_fungible, Fungible);636 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);637638 #[cfg(feature = "refungible")]639 add_benchmark!(params, batches, pallet_refungible, Refungible);640641 #[cfg(feature = "scheduler")]642 add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);643644 #[cfg(feature = "collator-selection")]645 add_benchmark!(params, batches, pallet_collator_selection, CollatorSelection);646647 #[cfg(feature = "collator-selection")]648 add_benchmark!(params, batches, pallet_identity, Identity);649650 #[cfg(feature = "foreign-assets")]651 add_benchmark!(params, batches, pallet_foreign_assets, ForeignAssets);652653 add_benchmark!(params, batches, pallet_maintenance, Maintenance);654655 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);656657 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }658 Ok(batches)659 }660 }661662 impl up_pov_estimate_rpc::PovEstimateApi<Block> for Runtime {663 #[allow(unused_variables)]664 fn pov_estimate(uxt: Vec<u8>) -> ApplyExtrinsicResult {665 #[cfg(feature = "pov-estimate")]666 {667 use codec::Decode;668669 let uxt_decode = <<Block as BlockT>::Extrinsic as Decode>::decode(&mut &uxt)670 .map_err(|_| DispatchError::Other("failed to decode the extrinsic"));671672 let uxt = match uxt_decode {673 Ok(uxt) => uxt,674 Err(err) => return Ok(err.into()),675 };676677 Executive::apply_extrinsic(uxt)678 }679680 #[cfg(not(feature = "pov-estimate"))]681 return Ok(unsupported!());682 }683 }684685 #[cfg(feature = "try-runtime")]686 impl frame_try_runtime::TryRuntime<Block> for Runtime {687 fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {688 log::info!("try-runtime::on_runtime_upgrade unique-chain.");689 let weight = Executive::try_runtime_upgrade(checks).unwrap();690 (weight, $crate::config::substrate::RuntimeBlockWeights::get().max_block)691 }692693 fn execute_block(694 block: Block,695 state_root_check: bool,696 signature_check: bool,697 select: frame_try_runtime::TryStateSelect698 ) -> Weight {699 log::info!(700 target: "node-runtime",701 "try-runtime: executing block {:?} / root checks: {:?} / try-state-select: {:?}",702 block.header.hash(),703 state_root_check,704 select,705 );706707 Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()708 }709 }710 }711 }712}