Skip to content

Instantly share code, notes, and snippets.

@SilentCicero
Last active November 11, 2022 06:47
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 SilentCicero/06995269d85b546d6269ff036bdd6c02 to your computer and use it in GitHub Desktop.
Save SilentCicero/06995269d85b546d6269ff036bdd6c02 to your computer and use it in GitHub Desktop.
A contract example for Ethers.rs, with use of provider get_logs and event decoding.
use anyhow::Result;
use ethers::{
prelude::*,
utils::{Ganache, Solc},
};
use std::{convert::TryFrom, sync::Arc, time::Duration};
// Generate the type-safe contract bindings by providing the ABI
// definition in human readable format
abigen!(
SimpleStorage,
r#"[
function setValue(string)
function getValue() external view (string)
event ValueChanged(address indexed,string,string)
]"#,
event_derives(serde::Deserialize, serde::Serialize)
);
pub async fn contract() -> Result<()> {
// 1. compile the contract (note this requires that you are inside the `ethers/examples` directory)
let compiled = Solc::new("./src/contracts/*")
.build()?;
let contract = compiled
.get("SimpleStorage")
.expect("could not find contract");
// 2. launch ganache
let ganache = Ganache::new().spawn();
// 3. instantiate our wallet
let wallet: LocalWallet = ganache.keys()[0].clone().into();
// 4. connect to the network
let provider =
Provider::<Http>::try_from(ganache.endpoint())?
.interval(Duration::from_millis(10u64));
let provider2 = provider.clone();
// 5. instantiate the client with the wallet
let client = SignerMiddleware::new(provider, wallet);
let client = Arc::new(client);
// 6. create a factory which will be used to deploy instances of the contract
let factory = ContractFactory::new(
contract.abi.clone(),
contract.bytecode.clone(),
client.clone(),
);
// 7. deploy it with the constructor arguments
let contract = factory.deploy("initial value".to_string())?.send().await?;
// 8. get the contract's address
let addr = contract.address();
// 9. instantiate the contract
let contract = SimpleStorage::new(addr, client.clone());
// 10. call the `setValue` method
// (first `await` returns a PendingTransaction, second one waits for it to be mined)
let _receipt = contract.set_value("hi".to_owned()).send().await?.await?;
/*
let event = "ValueChanged(address,string,string)";
let t0 = H256::from(keccak256(event.as_bytes()));
*/
let filter = Filter::new()
.from_block(0)
.address(contract.address())
.limit(100);
let contract_logs = provider2
.get_logs(&filter.clone()).await.unwrap();
let topics = contract_logs[0].topics.clone();
let data = contract_logs[0].data.clone();
let decoded: (Address, String, String) = contract
.decode_event("ValueChanged", topics, data)
.unwrap();
println!("{:?}", decoded);
// 11. get all events
let logs = contract
.value_changed_filter()
.from_block(0u64)
.query()
.await?;
// 12. get the new value
let value = contract.get_value().call().await?;
println!("Value: {}. Logs: {}", value, serde_json::to_string(&logs)?);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment