difftreelog
refactor rmrk proxy, add add_theme rmrk proxy
in: master
8 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/>.1617use std::sync::Arc;1819use codec::{Decode, Encode};20use jsonrpc_core::{Error as RpcError, ErrorCode, Result};21use jsonrpc_derive::rpc;22use up_data_structs::{23 RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId, Property,24 PropertyKeyPermission, TokenData,25};26use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};27use sp_blockchain::HeaderBackend;28use up_rpc::UniqueApi as UniqueRuntimeApi;2930// RMRK31use rmrk_rpc::RmrkApi as RmrkRuntimeApi;32use up_data_structs::{33 RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName, RmrkPropertyKey,34 RmrkResourceId,35};3637pub use rmrk_unique_rpc::RmrkApi;3839#[rpc]40pub trait UniqueApi<BlockHash, CrossAccountId, AccountId> {41 #[rpc(name = "unique_accountTokens")]42 fn account_tokens(43 &self,44 collection: CollectionId,45 account: CrossAccountId,46 at: Option<BlockHash>,47 ) -> Result<Vec<TokenId>>;48 #[rpc(name = "unique_collectionTokens")]49 fn collection_tokens(50 &self,51 collection: CollectionId,52 at: Option<BlockHash>,53 ) -> Result<Vec<TokenId>>;54 #[rpc(name = "unique_tokenExists")]55 fn token_exists(56 &self,57 collection: CollectionId,58 token: TokenId,59 at: Option<BlockHash>,60 ) -> Result<bool>;6162 #[rpc(name = "unique_tokenOwner")]63 fn token_owner(64 &self,65 collection: CollectionId,66 token: TokenId,67 at: Option<BlockHash>,68 ) -> Result<Option<CrossAccountId>>;69 #[rpc(name = "unique_topmostTokenOwner")]70 fn topmost_token_owner(71 &self,72 collection: CollectionId,73 token: TokenId,74 at: Option<BlockHash>,75 ) -> Result<Option<CrossAccountId>>;76 #[rpc(name = "unique_constMetadata")]77 fn const_metadata(78 &self,79 collection: CollectionId,80 token: TokenId,81 at: Option<BlockHash>,82 ) -> Result<Vec<u8>>;8384 #[rpc(name = "unique_collectionProperties")]85 fn collection_properties(86 &self,87 collection: CollectionId,88 keys: Option<Vec<String>>,89 at: Option<BlockHash>,90 ) -> Result<Vec<Property>>;9192 #[rpc(name = "unique_tokenProperties")]93 fn token_properties(94 &self,95 collection: CollectionId,96 token_id: TokenId,97 keys: Option<Vec<String>>,98 at: Option<BlockHash>,99 ) -> Result<Vec<Property>>;100101 #[rpc(name = "unique_propertyPermissions")]102 fn property_permissions(103 &self,104 collection: CollectionId,105 keys: Option<Vec<String>>,106 at: Option<BlockHash>,107 ) -> Result<Vec<PropertyKeyPermission>>;108109 #[rpc(name = "unique_tokenData")]110 fn token_data(111 &self,112 collection: CollectionId,113 token_id: TokenId,114 keys: Option<Vec<String>>,115 at: Option<BlockHash>,116 ) -> Result<TokenData<CrossAccountId>>;117118 #[rpc(name = "unique_totalSupply")]119 fn total_supply(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;120 #[rpc(name = "unique_accountBalance")]121 fn account_balance(122 &self,123 collection: CollectionId,124 account: CrossAccountId,125 at: Option<BlockHash>,126 ) -> Result<u32>;127 #[rpc(name = "unique_balance")]128 fn balance(129 &self,130 collection: CollectionId,131 account: CrossAccountId,132 token: TokenId,133 at: Option<BlockHash>,134 ) -> Result<String>;135 #[rpc(name = "unique_allowance")]136 fn allowance(137 &self,138 collection: CollectionId,139 sender: CrossAccountId,140 spender: CrossAccountId,141 token: TokenId,142 at: Option<BlockHash>,143 ) -> Result<String>;144145 #[rpc(name = "unique_adminlist")]146 fn adminlist(147 &self,148 collection: CollectionId,149 at: Option<BlockHash>,150 ) -> Result<Vec<CrossAccountId>>;151 #[rpc(name = "unique_allowlist")]152 fn allowlist(153 &self,154 collection: CollectionId,155 at: Option<BlockHash>,156 ) -> Result<Vec<CrossAccountId>>;157 #[rpc(name = "unique_allowed")]158 fn allowed(159 &self,160 collection: CollectionId,161 user: CrossAccountId,162 at: Option<BlockHash>,163 ) -> Result<bool>;164 #[rpc(name = "unique_lastTokenId")]165 fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;166 #[rpc(name = "unique_collectionById")]167 fn collection_by_id(168 &self,169 collection: CollectionId,170 at: Option<BlockHash>,171 ) -> Result<Option<RpcCollection<AccountId>>>;172 #[rpc(name = "unique_collectionStats")]173 fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;174175 #[rpc(name = "unique_nextSponsored")]176 fn next_sponsored(177 &self,178 collection: CollectionId,179 account: CrossAccountId,180 token: TokenId,181 at: Option<BlockHash>,182 ) -> Result<Option<u64>>;183 #[rpc(name = "unique_effectiveCollectionLimits")]184 fn effective_collection_limits(185 &self,186 collection_id: CollectionId,187 at: Option<BlockHash>,188 ) -> Result<Option<CollectionLimits>>;189}190191mod rmrk_unique_rpc {192 use super::*;193194 #[rpc(server)]195 pub trait RmrkApi<196 BlockHash,197 AccountId,198 CollectionInfo,199 NftInfo,200 ResourceInfo,201 PropertyInfo,202 BaseInfo,203 PartType,204 Theme,205 >206 {207 #[rpc(name = "rmrk_lastCollectionIdx")]208 /// Get the latest created collection id209 fn last_collection_idx(&self, at: Option<BlockHash>) -> Result<RmrkCollectionId>;210211 #[rpc(name = "rmrk_collectionById")]212 /// Get collection by id213 fn collection_by_id(214 &self,215 id: RmrkCollectionId,216 at: Option<BlockHash>,217 ) -> Result<Option<CollectionInfo>>;218219 #[rpc(name = "rmrk_nftById")]220 /// Get NFT by collection id and NFT id221 fn nft_by_id(222 &self,223 collection_id: RmrkCollectionId,224 nft_id: RmrkNftId,225 at: Option<BlockHash>,226 ) -> Result<Option<NftInfo>>;227228 #[rpc(name = "rmrk_accountTokens")]229 /// Get tokens owned by an account in a collection230 fn account_tokens(231 &self,232 account_id: AccountId,233 collection_id: RmrkCollectionId,234 at: Option<BlockHash>,235 ) -> Result<Vec<RmrkNftId>>;236237 #[rpc(name = "rmrk_nftChildren")]238 /// Get NFT children239 fn nft_children(240 &self,241 collection_id: RmrkCollectionId,242 nft_id: RmrkNftId,243 at: Option<BlockHash>,244 ) -> Result<Vec<RmrkNftChild>>;245246 #[rpc(name = "rmrk_collectionProperties")]247 /// Get collection properties248 fn collection_properties(249 &self,250 collection_id: RmrkCollectionId,251 filter_keys: Option<Vec<RmrkPropertyKey>>, //String252 at: Option<BlockHash>,253 ) -> Result<Vec<PropertyInfo>>;254255 #[rpc(name = "rmrk_nftProperties")]256 /// Get NFT properties257 fn nft_properties(258 &self,259 collection_id: RmrkCollectionId,260 nft_id: RmrkNftId,261 filter_keys: Option<Vec<RmrkPropertyKey>>,262 at: Option<BlockHash>,263 ) -> Result<Vec<PropertyInfo>>;264265 #[rpc(name = "rmrk_nftResources")]266 /// Get NFT resources267 fn nft_resources(268 &self,269 collection_id: RmrkCollectionId,270 nft_id: RmrkNftId,271 at: Option<BlockHash>,272 ) -> Result<Vec<ResourceInfo>>;273274 #[rpc(name = "rmrk_nftResourcePriorities")]275 /// Get NFT resource priorities276 fn nft_resource_priorities(277 &self,278 collection_id: RmrkCollectionId,279 nft_id: RmrkNftId,280 at: Option<BlockHash>,281 ) -> Result<Vec<RmrkResourceId>>;282283 #[rpc(name = "rmrk_base")]284 /// Get base info285 fn base(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Option<BaseInfo>>;286287 #[rpc(name = "rmrk_baseParts")]288 /// Get all Base's parts289 fn base_parts(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Vec<PartType>>;290291 #[rpc(name = "rmrk_themeNames")]292 fn theme_names(293 &self,294 base_id: RmrkBaseId,295 at: Option<BlockHash>,296 ) -> Result<Vec<RmrkThemeName>>;297298 #[rpc(name = "rmrk_themes")]299 fn theme(300 &self,301 base_id: RmrkBaseId,302 theme_name: RmrkThemeName, // String303 filter_keys: Option<Vec<RmrkPropertyKey>>,304 at: Option<BlockHash>,305 ) -> Result<Option<Theme>>;306 }307}308309pub struct Unique<C, P> {310 client: Arc<C>,311 _marker: std::marker::PhantomData<P>,312}313314impl<C, P> Unique<C, P> {315 pub fn new(client: Arc<C>) -> Self {316 Self {317 client,318 _marker: Default::default(),319 }320 }321}322323pub enum Error {324 RuntimeError,325}326327impl From<Error> for i64 {328 fn from(e: Error) -> i64 {329 match e {330 Error::RuntimeError => 1,331 }332 }333}334335macro_rules! pass_method {336 (337 $method_name:ident(338 $($(#[map(|$map_arg:ident| $map:expr)])? $name:ident: $ty:ty),* $(,)?339 ) -> $result:ty $(=> $mapper:expr)?,340 //$runtime_name:ident $(<$($lt: tt),+>)*341 $runtime_api_macro:ident342 $(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*343 ) => {344 fn $method_name(345 &self,346 $(347 $name: $ty,348 )*349 at: Option<<Block as BlockT>::Hash>,350 ) -> Result<$result> {351 let api = self.client.runtime_api();352 let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));353 let _api_version = if let Ok(Some(api_version)) =354 api.api_version::<$runtime_api_macro!()>(&at)355 {356 api_version357 } else {358 // unreachable for our runtime359 return Err(RpcError {360 code: ErrorCode::InvalidParams,361 message: "Api is not available".into(),362 data: None,363 })364 };365366 let result = $(if _api_version < $ver {367 api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))368 } else)*369 { api.$method_name(&at, $($((|$map_arg: $ty| $map))? ($name)),*) };370371 let result = result.map_err(|e| RpcError {372 code: ErrorCode::ServerError(Error::RuntimeError.into()),373 message: "Unable to query".into(),374 data: Some(format!("{:?}", e).into()),375 })?;376 result.map_err(|e| RpcError {377 code: ErrorCode::InvalidParams,378 message: "Runtime returned error".into(),379 data: Some(format!("{:?}", e).into()),380 })$(.map($mapper))?381 }382 };383}384385macro_rules! unique_api {386 () => {387 dyn UniqueRuntimeApi<Block, CrossAccountId, AccountId>388 };389}390391macro_rules! rmrk_api {392 () => {393 dyn RmrkRuntimeApi<Block, AccountId, CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme>394 };395}396397#[allow(deprecated)]398impl<C, Block, CrossAccountId, AccountId>399 UniqueApi<<Block as BlockT>::Hash, CrossAccountId, AccountId> for Unique<C, Block>400where401 Block: BlockT,402 AccountId: Decode,403 C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,404 C::Api: UniqueRuntimeApi<Block, CrossAccountId, AccountId>,405 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,406{407 pass_method!(408 account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>, unique_api409 );410 pass_method!(411 collection_tokens(collection: CollectionId) -> Vec<TokenId>, unique_api412 );413 pass_method!(414 token_exists(collection: CollectionId, token: TokenId) -> bool, unique_api415 );416 pass_method!(417 token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api418 );419 pass_method!(420 topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api421 );422 pass_method!(423 const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>, unique_api424 );425 pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);426 pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);427 pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);428 pass_method!(429 allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string(),430 unique_api431 );432433 pass_method!(collection_properties(434 collection: CollectionId,435436 #[map(|keys| string_keys_to_bytes_keys(keys))]437 keys: Option<Vec<String>>438 ) -> Vec<Property>, unique_api);439440 pass_method!(token_properties(441 collection: CollectionId,442 token_id: TokenId,443444 #[map(|keys| string_keys_to_bytes_keys(keys))]445 keys: Option<Vec<String>>446 ) -> Vec<Property>, unique_api);447448 pass_method!(property_permissions(449 collection: CollectionId,450451 #[map(|keys| string_keys_to_bytes_keys(keys))]452 keys: Option<Vec<String>>453 ) -> Vec<PropertyKeyPermission>, unique_api);454455 pass_method!(token_data(456 collection: CollectionId,457 token_id: TokenId,458459 #[map(|keys| string_keys_to_bytes_keys(keys))]460 keys: Option<Vec<String>>,461 ) -> TokenData<CrossAccountId>, unique_api);462463 pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);464 pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);465 pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool, unique_api);466 pass_method!(last_token_id(collection: CollectionId) -> TokenId, unique_api);467 pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>, unique_api);468 pass_method!(collection_stats() -> CollectionStats, unique_api);469 pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>, unique_api);470 pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);471}472473#[allow(deprecated)]474impl<475 C,476 Block,477 AccountId,478 CollectionInfo,479 NftInfo,480 ResourceInfo,481 PropertyInfo,482 BaseInfo,483 PartType,484 Theme,485 >486 rmrk_unique_rpc::RmrkApi<487 <Block as BlockT>::Hash,488 AccountId,489 CollectionInfo,490 NftInfo,491 ResourceInfo,492 PropertyInfo,493 BaseInfo,494 PartType,495 Theme,496 > for Unique<C, Block>497where498 C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,499 C::Api: RmrkRuntimeApi<500 Block,501 AccountId,502 CollectionInfo,503 NftInfo,504 ResourceInfo,505 PropertyInfo,506 BaseInfo,507 PartType,508 Theme,509 >,510 AccountId: Decode + Encode,511 CollectionInfo: Decode,512 NftInfo: Decode,513 ResourceInfo: Decode,514 PropertyInfo: Decode,515 BaseInfo: Decode,516 PartType: Decode,517 Theme: Decode,518 Block: BlockT,519{520 pass_method!(last_collection_idx() -> RmrkCollectionId, rmrk_api);521 pass_method!(collection_by_id(id: RmrkCollectionId) -> Option<CollectionInfo>, rmrk_api);522 pass_method!(nft_by_id(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Option<NftInfo>, rmrk_api);523 pass_method!(account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Vec<RmrkNftId>, rmrk_api);524 pass_method!(nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkNftChild>, rmrk_api);525 pass_method!(526 collection_properties(collection_id: RmrkCollectionId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Vec<PropertyInfo>,527 rmrk_api528 );529 pass_method!(530 nft_properties(collection_id: RmrkCollectionId, nft_id: RmrkNftId, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Vec<PropertyInfo>,531 rmrk_api532 );533 pass_method!(nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<ResourceInfo>, rmrk_api);534 pass_method!(nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkResourceId>, rmrk_api);535 pass_method!(base(base_id: RmrkBaseId) -> Option<BaseInfo>, rmrk_api);536 pass_method!(base_parts(base_id: RmrkBaseId) -> Vec<PartType>, rmrk_api);537 pass_method!(theme_names(base_id: RmrkBaseId) -> Vec<RmrkThemeName>, rmrk_api);538 pass_method!(theme(base_id: RmrkBaseId, theme_name: RmrkThemeName, filter_keys: Option<Vec<RmrkPropertyKey>>) -> Option<Theme>, rmrk_api);539}540541fn string_keys_to_bytes_keys(keys: Option<Vec<String>>) -> Option<Vec<Vec<u8>>> {542 keys.map(|keys| keys.into_iter().map(|key| key.into_bytes()).collect())543}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617use std::sync::Arc;1819use codec::{Decode, Encode};20use jsonrpc_core::{Error as RpcError, ErrorCode, Result};21use jsonrpc_derive::rpc;22use up_data_structs::{23 RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId, Property,24 PropertyKeyPermission, TokenData,25};26use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};27use sp_blockchain::HeaderBackend;28use up_rpc::UniqueApi as UniqueRuntimeApi;2930// RMRK31use rmrk_rpc::RmrkApi as RmrkRuntimeApi;32use up_data_structs::{33 RmrkCollectionId, RmrkNftId, RmrkBaseId, RmrkNftChild, RmrkThemeName,34 RmrkResourceId,35};3637pub use rmrk_unique_rpc::RmrkApi;3839#[rpc]40pub trait UniqueApi<BlockHash, CrossAccountId, AccountId> {41 #[rpc(name = "unique_accountTokens")]42 fn account_tokens(43 &self,44 collection: CollectionId,45 account: CrossAccountId,46 at: Option<BlockHash>,47 ) -> Result<Vec<TokenId>>;48 #[rpc(name = "unique_collectionTokens")]49 fn collection_tokens(50 &self,51 collection: CollectionId,52 at: Option<BlockHash>,53 ) -> Result<Vec<TokenId>>;54 #[rpc(name = "unique_tokenExists")]55 fn token_exists(56 &self,57 collection: CollectionId,58 token: TokenId,59 at: Option<BlockHash>,60 ) -> Result<bool>;6162 #[rpc(name = "unique_tokenOwner")]63 fn token_owner(64 &self,65 collection: CollectionId,66 token: TokenId,67 at: Option<BlockHash>,68 ) -> Result<Option<CrossAccountId>>;69 #[rpc(name = "unique_topmostTokenOwner")]70 fn topmost_token_owner(71 &self,72 collection: CollectionId,73 token: TokenId,74 at: Option<BlockHash>,75 ) -> Result<Option<CrossAccountId>>;76 #[rpc(name = "unique_constMetadata")]77 fn const_metadata(78 &self,79 collection: CollectionId,80 token: TokenId,81 at: Option<BlockHash>,82 ) -> Result<Vec<u8>>;8384 #[rpc(name = "unique_collectionProperties")]85 fn collection_properties(86 &self,87 collection: CollectionId,88 keys: Option<Vec<String>>,89 at: Option<BlockHash>,90 ) -> Result<Vec<Property>>;9192 #[rpc(name = "unique_tokenProperties")]93 fn token_properties(94 &self,95 collection: CollectionId,96 token_id: TokenId,97 keys: Option<Vec<String>>,98 at: Option<BlockHash>,99 ) -> Result<Vec<Property>>;100101 #[rpc(name = "unique_propertyPermissions")]102 fn property_permissions(103 &self,104 collection: CollectionId,105 keys: Option<Vec<String>>,106 at: Option<BlockHash>,107 ) -> Result<Vec<PropertyKeyPermission>>;108109 #[rpc(name = "unique_tokenData")]110 fn token_data(111 &self,112 collection: CollectionId,113 token_id: TokenId,114 keys: Option<Vec<String>>,115 at: Option<BlockHash>,116 ) -> Result<TokenData<CrossAccountId>>;117118 #[rpc(name = "unique_totalSupply")]119 fn total_supply(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;120 #[rpc(name = "unique_accountBalance")]121 fn account_balance(122 &self,123 collection: CollectionId,124 account: CrossAccountId,125 at: Option<BlockHash>,126 ) -> Result<u32>;127 #[rpc(name = "unique_balance")]128 fn balance(129 &self,130 collection: CollectionId,131 account: CrossAccountId,132 token: TokenId,133 at: Option<BlockHash>,134 ) -> Result<String>;135 #[rpc(name = "unique_allowance")]136 fn allowance(137 &self,138 collection: CollectionId,139 sender: CrossAccountId,140 spender: CrossAccountId,141 token: TokenId,142 at: Option<BlockHash>,143 ) -> Result<String>;144145 #[rpc(name = "unique_adminlist")]146 fn adminlist(147 &self,148 collection: CollectionId,149 at: Option<BlockHash>,150 ) -> Result<Vec<CrossAccountId>>;151 #[rpc(name = "unique_allowlist")]152 fn allowlist(153 &self,154 collection: CollectionId,155 at: Option<BlockHash>,156 ) -> Result<Vec<CrossAccountId>>;157 #[rpc(name = "unique_allowed")]158 fn allowed(159 &self,160 collection: CollectionId,161 user: CrossAccountId,162 at: Option<BlockHash>,163 ) -> Result<bool>;164 #[rpc(name = "unique_lastTokenId")]165 fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;166 #[rpc(name = "unique_collectionById")]167 fn collection_by_id(168 &self,169 collection: CollectionId,170 at: Option<BlockHash>,171 ) -> Result<Option<RpcCollection<AccountId>>>;172 #[rpc(name = "unique_collectionStats")]173 fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;174175 #[rpc(name = "unique_nextSponsored")]176 fn next_sponsored(177 &self,178 collection: CollectionId,179 account: CrossAccountId,180 token: TokenId,181 at: Option<BlockHash>,182 ) -> Result<Option<u64>>;183 #[rpc(name = "unique_effectiveCollectionLimits")]184 fn effective_collection_limits(185 &self,186 collection_id: CollectionId,187 at: Option<BlockHash>,188 ) -> Result<Option<CollectionLimits>>;189}190191mod rmrk_unique_rpc {192 use super::*;193194 #[rpc(server)]195 pub trait RmrkApi<196 BlockHash,197 AccountId,198 CollectionInfo,199 NftInfo,200 ResourceInfo,201 PropertyInfo,202 BaseInfo,203 PartType,204 Theme,205 >206 {207 #[rpc(name = "rmrk_lastCollectionIdx")]208 /// Get the latest created collection id209 fn last_collection_idx(&self, at: Option<BlockHash>) -> Result<RmrkCollectionId>;210211 #[rpc(name = "rmrk_collectionById")]212 /// Get collection by id213 fn collection_by_id(214 &self,215 id: RmrkCollectionId,216 at: Option<BlockHash>,217 ) -> Result<Option<CollectionInfo>>;218219 #[rpc(name = "rmrk_nftById")]220 /// Get NFT by collection id and NFT id221 fn nft_by_id(222 &self,223 collection_id: RmrkCollectionId,224 nft_id: RmrkNftId,225 at: Option<BlockHash>,226 ) -> Result<Option<NftInfo>>;227228 #[rpc(name = "rmrk_accountTokens")]229 /// Get tokens owned by an account in a collection230 fn account_tokens(231 &self,232 account_id: AccountId,233 collection_id: RmrkCollectionId,234 at: Option<BlockHash>,235 ) -> Result<Vec<RmrkNftId>>;236237 #[rpc(name = "rmrk_nftChildren")]238 /// Get NFT children239 fn nft_children(240 &self,241 collection_id: RmrkCollectionId,242 nft_id: RmrkNftId,243 at: Option<BlockHash>,244 ) -> Result<Vec<RmrkNftChild>>;245246 #[rpc(name = "rmrk_collectionProperties")]247 /// Get collection properties248 fn collection_properties(249 &self,250 collection_id: RmrkCollectionId,251 filter_keys: Option<Vec<String>>,252 at: Option<BlockHash>,253 ) -> Result<Vec<PropertyInfo>>;254255 #[rpc(name = "rmrk_nftProperties")]256 /// Get NFT properties257 fn nft_properties(258 &self,259 collection_id: RmrkCollectionId,260 nft_id: RmrkNftId,261 filter_keys: Option<Vec<String>>,262 at: Option<BlockHash>,263 ) -> Result<Vec<PropertyInfo>>;264265 #[rpc(name = "rmrk_nftResources")]266 /// Get NFT resources267 fn nft_resources(268 &self,269 collection_id: RmrkCollectionId,270 nft_id: RmrkNftId,271 at: Option<BlockHash>,272 ) -> Result<Vec<ResourceInfo>>;273274 #[rpc(name = "rmrk_nftResourcePriorities")]275 /// Get NFT resource priorities276 fn nft_resource_priorities(277 &self,278 collection_id: RmrkCollectionId,279 nft_id: RmrkNftId,280 at: Option<BlockHash>,281 ) -> Result<Vec<RmrkResourceId>>;282283 #[rpc(name = "rmrk_base")]284 /// Get base info285 fn base(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Option<BaseInfo>>;286287 #[rpc(name = "rmrk_baseParts")]288 /// Get all Base's parts289 fn base_parts(&self, base_id: RmrkBaseId, at: Option<BlockHash>) -> Result<Vec<PartType>>;290291 #[rpc(name = "rmrk_themeNames")]292 fn theme_names(293 &self,294 base_id: RmrkBaseId,295 at: Option<BlockHash>,296 ) -> Result<Vec<RmrkThemeName>>;297298 #[rpc(name = "rmrk_themes")]299 fn theme(300 &self,301 base_id: RmrkBaseId,302 theme_name: String,303 filter_keys: Option<Vec<String>>,304 at: Option<BlockHash>,305 ) -> Result<Option<Theme>>;306 }307}308309pub struct Unique<C, P> {310 client: Arc<C>,311 _marker: std::marker::PhantomData<P>,312}313314impl<C, P> Unique<C, P> {315 pub fn new(client: Arc<C>) -> Self {316 Self {317 client,318 _marker: Default::default(),319 }320 }321}322323pub enum Error {324 RuntimeError,325}326327impl From<Error> for i64 {328 fn from(e: Error) -> i64 {329 match e {330 Error::RuntimeError => 1,331 }332 }333}334335macro_rules! pass_method {336 (337 $method_name:ident(338 $($(#[map(|$map_arg:ident| $map:expr)])? $name:ident: $ty:ty),* $(,)?339 ) -> $result:ty $(=> $mapper:expr)?,340 //$runtime_name:ident $(<$($lt: tt),+>)*341 $runtime_api_macro:ident342 $(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*343 ) => {344 fn $method_name(345 &self,346 $(347 $name: $ty,348 )*349 at: Option<<Block as BlockT>::Hash>,350 ) -> Result<$result> {351 let api = self.client.runtime_api();352 let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));353 let _api_version = if let Ok(Some(api_version)) =354 api.api_version::<$runtime_api_macro!()>(&at)355 {356 api_version357 } else {358 // unreachable for our runtime359 return Err(RpcError {360 code: ErrorCode::InvalidParams,361 message: "Api is not available".into(),362 data: None,363 })364 };365366 let result = $(if _api_version < $ver {367 api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))368 } else)*369 { api.$method_name(&at, $($((|$map_arg: $ty| $map))? ($name)),*) };370371 let result = result.map_err(|e| RpcError {372 code: ErrorCode::ServerError(Error::RuntimeError.into()),373 message: "Unable to query".into(),374 data: Some(format!("{:?}", e).into()),375 })?;376 result.map_err(|e| RpcError {377 code: ErrorCode::InvalidParams,378 message: "Runtime returned error".into(),379 data: Some(format!("{:?}", e).into()),380 })$(.map($mapper))?381 }382 };383}384385macro_rules! unique_api {386 () => {387 dyn UniqueRuntimeApi<Block, CrossAccountId, AccountId>388 };389}390391macro_rules! rmrk_api {392 () => {393 dyn RmrkRuntimeApi<Block, AccountId, CollectionInfo, NftInfo, ResourceInfo, PropertyInfo, BaseInfo, PartType, Theme>394 };395}396397#[allow(deprecated)]398impl<C, Block, CrossAccountId, AccountId>399 UniqueApi<<Block as BlockT>::Hash, CrossAccountId, AccountId> for Unique<C, Block>400where401 Block: BlockT,402 AccountId: Decode,403 C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,404 C::Api: UniqueRuntimeApi<Block, CrossAccountId, AccountId>,405 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,406{407 pass_method!(408 account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>, unique_api409 );410 pass_method!(411 collection_tokens(collection: CollectionId) -> Vec<TokenId>, unique_api412 );413 pass_method!(414 token_exists(collection: CollectionId, token: TokenId) -> bool, unique_api415 );416 pass_method!(417 token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api418 );419 pass_method!(420 topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>, unique_api421 );422 pass_method!(423 const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>, unique_api424 );425 pass_method!(total_supply(collection: CollectionId) -> u32, unique_api);426 pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32, unique_api);427 pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string(), unique_api);428 pass_method!(429 allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string(),430 unique_api431 );432433 pass_method!(collection_properties(434 collection: CollectionId,435436 #[map(|keys| string_keys_to_bytes_keys(keys))]437 keys: Option<Vec<String>>438 ) -> Vec<Property>, unique_api);439440 pass_method!(token_properties(441 collection: CollectionId,442 token_id: TokenId,443444 #[map(|keys| string_keys_to_bytes_keys(keys))]445 keys: Option<Vec<String>>446 ) -> Vec<Property>, unique_api);447448 pass_method!(property_permissions(449 collection: CollectionId,450451 #[map(|keys| string_keys_to_bytes_keys(keys))]452 keys: Option<Vec<String>>453 ) -> Vec<PropertyKeyPermission>, unique_api);454455 pass_method!(token_data(456 collection: CollectionId,457 token_id: TokenId,458459 #[map(|keys| string_keys_to_bytes_keys(keys))]460 keys: Option<Vec<String>>,461 ) -> TokenData<CrossAccountId>, unique_api);462463 pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);464 pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>, unique_api);465 pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool, unique_api);466 pass_method!(last_token_id(collection: CollectionId) -> TokenId, unique_api);467 pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>, unique_api);468 pass_method!(collection_stats() -> CollectionStats, unique_api);469 pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>, unique_api);470 pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>, unique_api);471}472473#[allow(deprecated)]474impl<475 C,476 Block,477 AccountId,478 CollectionInfo,479 NftInfo,480 ResourceInfo,481 PropertyInfo,482 BaseInfo,483 PartType,484 Theme,485 >486 rmrk_unique_rpc::RmrkApi<487 <Block as BlockT>::Hash,488 AccountId,489 CollectionInfo,490 NftInfo,491 ResourceInfo,492 PropertyInfo,493 BaseInfo,494 PartType,495 Theme,496 > for Unique<C, Block>497where498 C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,499 C::Api: RmrkRuntimeApi<500 Block,501 AccountId,502 CollectionInfo,503 NftInfo,504 ResourceInfo,505 PropertyInfo,506 BaseInfo,507 PartType,508 Theme,509 >,510 AccountId: Decode + Encode,511 CollectionInfo: Decode,512 NftInfo: Decode,513 ResourceInfo: Decode,514 PropertyInfo: Decode,515 BaseInfo: Decode,516 PartType: Decode,517 Theme: Decode,518 Block: BlockT,519{520 pass_method!(last_collection_idx() -> RmrkCollectionId, rmrk_api);521 pass_method!(collection_by_id(id: RmrkCollectionId) -> Option<CollectionInfo>, rmrk_api);522 pass_method!(nft_by_id(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Option<NftInfo>, rmrk_api);523 pass_method!(account_tokens(account_id: AccountId, collection_id: RmrkCollectionId) -> Vec<RmrkNftId>, rmrk_api);524 pass_method!(nft_children(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkNftChild>, rmrk_api);525 pass_method!(526 collection_properties(527 collection_id: RmrkCollectionId,528529 #[map(|keys| string_keys_to_bytes_keys(keys))]530 filter_keys: Option<Vec<String>>531 ) -> Vec<PropertyInfo>,532 rmrk_api533 );534 pass_method!(535 nft_properties(536 collection_id: RmrkCollectionId,537 nft_id: RmrkNftId,538539 #[map(|keys| string_keys_to_bytes_keys(keys))]540 filter_keys: Option<Vec<String>>541 ) -> Vec<PropertyInfo>,542 rmrk_api543 );544 pass_method!(nft_resources(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<ResourceInfo>, rmrk_api);545 pass_method!(nft_resource_priorities(collection_id: RmrkCollectionId, nft_id: RmrkNftId) -> Vec<RmrkResourceId>, rmrk_api);546 pass_method!(base(base_id: RmrkBaseId) -> Option<BaseInfo>, rmrk_api);547 pass_method!(base_parts(base_id: RmrkBaseId) -> Vec<PartType>, rmrk_api);548 pass_method!(theme_names(base_id: RmrkBaseId) -> Vec<RmrkThemeName>, rmrk_api);549 pass_method!(550 theme(551 base_id: RmrkBaseId,552553 #[map(|n| n.into_bytes())]554 theme_name: String,555556 #[map(|keys| string_keys_to_bytes_keys(keys))]557 filter_keys: Option<Vec<String>>558 ) -> Option<Theme>, rmrk_api);559}560561fn string_keys_to_bytes_keys(keys: Option<Vec<String>>) -> Option<Vec<Vec<u8>>> {562 keys.map(|keys| keys.into_iter().map(|key| key.into_bytes()).collect())563}pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -795,11 +795,11 @@
}
pub fn set_scoped_collection_property(
- collection: &CollectionHandle<T>,
+ collection_id: CollectionId,
scope: PropertyScope,
property: Property,
) -> DispatchResult {
- CollectionProperties::<T>::try_mutate(collection.id, |properties| {
+ CollectionProperties::<T>::try_mutate(collection_id, |properties| {
properties.try_scoped_set(scope, property.key, property.value)
})
.map_err(<Error<T>>::from)?;
@@ -807,13 +807,12 @@
Ok(())
}
- #[transactional]
pub fn set_scoped_collection_properties(
- collection: &CollectionHandle<T>,
+ collection_id: CollectionId,
scope: PropertyScope,
properties: impl Iterator<Item = Property>,
) -> DispatchResult {
- CollectionProperties::<T>::try_mutate(collection.id, |stored_properties| {
+ CollectionProperties::<T>::try_mutate(collection_id, |stored_properties| {
stored_properties.try_scoped_set_from_iter(scope, properties)
})
.map_err(<Error<T>>::from)?;
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -195,12 +195,12 @@
}
pub fn set_scoped_token_property(
- collection: &CollectionHandle<T>,
+ collection_id: CollectionId,
token_id: TokenId,
scope: PropertyScope,
property: Property,
) -> DispatchResult {
- TokenProperties::<T>::try_mutate((collection.id, token_id), |properties| {
+ TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {
properties.try_scoped_set(scope, property.key, property.value)
})
.map_err(<CommonError<T>>::from)?;
@@ -209,12 +209,12 @@
}
pub fn set_scoped_token_properties(
- collection: &CollectionHandle<T>,
+ collection_id: CollectionId,
token_id: TokenId,
scope: PropertyScope,
properties: impl Iterator<Item=Property>,
) -> DispatchResult {
- TokenProperties::<T>::try_mutate((collection.id, token_id), |stored_properties| {
+ TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {
stored_properties.try_scoped_set_from_iter(scope, properties)
})
.map_err(<CommonError<T>>::from)?;
@@ -222,8 +222,8 @@
Ok(())
}
- pub fn current_token_id(collection: &CollectionHandle<T>) -> TokenId {
- TokenId(<TokensMinted<T>>::get(collection.id))
+ pub fn current_token_id(collection_id: CollectionId) -> TokenId {
+ TokenId(<TokensMinted<T>>::get(collection_id))
}
}
pallets/proxy-rmrk-core/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/lib.rs
+++ b/pallets/proxy-rmrk-core/src/lib.rs
@@ -33,6 +33,8 @@
use misc::*;
pub use property::*;
+use RmrkProperty::*;
+
#[frame_support::pallet]
pub mod pallet {
use super::*;
@@ -135,15 +137,13 @@
}
let collection_id = collection_id_res?;
-
- let collection = Self::get_nft_collection(collection_id)?.into_inner();
<PalletCommon<T>>::set_scoped_collection_properties(
- &collection,
+ collection_id,
PropertyScope::Rmrk,
[
- rmrk_property!(Config=T, Metadata: metadata)?,
- rmrk_property!(Config=T, CollectionType: CollectionType::Regular)?,
+ Self::rmrk_property(Metadata, &metadata)?,
+ Self::rmrk_property(CollectionType, &misc::CollectionType::Regular)?,
].into_iter()
)?;
@@ -168,7 +168,7 @@
let unique_collection_id = collection_id.into();
- let collection = Self::get_typed_nft_collection(unique_collection_id, CollectionType::Regular)?;
+ let collection = Self::get_typed_nft_collection(unique_collection_id, misc::CollectionType::Regular)?;
ensure!(collection.total_supply() == 0, <Error<T>>::CollectionNotEmpty);
@@ -193,7 +193,7 @@
Self::change_collection_owner(
collection_id.into(),
- CollectionType::Regular,
+ misc::CollectionType::Regular,
sender.clone(),
new_issuer.clone()
)?;
@@ -218,7 +218,7 @@
let collection = Self::get_typed_nft_collection(
collection_id.into(),
- CollectionType::Regular
+ misc::CollectionType::Regular
)?;
Self::check_collection_owner(&collection, &cross_sender)?;
@@ -253,20 +253,27 @@
amount
});
+ let collection = Self::get_typed_nft_collection(
+ collection_id.into(),
+ misc::CollectionType::Regular,
+ )?;
+
let nft_id = Self::create_nft(
&sender,
&cross_owner,
- collection_id.into(),
- CollectionType::Regular,
+ &collection,
NftType::Regular,
[
- rmrk_property!(Config=T, RoyaltyInfo: royalty_info)?,
- rmrk_property!(Config=T, Metadata: metadata)?,
- rmrk_property!(Config=T, Equipped: false)?,
- rmrk_property!(Config=T, ResourceCollection: None::<CollectionId>)?,
- rmrk_property!(Config=T, ResourcePriorities: <Vec<u8>>::new())?,
+ Self::rmrk_property(RoyaltyInfo, &royalty_info)?,
+ Self::rmrk_property(Metadata, &metadata)?,
+ Self::rmrk_property(Equipped, &false)?,
+ Self::rmrk_property(ResourceCollection, &None::<CollectionId>)?,
+ Self::rmrk_property(ResourcePriorities, &<Vec<u8>>::new())?,
].into_iter()
- )?;
+ ).map_err(|err| match err {
+ DispatchError::Arithmetic(_) => <Error<T>>::NoAvailableNftId.into(),
+ err => Self::map_common_err_to_proxy(err)
+ })?;
Self::deposit_event(Event::NftMinted {
owner,
@@ -290,7 +297,7 @@
Self::destroy_nft(
cross_sender,
collection_id.into(),
- CollectionType::Regular,
+ misc::CollectionType::Regular,
nft_id.into()
)?;
@@ -302,19 +309,37 @@
}
impl<T: Config> Pallet<T> {
+ pub fn rmrk_property_key(rmrk_key: RmrkProperty) -> Result<PropertyKey, DispatchError> {
+ let key = rmrk_key.to_key::<T>()?;
+
+ let scoped_key = PropertyScope::Rmrk.apply(key)
+ .map_err(|_| <Error<T>>::RmrkPropertyKeyIsTooLong)?;
+
+ Ok(scoped_key)
+ }
+
+ pub fn rmrk_property<E: Encode>(rmrk_key: RmrkProperty, value: &E) -> Result<Property, DispatchError> {
+ let key = rmrk_key.to_key::<T>()?;
+
+ let value = value.encode()
+ .try_into()
+ .map_err(|_| <Error<T>>::RmrkPropertyValueIsTooLong)?;
+
+ let property = Property {
+ key,
+ value,
+ };
+
+ Ok(property)
+ }
+
pub fn create_nft(
sender: &T::CrossAccountId,
owner: &T::CrossAccountId,
- collection_id: CollectionId,
- collection_type: CollectionType,
+ collection: &NonfungibleHandle<T>,
nft_type: NftType,
properties: impl Iterator<Item=Property>
) -> Result<TokenId, DispatchError> {
- let collection = Self::get_typed_nft_collection(
- collection_id,
- collection_type
- )?;
-
let data = CreateNftExData {
const_data: nft_type.encode()
.try_into()
@@ -326,16 +351,16 @@
let budget = budget::Value::new(2);
<PalletNft<T>>::create_item(
- &collection,
+ collection,
sender,
data,
&budget,
- ).map_err(Self::map_common_err_to_proxy)?;
+ )?;
- let nft_id = <PalletNft<T>>::current_token_id(&collection);
+ let nft_id = <PalletNft<T>>::current_token_id(collection.id);
<PalletNft<T>>::set_scoped_token_properties(
- &collection,
+ collection.id,
nft_id,
PropertyScope::Rmrk,
properties
@@ -347,7 +372,7 @@
fn destroy_nft(
sender: T::CrossAccountId,
collection_id: CollectionId,
- collection_type: CollectionType,
+ collection_type: misc::CollectionType,
token_id: TokenId
) -> DispatchResult {
let collection = Self::get_typed_nft_collection(
@@ -363,7 +388,7 @@
fn change_collection_owner(
collection_id: CollectionId,
- collection_type: CollectionType,
+ collection_type: misc::CollectionType,
sender: T::AccountId,
new_owner: T::AccountId,
) -> DispatchResult {
@@ -390,10 +415,12 @@
pub fn get_nft_collection(collection_id: CollectionId) -> Result<NonfungibleHandle<T>, DispatchError> {
let collection = <CollectionHandle<T>>::try_get(collection_id)
- .map_err(|_| <Error<T>>::CollectionUnknown)?
- .into_nft_collection()?;
+ .map_err(|_| <Error<T>>::CollectionUnknown)?;
- Ok(collection)
+ match collection.mode {
+ CollectionMode::NFT => Ok(NonfungibleHandle::cast(collection)),
+ _ => Err(<Error<T>>::CollectionUnknown.into())
+ }
}
// should this even be here, might displace it to common/nonfungible -- but they did not need it, only rmrk does
@@ -407,23 +434,23 @@
pub fn get_collection_property(collection_id: CollectionId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {
let collection_property = <PalletCommon<T>>::collection_properties(collection_id)
- .get(&rmrk_property!(Config=T, key)?)
+ .get(&Self::rmrk_property_key(key)?)
.ok_or(<Error<T>>::CollectionUnknown)?
.clone();
Ok(collection_property)
}
- pub fn get_collection_type(collection_id: CollectionId) -> Result<CollectionType, DispatchError> {
- let value = Self::get_collection_property(collection_id, RmrkProperty::CollectionType)?;
- let collection_type: CollectionType = (&value)
- .try_into()
- .map_err(<Error<T>>::from)?;
+ pub fn get_collection_type(collection_id: CollectionId) -> Result<misc::CollectionType, DispatchError> {
+ let value = Self::get_collection_property(collection_id, CollectionType)?;
+
+ let mut value = value.as_slice();
- Ok(collection_type)
+ misc::CollectionType::decode(&mut value)
+ .map_err(|_| <Error<T>>::CorruptedCollectionType.into())
}
- pub fn ensure_collection_type(collection_id: CollectionId, collection_type: CollectionType) -> DispatchResult {
+ pub fn ensure_collection_type(collection_id: CollectionId, collection_type: misc::CollectionType) -> DispatchResult {
let actual_type = Self::get_collection_type(collection_id)?;
ensure!(actual_type == collection_type, <CommonError<T>>::NoPermission);
@@ -432,7 +459,7 @@
pub fn get_nft_property(collection_id: CollectionId, nft_id: TokenId, key: RmrkProperty) -> Result<PropertyValue, DispatchError> {
let nft_property = <PalletNft<T>>::token_properties((collection_id, nft_id))
- .get(&rmrk_property!(Config=T, key)?)
+ .get(&Self::rmrk_property_key(key)?)
.ok_or(<Error<T>>::NoAvailableNftId)?
.clone();
@@ -440,10 +467,12 @@
}
pub fn get_nft_type(collection_id: CollectionId, token_id: TokenId) -> Result<NftType, DispatchError> {
- <TokenData<T>>::get((collection_id, token_id))
- .unwrap()
- .rmrk_nft_type()
- .ok_or_else(|| <Error<T>>::NoAvailableNftId.into())
+ let token_data = <TokenData<T>>::get((collection_id, token_id))
+ .ok_or(<Error<T>>::NoAvailableNftId)?;
+
+ let mut const_data = token_data.const_data.as_slice();
+
+ NftType::decode(&mut const_data).map_err(|_| <Error<T>>::NoAvailableNftId.into())
}
pub fn ensure_nft_type(collection_id: CollectionId, token_id: TokenId, nft_type: NftType) -> DispatchResult {
@@ -466,7 +495,7 @@
let value = Self::get_nft_property(
collection_id,
token_id,
- RmrkProperty::ThemeProperty(&key)
+ ThemeProperty(&key)
).ok()?.decode_or_default();
let property = RmrkThemeProperty {
@@ -491,7 +520,7 @@
collection_id: CollectionId,
token_id: TokenId
) -> Result<impl Iterator<Item=RmrkThemeProperty>, DispatchError> {
- let key_prefix = rmrk_property!(Config=T, key: ThemeProperty(&RmrkString::default()))?;
+ let key_prefix = Self::rmrk_property_key(ThemeProperty(&RmrkString::default()))?;
let properties = <PalletNft<T>>::token_properties((collection_id, token_id))
.into_iter()
@@ -514,7 +543,7 @@
pub fn get_typed_nft_collection(
collection_id: CollectionId,
- collection_type: CollectionType
+ collection_type: misc::CollectionType
) -> Result<NonfungibleHandle<T>, DispatchError> {
Self::ensure_collection_type(collection_id, collection_type)?;
pallets/proxy-rmrk-core/src/misc.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/misc.rs
+++ b/pallets/proxy-rmrk-core/src/misc.rs
@@ -1,23 +1,6 @@
use super::*;
use codec::{Encode, Decode};
-use pallet_nonfungible::{NonfungibleHandle, ItemData};
-
-macro_rules! impl_rmrk_value {
- ($enum_name:path, decode_error: $error:ident) => {
- impl TryFrom<&PropertyValue> for $enum_name {
- type Error = MiscError;
-
- fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
- let mut value = value.as_slice();
- <$enum_name>::decode(&mut value)
- .map_err(|_| MiscError::$error)
- }
- }
-
- };
-}
-
#[macro_export]
macro_rules! map_common_err_to_proxy {
(match $err:ident { $($common_err:ident => $proxy_err:ident),+ }) => {
@@ -29,59 +12,8 @@
$err
}
};
-}
-
-pub enum MiscError {
- RmrkPropertyValueIsTooLong,
- CorruptedCollectionType,
-}
-
-impl<T: Config> From<MiscError> for Error<T> {
- fn from(error: MiscError) -> Self {
- match error {
- MiscError::RmrkPropertyValueIsTooLong => Self::RmrkPropertyValueIsTooLong,
- MiscError::CorruptedCollectionType => Self::CorruptedCollectionType,
- }
- }
-}
-
-pub trait IntoNftCollection<T: Config> {
- fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>>;
}
-impl<T: Config> IntoNftCollection<T> for CollectionHandle<T> {
- fn into_nft_collection(self) -> Result<NonfungibleHandle<T>, Error<T>> {
- match self.mode {
- CollectionMode::NFT => Ok(NonfungibleHandle::cast(self)),
- _ => Err(<Error<T>>::CollectionUnknown)
- }
- }
-}
-
-pub trait IntoPropertyValue {
- fn into_property_value(self) -> Result<PropertyValue, MiscError>;
-}
-
-impl<T: Encode> IntoPropertyValue for T {
- fn into_property_value(self) -> Result<PropertyValue, MiscError> {
- self.encode()
- .try_into()
- .map_err(|_| MiscError::RmrkPropertyValueIsTooLong)
- }
-}
-
-pub trait RmrkNft {
- fn rmrk_nft_type(&self) -> Option<NftType>;
-}
-
-impl<CrossAccountId> RmrkNft for ItemData<CrossAccountId> {
- fn rmrk_nft_type(&self) -> Option<NftType> {
- let mut value = self.const_data.as_slice();
-
- NftType::decode(&mut value).ok()
- }
-}
-
pub trait RmrkDecode<T: Decode + Default, S> {
fn decode_or_default(&self) -> T;
}
@@ -121,5 +53,3 @@
SlotPart,
Theme
}
-
-impl_rmrk_value!(CollectionType, decode_error: CorruptedCollectionType);
pallets/proxy-rmrk-core/src/property.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-core/src/property.rs
+++ b/pallets/proxy-rmrk-core/src/property.rs
@@ -71,31 +71,3 @@
}
}
}
-
-#[macro_export]
-macro_rules! rmrk_property {
- (Config=$cfg:ty, key: $key:ident $(($key_ext:expr))?) => {
- rmrk_property!(Config=$cfg, $crate::RmrkProperty::$key $(($key_ext))?)
- };
-
- (Config=$cfg:ty, $key:ident $(($key_ext:expr))?: $value:expr) => {{
- let key = rmrk_property!(@$cfg, $crate::RmrkProperty::$key $(($key_ext))?)?;
-
- let value = $value.into_property_value()
- .map_err(<$crate::Error<$cfg>>::from)?;
-
- Ok::<_, $crate::Error<$cfg>>(Property {
- key,
- value,
- })
- }};
-
- (@$cfg:ty, $key_enum:expr) => {
- $key_enum.to_key::<$cfg>()
- };
-
- (Config=$cfg:ty, $key_enum:expr) => {
- PropertyScope::Rmrk.apply(rmrk_property!(@$cfg, $key_enum)?)
- .map_err(|_| <$crate::Error<$cfg>>::RmrkPropertyKeyIsTooLong)
- };
-}
pallets/proxy-rmrk-equip/src/lib.rsdiffbeforeafterboth--- a/pallets/proxy-rmrk-equip/src/lib.rs
+++ b/pallets/proxy-rmrk-equip/src/lib.rs
@@ -20,9 +20,9 @@
use frame_system::{pallet_prelude::*, ensure_signed};
use sp_runtime::DispatchError;
use up_data_structs::*;
-use pallet_common::{Pallet as PalletCommon, Error as CommonError, CollectionHandle};
-use pallet_rmrk_core::{Pallet as PalletCore, rmrk_property, misc::*};
-use pallet_nonfungible::{Pallet as PalletNft};
+use pallet_common::{Pallet as PalletCommon, Error as CommonError};
+use pallet_rmrk_core::{Pallet as PalletCore, misc::{self, *}, property::RmrkProperty::*};
+use pallet_nonfungible::{Pallet as PalletNft, NonfungibleHandle};
use pallet_evm::account::CrossAccountId;
pub use pallet::*;
@@ -48,6 +48,16 @@
TokenId
>;
+ #[pallet::storage]
+ #[pallet::getter(fn base_has_default_theme)]
+ pub type BaseHasDefaultTheme<T: Config> = StorageMap<
+ _,
+ Twox64Concat,
+ CollectionId,
+ bool,
+ ValueQuery
+ >;
+
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
@@ -63,7 +73,11 @@
#[pallet::error]
pub enum Error<T> {
+ PermissionError,
NoAvailableBaseId,
+ NoAvailablePartId,
+ BaseDoesntExist,
+ NeedsDefaultThemeFirst,
}
#[pallet::call]
@@ -95,17 +109,17 @@
let collection_id = collection_id_res?;
- let collection = <PalletCore<T>>::get_nft_collection(collection_id)?.into_inner();
-
<PalletCommon<T>>::set_scoped_collection_properties(
- &collection,
+ collection_id,
PropertyScope::Rmrk,
[
- rmrk_property!(Config=T, CollectionType: CollectionType::Base)?,
- rmrk_property!(Config=T, BaseType: base_type)?,
+ <PalletCore<T>>::rmrk_property(CollectionType, &misc::CollectionType::Base)?,
+ <PalletCore<T>>::rmrk_property(BaseType, &base_type)?,
].into_iter()
)?;
+ let collection = <PalletCore<T>>::get_nft_collection(collection_id)?;
+
for part in parts {
let part_id = part.id();
let part_token_id = Self::create_part(
@@ -117,10 +131,10 @@
<InernalPartId<T>>::insert(collection_id, part_id, part_token_id);
<PalletNft<T>>::set_scoped_token_property(
- &collection,
+ collection_id,
part_token_id,
PropertyScope::Rmrk,
- rmrk_property!(Config=T, ExternalPartId: part_id)?
+ <PalletCore<T>>::rmrk_property(ExternalPartId, &part_id)?
)?;
}
@@ -128,13 +142,64 @@
Ok(())
}
+
+ #[pallet::weight(10_000 + T::DbWeight::get().reads_writes(1,1))]
+ #[transactional]
+ pub fn theme_add(
+ origin: OriginFor<T>,
+ base_id: RmrkBaseId,
+ theme: RmrkTheme,
+ ) -> DispatchResult {
+ let sender = ensure_signed(origin)?;
+
+ let sender = T::CrossAccountId::from_sub(sender);
+ let owner = &sender;
+
+ let collection_id: CollectionId = base_id.into();
+
+ let collection = <PalletCore<T>>::get_typed_nft_collection(
+ collection_id,
+ misc::CollectionType::Base
+ ).map_err(|_| <Error<T>>::BaseDoesntExist)?;
+
+ if theme.name.as_slice() == b"default" {
+ <BaseHasDefaultTheme<T>>::insert(collection_id, true);
+ } else if !Self::base_has_default_theme(collection_id) {
+ return Err(<Error<T>>::NeedsDefaultThemeFirst.into());
+ }
+
+ let token_id = <PalletCore<T>>::create_nft(
+ &sender,
+ owner,
+ &collection,
+ NftType::Theme,
+ [
+ <PalletCore<T>>::rmrk_property(ThemeName, &theme.name)?,
+ <PalletCore<T>>::rmrk_property(ThemeInherit, &theme.inherit)?
+ ].into_iter()
+ ).map_err(|_| <Error<T>>::PermissionError)?;
+
+ for property in theme.properties {
+ <PalletNft<T>>::set_scoped_token_property(
+ collection_id,
+ token_id,
+ PropertyScope::Rmrk,
+ <PalletCore<T>>::rmrk_property(
+ ThemeProperty(&property.key),
+ &property.value
+ )?
+ )?;
+ }
+
+ Ok(())
+ }
}
}
impl<T: Config> Pallet<T> {
fn create_part(
sender: &T::CrossAccountId,
- collection: &CollectionHandle<T>,
+ collection: &NonfungibleHandle<T>,
part: RmrkPartType
) -> Result<TokenId, DispatchError> {
let owner = sender;
@@ -150,21 +215,23 @@
let token_id = <PalletCore<T>>::create_nft(
sender,
owner,
- collection.id,
- CollectionType::Base,
+ collection,
nft_type,
[
- rmrk_property!(Config=T, Src: src)?,
- rmrk_property!(Config=T, ZIndex: z_index)?
+ <PalletCore<T>>::rmrk_property(Src, &src)?,
+ <PalletCore<T>>::rmrk_property(ZIndex, &z_index)?
].into_iter()
- )?;
+ ).map_err(|err| match err {
+ DispatchError::Arithmetic(_) => <Error<T>>::NoAvailablePartId.into(),
+ err => err
+ })?;
if let RmrkPartType::SlotPart(part) = part {
<PalletNft<T>>::set_scoped_token_property(
- collection,
+ collection.id,
token_id,
PropertyScope::Rmrk,
- rmrk_property!(Config=T, EquippableList: part.equippable)?
+ <PalletCore<T>>::rmrk_property(EquippableList, &part.equippable)?
)?;
}
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -347,7 +347,7 @@
fn base_parts(base_id: RmrkBaseId) -> Result<Vec<RmrkPartType>, DispatchError> {
use frame_support::BoundedVec;
- use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkNft, RmrkDecode}};
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, NftType, RmrkDecode}};
let collection_id = CollectionId(base_id);
if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() { return Ok(Vec::new()); }
@@ -379,7 +379,7 @@
fn theme_names(base_id: RmrkBaseId) -> Result<Vec<RmrkThemeName>, DispatchError> {
use frame_support::BoundedVec;
- use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkNft, RmrkDecode}};
+ use pallet_proxy_rmrk_core::{RmrkProperty, misc::{CollectionType, RmrkDecode}};
let collection_id = CollectionId(base_id);
if RmrkCore::ensure_collection_type(collection_id, CollectionType::Base).is_err() {
@@ -407,7 +407,7 @@
use frame_support::BoundedVec;
use pallet_proxy_rmrk_core::{
RmrkProperty,
- misc::{CollectionType, NftType, RmrkNft, RmrkDecode}
+ misc::{CollectionType, NftType, RmrkDecode}
};
let collection_id = CollectionId(base_id);