gear_subxt/runtime_api/
runtime_client.rs

1// Copyright 2019-2023 Parity Technologies (UK) Ltd.
2// This file is dual-licensed as Apache-2.0 or GPL-3.0.
3// see LICENSE for license details.
4
5use super::runtime_types::RuntimeApi;
6
7use crate::{client::OnlineClientT, error::Error, Config};
8use derivative::Derivative;
9use std::{future::Future, marker::PhantomData};
10
11/// Execute runtime API calls.
12#[derive(Derivative)]
13#[derivative(Clone(bound = "Client: Clone"))]
14pub struct RuntimeApiClient<T, Client> {
15    client: Client,
16    _marker: PhantomData<T>,
17}
18
19impl<T, Client> RuntimeApiClient<T, Client> {
20    /// Create a new [`RuntimeApiClient`]
21    pub fn new(client: Client) -> Self {
22        Self {
23            client,
24            _marker: PhantomData,
25        }
26    }
27}
28
29impl<T, Client> RuntimeApiClient<T, Client>
30where
31    T: Config,
32    Client: OnlineClientT<T>,
33{
34    /// Obtain a runtime API interface at some block hash.
35    pub fn at(&self, block_hash: T::Hash) -> RuntimeApi<T, Client> {
36        RuntimeApi::new(self.client.clone(), block_hash)
37    }
38
39    /// Obtain a runtime API interface at the latest block hash.
40    pub fn at_latest(
41        &self,
42    ) -> impl Future<Output = Result<RuntimeApi<T, Client>, Error>> + Send + 'static {
43        // Clone and pass the client in like this so that we can explicitly
44        // return a Future that's Send + 'static, rather than tied to &self.
45        let client = self.client.clone();
46        async move {
47            // get the hash for the latest block and use that.
48            let block_hash = client
49                .rpc()
50                .block_hash(None)
51                .await?
52                .expect("didn't pass a block number; qed");
53
54            Ok(RuntimeApi::new(client, block_hash))
55        }
56    }
57}