Skip to content

Commit

Permalink
chore: update docs and readme examples, use u32 instead of u64
Browse files Browse the repository at this point in the history
  • Loading branch information
oleonardolima committed Jul 6, 2022
1 parent 3f8bd14 commit 14af46c
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 19 deletions.
31 changes: 17 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,40 +41,43 @@ cargo install --path .
cargo run -- data-stream --blocks

# to use regtest, you need to pass it as a parameter
cargo run -- --network testnet data-stream --blocks
cargo run -- --base-url localhost:8999/testnet/api/v1 data-stream --blocks
```
### Subscribing and consuming new block events through the lib:
``` rust
use anyhow::{self, Ok};
use block_events::api::BlockEvent;
use futures_util::{pin_mut, StreamExt};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
env_logger::init();

// for regtest network
let url = url::Url::parse("ws://localhost:8999/api/v1/ws").unwrap();
// for mempool.space regtest network
let base_url = "localhost:8999/testnet/api/v1";

// async fetch the data stream through the lib
let block_events = block_events::websocket::subscribe_to_blocks(&url).await?;
// no checkpoint for this example, check the other one if interested.
let checkpoint = None;

// consume and execute the code (current matching and printing) in async manner for each new block-event
// async fetch the block-events stream through the lib
let block_events = block_events::subscribe_to_blocks(base_url, checkpoint).await?;

// consume and execute your code (current only matching and printing) in async manner for each new block-event
pin_mut!(block_events);
while let Some(block_event) = block_events.next().await {
match block_event {
BlockEvent::Connected(block) => {
println!("Connected BlockEvent: {:#?}", block);
block_events::api::BlockEvent::Connected(block) => {
println!(
"[connected block][block_hash {:#?}][block_prev_hash {:#?}]",
block.block_hash(),
block.prev_blockhash
);
}
BlockEvent::Disconnected((height, block_hash)) => {
block_events::api::BlockEvent::Disconnected((height, block_hash)) => {
println!(
"Disconnected BlockEvent: [height {:#?}] [block_hash: {:#?}]",
"[disconnected block][height {:#?}][block_hash: {:#?}]",
height, block_hash
);
}
BlockEvent::Error() => {
eprint!("ERROR BlockEvent: received an error from the block-events stream");
}
}
}
Ok(())
Expand Down
1 change: 0 additions & 1 deletion src/bin.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use anyhow::Ok;
use block_events::api::BlockEvent;
use clap::{ArgGroup, Parser, Subcommand};
use futures_util::{pin_mut, StreamExt};
use serde::{Deserialize, Serialize};
Expand Down
4 changes: 2 additions & 2 deletions src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl HttpClient {
}

/// Get current blockchain block height (the current tip height)
pub async fn _get_height(&self) -> anyhow::Result<u64> {
pub async fn _get_height(&self) -> anyhow::Result<u32> {
let req = self
.client
.get(&format!("{}/blocks/tip/height", self.url))
Expand All @@ -48,7 +48,7 @@ impl HttpClient {
}

/// Get [`BlockHash`] from mempool.space, for given block height
pub async fn _get_block_height(&self, height: u64) -> anyhow::Result<BlockHash> {
pub async fn _get_block_height(&self, height: u32) -> anyhow::Result<BlockHash> {
let req = self
.client
.get(&format!("{}/block-height/{}", self.url, height))
Expand Down
46 changes: 44 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,48 @@
//! please check out the repository, project proposal or reach out.
//!
//! # Examples
//! ## Subscribe to all new block events for mempool.space
//! ``` no_run
//! use anyhow::{self, Ok};
//! use futures_util::{pin_mut, StreamExt};
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//! env_logger::init();
//!
//! // for mempool.space regtest network
//! let base_url = "localhost:8999/testnet/api/v1";
//!
//! // no checkpoint for this example, check the commented other one if interested.
//! // checkpoint for first BDK Taproot transaction on mainnet (base_url update needed)
//! // let checkpoint = (709635, bitcoin::BlockHash::from("00000000000000000001f9ee4f69cbc75ce61db5178175c2ad021fe1df5bad8f"));
//! let checkpoint = None;
//!
//! // async fetch the block-events stream through the lib
//! let block_events = block_events::subscribe_to_blocks(base_url, checkpoint).await?;
//!
//! // consume and execute your code (current only matching and printing) in async manner for each new block-event
//! pin_mut!(block_events);
//! while let Some(block_event) = block_events.next().await {
//! match block_event {
//! block_events::api::BlockEvent::Connected(block) => {
//! println!(
//! "[connected block][block_hash {:#?}][block_prev_hash {:#?}]",
//! block.block_hash(),
//! block.prev_blockhash
//! );
//! }
//! block_events::api::BlockEvent::Disconnected((height, block_hash)) => {
//! println!(
//! "[disconnected block][height {:#?}][block_hash: {:#?}]",
//! height, block_hash
//! );
//! }
//! }
//! }
//! Ok(())
//! }
//! ```
pub mod api;
pub mod http;
Expand Down Expand Up @@ -133,7 +175,7 @@ impl BlockHeadersCache {
/// Subscribe to a real-time stream of [`BlockEvent`], for all new blocks or starting from an optional checkpoint
pub async fn subscribe_to_blocks(
base_url: &str,
checkpoint: Option<(u64, BlockHash)>,
checkpoint: Option<(u32, BlockHash)>,
) -> anyhow::Result<Pin<Box<dyn Stream<Item = BlockEvent>>>> {
let http_client = http::HttpClient::new(base_url, DEFAULT_CONCURRENT_REQUESTS);

Expand Down Expand Up @@ -216,7 +258,7 @@ async fn process_candidates(
// FIXME: this fails when checkpoint is genesis block as it does not have a previousblockhash field
pub async fn fetch_blocks(
http_client: HttpClient,
checkpoint: (u64, BlockHash),
checkpoint: (u32, BlockHash),
) -> anyhow::Result<impl Stream<Item = BlockExtended>> {
let (ckpt_height, ckpt_hash) = checkpoint;

Expand Down

0 comments on commit 14af46c

Please sign in to comment.