Skip to content

Commit b2bb143

Browse files
authored
feat: add HBAR unit examples and update transfer transaction (#1259)
Signed-off-by: Shivakumar <[email protected]> Signed-off-by: Shivakumar <[email protected]>
1 parent 4b7d7e0 commit b2bb143

File tree

4 files changed

+346
-33
lines changed

4 files changed

+346
-33
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ This changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.
7070
- Add Linked Issue Enforcer to automatically close PRs without linked issues `.github/workflows/bot-linked-issue-enforcer.yml`.
7171
- Added support for include duplicates in get transaction receipt query (#1166)
7272
- Added `.github/workflows/cron-check-broken-links.yml` workflow to perform scheduled monthly Markdown link validation across the entire repository with automatic issue creation for broken links ([#1210](https://github.com/hiero-ledger/hiero-sdk-python/issues/1210))
73+
- Added `transfer_transaction_tinybar.py` example demonstrating tinybar transfers with both integer and Hbar object approaches. ([#1249](https://github.com/hiero-ledger/hiero-sdk-python/issues/1249))
74+
- Added `transfer_transaction_gigabar.py` example demonstrating `GIGABAR` unit usage for large-value transfers. ([#1249](https://github.com/hiero-ledger/hiero-sdk-python/issues/1249))
7375
- Coderabbit prompt for .github
7476
- Added merge conflict bot workflow (`.github/workflows/bot-merge-conflict.yml`) and helper script (`.github/scripts/bot-merge-conflict.js`) to detect and notify about PR merge conflicts, with retry logic for unknown mergeable states, idempotent commenting, and push-to-main recheck logic (#1247)
7577

@@ -115,6 +117,7 @@ This changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.
115117
- Added comprehensive unit tests for Timestamp class (#1158)
116118
- Enhance unit and integration test review instructions for clarity and coverage `.coderabbit.yaml`.
117119
- Issue reminder bot now explicitly mentions assignees (e.g., `@user`) in comments. ([#1232](https://github.com/hiero-ledger/hiero-sdk-python/issues/1232))
120+
- Updated `transfer_transaction_hbar.py` example to use `Hbar` objects instead of raw integers and added receipt checking with `ResponseCode` validation.([#1249](https://github.com/hiero-ledger/hiero-sdk-python/issues/1249))
118121

119122
### Fixed
120123

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
"""Example of transferring HBAR using the GIGABAR unit.
2+
3+
Usage:
4+
uv run examples/transaction/transfer_transaction_gigabar.py
5+
python examples/transaction/transfer_transaction_gigabar.py
6+
"""
7+
8+
import os
9+
import sys
10+
11+
from dotenv import load_dotenv
12+
13+
from hiero_sdk_python import (
14+
AccountCreateTransaction,
15+
AccountId,
16+
Client,
17+
CryptoGetAccountBalanceQuery,
18+
Hbar,
19+
HbarUnit,
20+
Network,
21+
PrivateKey,
22+
ResponseCode,
23+
TransferTransaction,
24+
)
25+
26+
load_dotenv()
27+
network_name = os.getenv("NETWORK", "testnet").lower()
28+
29+
# 0.00000001 Gigabars = 10 Hbar
30+
GIGABARS_TO_TRANSFER = 0.00000001
31+
32+
33+
def setup_client():
34+
"""Initialize and set up the client with operator account."""
35+
network = Network(network_name)
36+
print(f"Connecting to Hedera {network_name} network!")
37+
client = Client(network)
38+
39+
try:
40+
operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", ""))
41+
operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", ""))
42+
client.set_operator(operator_id, operator_key)
43+
print(f"Client set up with operator id {client.operator_account_id}")
44+
45+
return client, operator_id, operator_key
46+
except (TypeError, ValueError):
47+
print("❌ Error: Creating client, Please check your .env file")
48+
sys.exit(1)
49+
50+
51+
def create_account(client, operator_key):
52+
"""Create a new recipient account."""
53+
print("\nSTEP 1: Creating a new recipient account...")
54+
recipient_key = PrivateKey.generate()
55+
try:
56+
tx = AccountCreateTransaction().set_key(recipient_key.public_key()).set_initial_balance(Hbar.from_tinybars(0))
57+
58+
receipt = tx.freeze_with(client).sign(operator_key).execute(client)
59+
60+
if receipt.status != ResponseCode.SUCCESS:
61+
print(f"❌ Account creation failed with status: {ResponseCode(receipt.status).name}")
62+
sys.exit(1)
63+
64+
recipient_id = receipt.account_id
65+
print(f"✅ Success! Created a new recipient account with ID: {recipient_id}")
66+
return recipient_id, recipient_key
67+
68+
except Exception as e:
69+
print(f"Error creating new account: {e}")
70+
sys.exit(1)
71+
72+
73+
def transfer_gigabars(client, operator_id, recipient_id, operator_key):
74+
"""Transfer HBAR using the GIGABAR unit."""
75+
print(f"\nSTEP 2: Transferring {GIGABARS_TO_TRANSFER} GIGABARS...")
76+
print("(Note: 1 Gigabar = 1,000,000,000 Hbar)")
77+
78+
amount = Hbar.of(GIGABARS_TO_TRANSFER, HbarUnit.GIGABAR)
79+
80+
try:
81+
receipt = (
82+
TransferTransaction()
83+
.add_hbar_transfer(operator_id, amount.negated())
84+
.add_hbar_transfer(recipient_id, amount)
85+
.freeze_with(client)
86+
.sign(operator_key)
87+
.execute(client)
88+
)
89+
90+
if receipt.status == ResponseCode.SUCCESS:
91+
print(f"✅ Success! Transferred {amount} successfully.")
92+
else:
93+
print(f"❌ Failed with status: {receipt.status}")
94+
sys.exit(1)
95+
96+
except Exception as e:
97+
print(f"❌ Transfer failed: {str(e)}")
98+
sys.exit(1)
99+
100+
101+
def get_balance(client, account_id, when=""):
102+
"""Query and display account balance."""
103+
try:
104+
balance = CryptoGetAccountBalanceQuery(account_id=account_id).execute(client).hbars
105+
print(f"Recipient account balance{when}: {balance} hbars")
106+
return balance
107+
except Exception as e:
108+
print(f"❌ Balance query failed: {str(e)}")
109+
sys.exit(1)
110+
111+
112+
def main():
113+
"""Run example demonstrating large-value transfers using GIGABAR units.
114+
115+
Steps:
116+
1. Setup client.
117+
2. Create recipient account (0 balance).
118+
3. Transfer Gigabars using Hbar unit.
119+
4. Verify balance.
120+
"""
121+
client, operator_id, operator_key = setup_client()
122+
recipient_id, _ = create_account(client, operator_key)
123+
124+
transfer_gigabars(client, operator_id, recipient_id, operator_key)
125+
get_balance(client, recipient_id, " after transfer")
126+
127+
print("\n🎉 Example Finished Successfully!")
128+
129+
130+
if __name__ == "__main__":
131+
main()

examples/transaction/transfer_transaction_hbar.py

Lines changed: 50 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,35 @@
1-
"""
2-
uv run examples/transaction/transfer_transaction_hbar.py
3-
python examples/transaction/transfer_transaction_hbar.py
1+
"""Example of transferring HBAR using the Hiero Python SDK.
42
3+
Usage:
4+
uv run examples/transaction/transfer_transaction_hbar.py
5+
python examples/transaction/transfer_transaction_hbar.py
56
"""
67

78
import os
89
import sys
10+
911
from dotenv import load_dotenv
1012

1113
from hiero_sdk_python import (
12-
Client,
14+
AccountCreateTransaction,
1315
AccountId,
14-
PrivateKey,
16+
Client,
17+
CryptoGetAccountBalanceQuery,
18+
Hbar,
1519
Network,
20+
PrivateKey,
21+
ResponseCode,
1622
TransferTransaction,
17-
AccountCreateTransaction,
18-
Hbar,
19-
CryptoGetAccountBalanceQuery,
2023
)
2124

2225
load_dotenv()
2326
network_name = os.getenv("NETWORK", "testnet").lower()
2427

28+
HBAR_TO_TRANSFER = 1
29+
2530

2631
def setup_client():
27-
"""Initialize and set up the client with operator account"""
32+
"""Initialize and set up the client with operator account."""
2833
network = Network(network_name)
2934
print(f"Connecting to Hedera {network_name} network!")
3035
client = Client(network)
@@ -42,7 +47,7 @@ def setup_client():
4247

4348

4449
def create_account(client, operator_key):
45-
"""Create a new recipient account"""
50+
"""Create a new recipient account."""
4651
print("\nSTEP 1: Creating a new recipient account...")
4752
recipient_key = PrivateKey.generate()
4853
try:
@@ -52,6 +57,11 @@ def create_account(client, operator_key):
5257
.set_initial_balance(Hbar.from_tinybars(100_000_000))
5358
)
5459
receipt = tx.freeze_with(client).sign(operator_key).execute(client)
60+
61+
if receipt.status != ResponseCode.SUCCESS:
62+
print(f"❌ Account creation failed with status: {ResponseCode(receipt.status).name}")
63+
sys.exit(1)
64+
5565
recipient_id = receipt.account_id
5666
print(f"✅ Success! Created a new recipient account with ID: {recipient_id}")
5767
return recipient_id, recipient_key
@@ -61,31 +71,38 @@ def create_account(client, operator_key):
6171
sys.exit(1)
6272

6373

64-
def transfer_hbar(client, operator_id, recipient_id):
65-
"""Transfer HBAR from operator account to recipient account"""
66-
print("\nSTEP 2: Transfering HBAR...")
74+
def transfer_hbar(client, operator_id, recipient_id, operator_key):
75+
"""Transfer HBAR from operator account to recipient account."""
76+
print("\nSTEP 2: Transferring HBAR...")
77+
78+
amount = Hbar(HBAR_TO_TRANSFER) # HBAR object
6779

6880
try:
69-
transfer_tx = (
81+
receipt = (
7082
TransferTransaction()
71-
.add_hbar_transfer(operator_id, -100000000) # send 1 HBAR in tinybars
72-
.add_hbar_transfer(recipient_id, 100000000)
83+
.add_hbar_transfer(operator_id, amount.negated())
84+
.add_hbar_transfer(recipient_id, amount)
7385
.freeze_with(client)
86+
.sign(operator_key)
87+
.execute(client)
7488
)
75-
transfer_tx.execute(client)
7689

77-
print("\n✅ Success! HBAR transfer successful.\n")
90+
if receipt.status == ResponseCode.SUCCESS:
91+
print(f"\n✅ Success! Transferred {amount} to {recipient_id}.")
92+
print(f"Transaction ID: {receipt.transaction_id}\n")
93+
else:
94+
print(f"\n❌ Unexpected status: {receipt.status}")
95+
sys.exit(1)
96+
7897
except Exception as e:
7998
print(f"❌ HBAR transfer failed: {str(e)}")
8099
sys.exit(1)
81100

82101

83-
def account_balance_query(client, account_id, when=""):
84-
"""Query and display account balance"""
102+
def get_balance(client, account_id, when=""):
103+
"""Query and display account balance."""
85104
try:
86-
balance = (
87-
CryptoGetAccountBalanceQuery(account_id=account_id).execute(client).hbars
88-
)
105+
balance = CryptoGetAccountBalanceQuery(account_id=account_id).execute(client).hbars
89106
print(f"Recipient account balance{when}: {balance} hbars")
90107
return balance
91108
except Exception as e:
@@ -94,23 +111,23 @@ def account_balance_query(client, account_id, when=""):
94111

95112

96113
def main():
114+
"""Run a full example to create a new recipient account and transfer hbar to that account.
115+
116+
Steps:
117+
1. Setup client with operator credentials.
118+
2. Create a new account with initial balance.
119+
3. Transfer HBAR from operator to new account.
120+
4. Verify balance updates.
97121
"""
98-
A full example to create a new recipent account and transfer hbar to that account
99-
"""
100-
# Config Client
101122
client, operator_id, operator_key = setup_client()
102123

103-
# Create a new recipient account.
104124
recipient_id, _ = create_account(client, operator_key)
105125

106-
# Check balance before HBAR transfer
107-
account_balance_query(client, recipient_id, " before transfer")
126+
get_balance(client, recipient_id, " before transfer")
108127

109-
# Transfer HBAR
110-
transfer_hbar(client, operator_id, recipient_id)
128+
transfer_hbar(client, operator_id, recipient_id, operator_key)
111129

112-
# Check balance after HBAR transfer
113-
account_balance_query(client, recipient_id, " after transfer")
130+
get_balance(client, recipient_id, " after transfer")
114131

115132

116133
if __name__ == "__main__":

0 commit comments

Comments
 (0)