ethers-rs/examples/transfer_eth.rs

38 lines
1.1 KiB
Rust
Raw Normal View History

use ethers::{prelude::*, utils::Anvil};
use eyre::Result;
2020-05-22 18:37:21 +00:00
use std::convert::TryFrom;
#[tokio::main]
2020-05-26 11:00:56 +00:00
async fn main() -> Result<()> {
let anvil = Anvil::new().spawn();
2020-05-24 16:14:27 +00:00
// connect to the network
let provider = Provider::<Http>::try_from(anvil.endpoint())?;
2020-05-24 17:26:41 +00:00
let accounts = provider.get_accounts().await?;
let from = accounts[0];
let to = accounts[1];
2020-05-22 18:37:21 +00:00
2020-05-24 16:14:27 +00:00
// craft the tx
let tx = TransactionRequest::new().to(to).value(1000).from(from); // specify the `from` field so that the client knows which account to use
2020-05-24 16:14:27 +00:00
2020-05-24 17:26:41 +00:00
let balance_before = provider.get_balance(from, None).await?;
let nonce1 = provider.get_transaction_count(from, None).await?;
2020-05-24 17:26:41 +00:00
2020-05-24 16:14:27 +00:00
// broadcast it via the eth_sendTransaction API
let tx = provider.send_transaction(tx, None).await?.await?;
2020-05-23 00:01:20 +00:00
println!("{}", serde_json::to_string(&tx)?);
let nonce2 = provider.get_transaction_count(from, None).await?;
2020-05-23 00:01:20 +00:00
assert!(nonce1 < nonce2);
2020-05-23 00:01:20 +00:00
2020-05-24 17:26:41 +00:00
let balance_after = provider.get_balance(from, None).await?;
assert!(balance_after < balance_before);
println!("Balance before {}", balance_before);
println!("Balance after {}", balance_after);
2020-05-23 00:01:20 +00:00
Ok(())
2020-05-22 18:37:21 +00:00
}