xJonathanLEI / starknet-rs

Complete Starknet library in Rust™
https://starknet.rs
Apache License 2.0
286 stars 101 forks source link

feat: jsonrpc batch requests #653

Closed xJonathanLEI closed 2 months ago

xJonathanLEI commented 2 months ago

Resolves #593. Supersedes #600.

Implements a type-safe version of the JSON-RPC batch request feature. Users can now do this:

let responses = provider
    .batch_requests([
        ProviderRequestData::BlockNumber(BlockNumberRequest),
        ProviderRequestData::GetBlockTransactionCount(GetBlockTransactionCountRequest {
            block_id: BlockId::Number(100),
        }),
    ])
    .await
    .unwrap();

match (&responses[0], &responses[1]) {
    (
        ProviderResponseData::BlockNumber(block_number),
        ProviderResponseData::GetBlockTransactionCount(count),
    ) => {
        println!("The latest block is #{}", block_number);
        println!("Block #100 has {} transactions", count);
    }
    _ => panic!("unexpected response type"),
}

and the underlying requests would be sent in the just one HTTP request.

xJonathanLEI commented 2 months ago

Note: technically we can also implement a method that accepts only up to 32 requests but is truly type-safe by leveraging generic params. Something similar to:

let (block_number, count) =
  provider.batch_requests(BlockNumberRequest, GetBlockTransactionCountRequest {...}).await.unwrap();

which would be much nicer for use cases where the request types are statically known at compile time.

Let's settle for this for now though.