Created
March 25, 2022 00:33
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.