Skip to content

Commit 5ce953f

Browse files
authored
refactor: use native AccountInfo string representation in examples (#1269)
Signed-off-by: Shivakumar <shivakumarjagadish12@gmail.com>
1 parent dd3030f commit 5ce953f

File tree

5 files changed

+143
-201
lines changed

5 files changed

+143
-201
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ This changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.
158158
- Updated `pyproject.toml` to enforce stricter Ruff linting rules, including Google-style docstrings (`D`), import sorting (`I`), and modern Python syntax (`UP`).
159159
- Modified and renamed hasIntermediateOrAdvancedLabel() to check if issue label is beginner or higher (#1385)
160160
- Updated `.github/scripts/bot-office-hours.sh` to detect and skip PRs created by bot accounts when posting office hours reminders. (#1384)
161+
- Refactored `examples/account/account_create_transaction_create_with_alias.py` and `examples/account/account_create_transaction_evm_alias.py` to use the native `AccountInfo.__str__` method for printing account details, replacing manual JSON serialization. ([#1263](https://github.com/hiero-ledger/hiero-sdk-python/issues/1263))
161162

162163
### Fixed
163164
- Good First Issue bot no longer posts `/assign` reminders for repository collaborators. (#1367)
@@ -180,6 +181,10 @@ This changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.
180181
- Fixed bot-pr-missing-linked-issue to skip commenting on pull requests created by automated bots. (#1382)
181182
- Updated `.github/scripts/bot-community-calls.sh` to skip posting reminders on issues created by bot accounts. (#1383)
182183

184+
### Removed
185+
186+
- Deleted `examples/utils.py` as its helper functions are no longer needed. ([#1263](https://github.com/hiero-ledger/hiero-sdk-python/issues/1263))
187+
183188
### Breaking Change
184189

185190
- Remove deprecated 'in_tinybars' parameter and update related tests `/src/hiero_sdk_python/hbar.py`, `/tests/unit/hbar_test.py` and `/src/hiero_sdk_python/tokens/custom_fixed_fee.py`.

examples/account/account_create_transaction_create_with_alias.py

Lines changed: 32 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,41 @@
1-
"""
2-
Example: Create an account using a separate ECDSA key for the EVM alias.
1+
"""Example: Create an account using a separate ECDSA key for the EVM alias.
32
43
This demonstrates:
54
- Using a "main" key for the account
65
- Using a separate ECDSA public key as the EVM alias
76
- The need to sign the transaction with the alias private key
87
98
Usage:
10-
- uv run -m examples.account.account_create_transaction_create_with_alias
11-
- python -m examples.account.account_create_transaction_create_with_alias
12-
(we use -m because we use the util `info_to_dict`)
9+
uv run examples/account/account_create_transaction_create_with_alias.py
10+
python examples/account/account_create_transaction_create_with_alias.py
1311
"""
1412

15-
import os
1613
import sys
17-
import json
18-
from dotenv import load_dotenv
1914

20-
from examples.utils import info_to_dict
15+
from dotenv import load_dotenv
2116

2217
from hiero_sdk_python import (
23-
Client,
24-
PrivateKey,
2518
AccountCreateTransaction,
19+
AccountId,
2620
AccountInfo,
2721
AccountInfoQuery,
28-
Network,
29-
AccountId,
22+
Client,
3023
Hbar,
24+
PrivateKey,
3125
)
3226

3327
load_dotenv()
34-
network_name = os.getenv("NETWORK", "testnet").lower()
35-
3628

37-
def setup_client():
38-
"""Setup Client."""
39-
network = Network(network_name)
40-
print(f"Connecting to Hedera {network_name} network!")
41-
client = Client(network)
4229

30+
def setup_client() -> Client:
31+
"""Initialize client from environment variables."""
4332
try:
44-
operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", ""))
45-
operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", ""))
46-
client.set_operator(operator_id, operator_key)
33+
client = Client.from_env()
4734
print(f"Client set up with operator id {client.operator_account_id}")
4835
return client
36+
4937
except Exception:
50-
print("Error: Please check OPERATOR_ID and OPERATOR_KEY in your .env file.")
38+
print("Error: Please check OPERATOR_ID, OPERATOR_KEY, and NETWORK in your .env file.")
5139
sys.exit(1)
5240

5341

@@ -56,6 +44,7 @@ def generate_main_and_alias_keys() -> tuple[PrivateKey, PrivateKey]:
5644
5745
Returns:
5846
tuple: (main_private_key, alias_private_key)
47+
5948
"""
6049
print("\nSTEP 1: Generating main account key and separate ECDSA alias key...")
6150

@@ -84,13 +73,18 @@ def create_account_with_ecdsa_alias(
8473
) -> AccountId:
8574
"""Create an account with a separate ECDSA key as the EVM alias.
8675
76+
This uses `set_key_with_alias` to map the main key to the alias key.
77+
The transaction requires signatures from both the alias key (to authorize
78+
the use of the alias) and the operator (to pay fees).
79+
8780
Args:
8881
client: The Hedera client.
8982
main_private_key: The main account private key.
9083
alias_private_key: The ECDSA private key for the EVM alias.
9184
9285
Returns:
9386
AccountId: The newly created account ID.
87+
9488
"""
9589
print("\nSTEP 2: Creating the account with the EVM alias from the ECDSA key...")
9690

@@ -103,17 +97,16 @@ def create_account_with_ecdsa_alias(
10397
).set_key_with_alias(main_private_key, alias_public_key)
10498

10599
# Freeze and sign:
106-
# - operator key signs as payer (via client)
100+
# - operator key signs as payer (handled by client.execute)
107101
# - alias private key MUST sign to authorize the alias
108102
transaction = transaction.freeze_with(client).sign(alias_private_key)
109103

110104
response = transaction.execute(client)
111-
new_account_id = response.account_id
112105

106+
# Safe retrieval of account ID
107+
new_account_id = response.account_id
113108
if new_account_id is None:
114-
raise RuntimeError(
115-
"AccountID not found in receipt. Account may not have been created."
116-
)
109+
raise RuntimeError("AccountID not found in receipt. Account may not have been created.")
117110

118111
print(f"✅ Account created with ID: {new_account_id}\n")
119112
return new_account_id
@@ -128,41 +121,38 @@ def fetch_account_info(client: Client, account_id: AccountId) -> AccountInfo:
128121
129122
Returns:
130123
AccountInfo: The account info object.
124+
131125
"""
132126
print("\nSTEP 3: Fetching account information...")
133-
account_info = AccountInfoQuery().set_account_id(account_id).execute(client)
134-
return account_info
127+
return AccountInfoQuery().set_account_id(account_id).execute(client)
135128

136129

137130
def print_account_summary(account_info: AccountInfo) -> None:
138131
"""Print a summary of the account information.
139132
140133
Args:
141134
account_info: The account info object to display.
135+
142136
"""
143-
out = info_to_dict(account_info)
144-
print("Account Info:")
145-
print(json.dumps(out, indent=2) + "\n")
137+
print("--- Account Info ---")
138+
print(account_info)
139+
print("--------------------\n")
146140

147141
if account_info.contract_account_id is not None:
148-
print(
149-
f"✅ Contract Account ID (EVM alias on-chain): "
150-
f"{account_info.contract_account_id}"
151-
)
142+
print(f"✅ Contract Account ID (EVM alias on-chain): {account_info.contract_account_id}")
152143
else:
153144
print("❌ Error: Contract Account ID (alias) does not exist.")
154145

155146

156147
def main():
157-
"""Main entry point."""
148+
"""Execute the example workflow."""
158149
try:
159150
client = setup_client()
160151
main_private_key, alias_private_key = generate_main_and_alias_keys()
161-
account_id = create_account_with_ecdsa_alias(
162-
client, main_private_key, alias_private_key
163-
)
152+
account_id = create_account_with_ecdsa_alias(client, main_private_key, alias_private_key)
164153
account_info = fetch_account_info(client, account_id)
165154
print_account_summary(account_info)
155+
166156
except Exception as error:
167157
print(f"❌ Error: {error}")
168158
sys.exit(1)

0 commit comments

Comments
 (0)