Skip to content

Commit

Permalink
Adding some trait implementations and making APIClient use generics i…
Browse files Browse the repository at this point in the history
…nstead of Box and dyn
  • Loading branch information
poplexity committed Jan 17, 2024
1 parent dc14c31 commit 668c7ce
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 25 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ members = [
]

[workspace.package]
version = "0.1.2"
version = "0.1.3"
edition = "2021"
rust-version = "1.75"
authors = ["Jesse Schulman <[email protected]>"]
Expand Down
22 changes: 12 additions & 10 deletions crates/antelope/src/api/client.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::api::default_provider::DefaultProvider;
use crate::api::v1::chain::ChainAPI;
use std::fmt::{Display, Formatter};
use std::fmt::{Debug, Display, Formatter};

pub use crate::api::default_provider::DefaultProvider;

pub enum HTTPMethod {
GET,
Expand All @@ -21,24 +22,25 @@ impl Display for HTTPMethod {
}

// TODO: Make this return an APIResponse with status code, timing, etc..
pub trait Provider {
pub trait Provider: Debug + Default + Sync + Send {
fn post(&self, path: String, body: Option<String>) -> Result<String, String>;
fn get(&self, path: String) -> Result<String, String>;
}

pub struct APIClient {
pub v1_chain: ChainAPI,
#[derive(Debug, Default, Clone)]
pub struct APIClient<P: Provider> {
pub v1_chain: ChainAPI<P>,
}

impl APIClient {
pub fn default_provider(base_url: String) -> Result<Self, String> {
let provider = Box::new(DefaultProvider::new(base_url).unwrap());
impl<P: Provider> APIClient<P> {
pub fn default_provider(base_url: String) -> Result<APIClient<DefaultProvider>, String> {
let provider = DefaultProvider::new(base_url).unwrap();
APIClient::custom_provider(provider)
}

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

#[derive(Default, Clone)]
pub struct DefaultProvider {
base_url: String,
client: Client,
Expand All @@ -27,6 +29,12 @@ impl DefaultProvider {
}
}

impl Debug for DefaultProvider {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "DefaultProvider<{}>", self.base_url)
}
}

impl Provider for DefaultProvider {
fn get(&self, path: String) -> Result<String, String> {
let res = self.client.get(self.base_url.to_string() + &path).send();
Expand All @@ -49,4 +57,5 @@ 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 client;
mod default_provider;
pub mod default_provider;
pub mod v1;
18 changes: 10 additions & 8 deletions crates/antelope/src/api/v1/chain.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::fmt::{Debug};
use crate::api::client::Provider;
use crate::api::v1::structs::{
ClientError, GetInfoResponse, GetTableRowsParams, GetTableRowsResponse, ProcessedTransaction,
Expand All @@ -15,12 +16,13 @@ use crate::serializer::formatter::{JSONObject, ValueTo};
use crate::util::hex_to_bytes;
use serde_json::Value;

pub struct ChainAPI {
provider: Box<dyn Provider>,
#[derive(Debug, Default, Clone)]
pub struct ChainAPI<T: Provider> {
provider: T,
}

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

Expand Down Expand Up @@ -107,10 +109,10 @@ impl ChainAPI {
})
}

pub fn get_table_rows<T: Packer + Default>(
pub fn get_table_rows<P: Packer + Default>(
&self,
params: GetTableRowsParams,
) -> Result<GetTableRowsResponse<T>, ClientError<()>> {
) -> Result<GetTableRowsResponse<P>, ClientError<()>> {
let result = self.provider.post(
String::from("/v1/chain/get_table_rows"),
Some(params.to_json()),
Expand All @@ -121,12 +123,12 @@ impl ChainAPI {
let more = response_obj.get_bool("more")?;
let next_key_str = response_obj.get_string("next_key")?;
let rows_value = response_obj.get_vec("rows")?;
let mut rows: Vec<T> = Vec::with_capacity(rows_value.len());
let mut rows: Vec<P> = Vec::with_capacity(rows_value.len());
for encoded_row in rows_value {
let row_bytes_hex = &ValueTo::string(Some(encoded_row))?;
let row_bytes = hex_to_bytes(row_bytes_hex);
let mut decoder = Decoder::new(&row_bytes);
let mut row = T::default();
let mut row = P::default();
decoder.unpack(&mut row);
rows.push(row);
}
Expand Down
9 changes: 8 additions & 1 deletion crates/antelope/src/chain/private_key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ use crate::crypto::generate::generate;
use crate::crypto::get_public::get_public;
use crate::crypto::shared_secrets::shared_secret;
use crate::crypto::sign::sign;
use std::fmt::{Display, Formatter};
use std::fmt::{Debug, Display, Formatter};

#[derive(Default, Clone)]
pub struct PrivateKey {
pub key_type: KeyType,
value: Vec<u8>,
Expand Down Expand Up @@ -91,3 +92,9 @@ impl Display for PrivateKey {
write!(f, "{}", self.as_string())
}
}

impl Debug for PrivateKey {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.as_string())
}
}
6 changes: 3 additions & 3 deletions crates/antelope/tests/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use utils::mock_provider::MockProvider;
#[test]
fn chain_get_info() {
let mock_provider = MockProvider {};
let client = APIClient::custom_provider(Box::new(mock_provider));
let client = APIClient::custom_provider(mock_provider);
//let client = APIClient::default_provider(String::from("https://telos.caleos.io"));
let info = client.unwrap().v1_chain.get_info().unwrap();
assert_eq!(info.head_block_producer, name!("bp.boid"));
Expand All @@ -32,7 +32,7 @@ fn chain_get_info() {
#[test]
fn chain_send_transaction() {
let mock_provider = MockProvider {};
let client = APIClient::custom_provider(Box::new(mock_provider)).unwrap();
let client = APIClient::custom_provider(mock_provider).unwrap();
//let client = APIClient::default_provider(String::from("https://testnet.telos.caleos.io")).unwrap();
let info = client.v1_chain.get_info().unwrap();
let transaction =
Expand Down Expand Up @@ -93,7 +93,7 @@ pub fn chain_get_table_rows() {
}

let mock_provider = MockProvider {};
let client = APIClient::custom_provider(Box::new(mock_provider)).unwrap();
let client = APIClient::custom_provider(mock_provider).unwrap();
//let client = APIClient::default_provider(String::from("https://testnet.telos.caleos.io")).unwrap();

let res1 = client
Expand Down
9 changes: 9 additions & 0 deletions crates/antelope/tests/utils/mock_provider.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::fmt::{Debug, Formatter};
use antelope::api::client::{HTTPMethod, Provider};
use antelope::api::v1::structs::GetInfoResponse;
use antelope::chain::action::{Action, PermissionLevel};
Expand All @@ -12,6 +13,7 @@ use antelope_client_macros::StructPacker;
use std::fs;
use std::path::PathBuf;

#[derive(Default)]
pub struct MockProvider {}

impl MockProvider {
Expand All @@ -34,6 +36,12 @@ impl MockProvider {
}
}

impl Debug for MockProvider {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "MockProvider")
}
}

impl Provider for MockProvider {
fn post(&self, path: String, body: Option<String>) -> Result<String, String> {
self.call(HTTPMethod::POST, path, body)
Expand All @@ -42,6 +50,7 @@ impl Provider for MockProvider {
fn get(&self, path: String) -> Result<String, String> {
self.call(HTTPMethod::GET, path, None)
}

}

pub fn make_mock_transaction(info: &GetInfoResponse, asset_to_transfer: Asset) -> Transaction {
Expand Down

0 comments on commit 668c7ce

Please sign in to comment.