Skip to content

Commit cee7a49

Browse files
refactor: improve modularity of transfer_transaction_fungible example (#1023)
Signed-off-by: undefinedIsMyLife <shinetina169@gmail.com>
1 parent dd5fca5 commit cee7a49

File tree

2 files changed

+64
-35
lines changed

2 files changed

+64
-35
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ This changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.
77
## [Unreleased]
88

99
### Added
10+
- Modularized `transfer_transaction_fungible` example by introducing `account_balance_query()` & `transfer_transaction()`.Renamed `transfer_tokens()``main()`
1011
- Phase 2 of the inactivity-unassign bot:Automatically detects stale open pull requests (no commit activity for 21+ days), comments with a helpful InactivityBot message, closes the stale PR, and unassigns the contributor from the linked issue.
1112
- Added **str**() to CustomFixedFee and updated examples and tests accordingly.
1213
- Added a github template for good first issues

examples/transaction/transfer_transaction_fungible.py

Lines changed: 63 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@
2323
load_dotenv()
2424
network_name = os.getenv('NETWORK', 'testnet').lower()
2525

26+
# --------------------------
27+
# CLIENT SETUP
28+
# --------------------------
2629
def setup_client():
2730
"""Initialize and set up the client with operator account"""
2831
network = Network(network_name)
@@ -40,7 +43,9 @@ def setup_client():
4043
print("❌ Error: Creating client, Please check your .env file")
4144
sys.exit(1)
4245

43-
46+
# --------------------------
47+
# ACCOUNT CREATION
48+
# --------------------------
4449
def create_account(client, operator_key):
4550
"""Create a new recipient account"""
4651
print("\nSTEP 1: Creating a new recipient account...")
@@ -59,7 +64,10 @@ def create_account(client, operator_key):
5964
except Exception as e:
6065
print(f"Error creating new account: {e}")
6166
sys.exit(1)
62-
67+
68+
# --------------------------
69+
# TOKEN CREATION
70+
# --------------------------
6371
def create_token(client, operator_id, operator_key):
6472
print("\nSTEP 2: Creating a new token...")
6573
try:
@@ -81,6 +89,9 @@ def create_token(client, operator_id, operator_key):
8189
print(f"❌ Error creating token: {e}")
8290
sys.exit(1)
8391

92+
# --------------------------
93+
# TOKEN ASSOCIATION
94+
# --------------------------
8495
def associate_token(client, recipient_id, recipient_key, token_id):
8596
print("\nSTEP 3: Associating Token...")
8697
try:
@@ -96,7 +107,44 @@ def associate_token(client, recipient_id, recipient_key, token_id):
96107
print(f"❌ Error associating token: {e}")
97108
sys.exit(1)
98109

99-
def transfer_tokens():
110+
# --------------------------
111+
# ACCOUNT BALANCE QUERY
112+
# --------------------------
113+
def account_balance_query(client, account_id):
114+
"""Query and return token balances for an account."""
115+
try:
116+
result = CryptoGetAccountBalanceQuery(account_id=account_id).execute(client)
117+
return result.token_balances
118+
except Exception as e:
119+
print(f"❌ Error fetching account balance: {e}")
120+
sys.exit(1)
121+
122+
# --------------------------
123+
# TRANSFER TRANSACTION
124+
# --------------------------
125+
def transfer_transaction(client, operator_id, operator_key, recipient_id, token_id):
126+
"""Execute a token transfer transaction."""
127+
print("\nSTEP 4: Transfering Token...")
128+
try:
129+
tx = (
130+
TransferTransaction()
131+
.add_token_transfer(token_id, operator_id, -1)
132+
.add_token_transfer(token_id, recipient_id, 1)
133+
.freeze_with(client)
134+
.sign(operator_key)
135+
)
136+
137+
tx.execute(client)
138+
print("✅ Success! Token transfer complete.\n")
139+
140+
except Exception as e:
141+
print(f"❌ Error transferring token: {e}")
142+
sys.exit(1)
143+
144+
# --------------------------
145+
# MAIN ORCHESTRATOR (RENAMED)
146+
# --------------------------
147+
def main():
100148
"""
101149
A full example to create a new recipent account, a fungible token, and
102150
transfer the token to that account
@@ -113,40 +161,20 @@ def transfer_tokens():
113161
# Associate Token
114162
associate_token(client, recipient_id, recipient_key, token_id)
115163

116-
# Transfer Token
117-
print("\nSTEP 4: Transfering Token...")
118-
try:
119-
# Check balance before transfer
120-
balance_before = (
121-
CryptoGetAccountBalanceQuery(account_id=recipient_id)
122-
.execute(client)
123-
.token_balances
124-
)
125-
print("Token balance before token transfer:")
126-
print(f"{token_id}: {balance_before.get(token_id)}")
164+
# Balance before transfer
165+
balance_before = account_balance_query(client, recipient_id)
166+
print("Token balance BEFORE transfer:")
167+
print(f"{token_id}: {balance_before.get(token_id)}")
127168

128-
transfer_tx = (
129-
TransferTransaction()
130-
.add_token_transfer(token_id, operator_id, -1)
131-
.add_token_transfer(token_id, recipient_id, 1)
132-
.freeze_with(client)
133-
.sign(operator_key)
134-
)
135-
transfer_tx.execute(client)
169+
# Transfer
170+
transfer_transaction(client, operator_id, operator_key, recipient_id, token_id)
171+
172+
# Balance after transfer
173+
balance_after = account_balance_query(client, recipient_id)
174+
print("Token balance AFTER transfer:")
175+
print(f"{token_id}: {balance_after.get(token_id)}")
136176

137-
print("\n✅ Success! Token transfer complete.\n")
138177

139-
# Check balance after transfer
140-
balance_after = (
141-
CryptoGetAccountBalanceQuery(account_id=recipient_id)
142-
.execute(client)
143-
.token_balances
144-
)
145-
print("Token balance after token transfer:")
146-
print(f"{token_id}: {balance_after.get(token_id)}")
147-
except Exception as e:
148-
print(f"❌ Error transferring token: {str(e)}")
149-
sys.exit(1)
150178

151179
if __name__ == "__main__":
152-
transfer_tokens()
180+
main()

0 commit comments

Comments
 (0)