Skip to content

Commit

Permalink
Add more error types.
Browse files Browse the repository at this point in the history
  • Loading branch information
saeed-zil committed Jun 26, 2024
1 parent 424555e commit 1b4474e
Show file tree
Hide file tree
Showing 6 changed files with 127 additions and 27 deletions.
35 changes: 28 additions & 7 deletions crates/sdk/libs/near/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,39 @@
use serde_json::Value;
use thiserror::Error;

use crate::jsonrpc::RpcError;

#[derive(Debug, Error)]
pub enum Error<R> {
#[error(transparent)]
JsonError(#[from] serde_json::Error),

#[error(transparent)]
IoError(#[from] std::io::Error),

#[error("Failed to fetch: {0}")]
FetchError(String),

#[error(transparent)]
ServerError(#[from] RpcError<R>),
#[error("Server error {0}")]
ServerError(RpcError<R>),
}

#[derive(Debug, serde::Deserialize, Clone, PartialEq)]
#[serde(tag = "name", content = "cause", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RpcErrorKind<R> {
RequestValidationError(RpcRequestValidationErrorKind),
HandlerError(R),
InternalError(Value),
}

#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq)]
#[serde(tag = "name", content = "info", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RpcRequestValidationErrorKind {
MethodNotFound { method_name: String },
ParseError { error_message: String },
}

#[derive(Debug, serde::Deserialize, Clone, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct RpcError<T> {
#[serde(flatten)]
pub error_struct: Option<RpcErrorKind<T>>,
pub code: i64,
pub message: String,
pub data: Option<Value>,
}
12 changes: 3 additions & 9 deletions crates/sdk/libs/near/src/jsonrpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use calimero_sdk::env;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use crate::error::RpcError;
use crate::{Error, RpcMethod};

pub struct Client {
Expand Down Expand Up @@ -36,13 +37,13 @@ impl Client {
jsonrpc: "2.0",
id: *self.id.borrow(),
method: method.method_name(),
params: method.params()?,
params: method.params(),
})?;

let response = unsafe { env::ext::fetch(&self.url, "POST", &headers, &body) }
.map_err(Error::FetchError)?;

serde_json::from_slice::<Response<M::Response, M::Error>>(&response)?
serde_json::from_slice::<Response<_, _>>(&response)?
.data
.map_err(Error::ServerError)
}
Expand All @@ -65,10 +66,3 @@ pub struct Response<T: DeserializeOwned, E: DeserializeOwned> {
#[serde(with = "calimero_primitives::common::ResultAlt", flatten)]
pub data: Result<T, RpcError<E>>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct RpcError<E> {
pub code: i32,
pub message: String,
pub data: Option<E>,
}
2 changes: 1 addition & 1 deletion crates/sdk/libs/near/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,5 @@ pub trait RpcMethod {
type Error: serde::de::DeserializeOwned;

fn method_name(&self) -> &str;
fn params(&self) -> Result<serde_json::Value, std::io::Error>;
fn params(&self) -> serde_json::Value;
}
66 changes: 62 additions & 4 deletions crates/sdk/libs/near/src/query.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use serde_json::json;

use crate::types::{BlockHash, BlockHeight, BlockId};
use crate::types::{AccountId, BlockHash, BlockHeight, BlockId, BlockReference, ShardId};
use crate::views::{
AccessKeyList, AccessKeyView, AccountView, CallResult, ContractCodeView, QueryRequest,
ViewStateResult,
Expand Down Expand Up @@ -35,13 +35,71 @@ pub enum QueryResponseKind {

impl RpcMethod for RpcQueryRequest {
type Response = RpcQueryResponse;
type Error = String;
type Error = RpcQueryError;

fn method_name(&self) -> &str {
"query"
}

fn params(&self) -> Result<serde_json::Value, std::io::Error> {
Ok(json!(self))
fn params(&self) -> serde_json::Value {
json!(self)
}
}

#[derive(thiserror::Error, Debug, serde::Serialize, serde::Deserialize)]
#[serde(tag = "name", content = "info", rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RpcQueryError {
#[error("There are no fully synchronized blocks on the node yet")]
NoSyncedBlocks,
#[error("The node does not track the shard ID {requested_shard_id}")]
UnavailableShard { requested_shard_id: ShardId },
#[error(
"The data for block #{block_height} is garbage collected on this node, use an archival node to fetch historical data"
)]
GarbageCollectedBlock {
block_height: BlockHeight,
block_hash: calimero_primitives::hash::Hash,
},
#[error("Block either has never been observed on the node or has been garbage collected: {block_reference:?}")]
UnknownBlock { block_reference: BlockReference },
#[error("Account ID {requested_account_id} is invalid")]
InvalidAccount {
requested_account_id: AccountId,
block_height: BlockHeight,
block_hash: calimero_primitives::hash::Hash,
},
#[error("account {requested_account_id} does not exist while viewing")]
UnknownAccount {
requested_account_id: AccountId,
block_height: BlockHeight,
block_hash: calimero_primitives::hash::Hash,
},
#[error(
"Contract code for contract ID #{contract_account_id} has never been observed on the node"
)]
NoContractCode {
contract_account_id: AccountId,
block_height: BlockHeight,
block_hash: calimero_primitives::hash::Hash,
},
#[error("State of contract {contract_account_id} is too large to be viewed")]
TooLargeContractState {
contract_account_id: AccountId,
block_height: BlockHeight,
block_hash: calimero_primitives::hash::Hash,
},
#[error("Access key for public key {public_key} has never been observed on the node")]
UnknownAccessKey {
public_key: String,
block_height: BlockHeight,
block_hash: calimero_primitives::hash::Hash,
},
#[error("Function call returned an error: {vm_error}")]
ContractExecutionError {
vm_error: String,
block_height: BlockHeight,
block_hash: calimero_primitives::hash::Hash,
},
#[error("The node reached its limits. Try again later. More details: {error_message}")]
InternalError { error_message: String },
}
33 changes: 30 additions & 3 deletions crates/sdk/libs/near/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ pub type AccountId = near_account_id::AccountId;
pub type StorageUsage = u64;
pub type Nonce = u64;
pub type Balance = u128;
pub type ShardId = u64;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
Expand All @@ -18,14 +19,40 @@ pub enum BlockId {
#[serde_as]
#[derive(serde::Deserialize, Clone, Debug)]
#[serde(transparent)]
pub struct StoreValue(#[serde_as(as = "Base64")] pub Vec<u8>);
pub struct StoreValue(#[serde_as(as = "Base64")] pub Box<[u8]>);

#[serde_as]
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
#[serde(transparent)]
pub struct StoreKey(#[serde_as(as = "Base64")] pub Vec<u8>);
pub struct StoreKey(#[serde_as(as = "Base64")] pub Box<[u8]>);

#[serde_as]
#[derive(serde::Serialize, Clone, Debug)]
#[serde(transparent)]
pub struct FunctionArgs(#[serde_as(as = "Base64")] Vec<u8>);
pub struct FunctionArgs(#[serde_as(as = "Base64")] Box<[u8]>);

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BlockReference {
BlockId(BlockId),
Finality(Finality),
SyncCheckpoint(SyncCheckpoint),
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SyncCheckpoint {
Genesis,
EarliestAvailable,
}

#[derive(serde::Serialize, serde::Deserialize, Default, Clone, Debug)]
pub enum Finality {
#[serde(rename = "optimistic")]
None,
#[serde(rename = "near-final")]
DoomSlug,
#[serde(rename = "final")]
#[default]
Final,
}
6 changes: 3 additions & 3 deletions crates/sdk/libs/near/src/views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ pub enum QueryRequest {
},
ViewAccessKey {
account_id: AccountId,
public_key: String,
public_key: Box<str>,
},
ViewAccessKeyList {
account_id: AccountId,
Expand Down Expand Up @@ -69,7 +69,7 @@ pub struct StateItem {
#[serde_as]
#[derive(serde::Deserialize, Debug, Clone)]
pub struct ViewStateResult {
pub values: Vec<StateItem>,
pub values: Box<[StateItem]>,
#[serde_as(as = "Vec<Base64>")]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub proof: Vec<Arc<[u8]>>,
Expand All @@ -95,7 +95,7 @@ pub enum AccessKeyPermissionView {

#[derive(serde::Deserialize, Debug, Clone)]
pub struct AccessKeyList {
pub keys: Vec<AccessKeyInfoView>,
pub keys: Box<[AccessKeyInfoView]>,
}

#[derive(serde::Deserialize, Debug, Clone)]
Expand Down

0 comments on commit 1b4474e

Please sign in to comment.