Skip to content

Commit e2382e7

Browse files
committed
Cleaned up the get_balance endpoint.
1 parent 338c2d1 commit e2382e7

File tree

1 file changed

+18
-29
lines changed

1 file changed

+18
-29
lines changed

rust/basic_ethereum/src/lib.rs

Lines changed: 18 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ use ic_ethereum_types::Address;
1717
use num::{BigUint, Num};
1818
use std::str::FromStr;
1919

20-
2120
pub const EVM_RPC_CANISTER_ID: Principal =
2221
Principal::from_slice(b"\x00\x00\x00\x00\x02\x30\x00\xCC\x01\x01"); // 7hfb6-caaaa-aaaar-qadga-cai
2322
pub const EVM_RPC: EvmRpcCanister = EvmRpcCanister(EVM_RPC_CANISTER_ID);
@@ -37,20 +36,6 @@ pub async fn ethereum_address(owner: Option<Principal>) -> String {
3736
wallet.ethereum_address().to_string()
3837
}
3938

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-
5439
#[update]
5540
pub async fn get_balance(address: String) -> Nat {
5641
let _caller = validate_caller_not_anonymous();
@@ -74,24 +59,28 @@ pub async fn get_balance(address: String) -> Nat {
7459
.await
7560
.expect("RPC call failed");
7661

77-
match response {
62+
let hex_balance = match response {
7863
RequestResult::Ok(balance_result) => {
79-
let json_rpc_result: JsonRpcResult =
80-
serde_json::from_str(&balance_result).expect("JSON is not well-formatted");
8164
// 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()
9272
}
9373
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())
9584
}
9685

9786
#[update]

0 commit comments

Comments
 (0)