Skip to content

Instantly share code, notes, and snippets.

@haxpor
Created March 25, 2022 00:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haxpor/e1ccd10a813d743addb243d3f26a4215 to your computer and use it in GitHub Desktop.
Save haxpor/e1ccd10a813d743addb243d3f26a4215 to your computer and use it in GitHub Desktop.
Example of using rust-web3 crate to listen to certain event as emitted from target contract.
use hex_literal::hex;
use web3::{
contract::{Contract, Options},
futures::{future, StreamExt},
types::{FilterBuilder, Address},
};
use std::str::FromStr;
#[tokio::main]
async fn main() -> web3::contract::Result<()> {
let web3 = web3::Web3::new(web3::transports::WebSocket::new("<wss-provider-url>").await?);
let filter = FilterBuilder::default()
// this is BSC: TokenHub
.address(vec![Address::from_str("0x0000000000000000000000000000000000001004").unwrap()])
.topics(
// this is 'Transfer (index_topic_1 address from, index_topic_2 address to, uint256 value)' event
// use https://emn178.github.io/online-tools/keccak_256.html, and type in 'Transfer(address,address,uint256)'
// it will return result hash as used in next line
Some(vec![hex!("ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef").into()]),
None,
None,
None,
)
.build();
let sub = web3.eth_subscribe().subscribe_logs(filter).await?;
sub.for_each(|log| {
println!("{:?}", log);
future::ready(())
}).await;
Ok(())
}
@haxpor
Copy link
Author

haxpor commented Mar 25, 2022

Note: current state of rust-web3 doesn't implement re-connect to disconnected websocket, nor pings just yet. Also see tomusdrw/rust-web3#151 for timeout issue in websocket (to not silently hang waiting while connection is disconnected), and tomusdrw/rust-web3#249 for the case of reconnection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment