Skip to content

Commit

Permalink
Merge pull request #1 from hewigovens/batch-chunk
Browse files Browse the repository at this point in the history
Add `batch_by_chunk` support and remove `async_trait`
  • Loading branch information
hewigovens authored Apr 4, 2024
2 parents 8b328c3 + 0c41e22 commit c4f82af
Show file tree
Hide file tree
Showing 8 changed files with 210 additions and 50 deletions.
67 changes: 53 additions & 14 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
package.version = "0.1.0"
package.version = "0.1.1"
package.edition = "2021"
package.documentation = "https://docs.rs/reqwest_enum"
package.authors = ["Tao Xu <[email protected]>"]
Expand All @@ -17,3 +17,4 @@ serde = { version = "^1.0.0", features = ["derive"] }
serde_json = "^1.0.0"

async-trait = "^0.1.0"
futures = "^0.3.0"
51 changes: 39 additions & 12 deletions examples/ethereum-rpc/src/ethereum_rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use reqwest_enum::{
target::Target,
};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use serde_json::{Number, Value};
use std::collections::HashMap;

#[derive(Serialize, Deserialize)]
Expand All @@ -20,6 +20,7 @@ pub struct TransactionObject {
}

pub enum BlockParameter {
// hexadecimal block number
Number(&'static str),
Latest,
Earliest,
Expand Down Expand Up @@ -48,21 +49,33 @@ impl From<&BlockParameter> for serde_json::Value {
}
}

fn u64_to_value(val: &u64) -> serde_json::Value {
Value::Number(Number::from(*val))
}

pub enum EthereumRPC {
BlockNumber,
BlobBaseFee,
ChainId,
Call(TransactionObject, BlockParameter),
EstimateGas(TransactionObject),
// blockCount, newestBlock, rewardPercentiles
FeeHistory(u64, BlockParameter, Vec<u64>),
GasPrice,
BlockNumber,
// addrees
GetBalance(&'static str),
GetBlockByNumber(&'static str, bool),
GetBlockByNumber(BlockParameter, bool),
GetCode(&'static str, BlockParameter),
// address, blockNumber
GetTransactionCount(&'static str, BlockParameter),
Call(TransactionObject, BlockParameter),
EstimateGas(TransactionObject),
SendRawTransaction(&'static str),
Syncing,
}

impl JsonRpcTarget for EthereumRPC {
fn method_name(&self) -> &'static str {
match self {
EthereumRPC::Syncing => "eth_syncing",
EthereumRPC::ChainId => "eth_chainId",
EthereumRPC::GasPrice => "eth_gasPrice",
EthereumRPC::BlockNumber => "eth_blockNumber",
Expand All @@ -72,6 +85,9 @@ impl JsonRpcTarget for EthereumRPC {
EthereumRPC::GetTransactionCount(_, _) => "eth_getTransactionCount",
EthereumRPC::Call(_, _) => "eth_call",
EthereumRPC::EstimateGas(_) => "eth_estimateGas",
EthereumRPC::FeeHistory(_, _, _) => "eth_feeHistory",
EthereumRPC::GetCode(_, _) => "eth_getCode",
EthereumRPC::BlobBaseFee => "eth_blobBaseFee",
}
}

Expand All @@ -85,10 +101,7 @@ impl JsonRpcTarget for EthereumRPC {
vec![Value::String(tx.to_string())]
}
EthereumRPC::GetBlockByNumber(block, full) => {
vec![
Value::String(block.to_string()),
Value::Bool(full.to_owned()),
]
vec![block.into(), Value::Bool(full.to_owned())]
}
EthereumRPC::GetTransactionCount(address, block) => {
vec![Value::String(address.to_string()), block.into()]
Expand All @@ -101,9 +114,23 @@ impl JsonRpcTarget for EthereumRPC {
let value = serde_json::to_value(tx).unwrap();
vec![value]
}
EthereumRPC::ChainId => vec![],
EthereumRPC::GasPrice => vec![],
EthereumRPC::BlockNumber => vec![],
EthereumRPC::FeeHistory(block_count, block, reward_percentiles) => {
let mut params = vec![
u64_to_value(block_count),
block.into(),
Value::Array(reward_percentiles.iter().map(u64_to_value).collect()),
];
params.push(Value::Bool(false));
params
}
EthereumRPC::GetCode(address, block) => {
vec![Value::String(address.to_string()), block.into()]
}
EthereumRPC::ChainId
| EthereumRPC::GasPrice
| EthereumRPC::BlockNumber
| EthereumRPC::Syncing
| EthereumRPC::BlobBaseFee => vec![],
}
}
}
Expand Down
15 changes: 12 additions & 3 deletions examples/ethereum-rpc/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
extern crate reqwest_enum;
use ethereum_rpc::EthereumRPC;
use ethereum_rpc::{BlockParameter, EthereumRPC};
use reqwest_enum::jsonrpc::JsonRpcResult;
use reqwest_enum::provider::{JsonRpcProviderType, Provider};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider = Provider::<EthereumRPC>::default();

let targets = vec![EthereumRPC::ChainId, EthereumRPC::GasPrice];
let results: Vec<JsonRpcResult<String>> = provider.batch(targets).await?;
let targets = vec![
EthereumRPC::ChainId,
EthereumRPC::GasPrice,
EthereumRPC::BlockNumber,
EthereumRPC::GetBalance("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"),
EthereumRPC::GetCode(
"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
BlockParameter::Latest,
),
];
let results: Vec<JsonRpcResult<String>> = provider.batch_chunk_by(targets, 2).await?;
for result in results {
match result {
JsonRpcResult::Value(response) => {
Expand Down
21 changes: 20 additions & 1 deletion examples/ethereum-rpc/tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

mod ethereum_rpc_test {
use ethereum_rpc::{BlockParameter, EthereumRPC};
use reqwest_enum::jsonrpc::JsonRpcResponse;
use reqwest_enum::jsonrpc::{JsonRpcResponse, JsonRpcResult};
use reqwest_enum::provider::{JsonProviderType, Provider};

const TEST_ADDRESS: &str = "0xee5f5c53ce2159fc6dd4b0571e86a4a390d04846";
Expand Down Expand Up @@ -56,4 +56,23 @@ mod ethereum_rpc_test {
.unwrap();
assert_eq!(response.result, "0x0");
}

#[tokio::test]
async fn test_syncing() {
let provider = Provider::<EthereumRPC>::default();
let response: JsonRpcResponse<bool> =
provider.request_json(EthereumRPC::Syncing).await.unwrap();
assert!(!response.result);
}

#[tokio::test]
async fn test_blob_base_fee() {
let provider = Provider::<EthereumRPC>::default();
let result: JsonRpcResult<String> = provider
.request_json(EthereumRPC::BlobBaseFee)
.await
.expect("request error");

assert!(matches!(result, JsonRpcResult::Error(_)));
}
}
4 changes: 2 additions & 2 deletions reqwest-enum/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ edition = { workspace = true }

[features]
default = ["jsonrpc"]
jsonrpc = []
jsonrpc = ["dep:futures"]

[dependencies]
reqwest = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
async-trait = { workspace = true }
futures = { workspace = true, optional = true }
8 changes: 5 additions & 3 deletions reqwest-enum/src/jsonrpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl From<JsonRpcRequest> for HTTPBody {
#[cfg(feature = "jsonrpc")]
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonRpcResponse<T> {
pub id: u64,
pub id: JsonRpcId,
pub jsonrpc: String,
pub result: T,
}
Expand All @@ -49,8 +49,8 @@ pub struct JsonRpcResponse<T> {
#[derive(Debug, Serialize, Deserialize)]
pub struct JsonRpcErrorResponse {
pub jsonrpc: String,
pub id: u64,
pub error: String,
pub id: JsonRpcId,
pub error: JsonRpcError,
}

#[cfg(feature = "jsonrpc")]
Expand All @@ -60,8 +60,10 @@ pub struct JsonRpcError {
pub message: String,
}

#[cfg(feature = "jsonrpc")]
impl std::error::Error for JsonRpcError {}

#[cfg(feature = "jsonrpc")]
impl From<reqwest::Error> for JsonRpcError {
fn from(err: reqwest::Error) -> Self {
JsonRpcError {
Expand Down
Loading

0 comments on commit c4f82af

Please sign in to comment.