Skip to content

Commit

Permalink
Merge pull request #40 from telosnetwork/development
Browse files Browse the repository at this point in the history
Development >> Master
  • Loading branch information
poplexity authored Oct 16, 2024
2 parents 413f45c + 2aabfab commit ccd4422
Show file tree
Hide file tree
Showing 29 changed files with 935 additions and 124 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
on: [push, pull_request]
on: [pull_request]

name: Continuous integration

Expand Down Expand Up @@ -61,4 +61,4 @@ jobs:
- uses: actions-rs/cargo@v1
with:
command: clippy
args: -- -D warnings
args: --all-targets -- -D warnings
13 changes: 13 additions & 0 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ members = [
]

[workspace.package]
version = "0.2.1"
version = "0.3.0"
edition = "2021"
rust-version = "1.75"
authors = ["Jesse Schulman <[email protected]>"]
license = "MIT OR Apache-2.0"
homepage = "https://github.com/telosnetwork/antelope-rs"
repository = "https://github.com/telosnetwork/antelope-rs"
keywords = ["blockchain", "antelope"]
categories = ["cryptography::cryptocurrencies", "encoding"]
categories = ["cryptography::cryptocurrencies", "encoding"]
1 change: 1 addition & 0 deletions crates/antelope/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,4 @@ hmac = "0.12.1"
rand_core = "0.6.4"
async-trait = "0.1.77"
thiserror = "1.0.57"
tracing = "0.1.40"
7 changes: 5 additions & 2 deletions crates/antelope/src/api/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@ pub struct APIClient<P: Provider> {
}

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

Expand Down
37 changes: 26 additions & 11 deletions crates/antelope/src/api/default_provider.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::fmt::{Debug, Formatter};

use reqwest::Client;

use crate::api::client::Provider;
use reqwest::Client;
use std::fmt::{Debug, Formatter};
use tracing::debug;

#[derive(Default, Clone)]
pub struct DefaultProvider {
Expand All @@ -11,8 +10,13 @@ pub struct DefaultProvider {
}

impl DefaultProvider {
pub fn new(base_url: String) -> Result<Self, String> {
let client = Client::builder().build();
pub fn new(base_url: String, timeout: Option<u64>) -> Result<Self, String> {
let mut client_builder = Client::builder();
if timeout.is_some() {
client_builder =
client_builder.timeout(std::time::Duration::from_secs(timeout.unwrap()));
}
let client = client_builder.build();
if client.is_err() {
let err = client.err();
let mut err_message = String::from("Error building http client");
Expand Down Expand Up @@ -40,28 +44,39 @@ impl Debug for DefaultProvider {
#[async_trait::async_trait]
impl Provider for DefaultProvider {
async fn get(&self, path: String) -> Result<String, String> {
debug!("GET {}", self.base_url.to_string() + &path);
let res = self
.client
.get(self.base_url.to_string() + &path)
.send()
.await;
if res.is_err() {
return Err(res.err().unwrap().to_string());
let res_err = res.err().unwrap().to_string();
debug!("Error: {}", res_err);
return Err(res_err);
}

Ok(res.unwrap().text().await.unwrap())
let response = res.unwrap().text().await.unwrap();
debug!("Response: {}", response);
Ok(response)
}

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 body_str = body.unwrap();
debug!("POST {} {}", self.base_url.to_string() + &path, body_str);
builder = builder.body(body_str);
}
let res = builder.send().await;
if res.is_err() {
return Err(res.err().unwrap().to_string());
let err_str = res.err().unwrap().to_string();
debug!("Error: {}", err_str);
return Err(err_str);
}

Ok(res.unwrap().text().await.unwrap())
let response = res.unwrap().text().await.unwrap();
debug!("Response: {}", response);
Ok(response)
}
}
8 changes: 5 additions & 3 deletions crates/antelope/src/api/system/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use crate::chain::private_key::PrivateKey;
use crate::name;
use crate::serializer::Encoder;
use sha2::{Digest, Sha256};
use std::path::Path;
use tracing::info;

#[derive(Debug, Default, Clone)]
pub struct SystemAPI<T: Provider> {
Expand Down Expand Up @@ -104,8 +106,8 @@ impl<T: Provider> SystemAPI<T> {
memo: Option<String>,
private_key: PrivateKey,
) -> Result<SendTransactionResponse, ClientError<SendTransactionResponseError>> {
let wasm = std::fs::read(wasm_path).unwrap();
let abi_json_bytes = std::fs::read(abi_path).unwrap();
let wasm = std::fs::read(Path::new(wasm_path)).unwrap();
let abi_json_bytes = std::fs::read(Path::new(abi_path)).unwrap();
let abi: ABI = serde_json::from_slice(&abi_json_bytes).unwrap();
let abi_bytes = Encoder::pack(&abi);
self.set_contract(account, wasm, abi_bytes, memo, private_key)
Expand All @@ -123,7 +125,7 @@ impl<T: Provider> SystemAPI<T> {
let mut hasher = Sha256::new();
hasher.update(&wasm);
let wasm_hash = hasher.finalize();
println!(
info!(
"Setting contract for account: {:?}, with hash: {:?}",
account.as_string(),
wasm_hash
Expand Down
87 changes: 81 additions & 6 deletions crates/antelope/src/api/v1/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ use std::fmt::Debug;

use serde_json::{self, Value};

use crate::api::v1::structs::{ABIResponse, EncodingError, GetBlockResponse, ServerError};
use crate::api::v1::structs::{
ABIResponse, EncodingError, GetBlockResponse, GetTransactionStatusResponse, ServerError,
};
use crate::chain::checksum::{Checksum160, Checksum256};
use crate::{
api::{
client::Provider,
Expand Down Expand Up @@ -123,7 +126,7 @@ impl<T: Provider> ChainAPI<T> {
Ok(response) => {
match serde_json::from_str::<GetBlockResponse>(&response) {
Ok(block_response) => Ok(block_response),
Err(_) => {
Err(_serr) => {
// Attempt to parse the error response
match serde_json::from_str::<ErrorResponse>(&response) {
Ok(error_response) => Err(ClientError::SERVER(ServerError {
Expand Down Expand Up @@ -181,14 +184,54 @@ impl<T: Provider> ChainAPI<T> {
Err(e) => {
// If parsing the error response also fails, consider it an encoding error
Err(ClientError::ENCODING(EncodingError {
message: format!("Failed to parse response: {}", e),
message: format!(
"Failed to parse response: {} Raw response was: {}",
e, result
),
}))
}
}
}
}
}

pub async fn get_transaction_status(
&self,
trx_id: Checksum256,
) -> Result<GetTransactionStatusResponse, ClientError<ErrorResponse>> {
let payload = serde_json::json!({
"id": trx_id,
});

let result = self
.provider
.post(
String::from("/v1/chain/get_transaction_status"),
Some(payload.to_string()),
)
.await;

match result {
Ok(response) => {
match serde_json::from_str::<GetTransactionStatusResponse>(&response) {
Ok(status_response) => Ok(status_response),
Err(_) => {
// Attempt to parse the error response
match serde_json::from_str::<ErrorResponse>(&response) {
Ok(error_response) => Err(ClientError::SERVER(ServerError {
error: error_response,
})),
Err(_) => Err(ClientError::ENCODING(EncodingError {
message: "Failed to parse JSON".into(),
})),
}
}
}
}
Err(msg) => Err(ClientError::NETWORK(msg)),
}
}

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

let json: Value = serde_json::from_str(result.await.unwrap().as_str()).unwrap();
let response = match result.await {
Ok(response) => response,
Err(_) => return Err(ClientError::NETWORK("Failed to get table rows".into())),
};
let json: Value = serde_json::from_str(response.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 All @@ -213,13 +260,41 @@ impl<T: Provider> ChainAPI<T> {
rows.push(row);
}

let next_key = TableIndexType::NAME(name!(next_key_str.as_str()));
let mut next_key = None;

if !next_key_str.is_empty() {
match params.lower_bound {
Some(TableIndexType::NAME(_)) => {
next_key = Some(TableIndexType::NAME(name!(next_key_str.as_str())));
}
Some(TableIndexType::UINT64(_)) => {
next_key = Some(TableIndexType::UINT64(next_key_str.parse().unwrap()));
}
Some(TableIndexType::UINT128(_)) => {
next_key = Some(TableIndexType::UINT128(next_key_str.parse().unwrap()));
}
Some(TableIndexType::CHECKSUM160(_)) => {
next_key = Some(TableIndexType::CHECKSUM160(
Checksum160::from_bytes(hex_to_bytes(&next_key_str).as_slice()).unwrap(),
));
}
Some(TableIndexType::CHECKSUM256(_)) => {
next_key = Some(TableIndexType::CHECKSUM256(
Checksum256::from_bytes(hex_to_bytes(&next_key_str).as_slice()).unwrap(),
));
}
Some(TableIndexType::FLOAT64(_)) => {
next_key = Some(TableIndexType::FLOAT64(next_key_str.parse().unwrap()));
}
None => {}
};
}

Ok(GetTableRowsResponse {
rows,
more,
ram_payers: None,
next_key: Some(next_key),
next_key,
})
}
}
Loading

0 comments on commit ccd4422

Please sign in to comment.