erpc_sdk/near.rs
1//! Sealed, read-only NEAR JSON-RPC helpers.
2//!
3//! This module intentionally reuses [`crate::HttpJsonRpcTransport`] without a
4//! NEAR-specific response policy. Consequently it inherits the transport's
5//! compatibility behavior: response IDs are checked for the same numeric type
6//! and value as the request, a present `error` (including `null`) is decoded by
7//! the existing strict policy, and a valid non-null error takes precedence over
8//! a simultaneous result. The transport does not independently validate the
9//! response `jsonrpc` version. These are compatibility details of the shared
10//! transport, rather than a promise of full JSON-RPC envelope validation.
11//!
12//! The namespace exposes only typed status, block, and fixed `view_account`
13//! reads. It deliberately has no generic request/raw/batch/subscription or
14//! transaction surface.
15
16use std::{collections::HashMap, sync::Arc};
17
18use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error as DeError};
19use serde_json::Value;
20use url::Url;
21
22use crate::{
23 PendingRpcRequest, Result, RpcNamespace,
24 rpc::{BatchPolicy, HttpJsonRpcTransport},
25};
26
27/// NEAR JSON-RPC methods represented by this release.
28pub const NEAR_RPC_METHODS: &[&str] = &["block", "query", "status"];
29
30/// A named NEAR block finality selector.
31#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
32#[serde(rename_all = "lowercase")]
33pub enum NearFinality {
34 /// A finalized block.
35 Final,
36 /// The latest block observed by the node.
37 Optimistic,
38}
39
40/// A height or opaque hash identifying a NEAR block.
41#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
42#[serde(untagged)]
43pub enum NearBlockId {
44 /// A block height. The value remains an integer on the wire.
45 Height(u64),
46 /// A block hash. The value is passed through without local validation.
47 Hash(String),
48}
49
50/// One mutually exclusive selector for a NEAR block or account read.
51///
52/// An explicit block ID identifies the requested data; it does not imply that
53/// the block is finalized or that the provider retains archival history.
54#[derive(Clone, Debug, Eq, PartialEq)]
55pub enum NearBlockReference {
56 /// Select by the node's finality view.
57 Finality {
58 /// The finality mode requested from NEAR.
59 finality: NearFinality,
60 },
61 /// Select one explicit height or hash.
62 BlockId {
63 /// The explicit block identifier.
64 block_id: NearBlockId,
65 },
66}
67
68impl Serialize for NearBlockReference {
69 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
70 where
71 S: Serializer,
72 {
73 use serde::ser::SerializeMap;
74
75 let mut map = serializer.serialize_map(Some(1))?;
76 match self {
77 Self::Finality { finality } => map.serialize_entry("finality", finality)?,
78 Self::BlockId { block_id } => map.serialize_entry("block_id", block_id)?,
79 }
80 map.end()
81 }
82}
83
84impl<'de> Deserialize<'de> for NearBlockReference {
85 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
86 where
87 D: Deserializer<'de>,
88 {
89 #[derive(Deserialize)]
90 #[serde(deny_unknown_fields)]
91 struct WireReference {
92 finality: Option<NearFinality>,
93 block_id: Option<NearBlockId>,
94 }
95
96 let reference = WireReference::deserialize(deserializer)?;
97 match (reference.finality, reference.block_id) {
98 (Some(finality), None) => Ok(Self::Finality { finality }),
99 (None, Some(block_id)) => Ok(Self::BlockId { block_id }),
100 (Some(_), Some(_)) => Err(D::Error::custom(
101 "NEAR block reference cannot contain both finality and block_id",
102 )),
103 (None, None) => Err(D::Error::custom(
104 "NEAR block reference requires finality or block_id",
105 )),
106 }
107 }
108}
109
110/// NEAR node status.
111#[derive(Clone, Debug, Deserialize)]
112pub struct NearStatus {
113 /// Network identity, such as `mainnet`.
114 pub chain_id: String,
115 /// Genesis block hash.
116 pub genesis_hash: String,
117 /// Latest protocol version supported by the node.
118 pub latest_protocol_version: u64,
119 /// Current protocol version used by the node.
120 pub protocol_version: u64,
121 /// Synchronization state and latest observed block.
122 pub sync_info: NearSyncInfo,
123 /// Node software version.
124 pub version: NearNodeVersion,
125 /// Forward-compatible status fields.
126 #[serde(flatten)]
127 pub additional: HashMap<String, Value>,
128}
129
130/// NEAR node synchronization information.
131#[derive(Clone, Debug, Deserialize)]
132pub struct NearSyncInfo {
133 /// Latest observed block hash.
134 pub latest_block_hash: String,
135 /// Latest observed block height.
136 pub latest_block_height: u64,
137 /// Latest observed block timestamp as the raw RFC3339 timestamp string.
138 pub latest_block_time: String,
139 /// Latest observed state-root hash.
140 pub latest_state_root: String,
141 /// Whether the node is still synchronizing.
142 pub syncing: bool,
143 /// Forward-compatible synchronization fields.
144 #[serde(flatten)]
145 pub additional: HashMap<String, Value>,
146}
147
148/// NEAR node software version.
149#[derive(Clone, Debug, Deserialize)]
150pub struct NearNodeVersion {
151 /// Human-readable node version.
152 pub version: String,
153 /// Build identifier.
154 pub build: String,
155 /// Optional Rust compiler version reported by the node.
156 pub rustc_version: Option<String>,
157 /// Forward-compatible version fields.
158 #[serde(flatten)]
159 pub additional: HashMap<String, Value>,
160}
161
162/// A typed NEAR block response with a guarded chunk collection.
163#[derive(Clone, Debug, Deserialize)]
164pub struct NearBlockView {
165 /// Account that authored the block.
166 pub author: String,
167 /// Stable block header projection.
168 pub header: NearBlockHeader,
169 /// Chunk records retained as JSON for forward compatibility.
170 pub chunks: Vec<Value>,
171 /// Forward-compatible block fields.
172 #[serde(flatten)]
173 pub additional: HashMap<String, Value>,
174}
175
176/// Stable fields from a NEAR block header.
177#[derive(Clone, Debug, Deserialize)]
178pub struct NearBlockHeader {
179 /// Block hash.
180 pub hash: String,
181 /// Block height.
182 pub height: u64,
183 /// Parent block hash.
184 pub prev_hash: String,
185 /// Block timestamp in nanoseconds as a JSON integer.
186 pub timestamp: u64,
187 /// Exact nanosecond timestamp representation returned by NEAR.
188 pub timestamp_nanosec: String,
189 /// Exact gas-price decimal string.
190 pub gas_price: String,
191 /// Exact total-supply decimal string.
192 pub total_supply: String,
193 /// Forward-compatible header fields.
194 #[serde(flatten)]
195 pub additional: HashMap<String, Value>,
196}
197
198/// Typed account state returned by the fixed NEAR `view_account` query.
199#[derive(Clone, Debug, Deserialize)]
200pub struct NearAccountView {
201 /// Account balance in yoctoNEAR, preserved as an exact decimal string.
202 pub amount: String,
203 /// Locked balance in yoctoNEAR, preserved as an exact decimal string.
204 pub locked: String,
205 /// Contract code hash.
206 pub code_hash: String,
207 /// Account storage usage in bytes.
208 pub storage_usage: u64,
209 /// Optional storage payment height for uninitialized accounts.
210 pub storage_paid_at: Option<u64>,
211 /// Height of the block containing this account state.
212 pub block_height: u64,
213 /// Hash of the block containing this account state.
214 pub block_hash: String,
215 /// Optional account state marker.
216 pub state: Option<String>,
217 /// Optional bootstrap nonce.
218 pub bootstrap_nonce: Option<u64>,
219 /// Optional global-contract account ID.
220 pub global_contract_account_id: Option<String>,
221 /// Optional global-contract hash.
222 pub global_contract_hash: Option<String>,
223 /// Forward-compatible account fields.
224 #[serde(flatten)]
225 pub additional: HashMap<String, Value>,
226}
227
228/// NEAR service client.
229#[derive(Clone)]
230pub struct NearClient {
231 /// Sealed NEAR JSON-RPC namespace.
232 pub rpc: NearRpcClient,
233}
234
235impl NearClient {
236 pub(crate) fn new(transport: Arc<HttpJsonRpcTransport>) -> Self {
237 Self {
238 rpc: NearRpcClient::new(transport),
239 }
240 }
241}
242
243/// Read-only NEAR JSON-RPC namespace.
244///
245/// Only the three typed reads below are available. The private underlying
246/// [`RpcNamespace`] is intentionally not exposed and this type does not
247/// implement `Deref` or `AsRef`.
248///
249/// ```compile_fail
250/// # use erpc_sdk::{ErpcClient, ErpcClientConfig};
251/// # async fn forbidden() -> erpc_sdk::Result<()> {
252/// let rpc = ErpcClient::new(ErpcClientConfig::new("key"))?.near.rpc;
253/// let _ = rpc.raw::<serde_json::Value>("query", None);
254/// # Ok(())
255/// # }
256/// ```
257///
258/// ```compile_fail
259/// # use erpc_sdk::{ErpcClient, ErpcClientConfig};
260/// # async fn forbidden() -> erpc_sdk::Result<()> {
261/// let rpc = ErpcClient::new(ErpcClientConfig::new("key"))?.near.rpc;
262/// let _ = rpc.request::<serde_json::Value>("query", serde_json::Value::Null);
263/// # Ok(())
264/// # }
265/// ```
266///
267/// ```compile_fail
268/// # use erpc_sdk::{ErpcClient, ErpcClientConfig};
269/// # async fn forbidden() -> erpc_sdk::Result<()> {
270/// let rpc = ErpcClient::new(ErpcClientConfig::new("key"))?.near.rpc;
271/// let _ = rpc.batch(Vec::new());
272/// # Ok(())
273/// # }
274/// ```
275///
276/// ```compile_fail
277/// # use erpc_sdk::{ErpcClient, ErpcClientConfig};
278/// # async fn forbidden() -> erpc_sdk::Result<()> {
279/// let rpc = ErpcClient::new(ErpcClientConfig::new("key"))?.near.rpc;
280/// let _ = rpc.subscribe("heads", Vec::new());
281/// # Ok(())
282/// # }
283/// ```
284///
285/// ```compile_fail
286/// # use erpc_sdk::{ErpcClient, ErpcClientConfig};
287/// # async fn forbidden() -> erpc_sdk::Result<()> {
288/// let rpc = ErpcClient::new(ErpcClientConfig::new("key"))?.near.rpc;
289/// let _ = rpc.call_function("account", "method", Vec::<u8>::new());
290/// # Ok(())
291/// # }
292/// ```
293///
294/// ```compile_fail
295/// # use erpc_sdk::{ErpcClient, ErpcClientConfig};
296/// # async fn forbidden() -> erpc_sdk::Result<()> {
297/// let rpc = ErpcClient::new(ErpcClientConfig::new("key"))?.near.rpc;
298/// let _ = rpc.send_tx(Vec::<u8>::new());
299/// # Ok(())
300/// # }
301/// ```
302///
303/// ```compile_fail
304/// # use erpc_sdk::{ErpcClient, ErpcClientConfig};
305/// # async fn forbidden() -> erpc_sdk::Result<()> {
306/// let rpc = ErpcClient::new(ErpcClientConfig::new("key"))?.near.rpc;
307/// let _ = rpc.broadcast_tx_async(Vec::<u8>::new());
308/// # Ok(())
309/// # }
310/// ```
311///
312/// ```compile_fail
313/// # use erpc_sdk::{ErpcClient, ErpcClientConfig};
314/// # async fn forbidden() -> erpc_sdk::Result<()> {
315/// let rpc = ErpcClient::new(ErpcClientConfig::new("key"))?.near.rpc;
316/// let _ = rpc.broadcast_tx_commit(Vec::<u8>::new());
317/// # Ok(())
318/// # }
319/// ```
320#[derive(Clone)]
321pub struct NearRpcClient {
322 namespace: RpcNamespace,
323}
324
325impl NearRpcClient {
326 pub(crate) fn new(transport: Arc<HttpJsonRpcTransport>) -> Self {
327 Self {
328 namespace: RpcNamespace::new(transport, BatchPolicy::Unsupported),
329 }
330 }
331
332 /// Returns only the configured origin and `/`, with credentials and route
333 /// prefixes removed. Empty string denotes an unavailable namespace.
334 #[must_use]
335 pub fn endpoint(&self) -> String {
336 let endpoint = self.namespace.endpoint();
337 if endpoint.is_empty() {
338 return endpoint;
339 }
340 let Ok(mut url) = Url::parse(&endpoint) else {
341 return String::new();
342 };
343 url.set_path("/");
344 url.set_query(None);
345 url.set_fragment(None);
346 let _ = url.set_username("");
347 let _ = url.set_password(None);
348 url.to_string()
349 }
350
351 /// Creates a pending `status` read with exactly `params: []`.
352 ///
353 /// # Panics
354 ///
355 /// This method panics only if serializing the built-in empty parameter
356 /// array fails; serialization of `Vec<Value>` is infallible for this
357 /// value.
358 #[must_use]
359 pub fn status(&self) -> PendingRpcRequest<NearStatus> {
360 self.namespace
361 .request("status", Vec::<Value>::new())
362 .expect("empty parameters serialize")
363 }
364
365 /// Creates a pending `block` read for exactly one selector.
366 pub fn block(&self, reference: NearBlockReference) -> Result<PendingRpcRequest<NearBlockView>> {
367 self.namespace.request("block", reference)
368 }
369
370 /// Creates the fixed `view_account` query for an opaque account ID.
371 ///
372 /// # Panics
373 ///
374 /// This method panics only if the internal one-key block selector cannot
375 /// be serialized or does not serialize as an object. The selector type's
376 /// implementation guarantees both properties for its two variants.
377 pub fn view_account(
378 &self,
379 account_id: impl Into<String>,
380 reference: NearBlockReference,
381 ) -> Result<PendingRpcRequest<NearAccountView>> {
382 let selector = serde_json::to_value(reference)
383 .expect("NEAR block reference serialization is infallible");
384 let Some(selector) = selector.as_object() else {
385 unreachable!("NEAR block references serialize as one-key objects");
386 };
387 let mut params = serde_json::Map::with_capacity(3);
388 params.insert(
389 "request_type".to_owned(),
390 Value::String("view_account".to_owned()),
391 );
392 params.insert("account_id".to_owned(), Value::String(account_id.into()));
393 params.extend(selector.clone());
394 self.namespace.request("query", Value::Object(params))
395 }
396}