near_fetch/
query.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
//! This module defines a bunch of internal types used solely for querying into RPC
//! methods to retrieve info about what's on the chain. Note that the types defined
//! are exposed as-is for users to reference in their own functions or structs as
//! needed. These types cannot be created outside of near_fetch.

use std::fmt::{Debug, Display};

use near_account_id::AccountId;
use near_crypto::PublicKey;
use near_jsonrpc_client::methods::query::RpcQueryResponse;
use near_jsonrpc_client::methods::{self, RpcMethod};
use near_jsonrpc_primitives::types::chunks::ChunkReference;
use near_jsonrpc_primitives::types::query::QueryResponseKind;
use near_primitives::borsh;
use near_primitives::hash::CryptoHash;
use near_primitives::types::{BlockHeight, BlockId, BlockReference, Finality, ShardId, StoreKey};
use near_primitives::views::{
    AccessKeyList, AccessKeyView, AccountView, BlockView, CallResult, ChunkView, QueryRequest,
    ViewStateResult,
};
use near_token::NearToken;

use crate::ops::Function;
use crate::{Client, Error, Result};

/// Intenral type used to represent a boxed future.
pub(crate) type BoxFuture<'a, T> =
    std::pin::Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;

/// `Query` object allows creating queries into the network of our choice. This object is
/// usually given from making calls from other functions such as [`view_state`].
///
/// [`view_state`]: Client::view_state
pub struct Query<'a, T> {
    pub(crate) method: T,
    pub(crate) client: &'a Client,
    pub(crate) block_ref: Option<BlockReference>,
}

impl<'a, T> Query<'a, T> {
    pub(crate) fn new(client: &'a Client, method: T) -> Self {
        Self {
            method,
            client,
            block_ref: None,
        }
    }

    /// Specify at which block height to query from. Note that only archival
    /// networks will have the full history while networks like mainnet or testnet will
    /// only have the history from 5 or less epochs ago.
    pub fn block_height(mut self, height: BlockHeight) -> Self {
        self.block_ref = Some(BlockId::Height(height).into());
        self
    }

    /// Specify at which block hash to query from. Note that only archival
    /// networks will have the full history while networks like mainnet or testnet will
    /// only have the history from 5 or less epochs ago.
    pub fn block_hash(mut self, hash: CryptoHash) -> Self {
        self.block_ref = Some(BlockId::Hash(near_primitives::hash::CryptoHash(hash.0)).into());
        self
    }
}

// Constrained to RpcQueryRequest, since methods like GasPrice only take block_id but not Finality.
impl<'a, T> Query<'a, T>
where
    T: ProcessQuery<Method = methods::query::RpcQueryRequest>,
{
    /// Specify at which block [`Finality`] to query from.
    pub fn finality(mut self, value: Finality) -> Self {
        self.block_ref = Some(value.into());
        self
    }
}

impl<'a, T, R> std::future::IntoFuture for Query<'a, T>
where
    T: ProcessQuery<Output = R> + Send + Sync + 'static,
    <T as ProcessQuery>::Method: RpcMethod + Debug + Send + Sync,
    <<T as ProcessQuery>::Method as RpcMethod>::Response: Debug + Send + Sync,
    <<T as ProcessQuery>::Method as RpcMethod>::Error: Debug + Display + Send + Sync,
{
    type Output = Result<R>;

    // TODO: boxed future required due to impl Trait as type alias being unstable. So once
    // https://github.com/rust-lang/rust/issues/63063 is resolved, we can move to that instead.
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let block_reference = self.block_ref.unwrap_or_else(BlockReference::latest);
            let resp = self
                .client
                .send_query(&self.method.into_request(block_reference)?)
                .await
                .map_err(|err| Error::Rpc(err.into()))?;

            T::from_response(resp)
        })
    }
}

// Note: this trait is exposed publicly due to constraining with the impl offering `finality`.
/// Trait used as a high level APIs for consistent usages of block reference. Mostly used
/// internally to facilitate syntax sugar for performing RPC requests with async builders.
pub trait ProcessQuery {
    // TODO: associated default type is unstable. So for now, will require writing
    // the manual impls for query_request
    /// Method for doing the internal RPC request to the network of our choosing.
    type Method: RpcMethod;

    /// Expected output after performing a query.
    type Output;

    /// Convert into the Request object that is required to perform the RPC request.
    fn into_request(self, block_ref: BlockReference) -> Result<Self::Method>;

    /// Convert the response from the RPC request to a type of our choosing.
    fn from_response(resp: <Self::Method as RpcMethod>::Response) -> Result<Self::Output>;
}

pub struct ViewFunction {
    pub(crate) account_id: AccountId,
    pub(crate) function: Function,
}

pub struct ViewCode {
    pub(crate) account_id: AccountId,
}

pub struct ViewAccount {
    pub(crate) account_id: AccountId,
}

pub struct ViewBlock;

pub struct ViewState {
    account_id: AccountId,
    prefix: Option<Vec<u8>>,
}

pub struct ViewAccessKey {
    pub(crate) account_id: AccountId,
    pub(crate) public_key: PublicKey,
}

pub struct ViewAccessKeyList {
    pub(crate) account_id: AccountId,
}

pub struct GasPrice;

impl ProcessQuery for ViewFunction {
    type Method = methods::query::RpcQueryRequest;
    type Output = ViewResult;

    fn into_request(self, block_reference: BlockReference) -> Result<Self::Method> {
        Ok(Self::Method {
            block_reference,
            request: QueryRequest::CallFunction {
                account_id: self.account_id,
                method_name: self.function.name,
                args: self.function.args?.into(),
            },
        })
    }

    fn from_response(resp: RpcQueryResponse) -> Result<Self::Output> {
        match resp.kind {
            QueryResponseKind::CallResult(result) => Ok(result.into()),
            _ => Err(Error::RpcReturnedInvalidData(
                "while querying account".into(),
            )),
        }
    }
}

// Specific builder methods attached to a ViewFunction.
impl Query<'_, ViewFunction> {
    /// Provide the arguments for the call. These args are serialized bytes from either
    /// a JSON or Borsh serializable set of arguments. To use the more specific versions
    /// with better quality of life, use `args_json` or `args_borsh`.
    pub fn args(mut self, args: Vec<u8>) -> Self {
        self.method.function = self.method.function.args(args);
        self
    }

    /// Similar to `args`, specify an argument that is JSON serializable and can be
    /// accepted by the equivalent contract. Recommend to use something like
    /// `serde_json::json!` macro to easily serialize the arguments.
    pub fn args_json<U: serde::Serialize>(mut self, args: U) -> Self {
        self.method.function = self.method.function.args_json(args);
        self
    }

    /// Similar to `args`, specify an argument that is borsh serializable and can be
    /// accepted by the equivalent contract.
    pub fn args_borsh<U: borsh::BorshSerialize>(mut self, args: U) -> Self {
        self.method.function = self.method.function.args_borsh(args);
        self
    }
}

impl ProcessQuery for ViewCode {
    type Method = methods::query::RpcQueryRequest;
    type Output = Vec<u8>;

    fn into_request(self, block_reference: BlockReference) -> Result<Self::Method> {
        Ok(Self::Method {
            block_reference,
            request: QueryRequest::ViewCode {
                account_id: self.account_id,
            },
        })
    }

    fn from_response(resp: RpcQueryResponse) -> Result<Self::Output> {
        match resp.kind {
            QueryResponseKind::ViewCode(contract) => Ok(contract.code),
            _ => Err(Error::RpcReturnedInvalidData("while querying code".into())),
        }
    }
}

impl ProcessQuery for ViewAccount {
    type Method = methods::query::RpcQueryRequest;
    type Output = AccountView;

    fn into_request(self, block_reference: BlockReference) -> Result<Self::Method> {
        Ok(Self::Method {
            block_reference,
            request: QueryRequest::ViewAccount {
                account_id: self.account_id,
            },
        })
    }

    fn from_response(resp: RpcQueryResponse) -> Result<Self::Output> {
        match resp.kind {
            QueryResponseKind::ViewAccount(account) => Ok(account),
            _ => Err(Error::RpcReturnedInvalidData(
                "while querying account".into(),
            )),
        }
    }
}

impl ProcessQuery for ViewBlock {
    type Method = methods::block::RpcBlockRequest;
    type Output = BlockView;

    fn into_request(self, block_reference: BlockReference) -> Result<Self::Method> {
        Ok(Self::Method { block_reference })
    }

    fn from_response(view: BlockView) -> Result<Self::Output> {
        Ok(view)
    }
}

impl ProcessQuery for ViewState {
    type Method = methods::query::RpcQueryRequest;
    type Output = ViewStateResult;

    fn into_request(self, block_reference: BlockReference) -> Result<Self::Method> {
        Ok(Self::Method {
            block_reference,
            request: QueryRequest::ViewState {
                account_id: self.account_id,
                prefix: StoreKey::from(self.prefix.map(Vec::from).unwrap_or_default()),
                include_proof: false,
            },
        })
    }

    fn from_response(resp: <Self::Method as RpcMethod>::Response) -> Result<Self::Output> {
        match resp.kind {
            QueryResponseKind::ViewState(state) => Ok(state),
            _ => Err(Error::RpcReturnedInvalidData("while querying state".into())),
        }
    }
}

impl<'a> Query<'a, ViewState> {
    pub(crate) fn view_state(client: &'a Client, id: &AccountId) -> Self {
        Self::new(
            client,
            ViewState {
                account_id: id.clone(),
                prefix: None,
            },
        )
    }

    /// Set the prefix for viewing the state.
    pub fn prefix(mut self, value: &[u8]) -> Self {
        self.method.prefix = Some(value.into());
        self
    }
}

impl ProcessQuery for ViewAccessKey {
    type Method = methods::query::RpcQueryRequest;
    type Output = AccessKeyView;

    fn into_request(self, block_reference: BlockReference) -> Result<Self::Method> {
        Ok(Self::Method {
            block_reference,
            request: QueryRequest::ViewAccessKey {
                account_id: self.account_id,
                public_key: self.public_key,
            },
        })
    }

    fn from_response(resp: <Self::Method as RpcMethod>::Response) -> Result<Self::Output> {
        match resp.kind {
            QueryResponseKind::AccessKey(key) => Ok(key),
            _ => Err(Error::RpcReturnedInvalidData(
                "while querying access key".into(),
            )),
        }
    }
}

impl ProcessQuery for ViewAccessKeyList {
    type Method = methods::query::RpcQueryRequest;
    type Output = AccessKeyList;

    fn into_request(self, block_reference: BlockReference) -> Result<Self::Method> {
        Ok(Self::Method {
            block_reference,
            request: QueryRequest::ViewAccessKeyList {
                account_id: self.account_id,
            },
        })
    }

    fn from_response(resp: <Self::Method as RpcMethod>::Response) -> Result<Self::Output> {
        match resp.kind {
            QueryResponseKind::AccessKeyList(keylist) => Ok(keylist),
            _ => Err(Error::RpcReturnedInvalidData(
                "while querying access keys".into(),
            )),
        }
    }
}

impl ProcessQuery for GasPrice {
    type Method = methods::gas_price::RpcGasPriceRequest;
    type Output = NearToken;

    fn into_request(self, block_ref: BlockReference) -> Result<Self::Method> {
        let block_id = match block_ref {
            // User provided input via `block_hash` or `block_height` functions.
            BlockReference::BlockId(block_id) => Some(block_id),
            // default case, set by `Query` struct via BlockReference::latest.
            BlockReference::Finality(_finality) => None,
            // Should not be reachable, unless code got changed.
            BlockReference::SyncCheckpoint(point) => {
                return Err(Error::RpcReturnedInvalidData(format!(
                    "Cannot supply sync checkpoint to gas price: {point:?}. Potential API bug?"
                )))
            }
        };

        Ok(Self::Method { block_id })
    }

    fn from_response(resp: <Self::Method as RpcMethod>::Response) -> Result<Self::Output> {
        Ok(NearToken::from_yoctonear(resp.gas_price))
    }
}

/// Query object used to query for chunk related details at a specific `ChunkReference` which
/// consists of either a chunk [`CryptoHash`], or a `BlockShardId` (which consists of [`ShardId`]
/// and either block [`CryptoHash`] or [`BlockHeight`]).
///
/// The default behavior where a `ChunkReference` is not supplied will use a `BlockShardId`
/// referencing the latest block `CryptoHash` with `ShardId` of 0.
pub struct QueryChunk<'a> {
    client: &'a Client,
    chunk_ref: Option<ChunkReference>,
}

impl<'a> QueryChunk<'a> {
    pub(crate) fn new(client: &'a Client) -> Self {
        Self {
            client,
            chunk_ref: None,
        }
    }

    /// Specify at which block hash and shard id to query the chunk from. Note that only
    /// archival networks will have the full history while networks like mainnet or testnet
    /// will only have the history from 5 or less epochs ago.
    pub fn block_hash_and_shard(mut self, hash: CryptoHash, shard_id: ShardId) -> Self {
        self.chunk_ref = Some(ChunkReference::BlockShardId {
            block_id: BlockId::Hash(near_primitives::hash::CryptoHash(hash.0)),
            shard_id,
        });
        self
    }

    /// Specify at which block height and shard id to query the chunk from. Note that only
    /// archival networks will have the full history while networks like mainnet or testnet
    /// will only have the history from 5 or less epochs ago.
    pub fn block_height_and_shard(mut self, height: BlockHeight, shard_id: ShardId) -> Self {
        self.chunk_ref = Some(ChunkReference::BlockShardId {
            block_id: BlockId::Height(height),
            shard_id,
        });
        self
    }

    /// Specify at which chunk hash to query the chunk from.
    pub fn chunk_hash(mut self, hash: CryptoHash) -> Self {
        self.chunk_ref = Some(ChunkReference::ChunkHash {
            chunk_id: near_primitives::hash::CryptoHash(hash.0),
        });
        self
    }
}

impl<'a> std::future::IntoFuture for QueryChunk<'a> {
    type Output = Result<ChunkView>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let chunk_reference = if let Some(chunk_ref) = self.chunk_ref {
                chunk_ref
            } else {
                // Use the latest block hash in the case the user doesn't supply the ChunkReference. Note that
                // shard_id 0 is used in the default case.
                let block_view = self.client.view_block().await?;
                ChunkReference::BlockShardId {
                    block_id: BlockId::Hash(block_view.header.hash),
                    shard_id: 0,
                }
            };

            let chunk_view = self
                .client
                .send_query(&methods::chunk::RpcChunkRequest { chunk_reference })
                .await?;

            Ok(chunk_view)
        })
    }
}

/// The result from a call into a View function. This contains the contents or
/// the results from the view function call itself. The consumer of this object
/// can choose how to deserialize its contents.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ViewResult {
    /// Our result from our call into a view function.
    pub result: Vec<u8>,
    /// Logs generated from the view function.
    pub logs: Vec<String>,
}

impl ViewResult {
    /// Deserialize an instance of type `T` from bytes of JSON text sourced from the
    /// execution result of this call. This conversion can fail if the structure of
    /// the internal state does not meet up with [`serde::de::DeserializeOwned`]'s
    /// requirements.
    pub fn json<T: serde::de::DeserializeOwned>(&self) -> Result<T> {
        Ok(serde_json::from_slice(&self.result)?)
    }

    /// Deserialize an instance of type `T` from bytes sourced from this view call's
    /// result. This conversion can fail if the structure of the internal state does
    /// not meet up with [`borsh::BorshDeserialize`]'s requirements.
    pub fn borsh<T: borsh::BorshDeserialize>(&self) -> Result<T> {
        Ok(borsh::BorshDeserialize::try_from_slice(&self.result)?)
    }
}

impl From<CallResult> for ViewResult {
    fn from(result: CallResult) -> Self {
        Self {
            result: result.result,
            logs: result.logs,
        }
    }
}

impl Client {
    /// Call into a contract's view function. Returns a [`Query`] which allows us
    /// to specify further details like the arguments of the view call, or at what
    /// point in the chain we want to view.
    pub fn view(&self, contract_id: &AccountId, function: &str) -> Query<'_, ViewFunction> {
        Query::new(
            self,
            ViewFunction {
                account_id: contract_id.clone(),
                function: Function::new(function),
            },
        )
    }

    /// View the WASM code bytes of a contract on the network.
    pub fn view_code(&self, contract_id: &AccountId) -> Query<'_, ViewCode> {
        Query::new(
            self,
            ViewCode {
                account_id: contract_id.clone(),
            },
        )
    }

    /// View the state of a account/contract on the network. This will return the internal
    /// state of the account in the form of a map of key-value pairs; where STATE contains
    /// info on a contract's internal data.
    pub fn view_state(&self, contract_id: &AccountId) -> Query<'_, ViewState> {
        Query::view_state(self, contract_id)
    }

    /// View the block from the network. Supply additional parameters such as [`block_height`]
    /// or [`block_hash`] to get the block.
    ///
    /// [`block_height`]: Query::block_height
    /// [`block_hash`]: Query::block_hash
    pub fn view_block(&self) -> Query<'_, ViewBlock> {
        Query::new(self, ViewBlock)
    }

    /// View the chunk from the network once awaited. Supply additional parameters such as
    /// [`block_hash_and_shard`], [`block_height_and_shard`] or [`chunk_hash`] to get the
    /// chunk at a specific reference point. If none of those are supplied, the default
    /// reference point will be used, which will be the latest block_hash with a shard_id
    /// of 0.
    ///
    /// [`block_hash_and_shard`]: QueryChunk::block_hash_and_shard
    /// [`block_height_and_shard`]: QueryChunk::block_height_and_shard
    /// [`chunk_hash`]: QueryChunk::chunk_hash
    pub fn view_chunk(&self) -> QueryChunk<'_> {
        QueryChunk::new(self)
    }

    /// Views the [`AccessKey`] of the account specified by [`AccountId`] associated with
    /// the [`PublicKey`]
    ///
    /// [`AccessKey`]: crate::types::AccessKey
    pub fn view_access_key(&self, id: &AccountId, pk: &PublicKey) -> Query<'_, ViewAccessKey> {
        Query::new(
            self,
            ViewAccessKey {
                account_id: id.clone(),
                public_key: pk.clone(),
            },
        )
    }

    /// Views all the [`AccessKey`]s of the account specified by [`AccountId`]. This will
    /// return a list of [`AccessKey`]s along with the associated [`PublicKey`].
    ///
    /// [`AccessKey`]: crate::types::AccessKey
    pub fn view_access_keys(&self, id: &AccountId) -> Query<'_, ViewAccessKeyList> {
        Query::new(
            self,
            ViewAccessKeyList {
                account_id: id.clone(),
            },
        )
    }

    /// View account details of a specific account on the network.
    pub fn view_account(&self, account_id: &AccountId) -> Query<'_, ViewAccount> {
        Query::new(
            self,
            ViewAccount {
                account_id: account_id.clone(),
            },
        )
    }

    /// Fetches the latest gas price on the network.
    pub fn gas_price(&self) -> Query<'_, GasPrice> {
        Query::new(self, GasPrice)
    }
}