difftreelog
fix logic payout
in: master
3 files changed
client/rpc/src/lib.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// 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}420421macro_rules! define_struct_for_server_api {422 ($name:ident) => {423 pub struct $name<C, P> {424 client: Arc<C>,425 _marker: std::marker::PhantomData<P>,426 }427 428 impl<C, P> $name<C, P> {429 pub fn new(client: Arc<C>) -> Self {430 Self {431 client,432 _marker: Default::default(),433 }434 }435 }436 };437}438439define_struct_for_server_api!(Unique);440define_struct_for_server_api!(AppPromotion);441define_struct_for_server_api!(Rmrk);442443macro_rules! pass_method {444 (445 $method_name:ident(446 $($(#[map(|$map_arg:ident| $map:expr)])? $name:ident: $ty:ty),* $(,)?447 ) -> $result:ty $(=> $mapper:expr)?,448 //$runtime_name:ident $(<$($lt: tt),+>)*449 $runtime_api_macro:ident450 $(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*451 ) => {452 fn $method_name(453 &self,454 $(455 $name: $ty,456 )*457 at: Option<<Block as BlockT>::Hash>,458 ) -> Result<$result> {459 let api = self.client.runtime_api();460 let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));461 let _api_version = if let Ok(Some(api_version)) =462 api.api_version::<$runtime_api_macro!()>(&at)463 {464 api_version465 } else {466 // unreachable for our runtime467 return Err(anyhow!("api is not available").into())468 };469470 let result = $(if _api_version < $ver {471 api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))472 } else)*473 { api.$method_name(&at, $($((|$map_arg: $ty| $map))? ($name)),*) };474475 Ok(result476 .map_err(|e| anyhow!("unable to query: {e}"))?477 .map_err(|e| anyhow!("runtime error: {e:?}"))$(.map($mapper))??)478 }479 };480}481482macro_rules! unique_api {483 () => {484 dyn UniqueRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>485 };486}487488macro_rules! app_promotion_api {489 () => {490 dyn AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>491 };492}493494macro_rules! rmrk_api {495 () => {496 dyn RmrkRuntimeApi<Block, AccountId, CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme>497 };498}499500#[allow(deprecated)]501impl<C, Block, BlockNumber, CrossAccountId, AccountId>502 UniqueApiServer<<Block as BlockT>::Hash, BlockNumber, CrossAccountId, AccountId>503 for Unique<C, Block>504where505 Block: BlockT,506 BlockNumber: Decode + Member + AtLeast32BitUnsigned,507 AccountId: Decode,508 C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,509 C::Api: UniqueRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,510 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,511{512 pass_method!(513 account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>, unique_api514 );515 pass_method!(516 collection_tokens(collection: CollectionId) -> Vec<TokenId>, unique_api517 );518 pass_method!(519 token_exists(collection: CollectionId, token: TokenId) -> bool, unique_api520 );521 pass_method!(522 token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api523 );524 pass_method!(525 topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api526 );527 pass_method!(token_children(collection: CollectionId, token: TokenId) -> Vec<TokenChild>, unique_api);528 pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);529 pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);530 pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);531 pass_method!(532 allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string(),533 unique_api534 );535536 pass_method!(collection_properties(537 collection: CollectionId,538539 #[map(|keys| string_keys_to_bytes_keys(keys))]540 keys: Option<Vec<String>>541 ) -> Vec<Property>, unique_api);542543 pass_method!(token_properties(544 collection: CollectionId,545 token_id: TokenId,546547 #[map(|keys| string_keys_to_bytes_keys(keys))]548 keys: Option<Vec<String>>549 ) -> Vec<Property>, unique_api);550551 pass_method!(property_permissions(552 collection: CollectionId,553554 #[map(|keys| string_keys_to_bytes_keys(keys))]555 keys: Option<Vec<String>>556 ) -> Vec<PropertyKeyPermission>, unique_api);557558 pass_method!(token_data(559 collection: CollectionId,560 token_id: TokenId,561562 #[map(|keys| string_keys_to_bytes_keys(keys))]563 keys: Option<Vec<String>>,564 ) -> TokenData<CrossAccountId>, unique_api);565566 pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);567 pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);568 pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool, unique_api);569 pass_method!(last_token_id(collection: CollectionId) -> TokenId, unique_api);570 pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>, unique_api);571 pass_method!(collection_stats() -> CollectionStats, unique_api);572 pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>, unique_api);573 pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);574 pass_method!(total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<String> => |o| o.map(|number| number.to_string()) , unique_api);575 pass_method!(token_owners(collection: CollectionId, token: TokenId) -> Vec<CrossAccountId>, unique_api);576}577578impl<C, Block, BlockNumber, CrossAccountId, AccountId>579 app_promotion_unique_rpc::AppPromotionApiServer<580 <Block as BlockT>::Hash,581 BlockNumber,582 CrossAccountId,583 AccountId,584 > for AppPromotion<C, Block>585where586 Block: BlockT,587 BlockNumber: Decode + Member + AtLeast32BitUnsigned,588 AccountId: Decode,589 C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,590 C::Api: AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,591 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,592{593 pass_method!(total_staked(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);594 pass_method!(total_staked_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>595 |v| v596 .into_iter()597 .map(|(b, a)| (b, a.to_string()))598 .collect::<Vec<_>>(), app_promotion_api);599 pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), app_promotion_api);600 pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);601 pass_method!(pending_unstake_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>602 |v| v603 .into_iter()604 .map(|(b, a)| (b, a.to_string()))605 .collect::<Vec<_>>(), app_promotion_api);606}607608#[allow(deprecated)]609impl<610 C,611 Block,612 AccountId,613 CollectionInfo,614 NftInfo,615 ResourceInfo,616 PropertyInfo,617 BaseInfo,618 PartType,619 Theme,620 >621 rmrk_unique_rpc::RmrkApiServer<622 <Block as BlockT>::Hash,623 AccountId,624 CollectionInfo,625 NftInfo,626 ResourceInfo,627 PropertyInfo,628 BaseInfo,629 PartType,630 Theme,631 > for Rmrk<C, Block>632where633 C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,634 C::Api: RmrkRuntimeApi<635 Block,636 AccountId,637 CollectionInfo,638 NftInfo,639 ResourceInfo,640 PropertyInfo,641 BaseInfo,642 PartType,643 Theme,644 >,645 AccountId: Decode + Encode,646 CollectionInfo: Decode,647 NftInfo: Decode,648 ResourceInfo: Decode,649 PropertyInfo: Decode,650 BaseInfo: Decode,651 PartType: Decode,652 Theme: Decode,653 Block: BlockT,654{655 pass_method!(last_collection_idx() -> RmrkCollectionId, rmrk_api);656 pass_method!(collection_by_id(id: RmrkCollectionId) -> Option<CollectionInfo>, rmrk_api);657 pass_method!(nft_by_id(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Option<NftInfo>, rmrk_api);658 pass_method!(account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Vec<RmrkNftId>, rmrk_api);659 pass_method!(nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkNftChild>, rmrk_api);660 pass_method!(661 collection_properties(662 collection_id: RmrkCollectionId,663664 #[map(|keys| string_keys_to_bytes_keys(keys))]665 filter_keys: Option<Vec<String>>666 ) -> Vec<PropertyInfo>,667 rmrk_api668 );669 pass_method!(670 nft_properties(671 collection_id: RmrkCollectionId,672 nft_id: RmrkNftId,673674 #[map(|keys| string_keys_to_bytes_keys(keys))]675 filter_keys: Option<Vec<String>>676 ) -> Vec<PropertyInfo>,677 rmrk_api678 );679 pass_method!(nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<ResourceInfo>, rmrk_api);680 pass_method!(nft_resource_priority(collection_id: RmrkCollectionId, nft_id: RmrkNftId, resource_id: RmrkResourceId) -> Option<u32>, rmrk_api);681 pass_method!(base(base_id: RmrkBaseId) -> Option<BaseInfo>, rmrk_api);682 pass_method!(base_parts(base_id: RmrkBaseId) -> Vec<PartType>, rmrk_api);683 pass_method!(theme_names(base_id: RmrkBaseId) -> Vec<RmrkThemeName>, rmrk_api);684 pass_method!(685 theme(686 base_id: RmrkBaseId,687688 #[map(|n| n.into_bytes())]689 theme_name: String,690691 #[map(|keys| string_keys_to_bytes_keys(keys))]692 filter_keys: Option<Vec<String>>693 ) -> Option<Theme>, rmrk_api);694}695696fn string_keys_to_bytes_keys(keys: Option<Vec<String>>) -> Option<Vec<Vec<u8>>> {697 keys.map(|keys| keys.into_iter().map(|key| key.into_bytes()).collect())698}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}420421macro_rules! define_struct_for_server_api {422 ($name:ident) => {423 pub struct $name<C, P> {424 client: Arc<C>,425 _marker: std::marker::PhantomData<P>,426 }427428 impl<C, P> $name<C, P> {429 pub fn new(client: Arc<C>) -> Self {430 Self {431 client,432 _marker: Default::default(),433 }434 }435 }436 };437}438439define_struct_for_server_api!(Unique);440define_struct_for_server_api!(AppPromotion);441define_struct_for_server_api!(Rmrk);442443macro_rules! pass_method {444 (445 $method_name:ident(446 $($(#[map(|$map_arg:ident| $map:expr)])? $name:ident: $ty:ty),* $(,)?447 ) -> $result:ty $(=> $mapper:expr)?,448 //$runtime_name:ident $(<$($lt: tt),+>)*449 $runtime_api_macro:ident450 $(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*451 ) => {452 fn $method_name(453 &self,454 $(455 $name: $ty,456 )*457 at: Option<<Block as BlockT>::Hash>,458 ) -> Result<$result> {459 let api = self.client.runtime_api();460 let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));461 let _api_version = if let Ok(Some(api_version)) =462 api.api_version::<$runtime_api_macro!()>(&at)463 {464 api_version465 } else {466 // unreachable for our runtime467 return Err(anyhow!("api is not available").into())468 };469470 let result = $(if _api_version < $ver {471 api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))472 } else)*473 { api.$method_name(&at, $($((|$map_arg: $ty| $map))? ($name)),*) };474475 Ok(result476 .map_err(|e| anyhow!("unable to query: {e}"))?477 .map_err(|e| anyhow!("runtime error: {e:?}"))$(.map($mapper))??)478 }479 };480}481482macro_rules! unique_api {483 () => {484 dyn UniqueRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>485 };486}487488macro_rules! app_promotion_api {489 () => {490 dyn AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>491 };492}493494macro_rules! rmrk_api {495 () => {496 dyn RmrkRuntimeApi<Block, AccountId, CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme>497 };498}499500#[allow(deprecated)]501impl<C, Block, BlockNumber, CrossAccountId, AccountId>502 UniqueApiServer<<Block as BlockT>::Hash, BlockNumber, CrossAccountId, AccountId>503 for Unique<C, Block>504where505 Block: BlockT,506 BlockNumber: Decode + Member + AtLeast32BitUnsigned,507 AccountId: Decode,508 C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,509 C::Api: UniqueRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,510 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,511{512 pass_method!(513 account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>, unique_api514 );515 pass_method!(516 collection_tokens(collection: CollectionId) -> Vec<TokenId>, unique_api517 );518 pass_method!(519 token_exists(collection: CollectionId, token: TokenId) -> bool, unique_api520 );521 pass_method!(522 token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api523 );524 pass_method!(525 topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api526 );527 pass_method!(token_children(collection: CollectionId, token: TokenId) -> Vec<TokenChild>, unique_api);528 pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);529 pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);530 pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);531 pass_method!(532 allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string(),533 unique_api534 );535536 pass_method!(collection_properties(537 collection: CollectionId,538539 #[map(|keys| string_keys_to_bytes_keys(keys))]540 keys: Option<Vec<String>>541 ) -> Vec<Property>, unique_api);542543 pass_method!(token_properties(544 collection: CollectionId,545 token_id: TokenId,546547 #[map(|keys| string_keys_to_bytes_keys(keys))]548 keys: Option<Vec<String>>549 ) -> Vec<Property>, unique_api);550551 pass_method!(property_permissions(552 collection: CollectionId,553554 #[map(|keys| string_keys_to_bytes_keys(keys))]555 keys: Option<Vec<String>>556 ) -> Vec<PropertyKeyPermission>, unique_api);557558 pass_method!(token_data(559 collection: CollectionId,560 token_id: TokenId,561562 #[map(|keys| string_keys_to_bytes_keys(keys))]563 keys: Option<Vec<String>>,564 ) -> TokenData<CrossAccountId>, unique_api);565566 pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);567 pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);568 pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool, unique_api);569 pass_method!(last_token_id(collection: CollectionId) -> TokenId, unique_api);570 pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>, unique_api);571 pass_method!(collection_stats() -> CollectionStats, unique_api);572 pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>, unique_api);573 pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);574 pass_method!(total_pieces(collection_id: CollectionId, token_id: TokenId) -> Option<String> => |o| o.map(|number| number.to_string()) , unique_api);575 pass_method!(token_owners(collection: CollectionId, token: TokenId) -> Vec<CrossAccountId>, unique_api);576}577578impl<C, Block, BlockNumber, CrossAccountId, AccountId>579 app_promotion_unique_rpc::AppPromotionApiServer<580 <Block as BlockT>::Hash,581 BlockNumber,582 CrossAccountId,583 AccountId,584 > for AppPromotion<C, Block>585where586 Block: BlockT,587 BlockNumber: Decode + Member + AtLeast32BitUnsigned,588 AccountId: Decode,589 C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,590 C::Api: AppPromotionRuntimeApi<Block, BlockNumber, CrossAccountId, AccountId>,591 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,592{593 pass_method!(total_staked(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);594 pass_method!(total_staked_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>595 |v| v596 .into_iter()597 .map(|(b, a)| (b, a.to_string()))598 .collect::<Vec<_>>(), app_promotion_api);599 pass_method!(total_staking_locked(staker: CrossAccountId) -> String => |v| v.to_string(), app_promotion_api);600 pass_method!(pending_unstake(staker: Option<CrossAccountId>) -> String => |v| v.to_string(), app_promotion_api);601 pass_method!(pending_unstake_per_block(staker: CrossAccountId) -> Vec<(BlockNumber, String)> =>602 |v| v603 .into_iter()604 .map(|(b, a)| (b, a.to_string()))605 .collect::<Vec<_>>(), app_promotion_api);606}607608#[allow(deprecated)]609impl<610 C,611 Block,612 AccountId,613 CollectionInfo,614 NftInfo,615 ResourceInfo,616 PropertyInfo,617 BaseInfo,618 PartType,619 Theme,620 >621 rmrk_unique_rpc::RmrkApiServer<622 <Block as BlockT>::Hash,623 AccountId,624 CollectionInfo,625 NftInfo,626 ResourceInfo,627 PropertyInfo,628 BaseInfo,629 PartType,630 Theme,631 > for Rmrk<C, Block>632where633 C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,634 C::Api: RmrkRuntimeApi<635 Block,636 AccountId,637 CollectionInfo,638 NftInfo,639 ResourceInfo,640 PropertyInfo,641 BaseInfo,642 PartType,643 Theme,644 >,645 AccountId: Decode + Encode,646 CollectionInfo: Decode,647 NftInfo: Decode,648 ResourceInfo: Decode,649 PropertyInfo: Decode,650 BaseInfo: Decode,651 PartType: Decode,652 Theme: Decode,653 Block: BlockT,654{655 pass_method!(last_collection_idx() -> RmrkCollectionId, rmrk_api);656 pass_method!(collection_by_id(id: RmrkCollectionId) -> Option<CollectionInfo>, rmrk_api);657 pass_method!(nft_by_id(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Option<NftInfo>, rmrk_api);658 pass_method!(account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Vec<RmrkNftId>, rmrk_api);659 pass_method!(nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkNftChild>, rmrk_api);660 pass_method!(661 collection_properties(662 collection_id: RmrkCollectionId,663664 #[map(|keys| string_keys_to_bytes_keys(keys))]665 filter_keys: Option<Vec<String>>666 ) -> Vec<PropertyInfo>,667 rmrk_api668 );669 pass_method!(670 nft_properties(671 collection_id: RmrkCollectionId,672 nft_id: RmrkNftId,673674 #[map(|keys| string_keys_to_bytes_keys(keys))]675 filter_keys: Option<Vec<String>>676 ) -> Vec<PropertyInfo>,677 rmrk_api678 );679 pass_method!(nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<ResourceInfo>, rmrk_api);680 pass_method!(nft_resource_priority(collection_id: RmrkCollectionId, nft_id: RmrkNftId, resource_id: RmrkResourceId) -> Option<u32>, rmrk_api);681 pass_method!(base(base_id: RmrkBaseId) -> Option<BaseInfo>, rmrk_api);682 pass_method!(base_parts(base_id: RmrkBaseId) -> Vec<PartType>, rmrk_api);683 pass_method!(theme_names(base_id: RmrkBaseId) -> Vec<RmrkThemeName>, rmrk_api);684 pass_method!(685 theme(686 base_id: RmrkBaseId,687688 #[map(|n| n.into_bytes())]689 theme_name: String,690691 #[map(|keys| string_keys_to_bytes_keys(keys))]692 filter_keys: Option<Vec<String>>693 ) -> Option<Theme>, rmrk_api);694}695696fn string_keys_to_bytes_keys(keys: Option<Vec<String>>) -> Option<Vec<Vec<u8>>> {697 keys.map(|keys| keys.into_iter().map(|key| key.into_bytes()).collect())698}pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -41,6 +41,7 @@
vec,
iter::Sum,
borrow::ToOwned,
+ cell::RefCell,
};
use sp_core::H160;
use codec::EncodeLike;
@@ -474,58 +475,121 @@
let next_recalc_block = current_recalc_block + T::RecalculationInterval::get();
let mut storage_iterator = Self::get_next_calculated_key()
- .map_or(Staked::<T>::iter(), |key| {
- Staked::<T>::iter_from(key)
- });
+ .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));
NextCalculatedRecord::<T>::set(None);
+ // {
+ // let mut stakers_number = stakers_number.unwrap_or(20);
+ // let mut last_id = admin_id;
+ // let mut income_acc = BalanceOf::<T>::default();
+ // let mut amount_acc = BalanceOf::<T>::default();
+
+ // while let Some((
+ // (current_id, staked_block),
+ // (amount, next_recalc_block_for_stake),
+ // )) = storage_iterator.next()
+ // {
+ // if last_id != current_id {
+ // if income_acc != BalanceOf::<T>::default() {
+ // <T::Currency as Currency<T::AccountId>>::transfer(
+ // &T::TreasuryAccountId::get(),
+ // &last_id,
+ // income_acc,
+ // ExistenceRequirement::KeepAlive,
+ // )
+ // .and_then(|_| Self::add_lock_balance(&last_id, income_acc))?;
+
+ // Self::deposit_event(Event::StakingRecalculation(
+ // last_id, amount, income_acc,
+ // ));
+ // }
+
+ // if stakers_number == 0 {
+ // NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));
+ // break;
+ // }
+ // stakers_number -= 1;
+ // income_acc = BalanceOf::<T>::default();
+ // last_id = current_id;
+ // };
+ // if current_recalc_block >= next_recalc_block_for_stake {
+ // Self::recalculate_and_insert_stake(
+ // &last_id,
+ // staked_block,
+ // next_recalc_block,
+ // amount,
+ // ((current_recalc_block - next_recalc_block_for_stake)
+ // / T::RecalculationInterval::get())
+ // .into() + 1,
+ // &mut income_acc,
+ // );
+ // }
+ // }
+ // }
+
{
let mut stakers_number = stakers_number.unwrap_or(20);
- let mut last_id = admin_id;
- let mut income_acc = BalanceOf::<T>::default();
-
- while let Some(((current_id, staked_block), (amount, next_recalc_block_for_stake))) =
- storage_iterator.next()
- {
- if last_id != current_id {
- if income_acc != BalanceOf::<T>::default() {
+ let last_id = RefCell::new(None);
+ let income_acc = RefCell::new(BalanceOf::<T>::default());
+ let amount_acc = RefCell::new(BalanceOf::<T>::default());
+
+ let flush_stake = || -> DispatchResult {
+ if let Some(last_id) = &*last_id.borrow() {
+ if !income_acc.borrow().is_zero() {
<T::Currency as Currency<T::AccountId>>::transfer(
&T::TreasuryAccountId::get(),
- &last_id,
- income_acc,
+ last_id,
+ *income_acc.borrow(),
ExistenceRequirement::KeepAlive,
)
- .and_then(|_| Self::add_lock_balance(&last_id, income_acc))?;
+ .and_then(|_| Self::add_lock_balance(last_id, *income_acc.borrow()))?;
Self::deposit_event(Event::StakingRecalculation(
- last_id, amount, income_acc,
+ last_id.clone(),
+ *amount_acc.borrow(),
+ *income_acc.borrow(),
));
}
- if stakers_number == 0 {
- NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));
- break;
- }
- stakers_number -= 1;
- income_acc = BalanceOf::<T>::default();
- last_id = current_id;
+ *income_acc.borrow_mut() = BalanceOf::<T>::default();
+ *amount_acc.borrow_mut() = BalanceOf::<T>::default();
+ }
+ Ok(())
+ };
+
+ while let Some((
+ (current_id, staked_block),
+ (amount, next_recalc_block_for_stake),
+ )) = storage_iterator.next()
+ {
+ if stakers_number == 0 {
+ NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));
+ break;
+ }
+ stakers_number -= 1;
+ if last_id.borrow().as_ref() != Some(¤t_id) {
+ flush_stake()?;
};
+ *last_id.borrow_mut() = Some(current_id.clone());
if current_recalc_block >= next_recalc_block_for_stake {
+ *amount_acc.borrow_mut() += amount;
Self::recalculate_and_insert_stake(
- &last_id,
+ ¤t_id,
staked_block,
next_recalc_block,
amount,
((current_recalc_block - next_recalc_block_for_stake)
/ T::RecalculationInterval::get())
.into() + 1,
- &mut income_acc,
+ &mut *income_acc.borrow_mut(),
);
}
}
+ flush_stake()?;
}
+
Ok(())
}
}
runtime/common/config/pallets/app_promotion.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/app_promotion.rs
+++ b/runtime/common/config/pallets/app_promotion.rs
@@ -30,7 +30,7 @@
parameter_types! {
pub const AppPromotionId: PalletId = PalletId(*b"appstake");
pub const RecalculationInterval: BlockNumber = 20;
- pub const PendingInterval: BlockNumber = 20;
+ pub const PendingInterval: BlockNumber = 10;
pub const Nominal: Balance = UNIQUE;
pub const Day: BlockNumber = DAYS;
pub IntervalIncome: Perbill = Perbill::from_rational(RecalculationInterval::get(), RELAY_DAYS) * Perbill::from_rational(5u32, 10_000);