use anyhow::Result;
use ethers::{prelude::*, utils::Ganache};
use std::{convert::TryFrom, path::Path, sync::Arc, time::Duration};
abigen!(
SimpleContract,
"./examples/contract_abi.json",
event_derives(serde::Deserialize, serde::Serialize)
);
#[tokio::main]
async fn main() -> Result<()> {
let ganache = Ganache::new().spawn();
let source = Path::new(&env!("CARGO_MANIFEST_DIR")).join("examples/contract.sol");
let compiled = Solc::default().compile_source(source).expect("Could not compile contracts");
let (abi, bytecode, _runtime_bytecode) =
compiled.find("SimpleStorage").expect("could not find contract").into_parts_or_default();
let wallet: LocalWallet = ganache.keys()[0].clone().into();
let provider =
Provider::<Http>::try_from(ganache.endpoint())?.interval(Duration::from_millis(10u64));
let client = SignerMiddleware::new(provider, wallet);
let client = Arc::new(client);
let factory = ContractFactory::new(abi, bytecode, client.clone());
let contract = factory.deploy("initial value".to_string())?.legacy().send().await?;
let addr = contract.address();
let contract = SimpleContract::new(addr, client.clone());
let _receipt = contract.set_value("hi".to_owned()).legacy().send().await?.await?;
let logs = contract.value_changed_filter().from_block(0u64).query().await?;
let value = contract.get_value().call().await?;
println!("Value: {}. Logs: {}", value, serde_json::to_string(&logs)?);
Ok(())
}