difftreelog
Add properties RPC
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;20use jsonrpc_core::{Error as RpcError, ErrorCode, Result};21use jsonrpc_derive::rpc;22use up_data_structs::{RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId};23use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};24use sp_blockchain::HeaderBackend;25use up_rpc::UniqueApi as UniqueRuntimeApi;2627#[rpc]28pub trait UniqueApi<BlockHash, CrossAccountId, AccountId> {29 #[rpc(name = "unique_accountTokens")]30 fn account_tokens(31 &self,32 collection: CollectionId,33 account: CrossAccountId,34 at: Option<BlockHash>,35 ) -> Result<Vec<TokenId>>;36 #[rpc(name = "unique_collectionTokens")]37 fn collection_tokens(38 &self,39 collection: CollectionId,40 at: Option<BlockHash>,41 ) -> Result<Vec<TokenId>>;42 #[rpc(name = "unique_tokenExists")]43 fn token_exists(44 &self,45 collection: CollectionId,46 token: TokenId,47 at: Option<BlockHash>,48 ) -> Result<bool>;4950 #[rpc(name = "unique_tokenOwner")]51 fn token_owner(52 &self,53 collection: CollectionId,54 token: TokenId,55 at: Option<BlockHash>,56 ) -> Result<Option<CrossAccountId>>;57 #[rpc(name = "unique_topmostTokenOwner")]58 fn topmost_token_owner(59 &self,60 collection: CollectionId,61 token: TokenId,62 at: Option<BlockHash>,63 ) -> Result<Option<CrossAccountId>>;64 #[rpc(name = "unique_constMetadata")]65 fn const_metadata(66 &self,67 collection: CollectionId,68 token: TokenId,69 at: Option<BlockHash>,70 ) -> Result<Vec<u8>>;71 #[rpc(name = "unique_variableMetadata")]72 fn variable_metadata(73 &self,74 collection: CollectionId,75 token: TokenId,76 at: Option<BlockHash>,77 ) -> Result<Vec<u8>>;7879 #[rpc(name = "unique_totalSupply")]80 fn total_supply(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;81 #[rpc(name = "unique_accountBalance")]82 fn account_balance(83 &self,84 collection: CollectionId,85 account: CrossAccountId,86 at: Option<BlockHash>,87 ) -> Result<u32>;88 #[rpc(name = "unique_balance")]89 fn balance(90 &self,91 collection: CollectionId,92 account: CrossAccountId,93 token: TokenId,94 at: Option<BlockHash>,95 ) -> Result<String>;96 #[rpc(name = "unique_allowance")]97 fn allowance(98 &self,99 collection: CollectionId,100 sender: CrossAccountId,101 spender: CrossAccountId,102 token: TokenId,103 at: Option<BlockHash>,104 ) -> Result<String>;105106 #[rpc(name = "unique_adminlist")]107 fn adminlist(108 &self,109 collection: CollectionId,110 at: Option<BlockHash>,111 ) -> Result<Vec<CrossAccountId>>;112 #[rpc(name = "unique_allowlist")]113 fn allowlist(114 &self,115 collection: CollectionId,116 at: Option<BlockHash>,117 ) -> Result<Vec<CrossAccountId>>;118 #[rpc(name = "unique_allowed")]119 fn allowed(120 &self,121 collection: CollectionId,122 user: CrossAccountId,123 at: Option<BlockHash>,124 ) -> Result<bool>;125 #[rpc(name = "unique_lastTokenId")]126 fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;127 #[rpc(name = "unique_collectionById")]128 fn collection_by_id(129 &self,130 collection: CollectionId,131 at: Option<BlockHash>,132 ) -> Result<Option<RpcCollection<AccountId>>>;133 #[rpc(name = "unique_collectionStats")]134 fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;135136 #[rpc(name = "unique_nextSponsored")]137 fn next_sponsored(138 &self,139 collection: CollectionId,140 account: CrossAccountId,141 token: TokenId,142 at: Option<BlockHash>,143 ) -> Result<Option<u64>>;144 #[rpc(name = "unique_effectiveCollectionLimits")]145 fn effective_collection_limits(146 &self,147 collection_id: CollectionId,148 at: Option<BlockHash>,149 ) -> Result<Option<CollectionLimits>>;150}151152pub struct Unique<C, P> {153 client: Arc<C>,154 _marker: std::marker::PhantomData<P>,155}156157impl<C, P> Unique<C, P> {158 pub fn new(client: Arc<C>) -> Self {159 Self {160 client,161 _marker: Default::default(),162 }163 }164}165166pub enum Error {167 RuntimeError,168}169170impl From<Error> for i64 {171 fn from(e: Error) -> i64 {172 match e {173 Error::RuntimeError => 1,174 }175 }176}177178macro_rules! pass_method {179 (180 $method_name:ident($($name:ident: $ty:ty),* $(,)?) -> $result:ty $(=> $mapper:expr)?181 $(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*182 ) => {183 fn $method_name(184 &self,185 $(186 $name: $ty,187 )*188 at: Option<<Block as BlockT>::Hash>,189 ) -> Result<$result> {190 let api = self.client.runtime_api();191 let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));192 let _api_version = if let Ok(Some(api_version)) =193 api.api_version::<dyn UniqueRuntimeApi<Block, CrossAccountId, AccountId>>(&at)194 {195 api_version196 } else {197 // unreachable for our runtime198 return Err(RpcError {199 code: ErrorCode::InvalidParams,200 message: "Api is not available".into(),201 data: None,202 })203 };204205 let result = $(if _api_version < $ver {206 api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))207 } else)*208 { api.$method_name(&at, $($name),*) };209210 let result = result.map_err(|e| RpcError {211 code: ErrorCode::ServerError(Error::RuntimeError.into()),212 message: "Unable to query".into(),213 data: Some(format!("{:?}", e).into()),214 })?;215 result.map_err(|e| RpcError {216 code: ErrorCode::InvalidParams,217 message: "Runtime returned error".into(),218 data: Some(format!("{:?}", e).into()),219 })$(.map($mapper))?220 }221 };222}223224#[allow(deprecated)]225impl<C, Block, CrossAccountId, AccountId>226 UniqueApi<<Block as BlockT>::Hash, CrossAccountId, AccountId> for Unique<C, Block>227where228 Block: BlockT,229 AccountId: Decode,230 C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,231 C::Api: UniqueRuntimeApi<Block, CrossAccountId, AccountId>,232 CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,233{234 pass_method!(account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>);235 pass_method!(collection_tokens(collection: CollectionId) -> Vec<TokenId>);236 pass_method!(token_exists(collection: CollectionId, token: TokenId) -> bool);237 pass_method!(238 token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>;239 changed_in 2, token_owner_before_version_2(collection, token) => |u| Some(u)240 );241 pass_method!(topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>);242 pass_method!(const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);243 pass_method!(variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);244245 pass_method!(total_supply(collection: CollectionId) -> u32);246 pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32);247 pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string());248 pass_method!(allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string());249250 pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);251 pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);252 pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool);253 pass_method!(last_token_id(collection: CollectionId) -> TokenId);254 pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>);255 pass_method!(collection_stats() -> CollectionStats);256 pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>);257 pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>);258}pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -388,6 +388,7 @@
/// Collection properties
#[pallet::storage]
+ #[pallet::getter(fn collection_properties)]
pub type CollectionProperties<T> = StorageMap<
Hasher = Blake2_128Concat,
Key = CollectionId,
@@ -397,7 +398,7 @@
>;
#[pallet::storage]
- #[pallet::getter(fn property_permission)]
+ #[pallet::getter(fn property_permissions)]
pub type CollectionPropertyPermissions<T> = StorageMap<
Hasher = Blake2_128Concat,
Key = CollectionId,
@@ -656,9 +657,7 @@
CollectionProperties::<T>::insert(
id,
Properties::from_collection_props_vec(data.properties)
- .map_err(|e| -> Error::<T> {
- e.into()
- })?,
+ .map_err(|e| -> Error<T> { e.into() })?,
);
let token_props_permissions: PropertiesPermissionMap = data
@@ -667,9 +666,7 @@
.map(|property| (property.key, property.permission))
.collect::<BTreeMap<_, _>>()
.try_into()
- .map_err(|_| -> Error::<T> {
- PropertiesError::PropertyLimitReached.into()
- })?;
+ .map_err(|_| -> Error<T> { PropertiesError::PropertyLimitReached.into() })?;
CollectionPropertyPermissions::<T>::insert(id, token_props_permissions);
@@ -754,9 +751,7 @@
CollectionProperties::<T>::try_mutate(collection.id, |properties| {
properties.try_set_property(property.clone())
})
- .map_err(|e| -> Error::<T> {
- e.into()
- })?;
+ .map_err(|e| -> Error<T> { e.into() })?;
Self::deposit_event(Event::CollectionPropertySet(collection.id, property));
@@ -786,7 +781,10 @@
properties.remove_property(&property_key);
});
- Self::deposit_event(Event::CollectionPropertyDeleted(collection.id, property_key));
+ Self::deposit_event(Event::CollectionPropertyDeleted(
+ collection.id,
+ property_key,
+ ));
Ok(())
}
@@ -823,9 +821,7 @@
let property_permission = property_permission.clone();
permissions.try_insert(property_permission.key, property_permission.permission)
})
- .map_err(|_| -> Error::<T> {
- PropertiesError::PropertyLimitReached.into()
- })?;
+ .map_err(|_| -> Error<T> { PropertiesError::PropertyLimitReached.into() })?;
Self::deposit_event(Event::PropertyPermissionSet(
collection.id,
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -184,7 +184,7 @@
with_weight(
<Pallet<T>>::delete_collection_properties(self, &sender, property_keys),
- weight
+ weight,
)
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -96,6 +96,7 @@
>;
#[pallet::storage]
+ #[pallet::getter(fn token_properties)]
pub type TokenProperties<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
Value = up_data_structs::Properties,
@@ -265,9 +266,8 @@
<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {
properties.try_set_property(property.clone())
- }).map_err(|e| -> CommonError::<T> {
- e.into()
- })?;
+ })
+ .map_err(|e| -> CommonError<T> { e.into() })?;
<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(
collection.id,
@@ -318,7 +318,7 @@
token_id: TokenId,
property_key: &PropertyKey,
) -> DispatchResult {
- let permission = <PalletCommon<T>>::property_permission(collection.id)
+ let permission = <PalletCommon<T>>::property_permissions(collection.id)
.get(property_key)
.map(|p| p.clone())
.unwrap_or(PropertyPermission::None);
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -634,6 +634,7 @@
pub type PropertyValue = BoundedVec<u8, ConstU32<MAX_PROPERTY_VALUE_LENGTH>>;
#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub enum PropertyPermission {
None,
AdminConst,
@@ -644,14 +645,21 @@
}
#[derive(Encode, Decode, Debug, TypeInfo, Clone, PartialEq, MaxEncodedLen)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct Property {
+ #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
pub key: PropertyKey,
+
+ #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
pub value: PropertyValue,
}
#[derive(Encode, Decode, TypeInfo, Debug, MaxEncodedLen, PartialEq, Clone)]
+#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct PropertyKeyPermission {
+ #[cfg_attr(feature = "serde1", serde(with = "bounded::vec_serde"))]
pub key: PropertyKey,
+
pub permission: PropertyPermission,
}
@@ -723,6 +731,10 @@
pub fn get_property(&self, key: &PropertyKey) -> Option<&PropertyValue> {
self.map.get(key)
}
+
+ pub fn iter(&self) -> impl Iterator<Item = (&PropertyKey, &PropertyValue)> {
+ self.map.iter()
+ }
}
pub struct CollectionProperties;
primitives/rpc/src/lib.rsdiffbeforeafterboth--- a/primitives/rpc/src/lib.rs
+++ b/primitives/rpc/src/lib.rs
@@ -16,7 +16,10 @@
#![cfg_attr(not(feature = "std"), no_std)]
-use up_data_structs::{CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits};
+use up_data_structs::{
+ CollectionId, TokenId, RpcCollection, CollectionStats, CollectionLimits, Property, PropertyKey,
+ PropertyKeyPermission,
+};
use sp_std::vec::Vec;
use codec::Decode;
use sp_runtime::DispatchError;
@@ -41,6 +44,19 @@
fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>>;
fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>>;
+ fn collection_properties(collection: CollectionId, properties: Vec<Vec<u8>>) -> Result<Vec<Property>>;
+
+ fn token_properties(
+ collection: CollectionId,
+ token_id: TokenId,
+ properties: Vec<Vec<u8>>
+ ) -> Result<Vec<Property>>;
+
+ fn property_permissions(
+ collection: CollectionId,
+ properties: Vec<Vec<u8>>
+ ) -> Result<Vec<PropertyKeyPermission>>;
+
fn total_supply(collection: CollectionId) -> Result<u32>;
fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32>;
fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128>;
runtime/common/src/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/src/runtime_apis.rs
+++ b/runtime/common/src/runtime_apis.rs
@@ -7,6 +7,14 @@
$($custom_apis:tt)+
)?
) => {
+ fn bytes_keys_to_property_keys(keys: Vec<Vec<u8>>) -> Result<Vec<PropertyKey>, DispatchError> {
+ keys.into_iter()
+ .map(|key| -> Result<PropertyKey, DispatchError> {
+ key.try_into().map_err(|_| DispatchError::Other("Can't read property key"))
+ })
+ .collect::<Result<Vec<PropertyKey>, DispatchError>>()
+ }
+
impl_runtime_apis! {
$($($custom_apis)+)?
@@ -36,6 +44,76 @@
dispatch_unique_runtime!(collection.variable_metadata(token))
}
+ fn collection_properties(
+ collection: CollectionId,
+ keys: Vec<Vec<u8>>
+ ) -> Result<Vec<Property>, DispatchError> {
+ let keys = bytes_keys_to_property_keys(keys)?;
+
+ let properties = pallet_common::Pallet::<Runtime>::collection_properties(collection);
+
+ let properties = keys.into_iter()
+ .filter_map(|key| {
+ properties.get_property(&key)
+ .map(|value| {
+ Property {
+ key,
+ value: value.clone()
+ }
+ })
+ })
+ .collect();
+
+ Ok(properties)
+ }
+
+ fn token_properties(
+ collection: CollectionId,
+ token_id: TokenId,
+ keys: Vec<Vec<u8>>
+ ) -> Result<Vec<Property>, DispatchError> {
+ let keys = bytes_keys_to_property_keys(keys)?;
+
+ let properties = pallet_nonfungible::Pallet::<Runtime>::token_properties((collection, token_id));
+
+ let properties = keys.into_iter()
+ .filter_map(|key| {
+ properties.get_property(&key)
+ .map(|value| {
+ Property {
+ key,
+ value: value.clone()
+ }
+ })
+ })
+ .collect();
+
+ Ok(properties)
+ }
+
+ fn property_permissions(
+ collection: CollectionId,
+ keys: Vec<Vec<u8>>
+ ) -> Result<Vec<PropertyKeyPermission>, DispatchError> {
+ let keys = bytes_keys_to_property_keys(keys)?;
+
+ let permissions = pallet_common::Pallet::<Runtime>::property_permissions(collection);
+
+ let key_permissions = keys.into_iter()
+ .filter_map(|key| {
+ permissions.get(&key)
+ .map(|permission| {
+ PropertyKeyPermission {
+ key,
+ permission: permission.clone()
+ }
+ })
+ })
+ .collect();
+
+ Ok(key_permissions)
+ }
+
fn total_supply(collection: CollectionId) -> Result<u32, DispatchError> {
dispatch_unique_runtime!(collection.total_supply())
}
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -67,7 +67,7 @@
},
};
use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};
-use up_data_structs::{CollectionId, TokenId, CollectionStats, CollectionLimits, RpcCollection};
+use up_data_structs::*;
// use pallet_contracts::weights::WeightInfo;
// #[cfg(any(feature = "std", test))]
use frame_system::{