Skip to main content

forest/rpc/
request.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use super::ApiPaths;
5use anyhow::Context as _;
6use enumflags2::BitFlags;
7use jsonrpsee::core::traits::ToRpcParams;
8use serde::{Deserialize, Serialize};
9use std::{marker::PhantomData, time::Duration};
10
11/// An at-rest description of a remote procedure call, created using
12/// [`rpc::RpcMethodExt`](crate::rpc::RpcMethodExt::request), and called using [`rpc::Client::call`](crate::rpc::Client::call).
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct Request<T = serde_json::Value> {
15    pub method_name: std::borrow::Cow<'static, str>,
16    pub params: serde_json::Value,
17    #[serde(skip)]
18    pub result_type: PhantomData<T>,
19    #[serde(skip)]
20    pub api_path: ApiPaths,
21    #[serde(skip)]
22    pub timeout: Duration,
23}
24
25impl<T> Request<T> {
26    pub fn set_timeout(&mut self, timeout: Duration) {
27        self.timeout = timeout;
28    }
29
30    pub fn with_timeout(mut self, timeout: Duration) -> Self {
31        self.set_timeout(timeout);
32        self
33    }
34
35    pub fn set_api_path(&mut self, api_path: ApiPaths) {
36        self.api_path = api_path;
37    }
38
39    pub fn with_api_path(mut self, api_path: ApiPaths) -> Self {
40        self.set_api_path(api_path);
41        self
42    }
43
44    /// Map type information about the response.
45    pub fn map_ty<U>(self) -> Request<U> {
46        Request {
47            method_name: self.method_name,
48            params: self.params,
49            result_type: PhantomData,
50            api_path: self.api_path,
51            timeout: self.timeout,
52        }
53    }
54
55    pub fn max_api_path(api_paths: BitFlags<ApiPaths>) -> anyhow::Result<ApiPaths> {
56        api_paths.iter().max().context("No supported versions")
57    }
58}
59
60impl<T> ToRpcParams for Request<T> {
61    fn to_rpc_params(self) -> Result<Option<Box<serde_json::value::RawValue>>, serde_json::Error> {
62        Ok(Some(serde_json::value::to_raw_value(&self.params)?))
63    }
64}