@@ -69,7 +69,12 @@ defmodule Ethers do
69
69
alias Ethers.Utils
70
70
71
71
@ option_keys [ :rpc_client , :rpc_opts , :signer , :signer_opts , :tx_type ]
72
- @ hex_decode_post_process [ :estimate_gas , :current_gas_price , :current_block_number ]
72
+ @ hex_decode_post_process [
73
+ :estimate_gas ,
74
+ :current_gas_price ,
75
+ :current_block_number ,
76
+ :get_balance
77
+ ]
73
78
@ rpc_actions_map % {
74
79
call: :eth_call ,
75
80
chain_id: :eth_chain_id ,
@@ -108,6 +113,29 @@ defmodule Ethers do
108
113
|> post_process ( nil , :current_block_number )
109
114
end
110
115
116
+ @ doc """
117
+ Returns the native token (ETH) balance of an account in wei.
118
+
119
+ ## Parameters
120
+ - account: Account which the balance is queried for.
121
+ - overrides:
122
+ - block: The block you want to query the balance of account in (defaults to `latest`).
123
+ - rpc_client: The RPC module to use for this request (overrides default).
124
+ - rpc_opts: Specific RPC options to specify for this request.
125
+ """
126
+ @ spec get_balance ( Types . t_address ( ) , Keyword . t ( ) ) ::
127
+ { :ok , non_neg_integer ( ) } | { :error , term ( ) }
128
+ def get_balance ( account , overrides \\ [ ] ) do
129
+ { opts , overrides } = Keyword . split ( overrides , @ option_keys )
130
+
131
+ { rpc_client , rpc_opts } = get_rpc_client ( opts )
132
+
133
+ with { :ok , account , block } <- pre_process ( account , overrides , :get_balance , opts ) do
134
+ rpc_client . eth_get_balance ( account , block , rpc_opts )
135
+ |> post_process ( nil , :get_balance )
136
+ end
137
+ end
138
+
111
139
@ doc """
112
140
Deploys a contract to the blockchain.
113
141
@@ -485,6 +513,20 @@ defmodule Ethers do
485
513
end
486
514
end
487
515
516
+ defp pre_process ( account , overrides , :get_balance = _action , _opts ) do
517
+ block =
518
+ case Keyword . get ( overrides , :block , "latest" ) do
519
+ number when is_integer ( number ) -> Utils . integer_to_hex ( number )
520
+ v -> v
521
+ end
522
+
523
+ case account do
524
+ "0x" <> _ -> { :ok , account , block }
525
+ << _ :: binary - 20 >> -> { :ok , Utils . hex_encode ( account ) , block }
526
+ _ -> { :error , :invalid_account }
527
+ end
528
+ end
529
+
488
530
defp pre_process ( contract_binary , overrides , :deploy = _action , opts ) do
489
531
{ encoded_constructor , overrides } = Keyword . pop ( overrides , :encoded_constructor )
490
532
0 commit comments