Skip to content

Commit cfa37d1

Browse files
authored
refactor(example): sync transaction_to_bytes with main (#1045)
Signed-off-by: dantesb777 <[email protected]>
1 parent c47d3b1 commit cfa37d1

File tree

1 file changed

+90
-65
lines changed

1 file changed

+90
-65
lines changed

examples/transaction/transaction_to_bytes.py

Lines changed: 90 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22
Example demonstrating transaction byte serialization and deserialization.
33
44
This example shows how to:
5-
- Freeze a transaction
6-
- Serialize to bytes (for storage, transmission, or external signing)
5+
- Create and freeze a transaction
6+
- Serialize to bytes (for storage, transmission, or signing)
77
- Deserialize from bytes
8-
- Sign after deserialization
8+
- Sign a deserialized transaction
99
1010
Run with:
11-
uv run examples/transaction/transaction_to_bytes.py
12-
python examples/transaction/transaction_to_bytes.py
11+
uv run examples/transaction/transaction_to_bytes.py
12+
python examples/transaction/transaction_to_bytes.py
1313
"""
1414

1515
import os
@@ -26,77 +26,102 @@
2626
)
2727

2828
load_dotenv()
29-
network_name = os.getenv('NETWORK', 'testnet').lower()
29+
NETWORK = os.getenv("NETWORK", "testnet").lower()
30+
OPERATOR_ID = os.getenv("OPERATOR_ID", "")
31+
OPERATOR_KEY = os.getenv("OPERATOR_KEY", "")
3032

31-
def setup_client():
32-
"""Initialize and set up the client with operator account"""
33-
network = Network(network_name)
34-
print(f"Connecting to Hedera {network_name} network!")
35-
client = Client(network)
3633

34+
def setup_client() -> Client:
35+
"""Initialize the client using operator credentials from .env."""
3736
try:
38-
operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', ''))
39-
operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', ''))
37+
network = Network(NETWORK)
38+
client = Client(network)
39+
40+
operator_id = AccountId.from_string(OPERATOR_ID)
41+
operator_key = PrivateKey.from_string(OPERATOR_KEY)
42+
4043
client.set_operator(operator_id, operator_key)
41-
print(f"Client set up with operator id {client.operator_account_id}")
42-
return client, operator_id, operator_key
43-
44-
except (TypeError, ValueError):
45-
print("❌ Error: Creating client, Please check your .env file")
46-
sys.exit(1)
4744

45+
print(f"Connected to network '{NETWORK}' as {operator_id}")
46+
return client
4847

49-
def transaction_bytes_example():
50-
"""
51-
Demonstrates transaction serialization and deserialization workflow.
52-
"""
53-
client, operator_id, operator_key = setup_client()
48+
except Exception as e:
49+
print(f"❌ Error initializing client: {e}")
50+
sys.exit(1)
5451

55-
receiver_id = AccountId.from_string("0.0.3") # Node account
5652

57-
# Step 1: Create and freeze transaction
58-
print("\nSTEP 1: Creating and freezing transaction...")
59-
transaction = (
53+
def create_and_freeze_transaction(client: Client, sender: AccountId, receiver: AccountId):
54+
"""Create and freeze a simple HBAR transfer transaction."""
55+
tx = (
6056
TransferTransaction()
61-
.add_hbar_transfer(operator_id, -100_000_000) # -1 HBAR
62-
.add_hbar_transfer(receiver_id, 100_000_000) # +1 HBAR
57+
.add_hbar_transfer(sender, -100_000_000) # -1 HBAR
58+
.add_hbar_transfer(receiver, 100_000_000) # +1 HBAR
6359
.set_transaction_memo("Transaction bytes example")
6460
)
65-
transaction.freeze_with(client)
66-
print(f"✅ Transaction frozen with ID: {transaction.transaction_id}")
67-
68-
# Step 2: Serialize to bytes
69-
print("\nSTEP 2: Serializing transaction to bytes...")
70-
transaction_bytes = transaction.to_bytes()
71-
print(f"✅ Transaction serialized: {len(transaction_bytes)} bytes")
72-
print(f" First 40 bytes (hex): {transaction_bytes[:40].hex()}")
73-
74-
# Step 3: Deserialize from bytes
75-
print("\nSTEP 3: Deserializing transaction from bytes...")
76-
restored_transaction = Transaction.from_bytes(transaction_bytes)
77-
print(f"✅ Transaction restored from bytes")
78-
print(f" Transaction ID: {restored_transaction.transaction_id}")
79-
print(f" Node ID: {restored_transaction.node_account_id}")
80-
print(f" Memo: {restored_transaction.memo}")
81-
82-
# Step 4: Sign the restored transaction
83-
print("\nSTEP 4: Signing the restored transaction...")
84-
restored_transaction.sign(operator_key)
85-
print(f"✅ Transaction signed")
86-
87-
# Step 5: Verify round-trip produces identical bytes
88-
print("\nSTEP 5: Verifying serialization...")
89-
original_signed = transaction.sign(operator_key).to_bytes()
90-
final_bytes = restored_transaction.to_bytes()
91-
print(f"✅ Round-trip successful")
92-
93-
print("\n✅ Example completed successfully!")
94-
print("\nUse cases for transaction bytes:")
95-
print(" • Store transactions in a database")
96-
print(" • Send transactions to external signing services (HSM, hardware wallet)")
97-
print(" • Transmit transactions over a network")
98-
print(" • Create offline signing workflows")
61+
62+
tx.freeze_with(client)
63+
# print a concise confirmation for the user
64+
print(f"✅ Transaction frozen with ID: {tx.transaction_id}")
65+
return tx
66+
67+
68+
def serialize_transaction(transaction: Transaction) -> bytes:
69+
"""Serialize transaction to bytes."""
70+
tx_bytes = transaction.to_bytes()
71+
print(f"✅ Transaction serialized: {len(tx_bytes)} bytes")
72+
print(f" Preview (first 40 bytes hex): {tx_bytes[:40].hex()}")
73+
return tx_bytes
74+
75+
76+
def deserialize_transaction(bytes_data: bytes) -> Transaction:
77+
"""Restore a transaction from its byte representation."""
78+
restored = Transaction.from_bytes(bytes_data)
79+
print("✅ Transaction restored from bytes")
80+
print(f" Restored ID: {restored.transaction_id}")
81+
print(f" Memo: {restored.memo}")
82+
return restored
83+
84+
85+
def main():
86+
# Initialize client (exits with message if fails)
87+
client = setup_client()
88+
89+
# obtain operator information from the client
90+
operator_id = client.operator_account_id
91+
operator_key = client.operator_private_key
92+
93+
# receiver example (adjust as needed)
94+
receiver_id = AccountId.from_string("0.0.3")
95+
96+
try:
97+
print("\nSTEP 1 — Creating and freezing transaction...")
98+
tx = create_and_freeze_transaction(client, operator_id, receiver_id)
99+
100+
print("\nSTEP 2 — Serializing transaction...")
101+
tx_bytes = serialize_transaction(tx)
102+
103+
print("\nSTEP 3 — Deserializing transaction...")
104+
restored_tx = deserialize_transaction(tx_bytes)
105+
106+
print("\nSTEP 4 — Signing restored transaction...")
107+
restored_tx.sign(operator_key)
108+
print("✅ Signed restored transaction successfully.")
109+
110+
print("\nSTEP 5 — Verifying round-trip (signed bytes comparison)...")
111+
# Sign the original transaction as well to compare the signed bytes
112+
original_signed_bytes = tx.sign(operator_key).to_bytes()
113+
restored_signed_bytes = restored_tx.to_bytes()
114+
115+
if original_signed_bytes == restored_signed_bytes:
116+
print("✅ Round-trip serialization successful.")
117+
else:
118+
print("❌ Round-trip mismatch!")
119+
120+
print("\nExample completed.")
121+
122+
except Exception as e:
123+
print(f"❌ Error in example flow: {e}")
99124

100125

101126
if __name__ == "__main__":
102-
transaction_bytes_example()
127+
main()

0 commit comments

Comments
 (0)