Skip to content

Commit 44bd0bc

Browse files
committed
Fix: Examples and Unit Test
Signed-off-by: aceppaluni <aceppaluni@gmail.com>
1 parent cb161d0 commit 44bd0bc

3 files changed

Lines changed: 106 additions & 72 deletions

File tree

examples/query/account_balance_query.py

Lines changed: 47 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,16 @@
99
...
1010
"""
1111

12+
import json
13+
import os
1214
import sys
1315
import time
16+
from urllib.request import Request, urlopen
1417

1518
from hiero_sdk_python import (
1619
AccountCreateTransaction,
20+
AccountId,
1721
Client,
18-
CryptoGetAccountBalanceQuery,
1922
Hbar,
2023
PrivateKey,
2124
ResponseCode,
@@ -45,6 +48,22 @@ def setup_client():
4548
sys.exit(1)
4649

4750

51+
def get_mirror_node_url():
52+
"""Return the Mirror Node URL for the configured Hedera network."""
53+
network = os.getenv("HEDERA_NETWORK", "testnet").lower()
54+
55+
mirror_node_urls = {
56+
"mainnet": "https://mainnet-public.mirrornode.hedera.com",
57+
"testnet": "https://testnet.mirrornode.hedera.com",
58+
"previewnet": "https://previewnet.mirrornode.hedera.com",
59+
}
60+
61+
if network not in mirror_node_urls:
62+
raise ValueError(f"Unsupported HEDERA_NETWORK: {network}. Expected mainnet, testnet, or previewnet.")
63+
64+
return mirror_node_urls[network]
65+
66+
4867
def create_account(client, operator_key, initial_balance=Hbar(10)):
4968
"""
5069
Create a new account on the Hedera network with an initial balance.
@@ -80,18 +99,36 @@ def create_account(client, operator_key, initial_balance=Hbar(10)):
8099
return new_account_id, new_account_private_key
81100

82101

83-
def get_balance(client, account_id):
102+
def get_balance(account_id: AccountId):
84103
"""
85-
Demonstrate the deprecated account balance query.
104+
Get an account balance using the Mirror Node REST API.
105+
106+
Args:
107+
account_id (AccountId): The account whose balance should be retrieved.
86108
87-
.. deprecated::
88-
CryptoGetAccountBalanceQuery is no longer supported. Use the
89-
Mirror Node REST API, for example GET /api/v1/accounts/{accountId}.
109+
Returns:
110+
float: Account balance in HBAR.
90111
"""
91112
print(f"Querying balance for account {account_id}...")
92113

93-
balance_query = CryptoGetAccountBalanceQuery().set_account_id(account_id)
94-
return balance_query.execute(client)
114+
mirror_node_url = get_mirror_node_url()
115+
url = f"{mirror_node_url}/api/v1/accounts/{account_id}"
116+
117+
request = Request(
118+
url,
119+
headers={"Accept": "application/json"},
120+
)
121+
122+
with urlopen(request, timeout=10) as response:
123+
data = json.load(response)
124+
125+
balance_tinybars = data["balance"]
126+
balance_hbars = balance_tinybars / 100_000_000
127+
128+
print("✓ Account balance retrieved successfully")
129+
print(f" HBAR balance: {balance_hbars} hbars")
130+
131+
return balance_hbars
95132

96133

97134
def transfer_hbars(client, operator_id, operator_key, recipient_id, amount):
@@ -143,9 +180,7 @@ def main():
143180
print("=" * 60)
144181
print("INITIAL BALANCE CHECK")
145182
print("=" * 60)
146-
initial_balance = get_balance(client, new_account_id)
147-
if initial_balance is None:
148-
print(f"Use the Mirror Node REST API instead, for example GET /api/v1/accounts/{new_account_id}.")
183+
initial_balance = get_balance(new_account_id)
149184
print(f"Initial balance of new account: {initial_balance} hbars")
150185
print("=" * 60 + "\n")
151186

@@ -166,7 +201,7 @@ def main():
166201
print("=" * 60)
167202
print("UPDATED BALANCE CHECK")
168203
print("=" * 60)
169-
updated_balance = get_balance(client, new_account_id)
204+
updated_balance = get_balance(new_account_id)
170205
print(f"Updated balance of new account: {updated_balance} hbars")
171206
print("=" * 60 + "\n")
172207

examples/query/account_balance_query_2.py

Lines changed: 50 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,10 @@
88
account balances.
99
"""
1010

11+
import json
1112
import os
1213
import sys
14+
from urllib.request import Request, urlopen
1315

1416
from hiero_sdk_python import (
1517
AccountCreateTransaction,
@@ -23,7 +25,6 @@
2325
TokenMintTransaction,
2426
TokenType,
2527
)
26-
from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery
2728
from hiero_sdk_python.tokens.token_id import TokenId
2829

2930

@@ -41,6 +42,22 @@ def setup_client():
4142
sys.exit(1)
4243

4344

45+
def get_mirror_node_url():
46+
"""Return the Mirror Node URL for the configured Hedera network."""
47+
network = os.getenv("HEDERA_NETWORK", "testnet").lower()
48+
49+
mirror_node_urls = {
50+
"mainnet": "https://mainnet-public.mirrornode.hedera.com",
51+
"testnet": "https://testnet.mirrornode.hedera.com",
52+
"previewnet": "https://previewnet.mirrornode.hedera.com",
53+
}
54+
55+
if network not in mirror_node_urls:
56+
raise ValueError(f"Unsupported HEDERA_NETWORK: {network}. Expected mainnet, testnet, or previewnet.")
57+
58+
return mirror_node_urls[network]
59+
60+
4461
def create_account(client, name, initial_balance=Hbar(10)):
4562
"""Create a test account with initial balance."""
4663
account_private_key = PrivateKey.generate(key_type)
@@ -95,22 +112,43 @@ def create_and_mint_token(treasury_account_id, treasury_account_key, client):
95112
sys.exit(1)
96113

97114

98-
def get_account_balance(client: Client, account_id: AccountId):
99-
"""Get account balance using CryptoGetAccountBalanceQuery."""
100-
print(f"Retrieving account balance for account id: {account_id} ...")
115+
def get_account_balance(account_id: AccountId):
116+
"""Get account balance using the Mirror Node REST API."""
117+
print(f"Retrieving account balance for account id: {account_id} ...")
118+
119+
mirror_node_url = get_mirror_node_url()
120+
url = f"{mirror_node_url}/api/v1/accounts/{account_id}"
121+
122+
request = Request(
123+
url,
124+
headers={"Accept": "application/json"},
125+
)
126+
101127
try:
102-
# Use CryptoGetAccountBalanceQuery to get the account balance
103-
account_balance = CryptoGetAccountBalanceQuery().set_account_id(account_id).execute(client)
128+
with urlopen(request, timeout=10) as response:
129+
data = json.load(response)
130+
131+
hbar_balance = data["balance"] / 100_000_000
132+
104133
print("✅ Account balance retrieved successfully!")
105-
# Print account balance with account_id context
106-
print(f"💰 HBAR Balance for {account_id}: {account_balance.hbars} hbars")
107-
# Alternatively, you can use: print(account_balance)
108-
return account_balance
109-
except (ValueError, TypeError, RuntimeError, ConnectionError) as error:
110-
print(f"Error retrieving account balance: {error}")
134+
print(f"💰 HBAR Balance for {account_id}: {hbar_balance} hbars")
135+
136+
return data
137+
138+
except Exception as error:
139+
print(f"Error retrieving account balance: {error}")
111140
sys.exit(1)
112141

113142

143+
def get_token_balance(balance_data, token_id: TokenId):
144+
"""Get a token balance from a Mirror Node account response."""
145+
for token in balance_data.get("balance", {}).get("tokens", []):
146+
if token["token_id"] == str(token_id):
147+
return token["balance"]
148+
149+
return 0
150+
151+
114152
# OPTIONAL comparison function
115153
def compare_token_balances(client, treasury_id: AccountId, receiver_id: AccountId, token_id: TokenId):
116154
"""Compare token balances between two accounts."""

tests/unit/executable_test.py

Lines changed: 9 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@
1616
)
1717
from hiero_sdk_python.hapi.services import (
1818
basic_types_pb2,
19-
crypto_get_account_balance_pb2,
2019
query_pb2,
2120
response_header_pb2,
2221
response_pb2,
@@ -427,58 +426,20 @@ def test_transaction_node_switching_body_bytes():
427426
)
428427

429428

430-
def test_query_retry_on_busy():
429+
def test_query_raises_when_account_balance_query_is_unsupported():
431430
"""
432-
Test query retry behavior when receiving BUSY response.
433-
434-
This test simulates two scenarios:
435-
1. First node returns BUSY response
436-
2. Second node returns OK response with the balance
437-
438-
Verifies that the query successfully retries on a different node after receiving BUSY,
439-
that the balance is returned correctly and that time.sleep was called once for the retry delay.
431+
Test that account balance queries raise an error because the
432+
CryptoGetBalance endpoint is no longer supported.
440433
"""
441-
# Create a BUSY response to simulate a node being temporarily unavailable
442-
# This response indicates the node cannot process the request at this time
443-
busy_response = response_pb2.Response(
444-
cryptogetAccountBalance=crypto_get_account_balance_pb2.CryptoGetAccountBalanceResponse(
445-
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.BUSY)
446-
)
447-
)
448-
449-
# Create a successful OK response with a balance of 1 Hbar
450-
# This simulates a successful account balance query response
451-
ok_response = response_pb2.Response(
452-
cryptogetAccountBalance=crypto_get_account_balance_pb2.CryptoGetAccountBalanceResponse(
453-
header=response_header_pb2.ResponseHeader(nodeTransactionPrecheckCode=ResponseCode.OK),
454-
balance=100000000, # Balance in tinybars
455-
)
456-
)
457-
458-
# Set up response sequences for multiple nodes:
459-
# First node returns BUSY, forcing a retry
460-
# Second node returns OK with the balance
461-
response_sequences = [
462-
[busy_response, ok_response],
463-
[ok_response], # additional response to mimic additional node
464-
]
465-
466-
with (
467-
mock_hedera_servers(response_sequences) as client,
468-
patch("hiero_sdk_python.executable.time.sleep") as mock_sleep,
469-
):
434+
with mock_hedera_servers([]) as client:
470435
query = CryptoGetAccountBalanceQuery()
471436
query.set_account_id(AccountId(0, 0, 1234))
472437

473-
balance = query.execute(client)
474-
475-
# Verify we slept once for the retry
476-
assert mock_sleep.call_count == 1, "Should have retried once"
477-
478-
assert balance.hbars.to_tinybars() == 100000000
479-
# Verify we switched to the second node
480-
assert query._node_account_ids.index == 0
481-
assert query._node_account_ids.current == AccountId(0, 0, 3), "Client should have switched to the second node"
438+
with pytest.raises(
439+
RuntimeError,
440+
match="AccountBalanceQuery is no longer supported",
441+
):
442+
query.execute(client)
482443

483444

484445
# Set max_attempts

0 commit comments

Comments
 (0)