near_client/
lib.rs

1#![doc = include_str!("../README.md")]
2#![warn(missing_docs)]
3
4/// API for the network requests to the RPC endpoint.
5pub mod client;
6#[doc(hidden)]
7pub mod components;
8pub mod crypto;
9#[doc(hidden)]
10pub mod near_primitives_light;
11pub(crate) mod rpc;
12#[doc(hidden)]
13pub mod utils;
14
15use std::fmt::Display;
16
17pub use near_primitives_core as core;
18pub use near_units;
19
20type Result<T> = std::result::Result<T, Error>;
21
22/// Parse's human-readable string into [Gas](core::types::Gas)
23///
24/// # Panic
25/// If can't correctly parse input into [Gas](core::types::Gas)
26pub fn gas(input: &str) -> core::types::Gas {
27    near_units::gas::parse(input).unwrap() as u64
28}
29
30/// Parse's human-readable string into [Balance](core::types::Balance)
31///
32/// # Panic
33/// If can't correctly parse input into [Balance](core::types::Balance)
34pub fn near(input: &str) -> core::types::Balance {
35    near_units::near::parse(input).unwrap()
36}
37
38/// Converts a Near token amount to a human-readable format.
39///
40/// ## Arguments
41///
42/// - `amount` - The amount of Near tokens to convert.
43///
44/// ## Returns
45///
46/// Returns a formatted string representing the Near token amount in a
47/// human-readable format. The format may include commas for thousands separators,
48/// a specific number of decimal places, and a symbol such as "N" to indicate the
49/// token type.
50///
51/// ## Example
52///
53/// ```rust
54/// use near_client::prelude::*;
55///
56/// let amount: u128 = 123456789000000000000000000000;
57/// let formatted_amount = near_to_human(amount);
58/// assert_eq!(formatted_amount, "123,456.789 N");
59/// ```
60pub fn near_to_human(amount: core::types::Balance) -> String {
61    near_units::near::to_human(amount)
62}
63
64/// Converts a gas amount to a human-readable format.
65///
66/// ## Arguments
67///
68/// - `gas` - The amount of gas to convert.
69///
70/// ## Returns
71///
72/// Returns a formatted string representing the gas amount in a
73/// human-readable format. The format may include commas for thousands separators
74/// and a unit such as "MGas" to indicate the gas type.
75///
76/// ## Example
77///
78/// ```rust
79/// use near_client::prelude::*;
80///
81/// let gas: u64 = 123456789;
82/// let formatted_gas = gas_to_human(gas);
83/// assert_eq!(formatted_gas, "123.456789 Mgas");
84/// ```
85pub fn gas_to_human(gas: core::types::Gas) -> String {
86    near_units::gas::to_human(gas as u128)
87}
88
89/// Client prelude.
90/// All the frequently used API
91pub mod prelude {
92    pub use super::client::*;
93    pub use super::components::*;
94    pub use super::core::{
95        account::{AccessKeyPermission, Account, FunctionCallPermission},
96        types::{AccountId, Balance, Gas, Nonce},
97    };
98    pub use super::crypto::prelude::*;
99    pub use super::near_primitives_light::{
100        errors::{self as transaction_errors},
101        types::Finality,
102    };
103    pub use super::{gas, gas_to_human, near, near_to_human};
104    pub use transaction_errors::*;
105}
106
107/// Describes errors that could be thrown during execution.
108/// Each error is self-described
109#[derive(Debug, thiserror::Error)]
110pub enum Error {
111    #[doc(hidden)]
112    #[error("Failed to create a signer, cause [\"{0}\"]")]
113    CreateSigner(crypto::Error),
114    #[doc(hidden)]
115    #[error("Transaction not started, logs: [\"{0:?}\"]")]
116    TxNotStarted(Box<Vec<String>>),
117    #[doc(hidden)]
118    #[error("Transaction failed during execution, cause [\"{0:?}\"], logs: [\"{1:?}\"]")]
119    TxExecution(prelude::TxExecutionError, Box<Vec<String>>),
120    #[doc(hidden)]
121    #[error("Transaction serialization error: [\"{0}\"]")]
122    TxSerialization(std::io::Error),
123    #[doc(hidden)]
124    #[error("Couldn't serialize an argument [\"{0}\"] to view a transaction, cause: [\"{1}\"]")]
125    SerializeTxViewArg(&'static str, serde_json::Error),
126    #[doc(hidden)]
127    #[error("Couldn't serialize arguments for view or function call, cause: [\"{0}\"]")]
128    ArgsSerialization(serde_json::Error),
129    #[doc(hidden)]
130    #[error("Client creation failed, cause: [\"{0}\"]")]
131    CreateClient(rpc::Error),
132    #[doc(hidden)]
133    #[error("Can't view a transaction, cause: [\"{0}\"]")]
134    ViewTransaction(rpc::Error),
135    #[doc(hidden)]
136    #[error("Failed to execute rpc call to Near blockchain, cause: [\"{0}\"]")]
137    RpcError(rpc::Error),
138    #[doc(hidden)]
139    #[error("Block call failed with an error: \"{0}\"")]
140    BlockCall(rpc::Error),
141    #[doc(hidden)]
142    #[error("View access key call failed with an error: \"{0}\"")]
143    ViewAccessKeyCall(ViewAccessKeyCall),
144    #[doc(hidden)]
145    #[error("View access key list call failed with an error: \"{0}\"")]
146    ViewAccessKeyListCall(ViewAccessKeyCall),
147    #[doc(hidden)]
148    #[error("View call failed with an error: \"{0}\"")]
149    ViewCall(rpc::Error),
150    #[doc(hidden)]
151    #[error("Couldn't deserialize a transaction function output, cause: [\"{0}\"]")]
152    DeserializeTransactionOutput(serde_json::Error),
153    #[doc(hidden)]
154    #[error("Couldn't deserialize a transaction outcome, cause: [\"{0}\"]")]
155    DeserializeExecutionOutcome(serde_json::Error),
156    #[doc(hidden)]
157    #[error("Couldn't deserialize a transaction id, cause: [\"{0}\"]")]
158    DeserializeTransactionId(serde_json::Error),
159    #[doc(hidden)]
160    #[error("Couldn't deserialize a view call result, cause [\"{0}\"]")]
161    DeserializeViewCall(serde_json::Error),
162    #[doc(hidden)]
163    #[error("Couldn't deserialize a view response, cause [\"{0}\"]")]
164    DeserializeResponseView(serde_json::Error),
165    #[doc(hidden)]
166    #[error("Couldn't deserialize a block, cause: [\"{0}\"]")]
167    DeserializeBlock(serde_json::Error),
168    #[doc(hidden)]
169    #[error("Can't deserialize an access key response, cause: [\"{0}\"]")]
170    DeserializeAccessKeyViewCall(serde_json::Error),
171    #[doc(hidden)]
172    #[error("Can't deserialize an access key response, cause: [\"{0}\"]")]
173    DeserializeAccessKeyListViewCall(serde_json::Error),
174}
175
176#[doc(hidden)]
177#[derive(Debug)]
178pub enum ViewAccessKeyCall {
179    Rpc(rpc::Error),
180    ParseError { error: String, logs: Vec<String> },
181}
182
183#[doc(hidden)]
184impl Display for ViewAccessKeyCall {
185    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186        match self {
187            Self::Rpc(err) => {
188                write!(f, "Rpc error: {err}")
189            }
190            Self::ParseError { error, logs } => write!(f, "Error during parsing: {error},")
191                .and(write!(f, "with logs: "))
192                .and(writeln!(
193                    f,
194                    "{}",
195                    logs.iter().fold(String::new(), |init, next| {
196                        init + format!("{next}\n").as_str()
197                    })
198                )),
199        }
200    }
201}