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

difftreelog

feat custom rpc

Yaroslav Bolyukin2021-10-12parent: #5c24805.patch.diff
in: master

7 files changed

modifiedCargo.tomldiffbeforeafterboth
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -3,6 +3,7 @@
 members = [
     'node/*',
     'pallets/*',
+    'client/*',
     'primitives/*',
     'runtime',
     'crates/*',
addedclient/rpc/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/client/rpc/Cargo.toml
@@ -0,0 +1,19 @@
+[package]
+name = "uc-rpc"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+pallet-common = { default-features = false, path = '../../pallets/common' }
+nft-data-structs = { default-features = false, path = '../../primitives/nft' }
+up-rpc = { path = "../../primitives/rpc" }
+codec = { package = "parity-scale-codec", version = "2.0.0" }
+jsonrpc-core = "15.1.0"
+jsonrpc-core-client = "15.1.0"
+jsonrpc-derive = "15.1.0"
+
+sp-api = { default-features = false, version = '4.0.0-dev', git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.10" }
+sp-blockchain = { default-features = false, version = '4.0.0-dev', git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.10" }
+sp-core = { default-features = false, version = '4.0.0-dev', git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.10" }
+sp-rpc = { default-features = false, version = '4.0.0-dev', git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.10" }
+sp-runtime = { default-features = false, version = '4.0.0-dev', git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.10" }
addedclient/rpc/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/client/rpc/src/lib.rs
@@ -0,0 +1,141 @@
+use std::sync::Arc;
+
+use jsonrpc_core::{Error as RpcError, ErrorCode, Result};
+use jsonrpc_derive::rpc;
+use nft_data_structs::{CollectionId, TokenId};
+use sp_api::{BlockId, BlockT, ProvideRuntimeApi};
+use sp_blockchain::HeaderBackend;
+use up_rpc::NftApi as NftRuntimeApi;
+
+#[rpc]
+pub trait NftApi<BlockHash, CrossAccountId, AccountId> {
+	#[rpc(name = "nft_accountTokens")]
+	fn account_tokens(
+		&self,
+		collection: CollectionId,
+		account: CrossAccountId,
+		at: Option<BlockHash>,
+	) -> Result<Vec<TokenId>>;
+	#[rpc(name = "nft_tokenExists")]
+	fn token_exists(
+		&self,
+		collection: CollectionId,
+		token: TokenId,
+		at: Option<BlockHash>,
+	) -> Result<bool>;
+
+	#[rpc(name = "nft_tokenOwner")]
+	fn token_owner(
+		&self,
+		collection: CollectionId,
+		token: TokenId,
+		at: Option<BlockHash>,
+	) -> Result<CrossAccountId>;
+	#[rpc(name = "nft_constMetadata")]
+	fn const_metadata(
+		&self,
+		collection: CollectionId,
+		token: TokenId,
+		at: Option<BlockHash>,
+	) -> Result<Vec<u8>>;
+	#[rpc(name = "nft_variableMetadata")]
+	fn variable_metadata(
+		&self,
+		collection: CollectionId,
+		token: TokenId,
+		at: Option<BlockHash>,
+	) -> Result<Vec<u8>>;
+
+	#[rpc(name = "nft_collectionTokens")]
+	fn collection_tokens(&self, collection: CollectionId, at: Option<BlockHash>) -> Result<u32>;
+	#[rpc(name = "nft_accountBalance")]
+	fn account_balance(
+		&self,
+		collection: CollectionId,
+		account: CrossAccountId,
+		at: Option<BlockHash>,
+	) -> Result<u32>;
+	#[rpc(name = "nft_balance")]
+	fn balance(
+		&self,
+		collection: CollectionId,
+		account: CrossAccountId,
+		token: TokenId,
+		at: Option<BlockHash>,
+	) -> Result<u128>;
+	#[rpc(name = "nft_allowance")]
+	fn allowance(
+		&self,
+		collection: CollectionId,
+		sender: CrossAccountId,
+		spender: CrossAccountId,
+		token: TokenId,
+		at: Option<BlockHash>,
+	) -> Result<u128>;
+}
+
+pub struct Nft<C, P> {
+	client: Arc<C>,
+	_marker: std::marker::PhantomData<P>,
+}
+
+impl<C, P> Nft<C, P> {
+	pub fn new(client: Arc<C>) -> Self {
+		Self {
+			client,
+			_marker: Default::default(),
+		}
+	}
+}
+
+pub enum Error {
+	RuntimeError,
+}
+
+impl From<Error> for i64 {
+	fn from(e: Error) -> i64 {
+		match e {
+			Error::RuntimeError => 1,
+		}
+	}
+}
+
+macro_rules! pass_method {
+	($method_name:ident($($name:ident: $ty:ty),* $(,)?) -> $result:ty) => {
+		fn $method_name(
+			&self,
+			$(
+				$name: $ty,
+			)*
+			at: Option<<Block as BlockT>::Hash>,
+		) -> Result<$result> {
+			let api = self.client.runtime_api();
+			let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash));
+
+			api.$method_name(&at, $($name),*).map_err(|e| RpcError {
+				code: ErrorCode::ServerError(Error::RuntimeError.into()),
+				message: "Unable to query".into(),
+				data: Some(format!("{:?}", e).into()),
+			})
+		}
+	};
+}
+
+impl<C, Block, CrossAccountId, AccountId> NftApi<<Block as BlockT>::Hash, CrossAccountId, AccountId>
+	for Nft<C, Block>
+where
+	Block: BlockT,
+	C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
+	C::Api: NftRuntimeApi<Block, CrossAccountId, AccountId>,
+	CrossAccountId: pallet_common::account::CrossAccountId<AccountId>,
+{
+	pass_method!(account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>);
+	pass_method!(token_exists(collection: CollectionId, token: TokenId) -> bool);
+	pass_method!(token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId);
+	pass_method!(const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
+	pass_method!(variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>);
+	pass_method!(collection_tokens(collection: CollectionId) -> u32);
+	pass_method!(account_balance(collection: CollectionId, account: CrossAccountId) -> u32);
+	pass_method!(balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128);
+	pass_method!(allowance(collection: CollectionId, sender: CrossAccountId, spender: CrossAccountId, token: TokenId) -> u128);
+}
modifiednode/rpc/Cargo.tomldiffbeforeafterboth
--- a/node/rpc/Cargo.toml
+++ b/node/rpc/Cargo.toml
@@ -13,7 +13,7 @@
 futures = { version = "0.3.17", features = ["compat"] }
 jsonrpc-core = "15.1.0"
 jsonrpc-pubsub = "15.1.0"
-# pallet-contracts-rpc = { version = "4.0.0-dev", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.9' }
+# pallet-contracts-rpc = { version = "4.0.0-dev", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
 pallet-transaction-payment-rpc = { version = "4.0.0-dev", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
 pallet-transaction-payment-rpc-runtime-api = { version = "4.0.0-dev", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
 sc-client-api = { version = "4.0.0-dev", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
@@ -49,6 +49,8 @@
 fc-mapping-sync = { default-features = false, git = "https://github.com/uniquenetwork/frontier.git", branch = "unique-polkadot-v0.9.10" }
 
 pallet-nft = { path = "../../pallets/nft" }
+uc-rpc = { path = "../../client/rpc" }
+up-rpc = { path = "../../primitives/rpc" }
 nft-runtime = { path = "../../runtime" }
 
 [features]
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
before · node/rpc/src/lib.rs
1use nft_runtime::{Hash, AccountId, Index, opaque::Block, BlockNumber, Balance};2use fc_rpc::{OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override, StorageOverride};3use fc_rpc_core::types::{FilterPool, PendingTransactions};4use jsonrpc_pubsub::manager::SubscriptionManager;5use pallet_ethereum::EthereumStorageSchema;6use sc_client_api::{7	backend::{AuxStore, StorageProvider},8	client::BlockchainEvents,9};10use pallet_nft::NftApi;11use sc_finality_grandpa::{12	FinalityProofProvider, GrandpaJustificationStream, SharedAuthoritySet, SharedVoterState,13};14use sc_network::NetworkService;15use sc_rpc::SubscriptionTaskExecutor;16pub use sc_rpc_api::DenyUnsafe;17use sp_api::ProvideRuntimeApi;18use sp_block_builder::BlockBuilder;19use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata};20use sp_consensus::SelectChain;21use sc_service::TransactionPool;22use std::{collections::BTreeMap, marker::PhantomData, sync::Arc};2324/// Public io handler for exporting into other modules25pub type IoHandler = jsonrpc_core::IoHandler<sc_rpc::Metadata>;2627/// Light client extra dependencies.28pub struct LightDeps<C, F, P> {29	/// The client instance to use.30	pub client: Arc<C>,31	/// Transaction pool instance.32	pub pool: Arc<P>,33	/// Remote access to the blockchain (async).34	pub remote_blockchain: Arc<dyn sc_client_api::light::RemoteBlockchain<Block>>,35	/// Fetcher instance.36	pub fetcher: Arc<F>,37}3839/// Extra dependencies for GRANDPA40pub struct GrandpaDeps<B> {41	/// Voting round info.42	pub shared_voter_state: SharedVoterState,43	/// Authority set info.44	pub shared_authority_set: SharedAuthoritySet<Hash, BlockNumber>,45	/// Receives notifications about justification events from Grandpa.46	pub justification_stream: GrandpaJustificationStream<Block>,47	/// Executor to drive the subscription manager in the Grandpa RPC handler.48	pub subscription_executor: SubscriptionTaskExecutor,49	/// Finality proof provider.50	pub finality_provider: Arc<FinalityProofProvider<B, Block>>,51}5253/// Full client dependencies.54pub struct FullDeps<C, P, SC> {55	/// The client instance to use.56	pub client: Arc<C>,57	/// Transaction pool instance.58	pub pool: Arc<P>,59	/// The SelectChain Strategy60	pub select_chain: SC,61	/// The Node authority flag62	pub is_authority: bool,63	/// Whether to enable dev signer64	pub enable_dev_signer: bool,65	/// Network service66	pub network: Arc<NetworkService<Block, Hash>>,67	/// Whether to deny unsafe calls68	pub deny_unsafe: DenyUnsafe,69	/// Ethereum pending transactions.70	pub pending_transactions: PendingTransactions,71	/// EthFilterApi pool.72	pub filter_pool: Option<FilterPool>,73	/// Backend.74	pub backend: Arc<fc_db::Backend<Block>>,75	/// Maximum number of logs in a query.76	pub max_past_logs: u32,77}7879struct AccountCodes<C, B> {80	client: Arc<C>,81	_marker: PhantomData<B>,82}8384impl<C, Block> AccountCodes<C, Block>85where86	Block: sp_api::BlockT,87	C: ProvideRuntimeApi<Block>,88{89	fn new(client: Arc<C>) -> Self {90		Self {91			client,92			_marker: PhantomData,93		}94	}95}9697impl<C, Block> fc_rpc::AccountCodeProvider<Block> for AccountCodes<C, Block>98where99	Block: sp_api::BlockT,100	C: ProvideRuntimeApi<Block>,101	C::Api: pallet_nft::NftApi<Block>,102{103	fn code(&self, block: &sp_api::BlockId<Block>, account: sp_core::H160) -> Option<Vec<u8>> {104		self.client105			.runtime_api()106			.eth_contract_code(block, account)107			.ok()108			.flatten()109	}110}111112/// Instantiate all Full RPC extensions.113pub fn create_full<C, P, SC, A, B>(114	deps: FullDeps<C, P, SC>,115	subscription_task_executor: SubscriptionTaskExecutor,116) -> jsonrpc_core::IoHandler<sc_rpc_api::Metadata>117where118	C: ProvideRuntimeApi<Block> + StorageProvider<Block, B> + AuxStore,119	C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static,120	C: Send + Sync + 'static,121	C: BlockchainEvents<Block>,122	C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>,123	C::Api: BlockBuilder<Block>,124	// C::Api: pallet_contracts_rpc::ContractsRuntimeApi<Block, AccountId, Balance, BlockNumber, Hash>,125	C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>,126	C::Api: fp_rpc::EthereumRuntimeRPCApi<Block>,127	C::Api: pallet_nft::NftApi<Block>,128	P: TransactionPool<Block = Block> + 'static,129	SC: SelectChain<Block> + 'static,130	B: sc_client_api::Backend<Block> + Send + Sync + 'static,131	B::State: sc_client_api::backend::StateBackend<sp_runtime::traits::HashFor<Block>>,132{133	use fc_rpc::{134		EthApi, EthApiServer, EthDevSigner, EthFilterApi, EthFilterApiServer, EthPubSubApi,135		EthPubSubApiServer, EthSigner, HexEncodedIdProvider, NetApi, NetApiServer, Web3Api,136		Web3ApiServer,137	};138	// use pallet_contracts_rpc::{Contracts, ContractsApi};139	use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApi};140	use substrate_frame_rpc_system::{FullSystem, SystemApi};141142	let mut io = jsonrpc_core::IoHandler::default();143	let FullDeps {144		client,145		pool,146		select_chain: _,147		enable_dev_signer,148		is_authority,149		network,150		deny_unsafe,151		pending_transactions,152		filter_pool,153		backend,154		max_past_logs,155	} = deps;156157	io.extend_with(SystemApi::to_delegate(FullSystem::new(158		client.clone(),159		pool.clone(),160		deny_unsafe,161	)));162163	io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(164		client.clone(),165	)));166167	// io.extend_with(ContractsApi::to_delegate(Contracts::new(client.clone())));168169	let mut signers = Vec::new();170	if enable_dev_signer {171		signers.push(Box::new(EthDevSigner::new()) as Box<dyn EthSigner>);172	}173	let mut overrides_map = BTreeMap::new();174	overrides_map.insert(175		EthereumStorageSchema::V1,176		Box::new(SchemaV1Override::new_with_code_provider(177			client.clone(),178			Arc::new(AccountCodes::<C, Block>::new(client.clone())),179		)) as Box<dyn StorageOverride<_> + Send + Sync>,180	);181182	let overrides = Arc::new(OverrideHandle {183		schemas: overrides_map,184		fallback: Box::new(RuntimeApiStorageOverride::new(client.clone())),185	});186187	io.extend_with(EthApiServer::to_delegate(EthApi::new(188		client.clone(),189		pool.clone(),190		nft_runtime::TransactionConverter,191		network.clone(),192		pending_transactions,193		signers,194		overrides.clone(),195		backend.clone(),196		is_authority,197		max_past_logs,198	)));199200	if let Some(filter_pool) = filter_pool {201		io.extend_with(EthFilterApiServer::to_delegate(EthFilterApi::new(202			client.clone(),203			backend,204			filter_pool,205			500_usize, // max stored filters206			overrides.clone(),207			max_past_logs,208		)));209	}210211	io.extend_with(NetApiServer::to_delegate(NetApi::new(212		client.clone(),213		network.clone(),214		// Whether to format the `peer_count` response as Hex (default) or not.215		true,216	)));217218	io.extend_with(Web3ApiServer::to_delegate(Web3Api::new(client.clone())));219220	io.extend_with(EthPubSubApiServer::to_delegate(EthPubSubApi::new(221		pool,222		client,223		network,224		SubscriptionManager::<HexEncodedIdProvider>::with_id_provider(225			HexEncodedIdProvider::default(),226			Arc::new(subscription_task_executor),227		),228		overrides,229	)));230231	io232}233234/// Instantiate all Light RPC extensions.235pub fn create_light<C, P, M, F>(deps: LightDeps<C, F, P>) -> jsonrpc_core::IoHandler<M>236where237	C: sp_blockchain::HeaderBackend<Block>,238	C: Send + Sync + 'static,239	F: sc_client_api::light::Fetcher<Block> + 'static,240	P: TransactionPool + 'static,241	M: jsonrpc_core::Metadata + Default,242{243	use substrate_frame_rpc_system::{LightSystem, SystemApi};244245	let LightDeps {246		client,247		pool,248		remote_blockchain,249		fetcher,250	} = deps;251	let mut io = jsonrpc_core::IoHandler::default();252	io.extend_with(SystemApi::<Hash, AccountId, Index>::to_delegate(253		LightSystem::new(client, remote_blockchain, fetcher, pool),254	));255256	io257}
addedprimitives/rpc/Cargo.tomldiffbeforeafterboth
--- /dev/null
+++ b/primitives/rpc/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+name = "up-rpc"
+version = "0.1.0"
+edition = "2018"
+
+[dependencies]
+pallet-common = { default-features = false, path = '../../pallets/common' }
+nft-data-structs = { default-features = false, path = '../nft' }
+codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false, features = ["derive"] }
+sp-core = { default-features = false, version = "4.0.0-dev", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
+sp-std = { default-features = false, version = "4.0.0-dev", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
+sp-api = { default-features = false, version = "4.0.0-dev", git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
+sp-runtime = { default-features = false, version = '4.0.0-dev', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.10' }
+
+[features]
+default = ["std"]
+std = [
+	"codec/std",
+	"sp-core/std",
+	"sp-std/std",
+	"sp-api/std",
+	"sp-runtime/std",
+	"pallet-common/std",
+	"nft-data-structs/std",
+]
addedprimitives/rpc/src/lib.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/rpc/src/lib.rs
@@ -0,0 +1,31 @@
+#![cfg_attr(not(feature = "std"), no_std)]
+
+use nft_data_structs::{CollectionId, TokenId};
+use sp_std::vec::Vec;
+use sp_core::H160;
+
+sp_api::decl_runtime_apis! {
+	pub trait NftApi<CrossAccountId, AccountId> where
+		CrossAccountId: pallet_common::account::CrossAccountId<AccountId>,
+	{
+		fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId>;
+		fn token_exists(collection: CollectionId, token: TokenId) -> bool;
+
+		fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId;
+		fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>;
+		fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8>;
+
+		fn collection_tokens(collection: CollectionId) -> u32;
+		fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32;
+		fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128;
+		fn allowance(
+			collection: CollectionId,
+			sender: CrossAccountId,
+			spender: CrossAccountId,
+			token: TokenId,
+		) -> u128;
+
+		/// Used for ethereum integration
+		fn eth_contract_code(account: H160) -> Option<Vec<u8>>;
+	}
+}