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_paths: BitFlags<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    /// Map type information about the response.
36    pub fn map_ty<U>(self) -> Request<U> {
37        Request {
38            method_name: self.method_name,
39            params: self.params,
40            result_type: PhantomData,
41            api_paths: self.api_paths,
42            timeout: self.timeout,
43        }
44    }
45
46    pub fn max_api_path(api_paths: BitFlags<ApiPaths>) -> anyhow::Result<ApiPaths> {
47        api_paths.iter().max().context("No supported versions")
48    }
49
50    pub fn api_path(&self) -> anyhow::Result<ApiPaths> {
51        Self::max_api_path(self.api_paths)
52    }
53}
54
55impl<T> ToRpcParams for Request<T> {
56    fn to_rpc_params(self) -> Result<Option<Box<serde_json::value::RawValue>>, serde_json::Error> {
57        Ok(Some(serde_json::value::to_raw_value(&self.params)?))
58    }
59}