@@ -17,7 +17,6 @@ use ic_ethereum_types::Address;
17
17
use num:: { BigUint , Num } ;
18
18
use std:: str:: FromStr ;
19
19
20
-
21
20
pub const EVM_RPC_CANISTER_ID : Principal =
22
21
Principal :: from_slice ( b"\x00 \x00 \x00 \x00 \x02 \x30 \x00 \xCC \x01 \x01 " ) ; // 7hfb6-caaaa-aaaar-qadga-cai
23
22
pub const EVM_RPC : EvmRpcCanister = EvmRpcCanister ( EVM_RPC_CANISTER_ID ) ;
@@ -37,20 +36,6 @@ pub async fn ethereum_address(owner: Option<Principal>) -> String {
37
36
wallet. ethereum_address ( ) . to_string ( )
38
37
}
39
38
40
- #[ derive( Debug , Deserialize ) ]
41
- #[ allow( dead_code) ]
42
- struct JsonRpcResult {
43
- result : Option < String > ,
44
- error : Option < JsonRpcError > ,
45
- }
46
-
47
- #[ derive( Debug , Deserialize ) ]
48
- #[ allow( dead_code) ]
49
- struct JsonRpcError {
50
- code : isize ,
51
- message : String ,
52
- }
53
-
54
39
#[ update]
55
40
pub async fn get_balance ( address : String ) -> Nat {
56
41
let _caller = validate_caller_not_anonymous ( ) ;
@@ -74,24 +59,28 @@ pub async fn get_balance(address: String) -> Nat {
74
59
. await
75
60
. expect ( "RPC call failed" ) ;
76
61
77
- match response {
62
+ let hex_balance = match response {
78
63
RequestResult :: Ok ( balance_result) => {
79
- let json_rpc_result: JsonRpcResult =
80
- serde_json:: from_str ( & balance_result) . expect ( "JSON is not well-formatted" ) ;
81
64
// The response to a successful `eth_getBalance` call has the format
82
- // { "id": "[CHAIN ID]", "jsonrpc": "2.0", "result": "[BALANCE IN HEX]" }
83
- let hex_balance = json_rpc_result. result . expect ( "No balance received" ) ;
84
-
85
- // Make sure that the number of digits is even and remove the "0x" prefix.
86
- let hex_balance = if hex_balance. len ( ) % 2 != 0 {
87
- format ! ( "0{}" , & hex_balance[ 2 ..] )
88
- } else {
89
- hex_balance[ 2 ..] . to_string ( )
90
- } ;
91
- Nat ( BigUint :: from_str_radix ( & hex_balance, 16 ) . unwrap ( ) )
65
+ // { "id": "[ID]", "jsonrpc": "2.0", "result": "[BALANCE IN HEX]" }
66
+ let response: serde_json:: Value = serde_json:: from_str ( & balance_result) . unwrap ( ) ;
67
+ response
68
+ . get ( "result" )
69
+ . and_then ( |v| v. as_str ( ) )
70
+ . unwrap ( )
71
+ . to_string ( )
92
72
}
93
73
RequestResult :: Err ( e) => panic ! ( "Received an error response: {:?}" , e) ,
94
- }
74
+ } ;
75
+
76
+ // Make sure that the number of digits is even and remove the "0x" prefix.
77
+ let hex_balance = if hex_balance. len ( ) % 2 != 0 {
78
+ format ! ( "0{}" , & hex_balance[ 2 ..] )
79
+ } else {
80
+ hex_balance[ 2 ..] . to_string ( )
81
+ } ;
82
+
83
+ Nat ( BigUint :: from_str_radix ( & hex_balance, 16 ) . unwrap ( ) )
95
84
}
96
85
97
86
#[ update]
0 commit comments