Skip to main content

typed_openrpc/
rpc_method.rs

1use schemars::{JsonSchema, Schema};
2use serde::{de::DeserializeOwned, Serialize};
3
4/// Represents a JSON-RPC method with typed params and result.
5pub trait RpcMethod {
6    /// JSON-RPC method name.
7    const NAME: &'static str;
8    /// Short summary for documentation.
9    const SUMMARY: &'static str;
10    /// Optional tags describing the method.
11    const TAGS: &'static [&'static str] = &[];
12    /// Optional deprecation message.
13    const DEPRECATED: Option<&'static str> = None;
14
15    /// JSON-serializable params type.
16    type Params: Serialize + DeserializeOwned + JsonSchema;
17    /// JSON-serializable result type.
18    type Result: Serialize + DeserializeOwned + JsonSchema;
19
20    /// Generate JSON Schema for parameters.
21    fn param_schema() -> Schema {
22        schemars::schema_for!(Self::Params)
23    }
24
25    /// Generate JSON Schema for result.
26    fn result_schema() -> Schema {
27        schemars::schema_for!(Self::Result)
28    }
29}
30
31/// Captures documentation for a JSON-RPC method.
32#[derive(Clone, Debug)]
33pub struct MethodDoc {
34    pub name: String,
35    pub summary: String,
36    pub tags: Vec<String>,
37    pub deprecation: Option<String>,
38    pub params_schema: Schema,
39    pub result_schema: Schema,
40}
41
42impl MethodDoc {
43    /// Build documentation from a `RpcMethod` implementation.
44    pub fn from<M: RpcMethod>() -> Self {
45        Self {
46            name: M::NAME.to_string(),
47            summary: M::SUMMARY.to_string(),
48            tags: M::TAGS.iter().map(|tag| tag.to_string()).collect(),
49            deprecation: M::DEPRECATED.map(|msg| msg.to_string()),
50            params_schema: M::param_schema(),
51            result_schema: M::result_schema(),
52        }
53    }
54}