Skip to main content

near_api_types/
lib.rs

1use secp256k1::ThirtyTwoByteHash;
2use sha2::Digest;
3use std::fmt;
4
5pub mod account;
6pub mod contract;
7pub mod crypto;
8pub mod errors;
9pub mod ft;
10pub mod json;
11pub mod nft;
12pub mod reference;
13pub mod signable_message;
14pub mod stake;
15pub mod storage;
16pub mod tokens;
17pub mod transaction;
18pub mod utils;
19
20pub use near_abi as abi;
21pub use near_account_id::AccountId;
22pub use near_gas::NearGas;
23pub use near_openapi_types::{
24    AccountView, ContractCodeView, FunctionArgs, RpcBlockResponse,
25    RpcLightClientExecutionProofResponse, RpcReceiptResponse, RpcTransactionResponse,
26    RpcValidatorResponse, StoreKey, StoreValue, TxExecutionStatus, ViewStateResult,
27};
28pub use near_token::NearToken;
29pub use reference::{EpochReference, Reference};
30pub use storage::{StorageBalance, StorageBalanceInternal};
31
32pub use account::Account;
33pub use crypto::public_key::PublicKey;
34pub use crypto::secret_key::SecretKey;
35pub use crypto::signature::Signature;
36pub use transaction::actions::{AccessKey, AccessKeyPermission, Action};
37
38use crate::errors::DataConversionError;
39
40pub type BlockHeight = u64;
41pub type Nonce = u64;
42pub type StorageUsage = u64;
43
44/// A wrapper around a generic query result that includes the block height and block hash
45/// at which the query was executed
46#[derive(
47    Debug,
48    Clone,
49    serde::Serialize,
50    serde::Deserialize,
51    borsh::BorshDeserialize,
52    borsh::BorshSerialize,
53)]
54pub struct Data<T> {
55    /// The data returned by the query
56    pub data: T,
57    /// The block height at which the query was executed
58    pub block_height: BlockHeight,
59    /// The block hash at which the query was executed
60    pub block_hash: CryptoHash,
61}
62
63impl<T> Data<T> {
64    pub fn map<U>(self, f: impl FnOnce(T) -> U) -> Data<U> {
65        Data {
66            data: f(self.data),
67            block_height: self.block_height,
68            block_hash: self.block_hash,
69        }
70    }
71}
72
73/// A type that represents a hash of the data.
74///
75/// This type is copy of the [crate::CryptoHash]
76/// as part of the [decoupling initiative](https://github.com/near/near-api-rs/issues/5)
77#[derive(
78    Copy,
79    Clone,
80    Default,
81    Hash,
82    Eq,
83    PartialEq,
84    Ord,
85    PartialOrd,
86    borsh::BorshDeserialize,
87    borsh::BorshSerialize,
88)]
89pub struct CryptoHash(pub [u8; 32]);
90
91impl ThirtyTwoByteHash for CryptoHash {
92    fn into_32(self) -> [u8; 32] {
93        self.0
94    }
95}
96
97impl serde::Serialize for CryptoHash {
98    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
99    where
100        S: serde::Serializer,
101    {
102        serializer.serialize_str(&self.to_string())
103    }
104}
105
106impl<'de> serde::Deserialize<'de> for CryptoHash {
107    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
108    where
109        D: serde::Deserializer<'de>,
110    {
111        let s = String::deserialize(deserializer)?;
112        <Self as std::str::FromStr>::from_str(&s).map_err(serde::de::Error::custom)
113    }
114}
115
116impl CryptoHash {
117    pub fn hash(bytes: &[u8]) -> Self {
118        Self(sha2::Sha256::digest(bytes).into())
119    }
120}
121
122impl std::str::FromStr for CryptoHash {
123    type Err = DataConversionError;
124
125    fn from_str(s: &str) -> Result<Self, Self::Err> {
126        let bytes = bs58::decode(s).into_vec()?;
127        Self::try_from(bytes)
128    }
129}
130
131impl TryFrom<&[u8]> for CryptoHash {
132    type Error = DataConversionError;
133
134    fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
135        if bytes.len() != 32 {
136            return Err(DataConversionError::IncorrectLength(bytes.len()));
137        }
138        let mut buf = [0; 32];
139        buf.copy_from_slice(bytes);
140        Ok(Self(buf))
141    }
142}
143
144impl TryFrom<Vec<u8>> for CryptoHash {
145    type Error = DataConversionError;
146
147    fn try_from(v: Vec<u8>) -> Result<Self, Self::Error> {
148        <Self as TryFrom<&[u8]>>::try_from(v.as_ref())
149    }
150}
151
152impl From<near_openapi_types::CryptoHash> for CryptoHash {
153    fn from(value: near_openapi_types::CryptoHash) -> Self {
154        Self(value.0)
155    }
156}
157
158impl std::fmt::Debug for CryptoHash {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        write!(f, "{self}")
161    }
162}
163
164impl std::fmt::Display for CryptoHash {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        std::fmt::Display::fmt(&bs58::encode(self.0).into_string(), f)
167    }
168}
169
170impl From<CryptoHash> for near_openapi_types::CryptoHash {
171    fn from(hash: CryptoHash) -> Self {
172        Self(hash.0)
173    }
174}