Skip to content

Commit

Permalink
Merge pull request #14 from telosnetwork/async_http
Browse files Browse the repository at this point in the history
Switch to using async functions and http client
  • Loading branch information
poplexity authored Jan 19, 2024
2 parents 10577b8 + 729161c commit e94b728
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 30 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.3"
version = "0.1.4"
edition = "2021"
rust-version = "1.75"
authors = ["Jesse Schulman <[email protected]>"]
Expand Down
9 changes: 7 additions & 2 deletions crates/antelope/src/api/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,13 @@ impl Display for HTTPMethod {

// TODO: Make this return an APIResponse with status code, timing, etc..
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>;
fn post(
&self,
path: String,
body: Option<String>,
) -> impl std::future::Future<Output = Result<String, String>> + Send;
fn get(&self, path: String)
-> impl std::future::Future<Output = Result<String, String>> + Send;
}

#[derive(Debug, Default, Clone)]
Expand Down
18 changes: 11 additions & 7 deletions crates/antelope/src/api/default_provider.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::api::client::Provider;
use reqwest::blocking::Client;
use reqwest::Client;
use std::fmt::{Debug, Formatter};

#[derive(Default, Clone)]
Expand Down Expand Up @@ -36,25 +36,29 @@ impl Debug for DefaultProvider {
}

impl Provider for DefaultProvider {
fn get(&self, path: String) -> Result<String, String> {
let res = self.client.get(self.base_url.to_string() + &path).send();
async fn get(&self, path: String) -> Result<String, String> {
let res = self
.client
.get(self.base_url.to_string() + &path)
.send()
.await;
if res.is_err() {
return Err(res.err().unwrap().to_string());
}

Ok(res.unwrap().text().unwrap())
Ok(res.unwrap().text().await.unwrap())
}

fn post(&self, path: String, body: Option<String>) -> Result<String, String> {
async fn post(&self, path: String, body: Option<String>) -> Result<String, String> {
let mut builder = self.client.post(self.base_url.to_string() + &path);
if body.is_some() {
builder = builder.body(body.unwrap());
}
let res = builder.send();
let res = builder.send().await;
if res.is_err() {
return Err(res.err().unwrap().to_string());
}

Ok(res.unwrap().text().unwrap())
Ok(res.unwrap().text().await.unwrap())
}
}
12 changes: 6 additions & 6 deletions crates/antelope/src/api/v1/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ impl<T: Provider> ChainAPI<T> {
ChainAPI { provider }
}

pub fn get_info(&self) -> Result<GetInfoResponse, ClientError<()>> {
pub async fn get_info(&self) -> Result<GetInfoResponse, ClientError<()>> {
let result = self.provider.get(String::from("/v1/chain/get_info"));
let json = serde_json::from_str(result.unwrap().as_str());
let json = serde_json::from_str(result.await.unwrap().as_str());
if json.is_err() {
return Err(ClientError::encoding("Failed to parse JSON".into()));
}
Expand Down Expand Up @@ -59,7 +59,7 @@ impl<T: Provider> ChainAPI<T> {
})
}

pub fn send_transaction(
pub async fn send_transaction(
&self,
trx: SignedTransaction,
) -> Result<SendTransactionResponse, ClientError<SendTransactionResponseError>> {
Expand All @@ -72,7 +72,7 @@ impl<T: Provider> ChainAPI<T> {
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 json: Value = serde_json::from_str(result.await.unwrap().as_str()).unwrap();
let response_obj = JSONObject::new(json);
if response_obj.has("code") {
let error_value = response_obj.get_value("error").unwrap();
Expand Down Expand Up @@ -109,7 +109,7 @@ impl<T: Provider> ChainAPI<T> {
})
}

pub fn get_table_rows<P: Packer + Default>(
pub async fn get_table_rows<P: Packer + Default>(
&self,
params: GetTableRowsParams,
) -> Result<GetTableRowsResponse<P>, ClientError<()>> {
Expand All @@ -118,7 +118,7 @@ impl<T: Provider> ChainAPI<T> {
Some(params.to_json()),
);

let json: Value = serde_json::from_str(result.unwrap().as_str()).unwrap();
let json: Value = serde_json::from_str(result.await.unwrap().as_str()).unwrap();
let response_obj = JSONObject::new(json);
let more = response_obj.get_bool("more")?;
let next_key_str = response_obj.get_string("next_key")?;
Expand Down
2 changes: 1 addition & 1 deletion crates/antelope/src/chain/block_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub struct BlockId {
}

impl BlockId {
pub fn from_bytes(bytes: &Vec<u8>) -> Result<Self, String> {
pub fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
if bytes.len() != 32 {
return Err(String::from(
"BlockId.from_bytes expected bytes length of 32",
Expand Down
24 changes: 14 additions & 10 deletions crates/antelope/tests/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ mod utils;
use crate::utils::mock_provider;
use utils::mock_provider::MockProvider;

#[test]
fn chain_get_info() {
#[tokio::test]
async fn chain_get_info() {
let mock_provider = MockProvider {};
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();
let info = client.unwrap().v1_chain.get_info().await.unwrap();
assert_eq!(info.head_block_producer, name!("bp.boid"));
assert_eq!(
info.last_irreversible_block_id.bytes,
Expand All @@ -29,16 +29,16 @@ fn chain_get_info() {
assert_eq!(info.last_irreversible_block_num, 315556072);
}

#[test]
fn chain_send_transaction() {
#[tokio::test]
async fn chain_send_transaction() {
let mock_provider = MockProvider {};
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 info = client.v1_chain.get_info().await.unwrap();
let transaction =
mock_provider::make_mock_transaction(&info, Asset::from_string("0.0420 TLOS"));
let signed_transaction = mock_provider::sign_mock_transaction(&transaction, &info);
let result = client.v1_chain.send_transaction(signed_transaction);
let result = client.v1_chain.send_transaction(signed_transaction).await;
assert!(result.is_ok(), "Transaction result should be ok");
let send_trx_response = result.unwrap();

Expand Down Expand Up @@ -66,7 +66,10 @@ fn chain_send_transaction() {
mock_provider::make_mock_transaction(&info, Asset::from_string("0.0420 NUNYA"));
let signed_invalid_transaction =
mock_provider::sign_mock_transaction(&invalid_transaction, &info);
let failed_result = client.v1_chain.send_transaction(signed_invalid_transaction);
let failed_result = client
.v1_chain
.send_transaction(signed_invalid_transaction)
.await;
assert!(
failed_result.is_err(),
"Failed transaction result should be err"
Expand All @@ -85,8 +88,8 @@ fn chain_send_transaction() {
}
}

#[test]
pub fn chain_get_table_rows() {
#[tokio::test]
pub async fn chain_get_table_rows() {
#[derive(StructPacker, Default)]
struct UserRow {
balance: Asset,
Expand All @@ -109,6 +112,7 @@ pub fn chain_get_table_rows() {
index_position: None,
show_payer: None,
})
.await
.unwrap();

assert_eq!(res1.rows.len(), 1, "Should get 1 row back");
Expand Down
4 changes: 2 additions & 2 deletions crates/antelope/tests/utils/mock_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ impl Debug for MockProvider {
}

impl Provider for MockProvider {
fn post(&self, path: String, body: Option<String>) -> Result<String, String> {
async fn post(&self, path: String, body: Option<String>) -> Result<String, String> {
self.call(HTTPMethod::POST, path, body)
}

fn get(&self, path: String) -> Result<String, String> {
async fn get(&self, path: String) -> Result<String, String> {
self.call(HTTPMethod::GET, path, None)
}
}
Expand Down

0 comments on commit e94b728

Please sign in to comment.