Skip to content

Commit

Permalink
Merge pull request #6 from telosnetwork/fix_clippy
Browse files Browse the repository at this point in the history
Fix clippy and rustfmt CI checks
  • Loading branch information
poplexity authored Jan 3, 2024
2 parents 9e874a8 + fabad89 commit 16e7f36
Show file tree
Hide file tree
Showing 44 changed files with 2,294 additions and 2,023 deletions.
19 changes: 12 additions & 7 deletions crates/antelope/src/api/client.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
use std::fmt::{Display, Formatter};
use crate::api::default_provider::DefaultProvider;
use crate::api::v1::chain::ChainAPI;
use std::fmt::{Display, Formatter};

pub enum HTTPMethod {
GET, POST
GET,
POST,
}

impl Display for HTTPMethod {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
HTTPMethod::GET => { write!(f, "GET") }
HTTPMethod::POST => { write!(f, "POST") }
HTTPMethod::GET => {
write!(f, "GET")
}
HTTPMethod::POST => {
write!(f, "POST")
}
}
}
}
Expand All @@ -22,7 +27,7 @@ pub trait Provider {
}

pub struct APIClient {
pub v1_chain: ChainAPI
pub v1_chain: ChainAPI,
}

impl APIClient {
Expand All @@ -33,7 +38,7 @@ impl APIClient {

pub fn custom_provider(provider: Box<dyn Provider>) -> Result<Self, String> {
Ok(APIClient {
v1_chain: ChainAPI::new(provider)
v1_chain: ChainAPI::new(provider),
})
}
}
}
12 changes: 5 additions & 7 deletions crates/antelope/src/api/default_provider.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::api::client::Provider;
use reqwest::blocking::Client;
use crate::api::client::{Provider};

pub struct DefaultProvider {
base_url: String,
client: Client
client: Client,
}

impl DefaultProvider {
Expand All @@ -18,18 +18,16 @@ impl DefaultProvider {
return Err(err_message);
}

let url = base_url.trim_end_matches("/");
let url = base_url.trim_end_matches('/');

Ok(Self {
base_url: String::from(url),
client: client.unwrap()
client: client.unwrap(),
})
}

}

impl Provider for DefaultProvider {

fn get(&self, path: String) -> Result<String, String> {
let res = self.client.get(self.base_url.to_string() + &path).send();
if res.is_err() {
Expand All @@ -51,4 +49,4 @@ impl Provider for DefaultProvider {

Ok(res.unwrap().text().unwrap())
}
}
}
2 changes: 1 addition & 1 deletion crates/antelope/src/api/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub mod v1;
pub mod client;
mod default_provider;
pub mod v1;
59 changes: 40 additions & 19 deletions crates/antelope/src/api/v1/chain.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
use serde_json::Value;
use crate::api::client::{Provider};
use crate::api::client::Provider;
use crate::api::v1::structs::{
ClientError, GetInfoResponse, ProcessedTransaction, ProcessedTransactionReceipt,
SendTransactionResponse, SendTransactionResponseError,
};
use crate::chain::block_id::BlockId;
use crate::api::v1::structs::{ClientError, GetInfoResponse, ProcessedTransaction, ProcessedTransactionReceipt, SendTransactionError, SendTransactionResponse};
use crate::chain::checksum::Checksum256;
use crate::chain::time::TimePoint;
use crate::chain::name::Name;
use crate::chain::time::TimePoint;
use crate::chain::transaction::{CompressionType, PackedTransaction, SignedTransaction};
use crate::name;
use crate::serializer::formatter::{JSONObject};
use crate::serializer::formatter::JSONObject;
use serde_json::Value;

pub struct ChainAPI {
provider: Box<dyn Provider>
provider: Box<dyn Provider>,
}

impl ChainAPI {

pub fn new(provider: Box<dyn Provider>) -> Self {
ChainAPI {
provider
}
ChainAPI { provider }
}

pub fn get_info(&self) -> Result<GetInfoResponse, ClientError<()>> {
Expand All @@ -33,8 +33,12 @@ impl ChainAPI {
chain_id: Checksum256::from_hex(obj.get_string("chain_id")?.as_str())?,
head_block_num: obj.get_u32("head_block_num")?,
last_irreversible_block_num: obj.get_u32("last_irreversible_block_num")?,
last_irreversible_block_id: BlockId { bytes: obj.get_hex_bytes("last_irreversible_block_id")? },
head_block_id: BlockId { bytes: obj.get_hex_bytes("head_block_id")? },
last_irreversible_block_id: BlockId {
bytes: obj.get_hex_bytes("last_irreversible_block_id")?,
},
head_block_id: BlockId {
bytes: obj.get_hex_bytes("head_block_id")?,
},
head_block_time: TimePoint::from_timestamp(obj.get_str("head_block_time")?)?,
head_block_producer: name!(obj.get_str("head_block_producer")?),
virtual_block_cpu_limit: obj.get_u64("virtual_block_cpu_limit")?,
Expand All @@ -43,22 +47,39 @@ impl ChainAPI {
block_net_limit: obj.get_u64("block_net_limit")?,
server_version_string: obj.get_string("server_version_string").ok(),
fork_db_head_block_num: obj.get_u32("fork_db_head_block_num").ok(),
fork_db_head_block_id: BlockId::from_bytes(&obj.get_hex_bytes("fork_db_head_block_id")?).ok()
fork_db_head_block_id: BlockId::from_bytes(
&obj.get_hex_bytes("fork_db_head_block_id")?,
)
.ok(),
})
}

pub fn send_transaction(&self, trx: SignedTransaction) -> Result<SendTransactionResponse, ClientError<SendTransactionError>> {
pub fn send_transaction(
&self,
trx: SignedTransaction,
) -> Result<SendTransactionResponse, ClientError<SendTransactionResponseError>> {
let packed_result = PackedTransaction::from_signed(trx, CompressionType::ZLIB);
if packed_result.is_err() {
return Err(ClientError::server(SendTransactionError {
message: String::from("Failed to pack transaction"),
}));
return Err(ClientError::encoding("Failed to pack transaction".into()));
}
let packed = packed_result.unwrap();
let trx_json = packed.to_json();
let result = self.provider.post(String::from("/v1/chain/send_transaction"), Some(trx_json));
let result = self
.provider
.post(String::from("/v1/chain/send_transaction"), Some(trx_json));
let json: Value = serde_json::from_str(result.unwrap().as_str()).unwrap();
let response_obj = JSONObject::new(json);
if response_obj.has("code") {
let error_value = response_obj.get_value("error").unwrap();
let error_json = error_value.to_string();
let error_obj = JSONObject::new(error_value);
return Err(ClientError::server(SendTransactionResponseError {
code: error_obj.get_u32("code")?,
name: error_obj.get_string("name")?,
message: error_json,
stack: vec![],
}));
}
let processed_obj = JSONObject::new(response_obj.get_value("processed").unwrap());
let receipt_obj = JSONObject::new(processed_obj.get_value("receipt").unwrap());

Expand All @@ -77,7 +98,7 @@ impl ChainAPI {
except: None,
net_usage: processed_obj.get_u32("net_usage")?,
scheduled: false,
action_traces: "".to_string(), // TODO: Properly encode this
action_traces: "".to_string(), // TODO: Properly encode this
account_ram_delta: "".to_string(), // TODO: Properly encode this
},
})
Expand Down
2 changes: 1 addition & 1 deletion crates/antelope/src/api/v1/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pub mod chain;
pub mod structs;
pub mod chain;
60 changes: 24 additions & 36 deletions crates/antelope/src/api/v1/structs.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
use crate::chain::{
block_id::BlockId,
checksum::Checksum256,
name::Name,
time::{TimePoint, TimePointSec},
block_id::BlockId,
transaction::TransactionHeader,
varint::VarUint32,
};

#[derive(Debug)]
pub enum ClientError<T> {
SIMPLE(SimpleError),
SERVER(T),
SERVER(ServerError<T>),
HTTP(HTTPError),
ENCODING(EncodingError)
ENCODING(EncodingError),
}

impl<T> ClientError<T> {
Expand All @@ -24,8 +24,8 @@ impl<T> ClientError<T> {
ClientError::ENCODING(EncodingError { message })
}

pub fn server(server_error: T) -> Self {
ClientError::SERVER(server_error)
pub fn server(error: T) -> Self {
ClientError::SERVER(ServerError { error })
}
}

Expand All @@ -43,23 +43,23 @@ impl<T> From<String> for ClientError<T> {

#[derive(Debug)]
pub struct SimpleError {
pub message: String
pub message: String,
}

#[derive(Debug)]
pub struct ServerError<T> {
error: T
pub error: T,
}

#[derive(Debug)]
pub struct HTTPError {
pub code: u16,
pub message: String
pub message: String,
}

#[derive(Debug)]
pub struct EncodingError {
pub message: String
pub message: String,
}

impl EncodingError {
Expand Down Expand Up @@ -97,14 +97,14 @@ pub struct GetInfoResponse {
pub block_net_limit: u64,
pub server_version_string: Option<String>,
pub fork_db_head_block_num: Option<u32>,
pub fork_db_head_block_id: Option<BlockId>
pub fork_db_head_block_id: Option<BlockId>,
}

impl GetInfoResponse {
pub fn get_transaction_header(&self, seconds_ahead: u32) -> TransactionHeader {
let expiration = TimePointSec {
// head_block_time.elapsed is microseconds, convert to seconds
seconds: (self.head_block_time.elapsed / 1000 / 1000) as u32 + seconds_ahead
seconds: (self.head_block_time.elapsed / 1000 / 1000) as u32 + seconds_ahead,
};
let id = self.last_irreversible_block_id.bytes.to_vec();
let prefix_array = &id[8..12];
Expand All @@ -115,15 +115,15 @@ impl GetInfoResponse {
delay_sec: VarUint32::default(),
expiration,
ref_block_num: (self.last_irreversible_block_num & 0xffff) as u16,
ref_block_prefix: prefix
ref_block_prefix: prefix,
}
}
}

pub struct ProcessedTransactionReceipt {
pub status: String,
pub cpu_usage_us: u32,
pub net_usage_words: u32
pub net_usage_words: u32,
}

pub struct ProcessedTransaction {
Expand All @@ -132,52 +132,40 @@ pub struct ProcessedTransaction {
pub block_time: String,
pub receipt: ProcessedTransactionReceipt,
pub elapsed: u64,
pub except: Option<SendTransactionResponseException>,
pub except: Option<SendTransactionResponseError>,
pub net_usage: u32,
pub scheduled: bool,
pub action_traces: String, // TODO: create a type for this?
pub account_ram_delta: String // TODO: create a type for this?

pub action_traces: String, // TODO: create a type for this?
pub account_ram_delta: String, // TODO: create a type for this?
}

#[derive(Debug)]
pub struct SendTransactionResponseExceptionStackContext {
pub level: String,
pub file: String,
pub line: u32,
pub method: String,
pub hostname: String,
pub thread_name: String,
pub timestamp: String
pub timestamp: String,
}

#[derive(Debug)]
pub struct SendTransactionResponseExceptionStack {
pub context: SendTransactionResponseExceptionStackContext,
pub format: String,
pub data: String // TODO: create a type for this?
pub data: String, // TODO: create a type for this?
}

pub struct SendTransactionResponseException {
#[derive(Debug)]
pub struct SendTransactionResponseError {
pub code: u32,
pub name: String,
pub message: String,
pub stack: Vec<SendTransactionResponseExceptionStack>
pub stack: Vec<SendTransactionResponseExceptionStack>,
}

pub struct SendTransactionResponse {
pub transaction_id: String,
pub processed: ProcessedTransaction
pub processed: ProcessedTransaction,
}


#[derive(Debug)]
pub struct SendTransactionError {
pub message: String
}
//
// impl From<dyn ClientError> for SendTransactionError {
// fn from(value: ClientError) -> Self {
// Self {
// message: value.message
// }
// }
// }
Loading

0 comments on commit 16e7f36

Please sign in to comment.