1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//! RPC interface for the contracts registry pallet.

use std::sync::Arc;

use codec::Codec;
use jsonrpsee::{
    core::{Error as JsonRpseeError, RpcResult},
    proc_macros::rpc,
};
pub use pallet_contracts_registry_rpc_runtime_api::ContractsRegistryRuntimeApi;
use pallet_contracts_registry_rpc_runtime_api::FetchContractsResult;
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_runtime::traits::{Block as BlockT, MaybeDisplay};

const RUNTIME_ERROR: i64 = 1;

#[rpc(client, server)]
pub trait ContractsRegistryApi<AccountId> {
    /// Returns the contracts searchable by name, author or metadata
    #[method(name = "contractsRegistry_fetchContracts")]
    fn fetch_contracts(
        &self,
        author: Option<AccountId>,
        metadata: Option<Vec<u8>>,
    ) -> RpcResult<FetchContractsResult>;
}

/// A struct that implements the [ContractsRegistryApi].
pub struct ContractsRegistry<C, B> {
    client: Arc<C>,
    _marker: std::marker::PhantomData<B>,
}

impl<C, B> ContractsRegistry<C, B> {
    pub fn new(client: Arc<C>) -> Self {
        Self {
            client,
            _marker: Default::default(),
        }
    }
}
impl<C, Block, AccountId> ContractsRegistryApiServer<AccountId> for ContractsRegistry<C, Block>
where
    AccountId: Codec + MaybeDisplay,
    Block: BlockT,
    C: 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>,
    C::Api: ContractsRegistryRuntimeApi<Block, AccountId>,
{
    fn fetch_contracts(
        &self,
        author: Option<AccountId>,
        metadata: Option<Vec<u8>>,
    ) -> RpcResult<FetchContractsResult> {
        let api = self.client.runtime_api();
        let at = self.client.info().best_hash;

        let result = api
            .fetch_contracts(at, author, metadata)
            .map_err(runtime_error_into_rpc_err)?;

        Ok(result)
    }
}

fn runtime_error_into_rpc_err(err: impl std::fmt::Debug) -> JsonRpseeError {
    JsonRpseeError::Custom(format!("{err:?}"))
}