git.delta.rocks / unique-network / refs/commits / 834c75ed844b

difftreelog

change unstake and on_initrialize logicc and + added `Reserved`

PraetorP2022-09-02parent: #492b651.patch.diff
in: master

7 files changed

modifiedclient/rpc/src/lib.rsdiffbeforeafterboth
before · client/rpc/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original License18use std::sync::Arc;1920use codec::{Decode, Encode};21use jsonrpsee::{22	core::{RpcResult as Result},23	proc_macros::rpc,24};25use anyhow::anyhow;26use sp_runtime::traits::{AtLeast32BitUnsigned, Member};27use up_data_structs::{28	RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId, Property,29	PropertyKeyPermission, TokenData, TokenChild,30};31use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};32use sp_blockchain::HeaderBackend;33use up_rpc::UniqueApi as UniqueRuntimeApi;34use app_promotion_rpc::AppPromotionApi as AppPromotionRuntimeApi;3536// RMRK37use rmrk_rpc::RmrkApi as RmrkRuntimeApi;38use up_data_structs::{39	RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName, RmrkResourceId,40};4142pub use app_promotion_unique_rpc::AppPromotionApiServer;43pub use rmrk_unique_rpc::RmrkApiServer;4445#[rpc(server)]46#[async_trait]47pub trait UniqueApi<BlockHash, BlockNumber, CrossAccountId, AccountId> {48	/// Get tokens owned by account.49	#[method(name = "unique_accountTokens")]50	fn account_tokens(51		&self,52		collection: CollectionId,53		account: CrossAccountId,54		at: Option<BlockHash>,55	) -> Result<Vec<TokenId>>;5657	/// Get tokens contained within a collection.58	#[method(name = "unique_collectionTokens")]59	fn collection_tokens(60		&self,61		collection: CollectionId,62		at: Option<BlockHash>,63	) -> Result<Vec<TokenId>>;6465	/// Check if the token exists.66	#[method(name = "unique_tokenExists")]67	fn token_exists(68		&self,69		collection: CollectionId,70		token: TokenId,71		at: Option<BlockHash>,72	) -> Result<bool>;7374	/// Get the token owner.75	#[method(name = "unique_tokenOwner")]76	fn token_owner(77		&self,78		collection: CollectionId,79		token: TokenId,80		at: Option<BlockHash>,81	) -> Result<Option<CrossAccountId>>;8283	/// Returns 10 tokens owners in no particular order.84	#[method(name = "unique_tokenOwners")]85	fn token_owners(86		&self,87		collection: CollectionId,88		token: TokenId,89		at: Option<BlockHash>,90	) -> Result<Vec<CrossAccountId>>;9192	/// Get the topmost token owner in the hierarchy of a possibly nested token.93	#[method(name = "unique_topmostTokenOwner")]94	fn topmost_token_owner(95		&self,96		collection: CollectionId,97		token: TokenId,98		at: Option<BlockHash>,99	) -> Result<Option<CrossAccountId>>;100101	/// Get tokens nested directly into the token.102	#[method(name = "unique_tokenChildren")]103	fn token_children(104		&self,105		collection: CollectionId,106		token: TokenId,107		at: Option<BlockHash>,108	) -> Result<Vec<TokenChild>>;109110	/// Get collection properties, optionally limited to the provided keys.111	#[method(name = "unique_collectionProperties")]112	fn collection_properties(113		&self,114		collection: CollectionId,115		keys: Option<Vec<String>>,116		at: Option<BlockHash>,117	) -> Result<Vec<Property>>;118119	/// Get token properties, optionally limited to the provided keys.120	#[method(name = "unique_tokenProperties")]121	fn token_properties(122		&self,123		collection: CollectionId,124		token_id: TokenId,125		keys: Option<Vec<String>>,126		at: Option<BlockHash>,127	) -> Result<Vec<Property>>;128129	/// Get property permissions, optionally limited to the provided keys.130	#[method(name = "unique_propertyPermissions")]131	fn property_permissions(132		&self,133		collection: CollectionId,134		keys: Option<Vec<String>>,135		at: Option<BlockHash>,136	) -> Result<Vec<PropertyKeyPermission>>;137138	/// Get token data, including properties, optionally limited to the provided keys, and total pieces for an RFT.139	#[method(name = "unique_tokenData")]140	fn token_data(141		&self,142		collection: CollectionId,143		token_id: TokenId,144		keys: Option<Vec<String>>,145		at: Option<BlockHash>,146	) -> Result<TokenData<CrossAccountId>>;147148	/// Get the amount of distinctive tokens present in a collection.149	#[method(name = "unique_totalSupply")]150	fn total_supply(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;151152	/// Get the amount of any user tokens owned by an account.153	#[method(name = "unique_accountBalance")]154	fn account_balance(155		&self,156		collection: CollectionId,157		account: CrossAccountId,158		at: Option<BlockHash>,159	) -> Result<u32>;160161	/// Get the amount of a specific token owned by an account.162	#[method(name = "unique_balance")]163	fn balance(164		&self,165		collection: CollectionId,166		account: CrossAccountId,167		token: TokenId,168		at: Option<BlockHash>,169	) -> Result<String>;170171	/// Get the amount of currently possible sponsored transactions on a token for the fee to be taken off a sponsor.172	#[method(name = "unique_allowance")]173	fn allowance(174		&self,175		collection: CollectionId,176		sender: CrossAccountId,177		spender: CrossAccountId,178		token: TokenId,179		at: Option<BlockHash>,180	) -> Result<String>;181182	/// Get the list of admin accounts of a collection.183	#[method(name = "unique_adminlist")]184	fn adminlist(185		&self,186		collection: CollectionId,187		at: Option<BlockHash>,188	) -> Result<Vec<CrossAccountId>>;189190	/// Get the list of accounts allowed to operate within a collection.191	#[method(name = "unique_allowlist")]192	fn allowlist(193		&self,194		collection: CollectionId,195		at: Option<BlockHash>,196	) -> Result<Vec<CrossAccountId>>;197198	/// Check if a user is allowed to operate within a collection.199	#[method(name = "unique_allowed")]200	fn allowed(201		&self,202		collection: CollectionId,203		user: CrossAccountId,204		at: Option<BlockHash>,205	) -> Result<bool>;206207	/// Get the last token ID created in a collection.208	#[method(name = "unique_lastTokenId")]209	fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;210211	/// Get collection info by the specified ID.212	#[method(name = "unique_collectionById")]213	fn collection_by_id(214		&self,215		collection: CollectionId,216		at: Option<BlockHash>,217	) -> Result<Option<RpcCollection<AccountId>>>;218219	/// Get chain stats about collections.220	#[method(name = "unique_collectionStats")]221	fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;222223	/// Get the number of blocks until sponsoring a transaction is available.224	#[method(name = "unique_nextSponsored")]225	fn next_sponsored(226		&self,227		collection: CollectionId,228		account: CrossAccountId,229		token: TokenId,230		at: Option<BlockHash>,231	) -> Result<Option<u64>>;232233	/// Get effective collection limits. If not explicitly set, get the chain defaults.234	#[method(name = "unique_effectiveCollectionLimits")]235	fn effective_collection_limits(236		&self,237		collection_id: CollectionId,238		at: Option<BlockHash>,239	) -> Result<Option<CollectionLimits>>;240241	/// Get the total amount of pieces of an RFT.242	#[method(name = "unique_totalPieces")]243	fn total_pieces(244		&self,245		collection_id: CollectionId,246		token_id: TokenId,247		at: Option<BlockHash>,248	) -> Result<Option<String>>;249}250251mod app_promotion_unique_rpc {252	use super::*;253	254	#[rpc(server)]255	#[async_trait]256	pub trait AppPromotionApi<BlockHash, BlockNumber, CrossAccountId, AccountId> {257		/// Returns the total amount of staked tokens.258		#[method(name = "appPromotion_totalStaked")]259		fn total_staked(&self, staker: Option<CrossAccountId>, at: Option<BlockHash>)260			-> Result<String>;261262		///Returns the total amount of staked tokens per block when staked.263		#[method(name = "appPromotion_totalStakedPerBlock")]264		fn total_staked_per_block(265			&self,266			staker: CrossAccountId,267			at: Option<BlockHash>,268		) -> Result<Vec<(BlockNumber, String)>>;269270		/// Returns the total amount locked by staking tokens.271		#[method(name = "appPromotion_totalStakingLocked")]272		fn total_staking_locked(&self, staker: CrossAccountId, at: Option<BlockHash>)273			-> Result<String>;274275		/// Returns the total amount of tokens pending withdrawal from staking.276		#[method(name = "appPromotion_pendingUnstake")]277		fn pending_unstake(278			&self,279			staker: Option<CrossAccountId>,280			at: Option<BlockHash>,281		) -> Result<String>;282283		/// Returns the total amount of tokens pending withdrawal from staking per block.284		#[method(name = "appPromotion_pendingUnstakePerBlock")]285		fn pending_unstake_per_block(286			&self,287			staker: CrossAccountId,288			at: Option<BlockHash>,289		) -> Result<Vec<(BlockNumber, String)>>;290	}291}292293mod rmrk_unique_rpc {294	use super::*;295296	#[rpc(server)]297	#[async_trait]298	pub trait RmrkApi<299		BlockHash,300		AccountId,301		CollectionInfo,302		NftInfo,303		ResourceInfo,304		PropertyInfo,305		BaseInfo,306		PartType,307		Theme,308	>309	{310		/// Get the latest created collection ID.311		#[method(name = "rmrk_lastCollectionIdx")]312		fn last_collection_idx(&self, at: Option<BlockHash>) -> Result<RmrkCollectionId>;313314		/// Get collection info by ID.315		#[method(name = "rmrk_collectionById")]316		fn collection_by_id(317			&self,318			id: RmrkCollectionId,319			at: Option<BlockHash>,320		) -> Result<Option<CollectionInfo>>;321322		/// Get NFT info by collection and NFT IDs.323		#[method(name = "rmrk_nftById")]324		fn nft_by_id(325			&self,326			collection_id: RmrkCollectionId,327			nft_id: RmrkNftId,328			at: Option<BlockHash>,329		) -> Result<Option<NftInfo>>;330331		/// Get tokens owned by an account in a collection.332		#[method(name = "rmrk_accountTokens")]333		fn account_tokens(334			&self,335			account_id: AccountId,336			collection_id: RmrkCollectionId,337			at: Option<BlockHash>,338		) -> Result<Vec<RmrkNftId>>;339340		/// Get tokens nested in an NFT - its direct children (not the children's children).341		#[method(name = "rmrk_nftChildren")]342		fn nft_children(343			&self,344			collection_id: RmrkCollectionId,345			nft_id: RmrkNftId,346			at: Option<BlockHash>,347		) -> Result<Vec<RmrkNftChild>>;348349		/// Get collection properties, created by the user - not the proxy-specific properties.350		#[method(name = "rmrk_collectionProperties")]351		fn collection_properties(352			&self,353			collection_id: RmrkCollectionId,354			filter_keys: Option<Vec<String>>,355			at: Option<BlockHash>,356		) -> Result<Vec<PropertyInfo>>;357358		/// Get NFT properties, created by the user - not the proxy-specific properties.359		#[method(name = "rmrk_nftProperties")]360		fn nft_properties(361			&self,362			collection_id: RmrkCollectionId,363			nft_id: RmrkNftId,364			filter_keys: Option<Vec<String>>,365			at: Option<BlockHash>,366		) -> Result<Vec<PropertyInfo>>;367368		/// Get data of resources of an NFT.369		#[method(name = "rmrk_nftResources")]370		fn nft_resources(371			&self,372			collection_id: RmrkCollectionId,373			nft_id: RmrkNftId,374			at: Option<BlockHash>,375		) -> Result<Vec<ResourceInfo>>;376377		/// Get the priority of a resource in an NFT.378		#[method(name = "rmrk_nftResourcePriority")]379		fn nft_resource_priority(380			&self,381			collection_id: RmrkCollectionId,382			nft_id: RmrkNftId,383			resource_id: RmrkResourceId,384			at: Option<BlockHash>,385		) -> Result<Option<u32>>;386387		/// Get base info by its ID.388		#[method(name = "rmrk_base")]389		fn base(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Option<BaseInfo>>;390391		/// Get all parts of a base.392		#[method(name = "rmrk_baseParts")]393		fn base_parts(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Vec<PartType>>;394395		/// Get the theme names belonging to a base.396		#[method(name = "rmrk_themeNames")]397		fn theme_names(398			&self,399			base_id: RmrkBaseId,400			at: Option<BlockHash>,401		) -> Result<Vec<RmrkThemeName>>;402403		/// Get theme info, including properties, optionally limited to the provided keys.404		#[method(name = "rmrk_themes")]405		fn theme(406			&self,407			base_id: RmrkBaseId,408			theme_name: String,409			filter_keys: Option<Vec<String>>,410			at: Option<BlockHash>,411		) -> Result<Option<Theme>>;412	}413}414415pub struct Unique<C, P> {416	client: Arc<C>,417	_marker: std::marker::PhantomData<P>,418}419420impl<C, P> Unique<C, P> {421	pub fn new(client: Arc<C>) -> Self {422		Self {423			client,424			_marker: Default::default(),425		}426	}427}428429pub struct AppPromotion<C, P> {430	client: Arc<C>,431	_marker: std::marker::PhantomData<P>,432}433434impl<C, P> AppPromotion<C, P> {435	pub fn new(client: Arc<C>) -> Self {436		Self {437			client,438			_marker: Default::default(),439		}440	}441}442443pub struct Rmrk<C, P> {444	client: Arc<C>,445	_marker: std::marker::PhantomData<P>,446}447448impl<C, P> Rmrk<C, P> {449	pub fn new(client: Arc<C>) -> Self {450		Self {451			client,452			_marker: Default::default(),453		}454	}455}456457macro_rules! pass_method {458	(459		$method_name:ident(460			$($(#[map(|$map_arg:ident| $map:expr)])? $name:ident: $ty:ty),* $(,)?461		) -> $result:ty $(=> $mapper:expr)?,462		//$runtime_name:ident $(<$($lt: tt),+>)*463		$runtime_api_macro:ident464		$(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*465	) => {466		fn $method_name(467			&self,468			$(469				$name: $ty,470			)*471			at: Option<<Block as BlockT>::Hash>,472		) -> Result<$result> {473			let api = self.client.runtime_api();474			let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));475			let _api_version = if let Ok(Some(api_version)) =476				api.api_version::<$runtime_api_macro!()>(&at)477			{478				api_version479			} else {480				// unreachable for our runtime481				return Err(anyhow!("api is not available").into())482			};483484			let result = $(if _api_version < $ver {485				api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))486			} else)*487			{ api.$method_name(&at, $($((|$map_arg: $ty| $map))? ($name)),*) };488489			Ok(result490				.map_err(|e| anyhow!("unable to query: {e}"))?491				.map_err(|e| anyhow!("runtime error: {e:?}"))$(.map($mapper))??)492		}493	};494}495496macro_rules! unique_api {497	() => {498		dyn UniqueRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>499	};500}501502macro_rules! app_promotion_api {503	() => {504		dyn AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>505	};506}507508macro_rules! rmrk_api {509	() => {510		dyn RmrkRuntimeApi<Block, AccountId, CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme>511	};512}513514#[allow(deprecated)]515impl<C, Block, BlockNumber, CrossAccountId, AccountId>516	UniqueApiServer<<Block as BlockT>::Hash, BlockNumber, CrossAccountId, AccountId>517	for Unique<C, Block>518where519	Block: BlockT,520	BlockNumber: Decode + Member + AtLeast32BitUnsigned,521	AccountId: Decode,522	C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,523	C::Api: UniqueRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,524	CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,525{526	pass_method!(527		account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>, unique_api528	);529	pass_method!(530		collection_tokens(collection: CollectionId) -> Vec<TokenId>, unique_api531	);532	pass_method!(533		token_exists(collection: CollectionId, token: TokenId) -> bool, unique_api534	);535	pass_method!(536		token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api537	);538	pass_method!(539		topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api540	);541	pass_method!(token_children(collection: CollectionId, token: TokenId) -> Vec<TokenChild>, unique_api);542	pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);543	pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);544	pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);545	pass_method!(546		allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string(),547		unique_api548	);549550	pass_method!(collection_properties(551		collection: CollectionId,552553		#[map(|keys| string_keys_to_bytes_keys(keys))]554		keys: Option<Vec<String>>555	) -> Vec<Property>, unique_api);556557	pass_method!(token_properties(558		collection: CollectionId,559		token_id: TokenId,560561		#[map(|keys| string_keys_to_bytes_keys(keys))]562		keys: Option<Vec<String>>563	) -> Vec<Property>, unique_api);564565	pass_method!(property_permissions(566		collection: CollectionId,567568		#[map(|keys| string_keys_to_bytes_keys(keys))]569		keys: Option<Vec<String>>570	) -> Vec<PropertyKeyPermission>, unique_api);571572	pass_method!(token_data(573		collection: CollectionId,574		token_id: TokenId,575576		#[map(|keys| string_keys_to_bytes_keys(keys))]577		keys: Option<Vec<String>>,578	) -> TokenData<CrossAccountId>, unique_api);579580	pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);581	pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);582	pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool, unique_api);583	pass_method!(last_token_id(collection: CollectionId) -> TokenId, unique_api);584	pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>, unique_api);585	pass_method!(collection_stats() -> CollectionStats, unique_api);586	pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>, unique_api);587	pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);588	pass_method!(total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<String> => |o| o.map(|number| number.to_string()) , unique_api);589	pass_method!(token_owners(collection: CollectionId, token: TokenId) -> Vec<CrossAccountId>, unique_api);590}591592impl<C, Block, BlockNumber, CrossAccountId, AccountId>593 	app_promotion_unique_rpc::AppPromotionApiServer<<Block as BlockT>::Hash, BlockNumber, CrossAccountId, AccountId>594	for AppPromotion<C, Block>595where596	Block: BlockT,597	BlockNumber: Decode + Member + AtLeast32BitUnsigned,598	AccountId: Decode,599	C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,600	C::Api: AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,601	CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,602{603	pass_method!(total_staked(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);604	pass_method!(total_staked_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>605		|v| v606		.into_iter()607		.map(|(b, a)| (b, a.to_string()))608		.collect::<Vec<_>>(), unique_api);609	pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), unique_api);610	pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), unique_api);611	pass_method!(pending_unstake_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>612		|v| v613		.into_iter()614		.map(|(b, a)| (b, a.to_string()))615		.collect::<Vec<_>>(), unique_api);616}617618#[allow(deprecated)]619impl<620		C,621		Block,622		AccountId,623		CollectionInfo,624		NftInfo,625		ResourceInfo,626		PropertyInfo,627		BaseInfo,628		PartType,629		Theme,630	>631	rmrk_unique_rpc::RmrkApiServer<632		<Block as BlockT>::Hash,633		AccountId,634		CollectionInfo,635		NftInfo,636		ResourceInfo,637		PropertyInfo,638		BaseInfo,639		PartType,640		Theme,641	> for Rmrk<C, Block>642where643	C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,644	C::Api: RmrkRuntimeApi<645		Block,646		AccountId,647		CollectionInfo,648		NftInfo,649		ResourceInfo,650		PropertyInfo,651		BaseInfo,652		PartType,653		Theme,654	>,655	AccountId: Decode + Encode,656	CollectionInfo: Decode,657	NftInfo: Decode,658	ResourceInfo: Decode,659	PropertyInfo: Decode,660	BaseInfo: Decode,661	PartType: Decode,662	Theme: Decode,663	Block: BlockT,664{665	pass_method!(last_collection_idx() -> RmrkCollectionId, rmrk_api);666	pass_method!(collection_by_id(id: RmrkCollectionId) -> Option<CollectionInfo>, rmrk_api);667	pass_method!(nft_by_id(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Option<NftInfo>, rmrk_api);668	pass_method!(account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Vec<RmrkNftId>, rmrk_api);669	pass_method!(nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkNftChild>, rmrk_api);670	pass_method!(671		collection_properties(672			collection_id: RmrkCollectionId,673674			#[map(|keys| string_keys_to_bytes_keys(keys))]675			filter_keys: Option<Vec<String>>676		) -> Vec<PropertyInfo>,677		rmrk_api678	);679	pass_method!(680		nft_properties(681			collection_id: RmrkCollectionId,682			nft_id: RmrkNftId,683684			#[map(|keys| string_keys_to_bytes_keys(keys))]685			filter_keys: Option<Vec<String>>686		) -> Vec<PropertyInfo>,687		rmrk_api688	);689	pass_method!(nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<ResourceInfo>, rmrk_api);690	pass_method!(nft_resource_priority(collection_id: RmrkCollectionId, nft_id: RmrkNftId, resource_id: RmrkResourceId) -> Option<u32>, rmrk_api);691	pass_method!(base(base_id: RmrkBaseId) -> Option<BaseInfo>, rmrk_api);692	pass_method!(base_parts(base_id: RmrkBaseId) -> Vec<PartType>, rmrk_api);693	pass_method!(theme_names(base_id: RmrkBaseId) -> Vec<RmrkThemeName>, rmrk_api);694	pass_method!(695		theme(696			base_id: RmrkBaseId,697698			#[map(|n| n.into_bytes())]699			theme_name: String,700701			#[map(|keys| string_keys_to_bytes_keys(keys))]702			filter_keys: Option<Vec<String>>703		) -> Option<Theme>, rmrk_api);704}705706fn string_keys_to_bytes_keys(keys: Option<Vec<String>>) -> Option<Vec<Vec<u8>>> {707	keys.map(|keys| keys.into_iter().map(|key| key.into_bytes()).collect())708}
after · client/rpc/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original License18use std::sync::Arc;1920use codec::{Decode, Encode};21use jsonrpsee::{22	core::{RpcResult as Result},23	proc_macros::rpc,24};25use anyhow::anyhow;26use sp_runtime::traits::{AtLeast32BitUnsigned, Member};27use up_data_structs::{28	RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId, Property,29	PropertyKeyPermission, TokenData, TokenChild,30};31use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};32use sp_blockchain::HeaderBackend;33use up_rpc::UniqueApi as UniqueRuntimeApi;34use app_promotion_rpc::AppPromotionApi as AppPromotionRuntimeApi;3536// RMRK37use rmrk_rpc::RmrkApi as RmrkRuntimeApi;38use up_data_structs::{39	RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName, RmrkResourceId,40};4142pub use app_promotion_unique_rpc::AppPromotionApiServer;43pub use rmrk_unique_rpc::RmrkApiServer;4445#[rpc(server)]46#[async_trait]47pub trait UniqueApi<BlockHash, BlockNumber, CrossAccountId, AccountId> {48	/// Get tokens owned by account.49	#[method(name = "unique_accountTokens")]50	fn account_tokens(51		&self,52		collection: CollectionId,53		account: CrossAccountId,54		at: Option<BlockHash>,55	) -> Result<Vec<TokenId>>;5657	/// Get tokens contained within a collection.58	#[method(name = "unique_collectionTokens")]59	fn collection_tokens(60		&self,61		collection: CollectionId,62		at: Option<BlockHash>,63	) -> Result<Vec<TokenId>>;6465	/// Check if the token exists.66	#[method(name = "unique_tokenExists")]67	fn token_exists(68		&self,69		collection: CollectionId,70		token: TokenId,71		at: Option<BlockHash>,72	) -> Result<bool>;7374	/// Get the token owner.75	#[method(name = "unique_tokenOwner")]76	fn token_owner(77		&self,78		collection: CollectionId,79		token: TokenId,80		at: Option<BlockHash>,81	) -> Result<Option<CrossAccountId>>;8283	/// Returns 10 tokens owners in no particular order.84	#[method(name = "unique_tokenOwners")]85	fn token_owners(86		&self,87		collection: CollectionId,88		token: TokenId,89		at: Option<BlockHash>,90	) -> Result<Vec<CrossAccountId>>;9192	/// Get the topmost token owner in the hierarchy of a possibly nested token.93	#[method(name = "unique_topmostTokenOwner")]94	fn topmost_token_owner(95		&self,96		collection: CollectionId,97		token: TokenId,98		at: Option<BlockHash>,99	) -> Result<Option<CrossAccountId>>;100101	/// Get tokens nested directly into the token.102	#[method(name = "unique_tokenChildren")]103	fn token_children(104		&self,105		collection: CollectionId,106		token: TokenId,107		at: Option<BlockHash>,108	) -> Result<Vec<TokenChild>>;109110	/// Get collection properties, optionally limited to the provided keys.111	#[method(name = "unique_collectionProperties")]112	fn collection_properties(113		&self,114		collection: CollectionId,115		keys: Option<Vec<String>>,116		at: Option<BlockHash>,117	) -> Result<Vec<Property>>;118119	/// Get token properties, optionally limited to the provided keys.120	#[method(name = "unique_tokenProperties")]121	fn token_properties(122		&self,123		collection: CollectionId,124		token_id: TokenId,125		keys: Option<Vec<String>>,126		at: Option<BlockHash>,127	) -> Result<Vec<Property>>;128129	/// Get property permissions, optionally limited to the provided keys.130	#[method(name = "unique_propertyPermissions")]131	fn property_permissions(132		&self,133		collection: CollectionId,134		keys: Option<Vec<String>>,135		at: Option<BlockHash>,136	) -> Result<Vec<PropertyKeyPermission>>;137138	/// Get token data, including properties, optionally limited to the provided keys, and total pieces for an RFT.139	#[method(name = "unique_tokenData")]140	fn token_data(141		&self,142		collection: CollectionId,143		token_id: TokenId,144		keys: Option<Vec<String>>,145		at: Option<BlockHash>,146	) -> Result<TokenData<CrossAccountId>>;147148	/// Get the amount of distinctive tokens present in a collection.149	#[method(name = "unique_totalSupply")]150	fn total_supply(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;151152	/// Get the amount of any user tokens owned by an account.153	#[method(name = "unique_accountBalance")]154	fn account_balance(155		&self,156		collection: CollectionId,157		account: CrossAccountId,158		at: Option<BlockHash>,159	) -> Result<u32>;160161	/// Get the amount of a specific token owned by an account.162	#[method(name = "unique_balance")]163	fn balance(164		&self,165		collection: CollectionId,166		account: CrossAccountId,167		token: TokenId,168		at: Option<BlockHash>,169	) -> Result<String>;170171	/// Get the amount of currently possible sponsored transactions on a token for the fee to be taken off a sponsor.172	#[method(name = "unique_allowance")]173	fn allowance(174		&self,175		collection: CollectionId,176		sender: CrossAccountId,177		spender: CrossAccountId,178		token: TokenId,179		at: Option<BlockHash>,180	) -> Result<String>;181182	/// Get the list of admin accounts of a collection.183	#[method(name = "unique_adminlist")]184	fn adminlist(185		&self,186		collection: CollectionId,187		at: Option<BlockHash>,188	) -> Result<Vec<CrossAccountId>>;189190	/// Get the list of accounts allowed to operate within a collection.191	#[method(name = "unique_allowlist")]192	fn allowlist(193		&self,194		collection: CollectionId,195		at: Option<BlockHash>,196	) -> Result<Vec<CrossAccountId>>;197198	/// Check if a user is allowed to operate within a collection.199	#[method(name = "unique_allowed")]200	fn allowed(201		&self,202		collection: CollectionId,203		user: CrossAccountId,204		at: Option<BlockHash>,205	) -> Result<bool>;206207	/// Get the last token ID created in a collection.208	#[method(name = "unique_lastTokenId")]209	fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;210211	/// Get collection info by the specified ID.212	#[method(name = "unique_collectionById")]213	fn collection_by_id(214		&self,215		collection: CollectionId,216		at: Option<BlockHash>,217	) -> Result<Option<RpcCollection<AccountId>>>;218219	/// Get chain stats about collections.220	#[method(name = "unique_collectionStats")]221	fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;222223	/// Get the number of blocks until sponsoring a transaction is available.224	#[method(name = "unique_nextSponsored")]225	fn next_sponsored(226		&self,227		collection: CollectionId,228		account: CrossAccountId,229		token: TokenId,230		at: Option<BlockHash>,231	) -> Result<Option<u64>>;232233	/// Get effective collection limits. If not explicitly set, get the chain defaults.234	#[method(name = "unique_effectiveCollectionLimits")]235	fn effective_collection_limits(236		&self,237		collection_id: CollectionId,238		at: Option<BlockHash>,239	) -> Result<Option<CollectionLimits>>;240241	/// Get the total amount of pieces of an RFT.242	#[method(name = "unique_totalPieces")]243	fn total_pieces(244		&self,245		collection_id: CollectionId,246		token_id: TokenId,247		at: Option<BlockHash>,248	) -> Result<Option<String>>;249}250251mod app_promotion_unique_rpc {252	use super::*;253254	#[rpc(server)]255	#[async_trait]256	pub trait AppPromotionApi<BlockHash, BlockNumber, CrossAccountId, AccountId> {257		/// Returns the total amount of staked tokens.258		#[method(name = "appPromotion_totalStaked")]259		fn total_staked(260			&self,261			staker: Option<CrossAccountId>,262			at: Option<BlockHash>,263		) -> Result<String>;264265		///Returns the total amount of staked tokens per block when staked.266		#[method(name = "appPromotion_totalStakedPerBlock")]267		fn total_staked_per_block(268			&self,269			staker: CrossAccountId,270			at: Option<BlockHash>,271		) -> Result<Vec<(BlockNumber, String)>>;272273		/// Returns the total amount locked by staking tokens.274		#[method(name = "appPromotion_totalStakingLocked")]275		fn total_staking_locked(276			&self,277			staker: CrossAccountId,278			at: Option<BlockHash>,279		) -> Result<String>;280281		/// Returns the total amount of tokens pending withdrawal from staking.282		#[method(name = "appPromotion_pendingUnstake")]283		fn pending_unstake(284			&self,285			staker: Option<CrossAccountId>,286			at: Option<BlockHash>,287		) -> Result<String>;288289		/// Returns the total amount of tokens pending withdrawal from staking per block.290		#[method(name = "appPromotion_pendingUnstakePerBlock")]291		fn pending_unstake_per_block(292			&self,293			staker: CrossAccountId,294			at: Option<BlockHash>,295		) -> Result<Vec<(BlockNumber, String)>>;296	}297}298299mod rmrk_unique_rpc {300	use super::*;301302	#[rpc(server)]303	#[async_trait]304	pub trait RmrkApi<305		BlockHash,306		AccountId,307		CollectionInfo,308		NftInfo,309		ResourceInfo,310		PropertyInfo,311		BaseInfo,312		PartType,313		Theme,314	>315	{316		/// Get the latest created collection ID.317		#[method(name = "rmrk_lastCollectionIdx")]318		fn last_collection_idx(&self, at: Option<BlockHash>) -> Result<RmrkCollectionId>;319320		/// Get collection info by ID.321		#[method(name = "rmrk_collectionById")]322		fn collection_by_id(323			&self,324			id: RmrkCollectionId,325			at: Option<BlockHash>,326		) -> Result<Option<CollectionInfo>>;327328		/// Get NFT info by collection and NFT IDs.329		#[method(name = "rmrk_nftById")]330		fn nft_by_id(331			&self,332			collection_id: RmrkCollectionId,333			nft_id: RmrkNftId,334			at: Option<BlockHash>,335		) -> Result<Option<NftInfo>>;336337		/// Get tokens owned by an account in a collection.338		#[method(name = "rmrk_accountTokens")]339		fn account_tokens(340			&self,341			account_id: AccountId,342			collection_id: RmrkCollectionId,343			at: Option<BlockHash>,344		) -> Result<Vec<RmrkNftId>>;345346		/// Get tokens nested in an NFT - its direct children (not the children's children).347		#[method(name = "rmrk_nftChildren")]348		fn nft_children(349			&self,350			collection_id: RmrkCollectionId,351			nft_id: RmrkNftId,352			at: Option<BlockHash>,353		) -> Result<Vec<RmrkNftChild>>;354355		/// Get collection properties, created by the user - not the proxy-specific properties.356		#[method(name = "rmrk_collectionProperties")]357		fn collection_properties(358			&self,359			collection_id: RmrkCollectionId,360			filter_keys: Option<Vec<String>>,361			at: Option<BlockHash>,362		) -> Result<Vec<PropertyInfo>>;363364		/// Get NFT properties, created by the user - not the proxy-specific properties.365		#[method(name = "rmrk_nftProperties")]366		fn nft_properties(367			&self,368			collection_id: RmrkCollectionId,369			nft_id: RmrkNftId,370			filter_keys: Option<Vec<String>>,371			at: Option<BlockHash>,372		) -> Result<Vec<PropertyInfo>>;373374		/// Get data of resources of an NFT.375		#[method(name = "rmrk_nftResources")]376		fn nft_resources(377			&self,378			collection_id: RmrkCollectionId,379			nft_id: RmrkNftId,380			at: Option<BlockHash>,381		) -> Result<Vec<ResourceInfo>>;382383		/// Get the priority of a resource in an NFT.384		#[method(name = "rmrk_nftResourcePriority")]385		fn nft_resource_priority(386			&self,387			collection_id: RmrkCollectionId,388			nft_id: RmrkNftId,389			resource_id: RmrkResourceId,390			at: Option<BlockHash>,391		) -> Result<Option<u32>>;392393		/// Get base info by its ID.394		#[method(name = "rmrk_base")]395		fn base(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Option<BaseInfo>>;396397		/// Get all parts of a base.398		#[method(name = "rmrk_baseParts")]399		fn base_parts(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Vec<PartType>>;400401		/// Get the theme names belonging to a base.402		#[method(name = "rmrk_themeNames")]403		fn theme_names(404			&self,405			base_id: RmrkBaseId,406			at: Option<BlockHash>,407		) -> Result<Vec<RmrkThemeName>>;408409		/// Get theme info, including properties, optionally limited to the provided keys.410		#[method(name = "rmrk_themes")]411		fn theme(412			&self,413			base_id: RmrkBaseId,414			theme_name: String,415			filter_keys: Option<Vec<String>>,416			at: Option<BlockHash>,417		) -> Result<Option<Theme>>;418	}419}420421pub struct Unique<C, P> {422	client: Arc<C>,423	_marker: std::marker::PhantomData<P>,424}425426impl<C, P> Unique<C, P> {427	pub fn new(client: Arc<C>) -> Self {428		Self {429			client,430			_marker: Default::default(),431		}432	}433}434435pub struct AppPromotion<C, P> {436	client: Arc<C>,437	_marker: std::marker::PhantomData<P>,438}439440impl<C, P> AppPromotion<C, P> {441	pub fn new(client: Arc<C>) -> Self {442		Self {443			client,444			_marker: Default::default(),445		}446	}447}448449pub struct Rmrk<C, P> {450	client: Arc<C>,451	_marker: std::marker::PhantomData<P>,452}453454impl<C, P> Rmrk<C, P> {455	pub fn new(client: Arc<C>) -> Self {456		Self {457			client,458			_marker: Default::default(),459		}460	}461}462463macro_rules! pass_method {464	(465		$method_name:ident(466			$($(#[map(|$map_arg:ident| $map:expr)])? $name:ident: $ty:ty),* $(,)?467		) -> $result:ty $(=> $mapper:expr)?,468		//$runtime_name:ident $(<$($lt: tt),+>)*469		$runtime_api_macro:ident470		$(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*471	) => {472		fn $method_name(473			&self,474			$(475				$name: $ty,476			)*477			at: Option<<Block as BlockT>::Hash>,478		) -> Result<$result> {479			let api = self.client.runtime_api();480			let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));481			let _api_version = if let Ok(Some(api_version)) =482				api.api_version::<$runtime_api_macro!()>(&at)483			{484				api_version485			} else {486				// unreachable for our runtime487				return Err(anyhow!("api is not available").into())488			};489490			let result = $(if _api_version < $ver {491				api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))492			} else)*493			{ api.$method_name(&at, $($((|$map_arg: $ty| $map))? ($name)),*) };494495			Ok(result496				.map_err(|e| anyhow!("unable to query: {e}"))?497				.map_err(|e| anyhow!("runtime error: {e:?}"))$(.map($mapper))??)498		}499	};500}501502macro_rules! unique_api {503	() => {504		dyn UniqueRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>505	};506}507508macro_rules! app_promotion_api {509	() => {510		dyn AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>511	};512}513514macro_rules! rmrk_api {515	() => {516		dyn RmrkRuntimeApi<Block, AccountId, CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme>517	};518}519520#[allow(deprecated)]521impl<C, Block, BlockNumber, CrossAccountId, AccountId>522	UniqueApiServer<<Block as BlockT>::Hash, BlockNumber, CrossAccountId, AccountId>523	for Unique<C, Block>524where525	Block: BlockT,526	BlockNumber: Decode + Member + AtLeast32BitUnsigned,527	AccountId: Decode,528	C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,529	C::Api: UniqueRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,530	CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,531{532	pass_method!(533		account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>, unique_api534	);535	pass_method!(536		collection_tokens(collection: CollectionId) -> Vec<TokenId>, unique_api537	);538	pass_method!(539		token_exists(collection: CollectionId, token: TokenId) -> bool, unique_api540	);541	pass_method!(542		token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api543	);544	pass_method!(545		topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api546	);547	pass_method!(token_children(collection: CollectionId, token: TokenId) -> Vec<TokenChild>, unique_api);548	pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);549	pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);550	pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);551	pass_method!(552		allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string(),553		unique_api554	);555556	pass_method!(collection_properties(557		collection: CollectionId,558559		#[map(|keys| string_keys_to_bytes_keys(keys))]560		keys: Option<Vec<String>>561	) -> Vec<Property>, unique_api);562563	pass_method!(token_properties(564		collection: CollectionId,565		token_id: TokenId,566567		#[map(|keys| string_keys_to_bytes_keys(keys))]568		keys: Option<Vec<String>>569	) -> Vec<Property>, unique_api);570571	pass_method!(property_permissions(572		collection: CollectionId,573574		#[map(|keys| string_keys_to_bytes_keys(keys))]575		keys: Option<Vec<String>>576	) -> Vec<PropertyKeyPermission>, unique_api);577578	pass_method!(token_data(579		collection: CollectionId,580		token_id: TokenId,581582		#[map(|keys| string_keys_to_bytes_keys(keys))]583		keys: Option<Vec<String>>,584	) -> TokenData<CrossAccountId>, unique_api);585586	pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);587	pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);588	pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool, unique_api);589	pass_method!(last_token_id(collection: CollectionId) -> TokenId, unique_api);590	pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>, unique_api);591	pass_method!(collection_stats() -> CollectionStats, unique_api);592	pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>, unique_api);593	pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);594	pass_method!(total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<String> => |o| o.map(|number| number.to_string()) , unique_api);595	pass_method!(token_owners(collection: CollectionId, token: TokenId) -> Vec<CrossAccountId>, unique_api);596}597598impl<C, Block, BlockNumber, CrossAccountId, AccountId>599	app_promotion_unique_rpc::AppPromotionApiServer<600		<Block as BlockT>::Hash,601		BlockNumber,602		CrossAccountId,603		AccountId,604	> for AppPromotion<C, Block>605where606	Block: BlockT,607	BlockNumber: Decode + Member + AtLeast32BitUnsigned,608	AccountId: Decode,609	C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,610	C::Api: AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,611	CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,612{613	pass_method!(total_staked(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);614	pass_method!(total_staked_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>615		|v| v616		.into_iter()617		.map(|(b, a)| (b, a.to_string()))618		.collect::<Vec<_>>(), unique_api);619	pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), unique_api);620	pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), unique_api);621	pass_method!(pending_unstake_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>622		|v| v623		.into_iter()624		.map(|(b, a)| (b, a.to_string()))625		.collect::<Vec<_>>(), unique_api);626}627628#[allow(deprecated)]629impl<630		C,631		Block,632		AccountId,633		CollectionInfo,634		NftInfo,635		ResourceInfo,636		PropertyInfo,637		BaseInfo,638		PartType,639		Theme,640	>641	rmrk_unique_rpc::RmrkApiServer<642		<Block as BlockT>::Hash,643		AccountId,644		CollectionInfo,645		NftInfo,646		ResourceInfo,647		PropertyInfo,648		BaseInfo,649		PartType,650		Theme,651	> for Rmrk<C, Block>652where653	C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,654	C::Api: RmrkRuntimeApi<655		Block,656		AccountId,657		CollectionInfo,658		NftInfo,659		ResourceInfo,660		PropertyInfo,661		BaseInfo,662		PartType,663		Theme,664	>,665	AccountId: Decode + Encode,666	CollectionInfo: Decode,667	NftInfo: Decode,668	ResourceInfo: Decode,669	PropertyInfo: Decode,670	BaseInfo: Decode,671	PartType: Decode,672	Theme: Decode,673	Block: BlockT,674{675	pass_method!(last_collection_idx() -> RmrkCollectionId, rmrk_api);676	pass_method!(collection_by_id(id: RmrkCollectionId) -> Option<CollectionInfo>, rmrk_api);677	pass_method!(nft_by_id(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Option<NftInfo>, rmrk_api);678	pass_method!(account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Vec<RmrkNftId>, rmrk_api);679	pass_method!(nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkNftChild>, rmrk_api);680	pass_method!(681		collection_properties(682			collection_id: RmrkCollectionId,683684			#[map(|keys| string_keys_to_bytes_keys(keys))]685			filter_keys: Option<Vec<String>>686		) -> Vec<PropertyInfo>,687		rmrk_api688	);689	pass_method!(690		nft_properties(691			collection_id: RmrkCollectionId,692			nft_id: RmrkNftId,693694			#[map(|keys| string_keys_to_bytes_keys(keys))]695			filter_keys: Option<Vec<String>>696		) -> Vec<PropertyInfo>,697		rmrk_api698	);699	pass_method!(nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<ResourceInfo>, rmrk_api);700	pass_method!(nft_resource_priority(collection_id: RmrkCollectionId, nft_id: RmrkNftId, resource_id: RmrkResourceId) -> Option<u32>, rmrk_api);701	pass_method!(base(base_id: RmrkBaseId) -> Option<BaseInfo>, rmrk_api);702	pass_method!(base_parts(base_id: RmrkBaseId) -> Vec<PartType>, rmrk_api);703	pass_method!(theme_names(base_id: RmrkBaseId) -> Vec<RmrkThemeName>, rmrk_api);704	pass_method!(705		theme(706			base_id: RmrkBaseId,707708			#[map(|n| n.into_bytes())]709			theme_name: String,710711			#[map(|keys| string_keys_to_bytes_keys(keys))]712			filter_keys: Option<Vec<String>>713		) -> Option<Theme>, rmrk_api);714}715716fn string_keys_to_bytes_keys(keys: Option<Vec<String>>) -> Option<Vec<Vec<u8>>> {717	keys.map(|keys| keys.into_iter().map(|key| key.into_bytes()).collect())718}
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -148,7 +148,12 @@
 	C::Api: fp_rpc::ConvertTransactionRuntimeApi<Block>,
 	C::Api:
 		up_rpc::UniqueApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,
-	C::Api: app_promotion_rpc::AppPromotionApi<Block, BlockNumber, <R as RuntimeInstance>::CrossAccountId, AccountId>,
+	C::Api: app_promotion_rpc::AppPromotionApi<
+		Block,
+		BlockNumber,
+		<R as RuntimeInstance>::CrossAccountId,
+		AccountId,
+	>,
 	C::Api: rmrk_rpc::RmrkApi<
 		Block,
 		AccountId,
modifiedpallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/benchmarking.rs
+++ b/pallets/app-promotion/src/benchmarking.rs
@@ -39,13 +39,13 @@
 		T::BlockNumber: From<u32> + Into<u32>,
 		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>
 	}
-	start_app_promotion {
+	// start_app_promotion {
 
-	} : {PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), None)?}
+	// } : {PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), None)?}
 
-	stop_app_promotion{
-		PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), Some(25.into()))?;
-	} : {PromototionPallet::<T>::stop_app_promotion(RawOrigin::Root.into())?}
+	// stop_app_promotion{
+	// 	PromototionPallet::<T>::start_app_promotion(RawOrigin::Root.into(), Some(25.into()))?;
+	// } : {PromototionPallet::<T>::stop_app_promotion(RawOrigin::Root.into())?}
 
 	set_admin_address {
 		let pallet_admin = account::<T::AccountId>("admin", 0, SEED);
@@ -58,6 +58,10 @@
 		PromototionPallet::<T>::set_admin_address(RawOrigin::Root.into(), T::CrossAccountId::from_sub(pallet_admin.clone()))?;
 		let _ = <T as Config>::Currency::make_free_balance_be(&pallet_admin,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 		let staker: T::AccountId = account("caller", 0, SEED);
+		let stakers: Vec<T::AccountId> = (0..100).map(|index| account("staker", index, SEED)).collect();
+		stakers.iter().for_each(|staker| {
+			<T as Config>::Currency::make_free_balance_be(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
+		});
 		let _ = <T as Config>::Currency::make_free_balance_be(&staker,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
 		let _ = PromototionPallet::<T>::stake(RawOrigin::Signed(staker.clone()).into(), share * <T as Config>::Currency::total_balance(&staker))?;
 	} : {PromototionPallet::<T>::payout_stakers(RawOrigin::Signed(pallet_admin.clone()).into(), Some(1))?}
@@ -70,9 +74,9 @@
 
 	unstake {
 		let caller = account::<T::AccountId>("caller", 0, SEED);
-		let share = Perbill::from_rational(1u32, 10);
+		let share = Perbill::from_rational(1u32, 20);
 		let _ = <T as Config>::Currency::make_free_balance_be(&caller,  Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
-		let _ = PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))?;
+		(0..10).map(|_| PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))).collect::<Result<Vec<_>, _>>()?;
 
 	} : {PromototionPallet::<T>::unstake(RawOrigin::Signed(caller.clone()).into())?}
 
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -36,7 +36,12 @@
 pub mod types;
 pub mod weights;
 
-use sp_std::{vec::Vec, iter::Sum, borrow::ToOwned};
+use sp_std::{
+	vec::{Vec},
+	vec,
+	iter::Sum,
+	borrow::ToOwned,
+};
 use sp_core::H160;
 use codec::EncodeLike;
 use pallet_balances::BalanceLock;
@@ -63,6 +68,9 @@
 	ArithmeticError,
 };
 
+pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";
+const PENDING_LIMIT_PER_BLOCK: u32 = 3;
+
 type BalanceOf<T> =
 	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
 
@@ -71,18 +79,20 @@
 // const WEEK: u32 = 7 * DAY;
 // const TWO_WEEK: u32 = 2 * WEEK;
 // const YEAR: u32 = DAY * 365;
-
-pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";
 
 #[frame_support::pallet]
 pub mod pallet {
 	use super::*;
-	use frame_support::{Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId};
+	use frame_support::{
+		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,
+		traits::ReservableCurrency,
+	};
 	use frame_system::pallet_prelude::*;
 
 	#[pallet::config]
 	pub trait Config: frame_system::Config + pallet_evm::account::Config {
-		type Currency: ExtendedLockableCurrency<Self::AccountId>;
+		type Currency: ExtendedLockableCurrency<Self::AccountId>
+			+ ReservableCurrency<Self::AccountId>;
 
 		type CollectionHandler: CollectionHandler<
 			AccountId = Self::AccountId,
@@ -149,6 +159,7 @@
 		NoPermission,
 		/// Insufficient funds to perform an action
 		NotSufficientFounds,
+		PendingForBlockOverflow,
 		/// An error related to the fact that an invalid argument was passed to perform an action
 		InvalidArgument,
 	}
@@ -175,25 +186,33 @@
 		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;
 
 	/// Amount of tokens pending unstake per user per block.
+	// #[pallet::storage]
+	// pub type PendingUnstake<T: Config> = StorageNMap<
+	// 	Key = (
+	// 		Key<Blake2_128Concat, T::AccountId>,
+	// 		Key<Twox64Concat, T::BlockNumber>,
+	// 	),
+	// 	Value = BalanceOf<T>,
+	// 	QueryKind = ValueQuery,
+	// >;
 	#[pallet::storage]
-	pub type PendingUnstake<T: Config> = StorageNMap<
-		Key = (
-			Key<Blake2_128Concat, T::AccountId>,
-			Key<Twox64Concat, T::BlockNumber>,
-		),
-		Value = BalanceOf<T>,
-		QueryKind = ValueQuery,
+	pub type PendingUnstake<T: Config> = StorageMap<
+		_,
+		Twox64Concat,
+		T::BlockNumber,
+		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,
+		ValueQuery,
 	>;
 
 	/// A block when app-promotion has started .I think this is redundant, because we only need `NextInterestBlock`.
 	#[pallet::storage]
 	pub type StartBlock<T: Config> = StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
 
-	/// Next target block when interest is recalculated
-	#[pallet::storage]
-	#[pallet::getter(fn get_interest_block)]
-	pub type NextInterestBlock<T: Config> =
-		StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
+	// /// Next target block when interest is recalculated
+	// #[pallet::storage]
+	// #[pallet::getter(fn get_interest_block)]
+	// pub type NextInterestBlock<T: Config> =
+	// 	StorageValue<Value = T::BlockNumber, QueryKind = ValueQuery>;
 
 	/// Stores hash a record for which the last revenue recalculation was performed.
 	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.
@@ -204,59 +223,26 @@
 
 	#[pallet::hooks]
 	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
-		fn on_initialize(current_block: T::BlockNumber) -> Weight
+		fn on_initialize(current_block_number: T::BlockNumber) -> Weight
 		where
 			<T as frame_system::Config>::BlockNumber: From<u32>,
 		{
 			let mut consumed_weight = 0;
-			// let mut add_weight = |reads, writes, weight| {
-			// 	consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
-			// 	consumed_weight += weight;
-			// };
+			let mut add_weight = |reads, writes, weight| {
+				consumed_weight += T::DbWeight::get().reads_writes(reads, writes);
+				consumed_weight += weight;
+			};
 
-			let current_relay_block = T::RelayBlockNumberProvider::current_block_number();
-			PendingUnstake::<T>::iter()
-				.filter_map(|((staker, block), amount)| {
-					if block <= current_relay_block {
-						Some((staker, block, amount))
-					} else {
-						None
-					}
-				})
-				.for_each(|(staker, block, amount)| {
-					Self::unlock_balance_unchecked(&staker, amount);
-					<PendingUnstake<T>>::remove((staker, block));
-				});
+			let block_pending = PendingUnstake::<T>::take(current_block_number);
 
-			// let next_interest_block = Self::get_interest_block();
-			// let current_relay_block = T::RelayBlockNumberProvider::current_block_number();
-			// if next_interest_block != 0.into() && current_relay_block >= next_interest_block {
-			// 	let mut acc = <BalanceOf<T>>::default();
-			// 	let mut base_acc = <BalanceOf<T>>::default();
+			add_weight(0, 1, 0);
 
-			// 	NextInterestBlock::<T>::set(
-			// 		NextInterestBlock::<T>::get() + T::RecalculationInterval::get(),
-			// 	);
-			// 	add_weight(0, 1, 0);
-
-			// 	Staked::<T>::iter()
-			// 		.filter(|((_, block), _)| {
-			// 			*block + T::RecalculationInterval::get() <= current_relay_block
-			// 		})
-			// 		.for_each(|((staker, block), amount)| {
-			// 			Self::recalculate_stake(&staker, block, amount, &mut acc);
-			// 			add_weight(0, 0, T::WeightInfo::recalculate_stake());
-			// 			base_acc += amount;
-			// 		});
-			// 	<TotalStaked<T>>::get()
-			// 		.checked_add(&acc)
-			// 		.map(|res| <TotalStaked<T>>::set(res));
+			if !block_pending.is_empty() {
+				block_pending.into_iter().for_each(|(staker, amount)| {
+					<T::Currency as ReservableCurrency<T::AccountId>>::unreserve(&staker, amount);
+				});
+			}
 
-			// 	Self::deposit_event(Event::StakingRecalculation(base_acc, acc));
-			// 	add_weight(0, 1, 0);
-			// } else {
-			// 	add_weight(1, 0, 0)
-			// };
 			consumed_weight
 		}
 	}
@@ -275,44 +261,44 @@
 			Ok(())
 		}
 
-		#[pallet::weight(T::WeightInfo::start_app_promotion())]
-		pub fn start_app_promotion(
-			origin: OriginFor<T>,
-			promotion_start_relay_block: Option<T::BlockNumber>,
-		) -> DispatchResult
-		where
-			<T as frame_system::Config>::BlockNumber: From<u32>,
-		{
-			ensure_root(origin)?;
+		// #[pallet::weight(T::WeightInfo::start_app_promotion())]
+		// pub fn start_app_promotion(
+		// 	origin: OriginFor<T>,
+		// 	promotion_start_relay_block: Option<T::BlockNumber>,
+		// ) -> DispatchResult
+		// where
+		// 	<T as frame_system::Config>::BlockNumber: From<u32>,
+		// {
+		// 	ensure_root(origin)?;
 
-			// Start app-promotion mechanics if it has not been yet initialized
-			if <StartBlock<T>>::get() == 0u32.into() {
-				let start_block = promotion_start_relay_block
-					.unwrap_or(T::RelayBlockNumberProvider::current_block_number());
+		// 	// Start app-promotion mechanics if it has not been yet initialized
+		// 	if <StartBlock<T>>::get() == 0u32.into() {
+		// 		let start_block = promotion_start_relay_block
+		// 			.unwrap_or(T::RelayBlockNumberProvider::current_block_number());
 
-				// Set promotion global start block
-				<StartBlock<T>>::set(start_block);
+		// 		// Set promotion global start block
+		// 		<StartBlock<T>>::set(start_block);
 
-				<NextInterestBlock<T>>::set(start_block + T::RecalculationInterval::get());
-			}
+		// 		<NextInterestBlock<T>>::set(start_block + T::RecalculationInterval::get());
+		// 	}
 
-			Ok(())
-		}
+		// 	Ok(())
+		// }
 
-		#[pallet::weight(T::WeightInfo::stop_app_promotion())]
-		pub fn stop_app_promotion(origin: OriginFor<T>) -> DispatchResult
-		where
-			<T as frame_system::Config>::BlockNumber: From<u32>,
-		{
-			ensure_root(origin)?;
+		// #[pallet::weight(T::WeightInfo::stop_app_promotion())]
+		// pub fn stop_app_promotion(origin: OriginFor<T>) -> DispatchResult
+		// where
+		// 	<T as frame_system::Config>::BlockNumber: From<u32>,
+		// {
+		// 	ensure_root(origin)?;
 
-			if <StartBlock<T>>::get() != 0u32.into() {
-				<StartBlock<T>>::set(T::BlockNumber::default());
-				<NextInterestBlock<T>>::set(T::BlockNumber::default());
-			}
+		// 	if <StartBlock<T>>::get() != 0u32.into() {
+		// 		<StartBlock<T>>::set(T::BlockNumber::default());
+		// 		<NextInterestBlock<T>>::set(T::BlockNumber::default());
+		// 	}
 
-			Ok(())
-		}
+		// 	Ok(())
+		// }
 
 		#[pallet::weight(T::WeightInfo::stake())]
 		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {
@@ -369,6 +355,10 @@
 		#[pallet::weight(T::WeightInfo::unstake())]
 		pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {
 			let staker_id = ensure_signed(staker)?;
+			let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();
+			let mut pendings = <PendingUnstake<T>>::get(block);
+
+			ensure!(pendings.is_full(), Error::<T>::PendingForBlockOverflow);
 
 			let mut total_stakes = 0u64;
 
@@ -382,15 +372,17 @@
 			if total_staked.is_zero() {
 				return Ok(None.into());
 			}
-			let block =
-				T::RelayBlockNumberProvider::current_block_number() + T::PendingInterval::get();
-			<PendingUnstake<T>>::insert(
-				(&staker_id, block),
-				<PendingUnstake<T>>::get((&staker_id, block))
-					.checked_add(&total_staked)
-					.ok_or(ArithmeticError::Overflow)?,
-			);
 
+			pendings
+				.try_push((staker_id.clone(), total_staked))
+				.map_err(|_| Error::<T>::PendingForBlockOverflow)?;
+
+			<PendingUnstake<T>>::insert(block, pendings);
+
+			Self::unlock_balance_unchecked(&staker_id, total_staked);
+
+			<T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;
+
 			TotalStaked::<T>::set(
 				TotalStaked::<T>::get()
 					.checked_sub(&total_staked)
@@ -671,17 +663,37 @@
 	<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,
 {
 	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {
-		staker.map_or(PendingUnstake::<T>::iter_values().sum(), |s| {
-			PendingUnstake::<T>::iter_prefix_values((s.as_sub(),)).sum()
-		})
+		staker.map_or(
+			PendingUnstake::<T>::iter_values()
+				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))
+				.sum(),
+			|s| {
+				PendingUnstake::<T>::iter_values()
+					.flatten()
+					.filter_map(|(id, amount)| {
+						if id == *s.as_sub() {
+							Some(amount)
+						} else {
+							None
+						}
+					})
+					.sum()
+			},
+		)
 	}
 
 	pub fn cross_id_pending_unstake_per_block(
 		staker: T::CrossAccountId,
 	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {
-		let mut unsorted_res = PendingUnstake::<T>::iter_prefix((staker.as_sub(),))
-			.into_iter()
-			.collect::<Vec<_>>();
+		let mut unsorted_res = vec![];
+		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {
+			pendings.into_iter().for_each(|(id, amount)| {
+				if id == *staker.as_sub() {
+					unsorted_res.push((block, amount));
+				};
+			})
+		});
+
 		unsorted_res.sort_by_key(|(block, _)| *block);
 		unsorted_res
 	}
modifiedpallets/app-promotion/src/tests.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/tests.rs
+++ b/pallets/app-promotion/src/tests.rs
@@ -16,20 +16,20 @@
 
 #![cfg(test)]
 #![allow(clippy::from_over_into)]
-use crate as pallet_promotion;
+// use crate as pallet_promotion;
 
-use frame_benchmarking::{add_benchmark, BenchmarkBatch};
-use frame_support::{
-	assert_ok, parameter_types,
-	traits::{Currency, OnInitialize, Everything, ConstU32},
-};
-use frame_system::RawOrigin;
-use sp_core::H256;
-use sp_runtime::{
-	traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},
-	testing::Header,
-	Perbill, Perquintill,
-};
+// use frame_benchmarking::{add_benchmark, BenchmarkBatch};
+// use frame_support::{
+// 	assert_ok, parameter_types,
+// 	traits::{Currency, OnInitialize, Everything, ConstU32},
+// };
+// use frame_system::RawOrigin;
+// use sp_core::H256;
+// use sp_runtime::{
+// 	traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},
+// 	testing::Header,
+// 	Perbill, Perquintill,
+// };
 
 // type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;
 // type Block = frame_system::mocking::MockBlock<Test>;
@@ -127,24 +127,24 @@
 // 	} )
 // }
 
-#[test]
-fn test_perbill() {
-	const ONE_UNIQE: u128 = 1_000_000_000_000_000_000;
-	const SECONDS_TO_BLOCK: u32 = 12;
-	const DAY: u32 = 60 * 60 * 24 / SECONDS_TO_BLOCK;
-	const RECALCULATION_INTERVAL: u32 = 10;
-	let day_rate = Perbill::from_rational(5u64, 10_000);
-	let interval_rate =
-		Perbill::from_rational::<u64>(RECALCULATION_INTERVAL.into(), DAY.into()) * day_rate;
-	println!("{:?}", interval_rate * ONE_UNIQE + ONE_UNIQE);
-	println!("{:?}", day_rate * ONE_UNIQE);
-	println!("{:?}", Perbill::one() * ONE_UNIQE);
-	println!("{:?}", ONE_UNIQE);
-	let mut next_iters = ONE_UNIQE + interval_rate * ONE_UNIQE;
-	next_iters += interval_rate * next_iters;
-	println!("{:?}", next_iters);
-	let day_income = day_rate * ONE_UNIQE;
-	let interval_income = interval_rate * ONE_UNIQE;
-	let ratio = day_income / interval_income;
-	println!("{:?} || {:?}", ratio, DAY / RECALCULATION_INTERVAL);
-}
+// #[test]
+// fn test_perbill() {
+// 	const ONE_UNIQE: u128 = 1_000_000_000_000_000_000;
+// 	const SECONDS_TO_BLOCK: u32 = 12;
+// 	const DAY: u32 = 60 * 60 * 24 / SECONDS_TO_BLOCK;
+// 	const RECALCULATION_INTERVAL: u32 = 10;
+// 	let day_rate = Perbill::from_rational(5u64, 10_000);
+// 	let interval_rate =
+// 		Perbill::from_rational::<u64>(RECALCULATION_INTERVAL.into(), DAY.into()) * day_rate;
+// 	println!("{:?}", interval_rate * ONE_UNIQE + ONE_UNIQE);
+// 	println!("{:?}", day_rate * ONE_UNIQE);
+// 	println!("{:?}", Perbill::one() * ONE_UNIQE);
+// 	println!("{:?}", ONE_UNIQE);
+// 	let mut next_iters = ONE_UNIQE + interval_rate * ONE_UNIQE;
+// 	next_iters += interval_rate * next_iters;
+// 	println!("{:?}", next_iters);
+// 	let day_income = day_rate * ONE_UNIQE;
+// 	let interval_income = interval_rate * ONE_UNIQE;
+// 	let ratio = day_income / interval_income;
+// 	println!("{:?} || {:?}", ratio, DAY / RECALCULATION_INTERVAL);
+// }
modifiedpallets/app-promotion/src/weights.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/weights.rs
+++ b/pallets/app-promotion/src/weights.rs
@@ -3,7 +3,7 @@
 //! Autogenerated weights for pallet_app_promotion
 //!
 //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
-//! DATE: 2022-08-31, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
+//! DATE: 2022-09-01, STEPS: `50`, REPEAT: 80, LOW RANGE: `[]`, HIGH RANGE: `[]`
 //! EXECUTION: None, WASM-EXECUTION: Compiled, CHAIN: None, DB CACHE: 1024
 
 // Executed Command:
@@ -34,8 +34,6 @@
 
 /// Weight functions needed for pallet_app_promotion.
 pub trait WeightInfo {
-	fn start_app_promotion() -> Weight;
-	fn stop_app_promotion() -> Weight;
 	fn set_admin_address() -> Weight;
 	fn payout_stakers() -> Weight;
 	fn stake() -> Weight;
@@ -49,24 +47,9 @@
 /// Weights for pallet_app_promotion using the Substrate node and recommended hardware.
 pub struct SubstrateWeight<T>(PhantomData<T>);
 impl<T: frame_system::Config> WeightInfo for SubstrateWeight<T> {
-	// Storage: Promotion StartBlock (r:1 w:1)
-	// Storage: ParachainSystem ValidationData (r:1 w:0)
-	// Storage: Promotion NextInterestBlock (r:0 w:1)
-	fn start_app_promotion() -> Weight {
-		(3_995_000 as Weight)
-			.saturating_add(T::DbWeight::get().reads(2 as Weight))
-			.saturating_add(T::DbWeight::get().writes(2 as Weight))
-	}
-	// Storage: Promotion StartBlock (r:1 w:1)
-	// Storage: Promotion NextInterestBlock (r:0 w:1)
-	fn stop_app_promotion() -> Weight {
-		(3_623_000 as Weight)
-			.saturating_add(T::DbWeight::get().reads(1 as Weight))
-			.saturating_add(T::DbWeight::get().writes(2 as Weight))
-	}
 	// Storage: Promotion Admin (r:0 w:1)
 	fn set_admin_address() -> Weight {
-		(1_203_000 as Weight)
+		(515_000 as Weight)
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
@@ -74,54 +57,56 @@
 	// Storage: Promotion NextCalculatedRecord (r:1 w:1)
 	// Storage: Promotion Staked (r:2 w:0)
 	fn payout_stakers() -> Weight {
-		(10_859_000 as Weight)
+		(8_475_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(5 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
 	// Storage: System Account (r:1 w:1)
+	// Storage: Promotion StakesPerAccount (r:1 w:1)
 	// Storage: Balances Locks (r:1 w:1)
 	// Storage: ParachainSystem ValidationData (r:1 w:0)
 	// Storage: Promotion Staked (r:1 w:1)
 	// Storage: Promotion TotalStaked (r:1 w:1)
 	fn stake() -> Weight {
-		(14_789_000 as Weight)
-			.saturating_add(T::DbWeight::get().reads(5 as Weight))
-			.saturating_add(T::DbWeight::get().writes(4 as Weight))
+		(12_266_000 as Weight)
+			.saturating_add(T::DbWeight::get().reads(6 as Weight))
+			.saturating_add(T::DbWeight::get().writes(5 as Weight))
 	}
 	// Storage: Promotion Staked (r:2 w:1)
 	// Storage: ParachainSystem ValidationData (r:1 w:0)
 	// Storage: Promotion PendingUnstake (r:1 w:1)
 	// Storage: Promotion TotalStaked (r:1 w:1)
+	// Storage: Promotion StakesPerAccount (r:0 w:1)
 	fn unstake() -> Weight {
-		(16_889_000 as Weight)
+		(10_663_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(5 as Weight))
-			.saturating_add(T::DbWeight::get().writes(3 as Weight))
+			.saturating_add(T::DbWeight::get().writes(4 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn sponsor_collection() -> Weight {
-		(18_377_000 as Weight)
+		(10_879_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn stop_sponsoring_collection() -> Weight {
-		(13_989_000 as Weight)
+		(10_548_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
 	fn sponsor_contract() -> Weight {
-		(4_162_000 as Weight)
+		(2_130_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(1 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
 	fn stop_sponsoring_contract() -> Weight {
-		(5_457_000 as Weight)
+		(3_509_000 as Weight)
 			.saturating_add(T::DbWeight::get().reads(2 as Weight))
 			.saturating_add(T::DbWeight::get().writes(1 as Weight))
 	}
@@ -129,24 +114,9 @@
 
 // For backwards compatibility and tests
 impl WeightInfo for () {
-	// Storage: Promotion StartBlock (r:1 w:1)
-	// Storage: ParachainSystem ValidationData (r:1 w:0)
-	// Storage: Promotion NextInterestBlock (r:0 w:1)
-	fn start_app_promotion() -> Weight {
-		(3_995_000 as Weight)
-			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
-	}
-	// Storage: Promotion StartBlock (r:1 w:1)
-	// Storage: Promotion NextInterestBlock (r:0 w:1)
-	fn stop_app_promotion() -> Weight {
-		(3_623_000 as Weight)
-			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(2 as Weight))
-	}
 	// Storage: Promotion Admin (r:0 w:1)
 	fn set_admin_address() -> Weight {
-		(1_203_000 as Weight)
+		(515_000 as Weight)
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
@@ -154,54 +124,56 @@
 	// Storage: Promotion NextCalculatedRecord (r:1 w:1)
 	// Storage: Promotion Staked (r:2 w:0)
 	fn payout_stakers() -> Weight {
-		(10_859_000 as Weight)
+		(8_475_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
 	// Storage: System Account (r:1 w:1)
+	// Storage: Promotion StakesPerAccount (r:1 w:1)
 	// Storage: Balances Locks (r:1 w:1)
 	// Storage: ParachainSystem ValidationData (r:1 w:0)
 	// Storage: Promotion Staked (r:1 w:1)
 	// Storage: Promotion TotalStaked (r:1 w:1)
 	fn stake() -> Weight {
-		(14_789_000 as Weight)
-			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
+		(12_266_000 as Weight)
+			.saturating_add(RocksDbWeight::get().reads(6 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(5 as Weight))
 	}
 	// Storage: Promotion Staked (r:2 w:1)
 	// Storage: ParachainSystem ValidationData (r:1 w:0)
 	// Storage: Promotion PendingUnstake (r:1 w:1)
 	// Storage: Promotion TotalStaked (r:1 w:1)
+	// Storage: Promotion StakesPerAccount (r:0 w:1)
 	fn unstake() -> Weight {
-		(16_889_000 as Weight)
+		(10_663_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(5 as Weight))
-			.saturating_add(RocksDbWeight::get().writes(3 as Weight))
+			.saturating_add(RocksDbWeight::get().writes(4 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn sponsor_collection() -> Weight {
-		(18_377_000 as Weight)
+		(10_879_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
 	// Storage: Common CollectionById (r:1 w:1)
 	fn stop_sponsoring_collection() -> Weight {
-		(13_989_000 as Weight)
+		(10_548_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:0 w:1)
 	fn sponsor_contract() -> Weight {
-		(4_162_000 as Weight)
+		(2_130_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(1 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
 	// Storage: Promotion Admin (r:1 w:0)
 	// Storage: EvmContractHelpers Sponsoring (r:1 w:1)
 	fn stop_sponsoring_contract() -> Weight {
-		(5_457_000 as Weight)
+		(3_509_000 as Weight)
 			.saturating_add(RocksDbWeight::get().reads(2 as Weight))
 			.saturating_add(RocksDbWeight::get().writes(1 as Weight))
 	}
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -197,11 +197,11 @@
                     #[cfg(feature = "app-promotion")]
                     return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked(staker).unwrap_or_default());
                 }
-                
+
                 fn total_staked_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {
                     #[cfg(not(feature = "app-promotion"))]
                     return unsupported!();
-                    
+
                     #[cfg(feature = "app-promotion")]
                     return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_total_staked_per_block(staker));
                 }
@@ -209,7 +209,7 @@
                 fn total_staking_locked(staker: CrossAccountId) -> Result<u128, DispatchError> {
                     #[cfg(not(feature = "app-promotion"))]
                     return unsupported!();
-                    
+
                     #[cfg(feature = "app-promotion")]
                     return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_locked_balance(staker));
                 }
@@ -217,7 +217,7 @@
                 fn pending_unstake(staker: Option<CrossAccountId>) -> Result<u128, DispatchError> {
                     #[cfg(not(feature = "app-promotion"))]
                     return unsupported!();
-                    
+
                     #[cfg(feature = "app-promotion")]
                     return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake(staker));
                 }
@@ -225,7 +225,7 @@
                 fn pending_unstake_per_block(staker: CrossAccountId) -> Result<Vec<(BlockNumber, u128)>, DispatchError> {
                     #[cfg(not(feature = "app-promotion"))]
                     return unsupported!();
-                    
+
                     #[cfg(feature = "app-promotion")]
                     return Ok(<pallet_app_promotion::Pallet<Runtime>>::cross_id_pending_unstake_per_block(staker))
                 }