From f8ca81ab220a0852471c15a05dd9fc3a6113f215 Mon Sep 17 00:00:00 2001 From: Georgios Konstantopoulos Date: Sun, 24 May 2020 20:26:41 +0300 Subject: [PATCH] add eth_balance and eth_accounts --- examples/transfer_eth.rs | 11 ++++++++++- src/providers/mod.rs | 17 +++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/examples/transfer_eth.rs b/examples/transfer_eth.rs index 75f19a01..b46e3eba 100644 --- a/examples/transfer_eth.rs +++ b/examples/transfer_eth.rs @@ -8,7 +8,8 @@ use std::convert::TryFrom; async fn main() -> Result<(), failure::Error> { // connect to the network let provider = HttpProvider::try_from("http://localhost:8545")?; - let from = "784C1bA9846aB4CE78E9CFa27884E29dd31d593A".parse()?; + let accounts = provider.get_accounts().await?; + let from = accounts[0]; // craft the tx let tx = TransactionRequest { @@ -21,6 +22,8 @@ async fn main() -> Result<(), failure::Error> { nonce: None, }; + let balance_before = provider.get_balance(from, None).await?; + // broadcast it via the eth_sendTransaction API let tx_hash = provider.send_transaction(tx).await?; @@ -38,5 +41,11 @@ async fn main() -> Result<(), failure::Error> { assert!(nonce2 < nonce1); + let balance_after = provider.get_balance(from, None).await?; + assert!(balance_after < balance_before); + + println!("Balance before {}", balance_before); + println!("Balance after {}", balance_after); + Ok(()) } diff --git a/src/providers/mod.rs b/src/providers/mod.rs index a29e8312..f33ee288 100644 --- a/src/providers/mod.rs +++ b/src/providers/mod.rs @@ -46,6 +46,11 @@ impl Provider

{ } } + /// Gets the accounts on the node + pub async fn get_accounts(&self) -> Result, P::Error> { + self.0.request("eth_accounts", None::<()>).await + } + /// Gets the latest block number via the `eth_BlockNumber` API pub async fn get_block_number(&self) -> Result { self.0.request("eth_blockNumber", None::<()>).await @@ -71,6 +76,8 @@ impl Provider

{ self.0.request("eth_sendRawTransaction", Some(rlp)).await } + // Account state + pub async fn get_transaction_count( &self, from: Address, @@ -82,4 +89,14 @@ impl Provider

{ .request("eth_getTransactionCount", Some(&[from, block])) .await } + + pub async fn get_balance( + &self, + from: Address, + block: Option, + ) -> Result { + let from = utils::serialize(&from); + let block = utils::serialize(&block.unwrap_or(BlockNumber::Latest)); + self.0.request("eth_getBalance", Some(&[from, block])).await + } }