Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(rpc): add tonapi interface #588

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,108 changes: 742 additions & 366 deletions Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ base64 = { workspace = true }
bytes = { workspace = true }
everscale-types = { workspace = true }
futures-util = { workspace = true }
hex = { workspace = true }
metrics = { workspace = true }
moka = { workspace = true }
num-bigint = "0.4"
parking_lot = { workspace = true }
prost = { workspace = true }
serde = { workspace = true }
Expand All @@ -28,6 +30,7 @@ tokio = { workspace = true, features = ["rt"] }
tower = { workspace = true }
tower-http = { workspace = true, features = ["cors", "timeout"] }
tracing = { workspace = true }
tycho-vm = { workspace = true }

# local deps
tycho-block-util = { workspace = true }
Expand Down
73 changes: 73 additions & 0 deletions rpc/src/endpoint/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;

use crate::state::RpcStateError;

pub type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("an internal server error occurred: {0}")]
Anyhow(#[from] anyhow::Error),

#[error("serde error occurred")]
Serde(#[from] serde_json::Error),

#[error("ever types error occurred")]
Ever(#[from] everscale_types::error::Error),

#[error("rpc error occurred")]
Rpc(#[from] RpcStateError),

#[error("bad request: {0}")]
BadRequest(&'static str),

#[error("not found: {0}")]
NotFound(&'static str),
}

impl Error {
fn status_code(&self) -> StatusCode {
match self {
Self::Anyhow(_) | Self::Ever(_) | Self::Rpc(_) => StatusCode::INTERNAL_SERVER_ERROR,
Self::Serde(_) | Self::BadRequest(_) => StatusCode::BAD_REQUEST,
Self::NotFound(_) => StatusCode::NOT_FOUND,
}
}
}
/// Axum allows you to return `Result` from handler functions, but the error type
/// also must be some sort of response type.
///
/// By default, the generated `Display` impl is used to return a plaintext error message
/// to the client.
impl IntoResponse for Error {
fn into_response(self) -> Response {
match self {
Self::Anyhow(ref e) => {
tracing::error!("Generic error: {:?}", e);
}
Self::Serde(ref e) => {
tracing::error!("Failed to deserialize string {:?}", e);
}
Self::Ever(ref e) => {
tracing::error!("Internal error {:?}", e);
}
Self::Rpc(ref e) => {
tracing::error!("Internal error {:?}", e);
}
Self::BadRequest(ref e) => {
tracing::error!("Bad request: {:?}", e);
}
Self::NotFound(ref e) => {
tracing::error!("Not found: {:?}", e);
}
}

(
self.status_code(),
Json(serde_json::json!({"error": self.to_string(), "error_code": 0})),
)
.into_response()
}
}
6 changes: 6 additions & 0 deletions rpc/src/endpoint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,12 @@ pub use self::jrpc::JrpcEndpointCache;
pub use self::proto::ProtoEndpointCache;
use crate::state::RpcState;

mod error;
mod jrpc;
mod proto;
mod tonapi;
mod toncenter;
mod utils;

pub struct RpcEndpoint {
listener: TcpListener,
Expand Down Expand Up @@ -45,6 +49,8 @@ impl RpcEndpoint {
.route("/", post(common_route))
.route("/rpc", post(common_route))
.route("/proto", post(common_route))
.nest("/v2", tonapi::router())
.nest("/api/v2", toncenter::router())
.layer(service)
.with_state(self.state);

Expand Down
57 changes: 57 additions & 0 deletions rpc/src/endpoint/tonapi/accounts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use axum::extract::{Path, State};
use axum::routing::get;
use axum::Json;
use everscale_types::models::StdAddr;

use super::responses::{status_to_string, GetAccountResponse};
use crate::endpoint::error::{Error, Result};
use crate::state::LoadedAccountState;
use crate::RpcState;

pub fn router() -> axum::Router<RpcState> {
axum::Router::new().route("/accounts/:account", get(get_account))
}

async fn get_account(
Path(address): Path<StdAddr>,
State(state): State<RpcState>,
) -> Result<Json<GetAccountResponse>> {
let item = state.get_account_state(&address)?;

match &item {
&LoadedAccountState::NotFound { .. } => Err(Error::NotFound("account not found")),
LoadedAccountState::Found { state, .. } => {
let account = state.load_account()?;
match account {
Some(loaded) => {
Ok(Json(GetAccountResponse {
address: address.to_string(),
balance: loaded.balance.tokens.into_inner() as u64,
extra_balance: None, // TODO: fill with correct extra balance
status: status_to_string(loaded.state.status()),
currencies_balance: Some(
loaded
.balance
.other
.as_dict()
.iter()
.filter_map(|res| res.ok())
.map(|(id, balance)| (id, balance.as_usize() as u64))
.collect(),
),
last_activity: loaded.last_trans_lt,
interfaces: None, // TODO: fill with correct interfaces,
name: None, // TODO: fill with correct name,
is_scam: None, // TODO: fill with correct is_scam,
icon: None, // TODO: fill with correct icon,
memo_required: None, // TODO: fill with correct memo_required,
get_methods: vec![], // TODO: fill with correct get_methods,
is_suspended: None, // TODO: fill with correct is_suspended,
is_wallet: true, // TODO: fill with correct is_wallet,
}))
}
None => Err(Error::NotFound("account not found")),
}
}
}
}
Loading
Loading