Skip to content

Commit 9a4c8d6

Browse files
authored
chore: format transaction examples with black (#1126)
Signed-off-by: Rahul Sangwan <[email protected]>
1 parent ec301a5 commit 9a4c8d6

File tree

7 files changed

+105
-65
lines changed

7 files changed

+105
-65
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ This changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.
4343
- Added Issue Reminder (no-PR) bot, .github/scripts/issue_reminder_no_pr.sh and .github/workflows/bot-issue-reminder-no-pr.yml to automatically detect assigned issues with no linked pull requests for 7+ days and post a gentle ReminderBot comment.(#951)
4444

4545
### Changed
46+
- Improved consistency of transaction examples (#1120)
4647
- Refactored `account_create_transaction_with_fallback_alias.py` by splitting the monolithic `create_account_with_fallback_alias` function into modular functions: `generate_fallback_key`, `fetch_account_info`, and `print_account_summary`. The existing `setup_client()` function was reused for improved readability and structure (#1018)
4748
- Allow `PublicKey` for `TokenUpdateKeys` in `TokenUpdateTransaction`, enabling non-custodial workflows where operators can build transactions using only public keys (#934).
4849
- Bump protobuf toml to protobuf==6.33.2

examples/transaction/batch_transaction.py

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
uv run examples/transaction/batch_transaction.py
33
"""
4+
45
import os
56
import sys
67

@@ -19,11 +20,12 @@
1920
TokenType,
2021
TokenUnfreezeTransaction,
2122
BatchTransaction,
22-
TransferTransaction
23+
TransferTransaction,
2324
)
2425

2526
load_dotenv()
2627

28+
2729
def get_balance(client, account_id, token_id):
2830
tokens_balance = (
2931
CryptoGetAccountBalanceQuery(account_id=account_id)
@@ -33,28 +35,30 @@ def get_balance(client, account_id, token_id):
3335

3436
print(f"Account: {account_id}: {tokens_balance[token_id] if tokens_balance else 0}")
3537

38+
3639
def setup_client():
3740
"""
3841
Set up and configure a Hedera client for testnet operations.
3942
"""
40-
network_name = os.getenv('NETWORK', 'testnet').lower()
43+
network_name = os.getenv("NETWORK", "testnet").lower()
4144

4245
print(f"Connecting to Hedera {network_name} network!")
4346

44-
try :
47+
try:
4548
network = Network(network_name)
4649
client = Client(network)
47-
48-
operator_id = AccountId.from_string(os.getenv('OPERATOR_ID',''))
49-
operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY',''))
50-
50+
51+
operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", ""))
52+
operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", ""))
53+
5154
client.set_operator(operator_id, operator_key)
5255
print(f"Client initialized with operator: {operator_id}")
5356
return client
5457
except Exception as e:
5558
print(f"Failed to set up client: {e}")
5659
sys.exit(1)
5760

61+
5862
def create_account(client):
5963
"""
6064
Create a new recipient account.
@@ -65,19 +69,22 @@ def create_account(client):
6569
tx = (
6670
AccountCreateTransaction()
6771
.set_key_without_alias(key.public_key())
68-
.set_max_automatic_token_associations(2) # to transfer token without associating it
72+
.set_max_automatic_token_associations(
73+
2
74+
) # to transfer token without associating it
6975
.set_initial_balance(1)
7076
)
71-
77+
7278
receipt = tx.freeze_with(client).execute(client)
7379
recipient_id = receipt.account_id
74-
80+
7581
print(f"New account created: {receipt.account_id}")
7682
return recipient_id
7783
except Exception as e:
7884
print(f"Error creating new account: {e}")
7985
sys.exit(1)
8086

87+
8188
def create_fungible_token(client, freeze_key):
8289
"""
8390
Create a fungible token with freeze_key.
@@ -106,6 +113,7 @@ def create_fungible_token(client, freeze_key):
106113
print(f"Error creating token: {e}")
107114
sys.exit(1)
108115

116+
109117
def freeze_token(client, account_id, token_id, freeze_key):
110118
"""
111119
Freeze token for an account.
@@ -121,16 +129,17 @@ def freeze_token(client, account_id, token_id, freeze_key):
121129
)
122130

123131
receipt = tx.execute(client)
124-
132+
125133
if receipt.status != ResponseCode.SUCCESS:
126134
print(f"Freeze failed: {ResponseCode(receipt.status).name})")
127135
sys.exit(1)
128-
136+
129137
print("Token freeze successful!")
130138
except Exception as e:
131139
print(f"Error freezing token for account: {e}")
132140
sys.exit(1)
133141

142+
134143
def transfer_token(client, sender, recipient, token_id):
135144
"""
136145
Perform a token trasfer transaction.
@@ -150,6 +159,7 @@ def transfer_token(client, sender, recipient, token_id):
150159
print(f"Error transfering token: {e}")
151160
sys.exit(1)
152161

162+
153163
def perform_batch_tx(client, sender, recipient, token_id, freeze_key):
154164
"""
155165
Perform a batch transaction.
@@ -193,6 +203,7 @@ def perform_batch_tx(client, sender, recipient, token_id, freeze_key):
193203
receipt = batch.execute(client)
194204
print(f"Batch transaction status: {ResponseCode(receipt.status).name}")
195205

206+
196207
def main():
197208
client = setup_client()
198209
freeze_key = PrivateKey.generate()
@@ -210,19 +221,21 @@ def main():
210221
else:
211222
print("\nExpected freeze to block transfer!")
212223
sys.exit(1)
213-
224+
214225
# Show balances
215226
print("\nBalances before batch:")
216227
get_balance(client, client.operator_account_id, token_id)
217228
get_balance(client, recipient_id, token_id)
218229

219230
# Batch unfreeze → transfer → freeze
220-
perform_batch_tx(client, client.operator_account_id, recipient_id, token_id, freeze_key)
231+
perform_batch_tx(
232+
client, client.operator_account_id, recipient_id, token_id, freeze_key
233+
)
221234

222235
print("\nBalances after batch:")
223236
get_balance(client, client.operator_account_id, token_id)
224-
get_balance(client, recipient_id,token_id)
225-
237+
get_balance(client, recipient_id, token_id)
238+
226239
# Should fail again Verify that token is again freeze for account
227240
receipt = transfer_token(client, client.operator_account_id, recipient_id, token_id)
228241
if receipt.status == ResponseCode.ACCOUNT_FROZEN_FOR_TOKEN:
@@ -233,4 +246,4 @@ def main():
233246

234247

235248
if __name__ == "__main__":
236-
main()
249+
main()

examples/transaction/custom_fee_limit.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def create_revenue_generating_topic(client: Client, operator_id: AccountId):
7878
print("This topic charges a fixed fee of 1 HBAR per message.")
7979

8080
return topic_id
81-
except Exception as e: # noqa: BLE001
81+
except Exception as e: # noqa: BLE001
8282
print(f"Failed to create topic: {e}")
8383
return None
8484

@@ -124,7 +124,7 @@ def submit_message_with_custom_fee_limit(
124124

125125
print("Message submitted successfully!")
126126
print(f"Transaction status: {submit_receipt.status}")
127-
except Exception as e: # noqa: BLE001
127+
except Exception as e: # noqa: BLE001
128128
print(f"Transaction failed: {e}")
129129

130130

examples/transaction/transaction_to_bytes.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,9 @@ def setup_client() -> Client:
5050
sys.exit(1)
5151

5252

53-
def create_and_freeze_transaction(client: Client, sender: AccountId, receiver: AccountId):
53+
def create_and_freeze_transaction(
54+
client: Client, sender: AccountId, receiver: AccountId
55+
):
5456
"""Create and freeze a simple HBAR transfer transaction."""
5557
tx = (
5658
TransferTransaction()

examples/transaction/transfer_transaction_fungible.py

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
python examples/transaction/transfer_transaction_fungible.py
44
55
"""
6+
67
import os
78
import sys
89
from dotenv import load_dotenv
@@ -17,11 +18,12 @@
1718
Hbar,
1819
TokenCreateTransaction,
1920
CryptoGetAccountBalanceQuery,
20-
TokenAssociateTransaction
21+
TokenAssociateTransaction,
2122
)
2223

2324
load_dotenv()
24-
network_name = os.getenv('NETWORK', 'testnet').lower()
25+
network_name = os.getenv("NETWORK", "testnet").lower()
26+
2527

2628
# --------------------------
2729
# CLIENT SETUP
@@ -33,8 +35,8 @@ def setup_client():
3335
client = Client(network)
3436

3537
try:
36-
operator_id = AccountId.from_string(os.getenv('OPERATOR_ID',''))
37-
operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY',''))
38+
operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", ""))
39+
operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", ""))
3840
client.set_operator(operator_id, operator_key)
3941
print(f"Client set up with operator id {client.operator_account_id}")
4042

@@ -43,6 +45,7 @@ def setup_client():
4345
print("❌ Error: Creating client, Please check your .env file")
4446
sys.exit(1)
4547

48+
4649
# --------------------------
4750
# ACCOUNT CREATION
4851
# --------------------------
@@ -60,11 +63,12 @@ def create_account(client, operator_key):
6063
recipient_id = receipt.account_id
6164
print(f"✅ Success! Created a new recipient account with ID: {recipient_id}")
6265
return recipient_id, recipient_key
63-
66+
6467
except Exception as e:
6568
print(f"Error creating new account: {e}")
6669
sys.exit(1)
67-
70+
71+
6872
# --------------------------
6973
# TOKEN CREATION
7074
# --------------------------
@@ -89,6 +93,7 @@ def create_token(client, operator_id, operator_key):
8993
print(f"❌ Error creating token: {e}")
9094
sys.exit(1)
9195

96+
9297
# --------------------------
9398
# TOKEN ASSOCIATION
9499
# --------------------------
@@ -107,8 +112,9 @@ def associate_token(client, recipient_id, recipient_key, token_id):
107112
print(f"❌ Error associating token: {e}")
108113
sys.exit(1)
109114

115+
110116
# --------------------------
111-
# ACCOUNT BALANCE QUERY
117+
# ACCOUNT BALANCE QUERY
112118
# --------------------------
113119
def account_balance_query(client, account_id):
114120
"""Query and return token balances for an account."""
@@ -119,8 +125,9 @@ def account_balance_query(client, account_id):
119125
print(f"❌ Error fetching account balance: {e}")
120126
sys.exit(1)
121127

128+
122129
# --------------------------
123-
# TRANSFER TRANSACTION
130+
# TRANSFER TRANSACTION
124131
# --------------------------
125132
def transfer_transaction(client, operator_id, operator_key, recipient_id, token_id):
126133
"""Execute a token transfer transaction."""
@@ -141,6 +148,7 @@ def transfer_transaction(client, operator_id, operator_key, recipient_id, token_
141148
print(f"❌ Error transferring token: {e}")
142149
sys.exit(1)
143150

151+
144152
# --------------------------
145153
# MAIN ORCHESTRATOR (RENAMED)
146154
# --------------------------
@@ -173,7 +181,6 @@ def main():
173181
balance_after = account_balance_query(client, recipient_id)
174182
print("Token balance AFTER transfer:")
175183
print(f"{token_id}: {balance_after.get(token_id)}")
176-
177184

178185

179186
if __name__ == "__main__":

examples/transaction/transfer_transaction_hbar.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
python examples/transaction/transfer_transaction_hbar.py
44
55
"""
6+
67
import os
78
import sys
89
from dotenv import load_dotenv
@@ -15,20 +16,22 @@
1516
TransferTransaction,
1617
AccountCreateTransaction,
1718
Hbar,
18-
CryptoGetAccountBalanceQuery
19+
CryptoGetAccountBalanceQuery,
1920
)
2021

2122
load_dotenv()
22-
network_name = os.getenv('NETWORK', 'testnet').lower()
23+
network_name = os.getenv("NETWORK", "testnet").lower()
24+
25+
2326
def setup_client():
2427
"""Initialize and set up the client with operator account"""
2528
network = Network(network_name)
2629
print(f"Connecting to Hedera {network_name} network!")
2730
client = Client(network)
2831

2932
try:
30-
operator_id = AccountId.from_string(os.getenv('OPERATOR_ID',''))
31-
operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY',''))
33+
operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", ""))
34+
operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", ""))
3235
client.set_operator(operator_id, operator_key)
3336
print(f"Client set up with operator id {client.operator_account_id}")
3437

@@ -52,11 +55,12 @@ def create_account(client, operator_key):
5255
recipient_id = receipt.account_id
5356
print(f"✅ Success! Created a new recipient account with ID: {recipient_id}")
5457
return recipient_id, recipient_key
55-
58+
5659
except Exception as e:
5760
print(f"Error creating new account: {e}")
5861
sys.exit(1)
5962

63+
6064
def transfer_hbar(client, operator_id, recipient_id):
6165
"""Transfer HBAR from operator account to recipient account"""
6266
print("\nSTEP 2: Transfering HBAR...")
@@ -69,7 +73,7 @@ def transfer_hbar(client, operator_id, recipient_id):
6973
.freeze_with(client)
7074
)
7175
transfer_tx.execute(client)
72-
76+
7377
print("\n✅ Success! HBAR transfer successful.\n")
7478
except Exception as e:
7579
print(f"❌ HBAR transfer failed: {str(e)}")
@@ -80,9 +84,7 @@ def account_balance_query(client, account_id, when=""):
8084
"""Query and display account balance"""
8185
try:
8286
balance = (
83-
CryptoGetAccountBalanceQuery(account_id=account_id)
84-
.execute(client)
85-
.hbars
87+
CryptoGetAccountBalanceQuery(account_id=account_id).execute(client).hbars
8688
)
8789
print(f"Recipient account balance{when}: {balance} hbars")
8890
return balance
@@ -110,5 +112,6 @@ def main():
110112
# Check balance after HBAR transfer
111113
account_balance_query(client, recipient_id, " after transfer")
112114

115+
113116
if __name__ == "__main__":
114117
main()

0 commit comments

Comments
 (0)