git.delta.rocks / unique-network / refs/commits / a66e7a4819dc

difftreelog

source

client/rpc/src/lib.rs9.3 KiBsourcehistory
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;20use jsonrpc_core::{Error as RpcError, ErrorCode, Result};21use jsonrpc_derive::rpc;22use up_data_structs::{23	RpcCollection, CollectionId, CollectionStats, CollectionLimits, TokenId, Property, PropertyKey,24	PropertyKeyPermission,25};26use sp_api::{BlockId, BlockT, ProvideRuntimeApi, ApiExt};27use sp_blockchain::HeaderBackend;28use up_rpc::UniqueApi as UniqueRuntimeApi;2930#[rpc]31pub trait UniqueApi<BlockHash, CrossAccountId, AccountId> {32	#[rpc(name = "unique_accountTokens")]33	fn account_tokens(34		&self,35		collection: CollectionId,36		account: CrossAccountId,37		at: Option<BlockHash>,38	) -> Result<Vec<TokenId>>;39	#[rpc(name = "unique_collectionTokens")]40	fn collection_tokens(41		&self,42		collection: CollectionId,43		at: Option<BlockHash>,44	) -> Result<Vec<TokenId>>;45	#[rpc(name = "unique_tokenExists")]46	fn token_exists(47		&self,48		collection: CollectionId,49		token: TokenId,50		at: Option<BlockHash>,51	) -> Result<bool>;5253	#[rpc(name = "unique_tokenOwner")]54	fn token_owner(55		&self,56		collection: CollectionId,57		token: TokenId,58		at: Option<BlockHash>,59	) -> Result<Option<CrossAccountId>>;60	#[rpc(name = "unique_topmostTokenOwner")]61	fn topmost_token_owner(62		&self,63		collection: CollectionId,64		token: TokenId,65		at: Option<BlockHash>,66	) -> Result<Option<CrossAccountId>>;67	#[rpc(name = "unique_constMetadata")]68	fn const_metadata(69		&self,70		collection: CollectionId,71		token: TokenId,72		at: Option<BlockHash>,73	) -> Result<Vec<u8>>;74	#[rpc(name = "unique_variableMetadata")]75	fn variable_metadata(76		&self,77		collection: CollectionId,78		token: TokenId,79		at: Option<BlockHash>,80	) -> Result<Vec<u8>>;8182	#[rpc(name = "unique_collectionProperties")]83	fn collection_properties(84		&self,85		collection: CollectionId,86		keys: Vec<String>,87		at: Option<BlockHash>,88	) -> Result<Vec<Property>>;8990	#[rpc(name = "unique_tokenProperties")]91	fn token_properties(92		&self,93		collection: CollectionId,94		token_id: TokenId,95		properties: Vec<String>,96		at: Option<BlockHash>,97	) -> Result<Vec<Property>>;9899	#[rpc(name = "unique_propertyPermissions")]100	fn property_permissions(101		&self,102		collection: CollectionId,103		keys: Vec<String>,104		at: Option<BlockHash>,105	) -> Result<Vec<PropertyKeyPermission>>;106107	#[rpc(name = "unique_totalSupply")]108	fn total_supply(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;109	#[rpc(name = "unique_accountBalance")]110	fn account_balance(111		&self,112		collection: CollectionId,113		account: CrossAccountId,114		at: Option<BlockHash>,115	) -> Result<u32>;116	#[rpc(name = "unique_balance")]117	fn balance(118		&self,119		collection: CollectionId,120		account: CrossAccountId,121		token: TokenId,122		at: Option<BlockHash>,123	) -> Result<String>;124	#[rpc(name = "unique_allowance")]125	fn allowance(126		&self,127		collection: CollectionId,128		sender: CrossAccountId,129		spender: CrossAccountId,130		token: TokenId,131		at: Option<BlockHash>,132	) -> Result<String>;133134	#[rpc(name = "unique_adminlist")]135	fn adminlist(136		&self,137		collection: CollectionId,138		at: Option<BlockHash>,139	) -> Result<Vec<CrossAccountId>>;140	#[rpc(name = "unique_allowlist")]141	fn allowlist(142		&self,143		collection: CollectionId,144		at: Option<BlockHash>,145	) -> Result<Vec<CrossAccountId>>;146	#[rpc(name = "unique_allowed")]147	fn allowed(148		&self,149		collection: CollectionId,150		user: CrossAccountId,151		at: Option<BlockHash>,152	) -> Result<bool>;153	#[rpc(name = "unique_lastTokenId")]154	fn last_token_id(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<TokenId>;155	#[rpc(name = "unique_collectionById")]156	fn collection_by_id(157		&self,158		collection: CollectionId,159		at: Option<BlockHash>,160	) -> Result<Option<RpcCollection<AccountId>>>;161	#[rpc(name = "unique_collectionStats")]162	fn collection_stats(&self, at: Option<BlockHash>) -> Result<CollectionStats>;163164	#[rpc(name = "unique_nextSponsored")]165	fn next_sponsored(166		&self,167		collection: CollectionId,168		account: CrossAccountId,169		token: TokenId,170		at: Option<BlockHash>,171	) -> Result<Option<u64>>;172	#[rpc(name = "unique_effectiveCollectionLimits")]173	fn effective_collection_limits(174		&self,175		collection_id: CollectionId,176		at: Option<BlockHash>,177	) -> Result<Option<CollectionLimits>>;178}179180pub struct Unique<C, P> {181	client: Arc<C>,182	_marker: std::marker::PhantomData<P>,183}184185impl<C, P> Unique<C, P> {186	pub fn new(client: Arc<C>) -> Self {187		Self {188			client,189			_marker: Default::default(),190		}191	}192}193194pub enum Error {195	RuntimeError,196}197198impl From<Error> for i64 {199	fn from(e: Error) -> i64 {200		match e {201			Error::RuntimeError => 1,202		}203	}204}205206macro_rules! pass_method {207	(208		$method_name:ident(209			$($(#[map(|$map_arg:ident| $map:expr)])? $name:ident: $ty:ty),* $(,)?210		) -> $result:ty $(=> $mapper:expr)?211		$(; changed_in $ver:expr, $changed_method_name:ident ($($changed_name:expr), * $(,)?) => $fixer:expr)*212	) => {213		fn $method_name(214			&self,215			$(216				$name: $ty,217			)*218			at: Option<<Block as BlockT>::Hash>,219		) -> Result<$result> {220			let api = self.client.runtime_api();221			let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));222			let _api_version = if let Ok(Some(api_version)) =223				api.api_version::<dyn UniqueRuntimeApi<Block, CrossAccountId, AccountId>>(&at)224			{225				api_version226			} else {227				// unreachable for our runtime228				return Err(RpcError {229					code: ErrorCode::InvalidParams,230					message: "Api is not available".into(),231					data: None,232				})233			};234235			let result = $(if _api_version < $ver {236				api.$changed_method_name(&at, $($changed_name),*).map(|r| r.map($fixer))237			} else)*238			{ api.$method_name(&at, $($((|$map_arg: $ty| $map))? ($name)),*) };239240			let result = result.map_err(|e| RpcError {241				code: ErrorCode::ServerError(Error::RuntimeError.into()),242				message: "Unable to query".into(),243				data: Some(format!("{:?}", e).into()),244			})?;245			result.map_err(|e| RpcError {246				code: ErrorCode::InvalidParams,247				message: "Runtime returned error".into(),248				data: Some(format!("{:?}", e).into()),249			})$(.map($mapper))?250		}251	};252}253254#[allow(deprecated)]255impl<C, Block, CrossAccountId, AccountId>256	UniqueApi<<Block as BlockT>::Hash, CrossAccountId, AccountId> for Unique<C, Block>257where258	Block: BlockT,259	AccountId: Decode,260	C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,261	C::Api: UniqueRuntimeApi<Block, CrossAccountId, AccountId>,262	CrossAccountId: pallet_evm::account::CrossAccountId<AccountId>,263{264	pass_method!(account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>);265	pass_method!(collection_tokens(collection: CollectionId) -> Vec<TokenId>);266	pass_method!(token_exists(collection: CollectionId, token: TokenId) -> bool);267	pass_method!(268		token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>;269		changed_in 2, token_owner_before_version_2(collection, token) => |u| Some(u)270	);271	pass_method!(topmost_token_owner(collection: CollectionId, token: TokenId) -> Option<CrossAccountId>);272	pass_method!(const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);273	pass_method!(variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);274275	pass_method!(collection_properties(276		collection: CollectionId,277278		#[map(|keys| string_keys_to_bytes_keys(keys))]279		keys: Vec<String>280	) -> Vec<Property>);281282	pass_method!(token_properties(283		collection: CollectionId,284		token_id: TokenId,285286		#[map(|keys| string_keys_to_bytes_keys(keys))]287		properties: Vec<String>288	) -> Vec<Property>);289290	pass_method!(property_permissions(291		collection: CollectionId,292293		#[map(|keys| string_keys_to_bytes_keys(keys))]294		keys: Vec<String>295	) -> Vec<PropertyKeyPermission>);296297	pass_method!(total_supply(collection: CollectionId) -> u32);298	pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32);299	pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> String => |v| v.to_string());300	pass_method!(allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> String => |v| v.to_string());301302	pass_method!(adminlist(collection: CollectionId) -> Vec<CrossAccountId>);303	pass_method!(allowlist(collection: CollectionId) -> Vec<CrossAccountId>);304	pass_method!(allowed(collection: CollectionId, user: CrossAccountId) -> bool);305	pass_method!(last_token_id(collection: CollectionId) -> TokenId);306	pass_method!(collection_by_id(collection: CollectionId) -> Option<RpcCollection<AccountId>>);307	pass_method!(collection_stats() -> CollectionStats);308	pass_method!(next_sponsored(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Option<u64>);309	pass_method!(effective_collection_limits(collection_id: CollectionId) -> Option<CollectionLimits>);310}311312fn string_keys_to_bytes_keys(keys: Vec<String>) -> Vec<Vec<u8>> {313	keys.into_iter().map(|key| key.into_bytes()).collect()314}