diff --git a/.github/scripts/bot-assignment-check.sh b/.github/scripts/bot-assignment-check.sh index 4fe5d8ce8..50212d7ca 100644 --- a/.github/scripts/bot-assignment-check.sh +++ b/.github/scripts/bot-assignment-check.sh @@ -36,8 +36,7 @@ issue_has_gfi() { } assignments_count() { - # Count only issues (not PRs) assigned to the user, using structured isPullRequest field - gh issue list --repo "${REPO}" --assignee "${ASSIGNEE}" --state open --limit 100 --json number,isPullRequest --jq '[.[] | select(.isPullRequest | not)] | length' + gh issue list --repo "${REPO}" --assignee "${ASSIGNEE}" --state open --limit 100 --json number --jq 'length' } remove_assignee() { @@ -76,7 +75,7 @@ Hi @$ASSIGNEE, this is the Assignment Bot. :warning: **Assignment Limit Exceeded** -Your account currently has limited assignment privileges with a maximum of **1 open issue assignment** at a time. +Your account currently has limited assignment privileges with a maximum of **1 open assignment** at a time. You currently have $count open issue(s) assigned. Please complete and merge your existing assignment before requesting a new one. @@ -97,7 +96,7 @@ msg_normal_limit_exceeded() { cat < None: - """ - Create a new Hedera account with generated keys and initial balance. - - This function generates a new Ed25519 key pair, creates an account creation - transaction, signs it with the operator key, and executes it on the network. - The new account is created with an initial balance and a custom memo. - - Args: - client (Client): Configured Hedera client instance with operator set - - Returns: - None: This function doesn't return a value but prints the results - - Raises: - Exception: If the transaction fails or the account ID is not found in the receipt - SystemExit: Calls sys.exit(1) if account creation fails - - Side Effects: - - Prints transaction status and account details to stdout - - Creates a new account on the Hedera network - - Deducts transaction fees from the operator account - - Exits the program with code 1 if creation fails - - Example Output: - Transaction status: ResponseCode.SUCCESS - Account creation successful. New Account ID: 0.0.123456 - New Account Private Key: 302e020100300506032b657004220420... - New Account Public Key: 302a300506032b6570032100... - """ - new_account_private_key = PrivateKey.generate("ed25519") - new_account_public_key = new_account_private_key.public_key() - - # Get the operator key from the client for signing - operator_key = client.operator_private_key - - transaction = ( - AccountCreateTransaction() - .set_key_without_alias(new_account_public_key) - .set_initial_balance(100000000) # 1 HBAR in tinybars - .set_account_memo("My new account") - ) - - try: - # Explicit signing with key retrieved from client - receipt = transaction.freeze_with(client).sign(operator_key).execute(client) - print(f"Transaction status: {receipt.status}") - - if receipt.status != ResponseCode.SUCCESS: - status_message = ResponseCode(receipt.status).name - raise Exception(f"Transaction failed with status: {status_message}") - - new_account_id = receipt.account_id - if new_account_id is not None: - print(f"✅ Account creation successful. New Account ID: {new_account_id}") - print(f" New Account Private Key: {new_account_private_key.to_string()}") - print(f" New Account Public Key: {new_account_public_key.to_string()}") - else: - raise Exception( - "AccountID not found in receipt. Account may not have been created." - ) - - except Exception as e: - print(f"❌ Account creation failed: {str(e)}") - sys.exit(1) - - -if __name__ == "__main__": - client = Client.from_env() - print(f"Operator: {client.operator_account_id}") - create_new_account(client) - client.close() +""" + +Account Creation Example. + +This module demonstrates how to create a new Hedera account using the Hiero Python SDK. +It shows the complete workflow from setting up a client with operator credentials +to creating a new account and handling the transaction response. + +The example creates an account with: +- A generated Ed25519 key pair +- An initial balance of 1 HBAR (100,000,000 tinybars) +- A custom account memo + +Usage: + Run this script directly: + python examples/account/account_create_transaction.py + + Or using uv: + uv run examples/account/account_create_transaction.py + +Requirements: + - Environment variables OPERATOR_ID and OPERATOR_KEY must be set + - A .env file with the operator credentials (recommended) + - Sufficient HBAR balance in the operator account to pay for account creation + +Environment Variables: + OPERATOR_ID (str): The account ID of the operator (format: "0.0.xxxxx") + OPERATOR_KEY (str): The private key of the operator account + NETWORK (str, optional): Network to use (default: "testnet") +""" + +import sys + +from hiero_sdk_python import ( + AccountCreateTransaction, + Client, + PrivateKey, + ResponseCode, +) + + +def create_new_account(client: Client) -> None: + """Create a new Hedera account with generated keys and initial balance. + + This function generates a new Ed25519 key pair, creates an account creation + transaction, signs it with the operator key, and executes it on the network. + The new account is created with an initial balance and a custom memo. + + Args: + client (Client): Configured Hedera client instance with operator set + + Returns: + None: This function doesn't return a value but prints the results + + Raises: + Exception: If the transaction fails or the account ID is not found in the receipt + SystemExit: Calls sys.exit(1) if account creation fails + + Side Effects: + - Prints transaction status and account details to stdout + - Creates a new account on the Hedera network + - Deducts transaction fees from the operator account + - Exits the program with code 1 if creation fails + + Example Output: + Transaction status: ResponseCode.SUCCESS + Account creation successful. New Account ID: 0.0.123456 + New Account Private Key: 302e020100300506032b657004220420... + New Account Public Key: 302a300506032b6570032100... + """ + new_account_private_key = PrivateKey.generate("ed25519") + new_account_public_key = new_account_private_key.public_key() + + # Get the operator key from the client for signing + operator_key = client.operator_private_key + + transaction = ( + AccountCreateTransaction() + .set_key_without_alias(new_account_public_key) + .set_initial_balance(100000000) # 1 HBAR in tinybars + .set_account_memo("My new account") + ) + + try: + # Explicit signing with key retrieved from client + receipt = transaction.freeze_with(client).sign(operator_key).execute(client) + print(f"Transaction status: {receipt.status}") + + if receipt.status != ResponseCode.SUCCESS: + status_message = ResponseCode(receipt.status).name + raise Exception(f"Transaction failed with status: {status_message}") + + new_account_id = receipt.account_id + if new_account_id is not None: + print(f"✅ Account creation successful. New Account ID: {new_account_id}") + print(f" New Account Private Key: {new_account_private_key.to_string()}") + print(f" New Account Public Key: {new_account_public_key.to_string()}") + else: + raise Exception( + "AccountID not found in receipt. Account may not have been created." + ) + + except Exception as e: + print(f"❌ Account creation failed: {str(e)}") + sys.exit(1) + + +if __name__ == "__main__": + client = Client.from_env() + print(f"Operator: {client.operator_account_id}") + create_new_account(client) + client.close() diff --git a/examples/account/account_create_transaction_create_with_alias.py b/examples/account/account_create_transaction_create_with_alias.py index 11b0f03c4..093c2cf2d 100644 --- a/examples/account/account_create_transaction_create_with_alias.py +++ b/examples/account/account_create_transaction_create_with_alias.py @@ -1,4 +1,5 @@ -"""Example: Create an account using a separate ECDSA key for the EVM alias. +""" +Example: Create an account using a separate ECDSA key for the EVM alias. This demonstrates: - Using a "main" key for the account @@ -40,7 +41,9 @@ def setup_client() -> Client: def generate_main_and_alias_keys() -> tuple[PrivateKey, PrivateKey]: - """Generate the main account key and a separate ECDSA alias key. + """ + + Generate the main account key and a separate ECDSA alias key. Returns: tuple: (main_private_key, alias_private_key) @@ -71,7 +74,9 @@ def generate_main_and_alias_keys() -> tuple[PrivateKey, PrivateKey]: def create_account_with_ecdsa_alias( client: Client, main_private_key: PrivateKey, alias_private_key: PrivateKey ) -> AccountId: - """Create an account with a separate ECDSA key as the EVM alias. + """ + + Create an account with a separate ECDSA key as the EVM alias. This uses `set_key_with_alias` to map the main key to the alias key. The transaction requires signatures from both the alias key (to authorize @@ -113,7 +118,9 @@ def create_account_with_ecdsa_alias( def fetch_account_info(client: Client, account_id: AccountId) -> AccountInfo: - """Fetch account information from the network. + """ + + Fetch account information from the network. Args: client: The Hedera client. @@ -128,7 +135,9 @@ def fetch_account_info(client: Client, account_id: AccountId) -> AccountInfo: def print_account_summary(account_info: AccountInfo) -> None: - """Print a summary of the account information. + """ + + Print a summary of the account information. Args: account_info: The account info object to display. diff --git a/examples/account/account_create_transaction_evm_alias.py b/examples/account/account_create_transaction_evm_alias.py index fc5caa23e..9e151a798 100644 --- a/examples/account/account_create_transaction_evm_alias.py +++ b/examples/account/account_create_transaction_evm_alias.py @@ -1,4 +1,6 @@ -"""Example: Create an account using an EVM-style alias (evm_address). +""" + +Example: Create an account using an EVM-style alias (evm_address). This example demonstrates: 1. Generating an ECDSA key pair (required for EVM compatibility). @@ -10,7 +12,6 @@ uv run examples/account/account_create_transaction_evm_alias.py python examples/account/account_create_transaction_evm_alias.py """ - import sys from dotenv import load_dotenv @@ -43,7 +44,9 @@ def setup_client() -> Client: def generate_alias_key() -> tuple[PrivateKey, PublicKey, EvmAddress]: - """Generate a new ECDSA key pair and derive its EVM-style alias address. + """ + + Generate a new ECDSA key pair and derive its EVM-style alias address. EVM aliases on Hedera must be derived from an ECDSA (secp256k1) key pair. The EVM address is the last 20 bytes of the keccak256 hash of the public key. @@ -74,7 +77,9 @@ def generate_alias_key() -> tuple[PrivateKey, PublicKey, EvmAddress]: def create_account_with_alias( client: Client, private_key: PrivateKey, public_key: PublicKey, evm_address: EvmAddress ) -> AccountId: - """Create a new Hedera account using the provided EVM-style alias. + """ + + Create a new Hedera account using the provided EVM-style alias. Important: When creating an account with an alias, the transaction must be signed by the private key corresponding to that alias. This proves ownership diff --git a/examples/account/account_create_transaction_with_fallback_alias.py b/examples/account/account_create_transaction_with_fallback_alias.py index 49661e09a..3f526f3d2 100644 --- a/examples/account/account_create_transaction_with_fallback_alias.py +++ b/examples/account/account_create_transaction_with_fallback_alias.py @@ -1,4 +1,6 @@ -"""Example: Create an account where the EVM alias is derived from the main ECDSA key. +""" + +Example: Create an account where the EVM alias is derived from the main ECDSA key. This demonstrates: - Passing only an ECDSA PrivateKey to `set_key_with_alias` @@ -8,7 +10,6 @@ uv run examples/account/account_create_transaction_with_fallback_alias.py python examples/account/account_create_transaction_with_fallback_alias.py """ - import sys from dotenv import load_dotenv diff --git a/examples/account/account_create_transaction_without_alias.py b/examples/account/account_create_transaction_without_alias.py index 63abbd6dc..4c5544419 100644 --- a/examples/account/account_create_transaction_without_alias.py +++ b/examples/account/account_create_transaction_without_alias.py @@ -1,4 +1,6 @@ """ + + Example: Create an account without using any alias. This demonstrates: @@ -9,22 +11,21 @@ - uv run python examples/account/account_create_transaction_without_alias.py - python examples/account/account_create_transaction_without_alias.py """ - -from typing import Tuple import sys from hiero_sdk_python import ( - Client, - PrivateKey, - PublicKey, AccountCreateTransaction, - AccountInfoQuery, AccountId, AccountInfo, + AccountInfoQuery, + Client, Hbar, + PrivateKey, + PublicKey, ResponseCode, ) + def setup_client() -> Client: """Setup Client.""" client = Client.from_env() @@ -32,7 +33,7 @@ def setup_client() -> Client: print(f"Client set up with operator id {client.operator_account_id}") return client -def generate_account_key() -> Tuple[PrivateKey, PublicKey]: +def generate_account_key() -> tuple[PrivateKey, PublicKey]: """Generate a key pair for the account.""" print("\nSTEP 1: Generating a key pair for the account (no alias)...") account_private_key = PrivateKey.generate() @@ -73,12 +74,11 @@ def create_account_without_alias(client: Client, account_public_key: PublicKey, def fetch_account_info(client: Client, account_id: AccountId) -> AccountInfo: """Fetch account information.""" - account_info = ( + return ( AccountInfoQuery() .set_account_id(account_id) .execute(client) ) - return account_info def main() -> None: """Main entry point.""" diff --git a/examples/account/account_delete_transaction.py b/examples/account/account_delete_transaction.py index aeb9ff02c..ba20ae856 100644 --- a/examples/account/account_delete_transaction.py +++ b/examples/account/account_delete_transaction.py @@ -1,24 +1,27 @@ """ + + Example demonstrating account delete functionality. + Run: uv run examples/account/account_delete_transaction.py python examples/account/account_delete_transaction.py """ - import sys + from hiero_sdk_python import ( + AccountCreateTransaction, + AccountDeleteTransaction, Client, Hbar, PrivateKey, - AccountCreateTransaction, - AccountDeleteTransaction, ResponseCode, ) def create_account(client): - """Create a test account""" + """Create a test account.""" account_private_key = PrivateKey.generate_ed25519() account_public_key = account_private_key.public_key() @@ -47,9 +50,10 @@ def create_account(client): def account_delete(): """ Demonstrates account delete functionality by: + 1. Setting up client with operator account 2. Creating an account - 3. Deleting the account + 3. Deleting the account. """ client = Client.from_env() diff --git a/examples/account/account_id.py b/examples/account/account_id.py index 0aff4d66e..1088883e9 100644 --- a/examples/account/account_id.py +++ b/examples/account/account_id.py @@ -1,4 +1,7 @@ """ + +Example: Account Id. + uv run examples/account/account_id.py python examples/account/account_id.py @@ -8,7 +11,6 @@ 3. Comparing AccountId instances 4. Creating an AccountId with a public key alias """ - from hiero_sdk_python import AccountId, PrivateKey @@ -111,9 +113,7 @@ def create_account_id_with_alias(): def main(): - """ - Main function that runs all AccountId examples. - """ + """Main function that runs all AccountId examples.""" print("=" * 60) print("AccountId Examples") print("=" * 60) diff --git a/examples/account/account_id_populate_from_mirror.py b/examples/account/account_id_populate_from_mirror.py index 463787373..bee0edcba 100644 --- a/examples/account/account_id_populate_from_mirror.py +++ b/examples/account/account_id_populate_from_mirror.py @@ -1,4 +1,7 @@ """ + +Example: Account Id Populate From Mirror. + uv run examples/account/account_id_populate_from_mirror.py python examples/account/account_id_populate_from_mirror.py @@ -10,31 +13,29 @@ 3. Populate account number (num) from mirror node 4. Populate EVM address from mirror node """ - import sys import time from hiero_sdk_python import ( - Client, AccountId, - PrivateKey, - TransferTransaction, + Client, Hbar, + PrivateKey, TransactionGetReceiptQuery, + TransferTransaction, ) def generate_evm_address(): - """ - Generates a new ECDSA key pair and returns its EVM address. - """ + """Generates a new ECDSA key pair and returns its EVM address.""" private_key = PrivateKey.generate_ecdsa() return private_key.public_key().to_evm_address() def auto_create_account(client, evm_address): """ - Triggers auto account creation by transferring HBAR + Triggers auto account creation by transferring HBAR. + to an EVM address. """ print("\nAuto Account Creation...") @@ -69,9 +70,7 @@ def auto_create_account(client, evm_address): def populate_account_num_example(client, evm_address, created_account_id): - """ - Demonstrates populating AccountId.num from the mirror node. - """ + """Demonstrates populating AccountId.num from the mirror node.""" print("\nExample 1: Populate Account Number from Mirror Node...") mirror_account_id = AccountId.from_evm_address(evm_address, 0, 0) @@ -100,9 +99,7 @@ def populate_account_num_example(client, evm_address, created_account_id): def populate_evm_address_example(client, created_account_id, evm_address): - """ - Demonstrates populating AccountId.evm_address from the mirror node. - """ + """Demonstrates populating AccountId.evm_address from the mirror node.""" print("\nExample 2: Populate EVM Address from Mirror Node") print(f"Before populate: evm_address = {created_account_id.evm_address}") diff --git a/examples/account/account_info.py b/examples/account/account_info.py index fc1cfef9f..a9e2a977b 100644 --- a/examples/account/account_info.py +++ b/examples/account/account_info.py @@ -1,16 +1,19 @@ """ -uv run examples/account/account_info.py + +Example: Account Info. + +uv run examples/account/account_info.py. """ from hiero_sdk_python.account.account_id import AccountId +from hiero_sdk_python.account.account_info import AccountInfo from hiero_sdk_python.crypto.private_key import PrivateKey from hiero_sdk_python.crypto.public_key import PublicKey +from hiero_sdk_python.Duration import Duration from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.timestamp import Timestamp -from hiero_sdk_python.Duration import Duration from hiero_sdk_python.tokens.token_id import TokenId from hiero_sdk_python.tokens.token_relationship import TokenRelationship -from hiero_sdk_python.account.account_info import AccountInfo def create_mock_account_id() -> AccountId: @@ -21,8 +24,7 @@ def create_mock_account_id() -> AccountId: def create_mock_public_key() -> PublicKey: """Generate a random ED25519 public key for demonstration.""" private_key_demo = PrivateKey.generate_ecdsa() - public_key_demo = private_key_demo.public_key() - return public_key_demo + return private_key_demo.public_key() def create_mock_balance() -> Hbar: diff --git a/examples/account/account_records_query.py b/examples/account/account_records_query.py index 9f1430fa2..9cf429101 100644 --- a/examples/account/account_records_query.py +++ b/examples/account/account_records_query.py @@ -1,9 +1,11 @@ """ + + Example demonstrating account records query on the network. + uv run examples/account/account_records_query.py python examples/account/account_records_query.py """ - import os import sys @@ -27,7 +29,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -41,7 +43,7 @@ def setup_client(): def create_account(client): - """Create a test account""" + """Create a test account.""" account_private_key = PrivateKey.generate_ed25519() account_public_key = account_private_key.public_key() @@ -67,7 +69,7 @@ def create_account(client): def format_single_record(record, idx): - """Format a single account record""" + """Format a single account record.""" lines = [] lines.append(f"\nRecord #{idx}") lines.append("-" * 80) @@ -94,7 +96,7 @@ def format_single_record(record, idx): transfers = getattr(record, "transfers", None) if transfers: - lines.append(f" Transfers:") + lines.append(" Transfers:") for account_id, amount_in_tinybar in transfers.items(): amount_hbar = amount_in_tinybar / 100_000_000 # Convert tinybar to hbar lines.append(f" {account_id}: {amount_hbar:+.8f} ℏ") @@ -104,7 +106,7 @@ def format_single_record(record, idx): def format_account_records(records): - """Format account records for readable display""" + """Format account records for readable display.""" if not records: return "No records found" @@ -120,11 +122,12 @@ def format_account_records(records): def query_account_records(): """ Demonstrates the account record query functionality by: + 1. Setting up client with operator account 2. Creating a new account and setting it as the operator 3. Querying account records and displaying basic information 4. Performing a transfer transaction - 5. Querying account records again to see updated transaction history + 5. Querying account records again to see updated transaction history. """ client = setup_client() diff --git a/examples/account/account_update_transaction.py b/examples/account/account_update_transaction.py index e496a4364..b68355767 100644 --- a/examples/account/account_update_transaction.py +++ b/examples/account/account_update_transaction.py @@ -1,10 +1,12 @@ """ + + Example demonstrating account update functionality. + run with: uv run examples/account/account_update_transaction.py python examples/account/account_update_transaction.py """ - import datetime import os import sys @@ -24,7 +26,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -38,7 +40,7 @@ def setup_client(): def create_account(client): - """Create a test account""" + """Create a test account.""" account_private_key = PrivateKey.generate_ed25519() account_public_key = account_private_key.public_key() @@ -65,7 +67,7 @@ def create_account(client): def query_account_info(client, account_id): - """Query and display account information""" + """Query and display account information.""" info = AccountInfoQuery(account_id).execute(client) print(f"Account ID: {info.account_id}") @@ -80,11 +82,12 @@ def query_account_info(client, account_id): def account_update(): """ Demonstrates account update functionality by: + 1. Setting up client with operator account 2. Creating a test account 3. Querying the account info 4. Updating the account properties - 5. Querying the account info again + 5. Querying the account info again. """ client = setup_client() diff --git a/examples/client/client.py b/examples/client/client.py index 1cd7e8a40..552a938a5 100644 --- a/examples/client/client.py +++ b/examples/client/client.py @@ -1,4 +1,6 @@ """ + + Complete network and client setup example with detailed logging. This example demonstrates the internal steps of setting up a client @@ -9,11 +11,11 @@ uv run examples/client/client.py python examples/client/client.py """ - import os + from dotenv import load_dotenv -from hiero_sdk_python import Client, Network, AccountId, PrivateKey +from hiero_sdk_python import AccountId, Client, Network, PrivateKey load_dotenv() @@ -61,7 +63,7 @@ def setup_operator(client): def display_client_configuration(client): """Display client configuration details.""" print("\n=== Client Configuration ===") - print(f"Client is ready to use!") + print("Client is ready to use!") print(f"Max retry attempts: {client.max_attempts}") nodes = client.get_node_account_ids() @@ -74,7 +76,7 @@ def display_available_nodes(client): nodes = client.get_node_account_ids() # showing first 5 Nodes - for i, node_id in enumerate(nodes[:5]): + for _i, node_id in enumerate(nodes[:5]): print(f" - Node: {node_id}") if len(nodes) > 5: diff --git a/examples/consensus/topic_create_transaction.py b/examples/consensus/topic_create_transaction.py index 553c729a7..756974317 100644 --- a/examples/consensus/topic_create_transaction.py +++ b/examples/consensus/topic_create_transaction.py @@ -1,12 +1,17 @@ """ + +Example demonstrating topic create transaction. + uv run examples/consensus/topic_create_transaction.py python examples/consensus/topic_create_transaction.py """ -from hiero_sdk_python import Client, TopicCreateTransaction, ResponseCode, PrivateKey +from hiero_sdk_python import Client, PrivateKey, ResponseCode, TopicCreateTransaction + def setup_client(): """ Sets up and configures the Hiero client. + Reads OPERATOR_ID and OPERATOR_KEY from environment variables via Client.from_env(). """ client = Client.from_env() @@ -15,9 +20,7 @@ def setup_client(): return client, client.operator_private_key def create_topic(client: Client, operator_key: PrivateKey): - """ - Builds, signs, and executes a new topic creation transaction. - """ + """Builds, signs, and executes a new topic creation transaction.""" transaction = ( TopicCreateTransaction( memo="Python SDK created topic", admin_key=operator_key.public_key() @@ -39,9 +42,7 @@ def create_topic(client: Client, operator_key: PrivateKey): raise SystemExit(1) def main(): - """ - Main workflow to set up the client and create a new topic. - """ + """Main workflow to set up the client and create a new topic.""" client, operator_key = setup_client() create_topic(client, operator_key) diff --git a/examples/consensus/topic_create_transaction_revenue_generating.py b/examples/consensus/topic_create_transaction_revenue_generating.py index 7a513cffb..f981661eb 100644 --- a/examples/consensus/topic_create_transaction_revenue_generating.py +++ b/examples/consensus/topic_create_transaction_revenue_generating.py @@ -1,5 +1,7 @@ """ -Revenue Generating Topics Example + + +Revenue Generating Topics Example. This example demonstrates how to create and use revenue generating topics with custom fees. It covers: @@ -14,7 +16,6 @@ uv run examples/consensus/topic_create_transaction_revenue_generating.py python examples/consensus/topic_create_transaction_revenue_generating.py """ - import os import sys @@ -45,7 +46,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -59,7 +60,7 @@ def setup_client(): def create_account(client, name, initial_balance=Hbar(10)): - """Create a test account""" + """Create a test account.""" account_private_key = PrivateKey.generate_ed25519() account_public_key = account_private_key.public_key() @@ -83,7 +84,7 @@ def create_account(client, name, initial_balance=Hbar(10)): def create_revenue_generating_topic(client, custom_fees): - """Create a revenue generating topic with custom fees""" + """Create a revenue generating topic with custom fees.""" receipt = ( TopicCreateTransaction() .set_admin_key(client.operator_private_key.public_key()) @@ -103,7 +104,7 @@ def create_revenue_generating_topic(client, custom_fees): def submit_message_with_custom_fee_limit(client, topic_id, custom_fee_limit): - """Submit a message to a topic with custom fee limit""" + """Submit a message to a topic with custom fee limit.""" tx = ( TopicMessageSubmitTransaction() .set_topic_id(topic_id) @@ -124,7 +125,7 @@ def submit_message_with_custom_fee_limit(client, topic_id, custom_fee_limit): def submit_message_without_custom_fee_limit(client, topic_id): - """Submit a message to a topic without custom fee limit""" + """Submit a message to a topic without custom fee limit.""" tx = TopicMessageSubmitTransaction().set_message("message").set_topic_id(topic_id) tx.transaction_fee = Hbar(2).to_tinybars() receipt = tx.execute(client) @@ -140,9 +141,8 @@ def submit_message_without_custom_fee_limit(client, topic_id): def get_account_balance(client, account_id): - """Get the balance of an account""" - balance = CryptoGetAccountBalanceQuery(account_id).execute(client) - return balance + """Get the balance of an account.""" + return CryptoGetAccountBalanceQuery(account_id).execute(client) def create_fungible_token( @@ -151,7 +151,7 @@ def create_fungible_token( treasury_key, initial_supply=100, ): - """Create a fungible token""" + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("revenue-generating token") @@ -174,7 +174,7 @@ def create_fungible_token( def associate_token_with_account(client, account_id, token_id, account_key): - """Associate a token with an account""" + """Associate a token with an account.""" receipt = ( TokenAssociateTransaction() .set_account_id(account_id) @@ -194,7 +194,7 @@ def associate_token_with_account(client, account_id, token_id, account_key): def transfer_tokens(client, token_id, from_account_id, to_account_id, amount): - """Transfer tokens between accounts""" + """Transfer tokens between accounts.""" receipt = ( TransferTransaction() .add_token_transfer(token_id, from_account_id, -amount) @@ -210,7 +210,7 @@ def transfer_tokens(client, token_id, from_account_id, to_account_id, amount): def update_topic_custom_fees(client, topic_id, custom_fees): - """Update topic custom fees""" + """Update topic custom fees.""" receipt = ( TopicUpdateTransaction() .set_topic_id(topic_id) @@ -226,7 +226,7 @@ def update_topic_custom_fees(client, topic_id, custom_fees): def update_topic_fee_exempt_keys(client, topic_id, fee_exempt_keys): - """Update topic fee exempt keys""" + """Update topic fee exempt keys.""" receipt = ( TopicUpdateTransaction() .set_topic_id(topic_id) @@ -244,7 +244,7 @@ def update_topic_fee_exempt_keys(client, topic_id, fee_exempt_keys): def test_hbar_fee_flow( client, topic_id, alice_id, alice_key, operator_id, operator_key ): - """Test Steps 3-4: Submit message with custom fee limit and verify Hbar fee collection""" + """Test Steps 3-4: Submit message with custom fee limit and verify Hbar fee collection.""" print("Submitting a message as Alice to the topic") alice_balance_before = get_account_balance(client, alice_id) fee_collector_balance_before = get_account_balance(client, operator_id) @@ -281,7 +281,7 @@ def test_hbar_fee_flow( def setup_token_and_update_topic( client, topic_id, alice_id, alice_key, operator_id, operator_key ): - """Test Steps 5-6: Create token, transfer to Alice, and update topic with token fee""" + """Test Steps 5-6: Create token, transfer to Alice, and update topic with token fee.""" print("Creating a token") token_id = create_fungible_token(client, operator_id, operator_key) @@ -307,7 +307,7 @@ def setup_token_and_update_topic( def test_token_fee_flow( client, topic_id, token_id, alice_id, alice_key, operator_id, operator_key ): - """Test Steps 7-8: Submit message without custom fee limit and verify token fee collection""" + """Test Steps 7-8: Submit message without custom fee limit and verify token fee collection.""" print("Submitting a message as Alice to the topic") alice_balance_before = get_account_balance(client, alice_id) fee_collector_balance_before = get_account_balance(client, operator_id) @@ -344,7 +344,7 @@ def test_token_fee_flow( def test_fee_exempt_flow(client, topic_id, token_id, operator_id, operator_key): - """Test Steps 9-12: Create Bob, update fee exempt keys, and verify Bob isn't charged""" + """Test Steps 9-12: Create Bob, update fee exempt keys, and verify Bob isn't charged.""" print("Creating account - Bob") bob_id, bob_key = create_account(client, "Bob") @@ -379,6 +379,7 @@ def test_fee_exempt_flow(client, topic_id, token_id, operator_id, operator_key): def revenue_generating_topics(): """ Demonstrates revenue generating topics functionality by: + 1. Creating Alice account 2. Creating a topic with Hbar custom fee 3. Submitting message with custom fee limit @@ -390,7 +391,7 @@ def revenue_generating_topics(): 9. Creating Bob account 10. Updating topic's fee exempt keys and add Bob's public key 11. Submitting message, paid by Bob, without specifying max custom fee amount - 12. Verifying Bob was not debited the fee amount + 12. Verifying Bob was not debited the fee amount. """ client = setup_client() operator_id = client.operator_account_id diff --git a/examples/consensus/topic_delete_transaction.py b/examples/consensus/topic_delete_transaction.py index 07f4ffc6c..4775a4c68 100644 --- a/examples/consensus/topic_delete_transaction.py +++ b/examples/consensus/topic_delete_transaction.py @@ -1,4 +1,7 @@ """ + +Example demonstrating topic delete transaction. + uv run examples/consensus/topic_delete_transaction.py python examples/consensus/topic_delete_transaction.py @@ -6,19 +9,19 @@ - topic_delete_transaction() performs the create+delete transaction steps - main() orchestrates setup and calls helper functions """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, AccountId, - PrivateKey, - TopicDeleteTransaction, + Client, Network, - TopicCreateTransaction, + PrivateKey, ResponseCode, + TopicCreateTransaction, + TopicDeleteTransaction, ) load_dotenv() @@ -26,7 +29,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" print(f"🌐 Connecting to Hedera {network_name}...") network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") @@ -50,7 +53,7 @@ def setup_client(): def create_topic(client, operator_key): - """Create a new topic""" + """Create a new topic.""" print("\nSTEP 1: Creating a Topic...") try: topic_tx = ( @@ -73,6 +76,7 @@ def create_topic(client, operator_key): def topic_delete_transaction(client, operator_key, topic_id): """ Perform the topic delete transaction for the given topic_id. + Separated so it can be called independently in tests or other scripts. """ print("\nSTEP 2: Deleting Topic...") @@ -94,7 +98,7 @@ def topic_delete_transaction(client, operator_key, topic_id): def main(): - """Orchestrator — runs the example start-to-finish""" + """Orchestrator — runs the example start-to-finish.""" # Config Client client, _, operator_key = setup_client() diff --git a/examples/consensus/topic_id.py b/examples/consensus/topic_id.py index ed0817e1c..6c3ebfc53 100644 --- a/examples/consensus/topic_id.py +++ b/examples/consensus/topic_id.py @@ -1,8 +1,13 @@ -"""uv run examples/consensus/topic_id.py""" +""" + +Example: Topic Id. + +uv run examples/consensus/topic_id.py. +""" -from hiero_sdk_python.consensus.topic_id import TopicId from hiero_sdk_python.client.client import Client from hiero_sdk_python.client.network import Network +from hiero_sdk_python.consensus.topic_id import TopicId def create_topic_id() -> TopicId: diff --git a/examples/consensus/topic_message.py b/examples/consensus/topic_message.py index 084065367..de7408447 100644 --- a/examples/consensus/topic_message.py +++ b/examples/consensus/topic_message.py @@ -1,4 +1,6 @@ """ + + This example should demonstrate: 1. How to manually create TopicMessageChunk objects with mock data. @@ -11,8 +13,7 @@ python examples/consensus/topic_message.py """ - -from hiero_sdk_python.consensus.topic_message import TopicMessage, TopicMessageChunk +from hiero_sdk_python.consensus.topic_message import TopicMessage class MockTimestamp: @@ -89,7 +90,8 @@ def mock_consensus_response( has_tx_id: bool = False, ) -> MockResponse: """ - Creates a lightweight mock of a ConsensusTopicResponse + Creates a lightweight mock of a ConsensusTopicResponse. + that satisfies the interface required by TopicMessage. """ timestamp = MockTimestamp(1736539200 + seq, 123456000 + seq) @@ -176,6 +178,7 @@ def demonstrate_transaction_id(): def main(): """ Runs all demonstrations for TopicMessage and TopicMessageChunk. + This example is self-contained and does not connect to the network. """ print("Running TopicMessage examples...") diff --git a/examples/consensus/topic_message_submit_chunked_transaction.py b/examples/consensus/topic_message_submit_chunked_transaction.py index 44bf95f7b..a6be1378c 100644 --- a/examples/consensus/topic_message_submit_chunked_transaction.py +++ b/examples/consensus/topic_message_submit_chunked_transaction.py @@ -1,26 +1,31 @@ """ + +Example demonstrating topic message submit chunked transaction. + uv run examples/consensus/topic_message_submit_chunked.py python examples/consensus/topic_message_submit_chunked.py - """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, AccountId, - PrivateKey, + Client, Network, - TopicMessageSubmitTransaction, - TopicCreateTransaction, + PrivateKey, ResponseCode, + TopicCreateTransaction, TopicInfoQuery, + TopicMessageSubmitTransaction, ) BIG_CONTENT = """ + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur aliquam augue sem, ut mattis dui laoreet a. Curabitur consequat est euismod, scelerisque metus et, tristique dui. Nulla commodo mauris ut faucibus ultricies. Quisque venenatis nisl nec augue tempus, at efficitur elit eleifend. Duis pharetra felis metus, sed dapibus urna vehicula id. Duis non venenatis turpis, sit amet ornare orci. Donec non interdum quam. Sed finibus nunc et risus finibus, non sagittis lorem cursus. Proin pellentesque tempor aliquam. Sed congue nisl in enim bibendum, condimentum vehicula nisi feugiat. + Suspendisse non sodales arcu. Suspendisse sodales, lorem ac mollis blandit, ipsum neque porttitor nulla, et sodales arcu ante fermentum tellus. Integer sagittis dolor sed augue fringilla accumsan. Cras vitae finibus arcu, sit amet varius dolor. Etiam id finibus dolor, vitae luctus velit. Proin efficitur augue nec pharetra accumsan. Aliquam lobortis nisl diam, vel fermentum purus finibus id. Etiam at finibus orci, et tincidunt turpis. Aliquam imperdiet congue lacus vel facilisis. Phasellus id magna vitae enim dapibus vestibulum vitae quis augue. Morbi eu consequat enim. Maecenas neque nulla, pulvinar sit amet consequat sed, tempor sed magna. Mauris lacinia sem feugiat faucibus aliquet. Etiam congue non turpis at commodo. Nulla facilisi. Nunc velit turpis, cursus ornare fringilla eu, lacinia posuere leo. Mauris rutrum ultricies dui et suscipit. Curabitur in euismod ligula. Curabitur vitae faucibus orci. Phasellus volutpat vestibulum diam sit amet vestibulum. In vel purus leo. Nulla condimentum lectus vestibulum lectus faucibus, id lobortis eros consequat. Proin mollis libero elit, vel aliquet nisi imperdiet et. Morbi ornare est velit, in vehicula nunc malesuada quis. Donec vehicula convallis interdum. Integer pellentesque in nibh vitae aliquet. Ut at justo id libero dignissim hendrerit. Interdum et malesuada fames ac ante ipsum primis in faucibus. Praesent quis ornare lectus. Nam malesuada non diam quis cursus. Phasellus a libero ligula. Suspendisse ligula elit, congue et nisi sit amet, cursus euismod dolor. Morbi aliquam, nulla a posuere pellentesque, diam massa ornare risus, nec eleifend neque eros et elit. @@ -44,14 +49,11 @@ In consequat, nisi iaculis laoreet elementum, massa mauris varius nisi, et porta nisi velit at urna. Maecenas sit amet aliquet eros, a rhoncus nisl. Maecenas convallis enim nunc. Morbi purus nisl, aliquam ac tincidunt sed, mattis in augue. Quisque et elementum quam, vitae maximus orci. Suspendisse hendrerit risus nec vehicula placerat. Nulla et lectus nunc. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam ut sodales ex. Nulla luctus, magna eu scelerisque sagittis, nibh quam consectetur neque, non rutrum dolor metus nec ex. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed egestas augue elit, sollicitudin accumsan massa lobortis ac. Curabitur placerat, dolor a aliquam maximus, velit ipsum laoreet ligula, id ullamcorper lacus nibh eget nisl. Donec eget lacus venenatis enim consequat auctor vel in. """ - load_dotenv() def setup_client(): - """ - Set up and configure a Hedera client for testnet operations. - """ + """Set up and configure a Hedera client for testnet operations.""" network_name = os.getenv("NETWORK", "testnet").lower() print(f"Connecting to Hedera {network_name} network!") @@ -72,9 +74,7 @@ def setup_client(): def create_topic(client): - """ - Create a new topic. - """ + """Create a new topic.""" print("\nCreating a Topic...") try: topic_receipt = ( @@ -93,9 +93,7 @@ def create_topic(client): def submit_topic_message_transaction(client, topic_id): - """ - Submit a chunked message to the specified topic. - """ + """Submit a chunked message to the specified topic.""" print("\nSubmitting large message...") try: message_receipt = ( @@ -115,7 +113,7 @@ def submit_topic_message_transaction(client, topic_id): print( f"Message submitted (status={ResponseCode(message_receipt.status)}, txId={message_receipt.transaction_id})" ) - print(f"Message size:", len(BIG_CONTENT), "bytes") + print("Message size:", len(BIG_CONTENT), "bytes") print( f"Message Content: {(BIG_CONTENT[:140] + '...') if len(BIG_CONTENT) > 140 else BIG_CONTENT}" ) @@ -126,9 +124,7 @@ def submit_topic_message_transaction(client, topic_id): def fetch_topic_info(client, topic_id): - """ - Fetch and print topic info. - """ + """Fetch and print topic info.""" print("\nFetching topic info...") try: @@ -148,9 +144,7 @@ def fetch_topic_info(client, topic_id): def main(): - """ - Create a topic and submit a large multi-chunk message to it. - """ + """Create a topic and submit a large multi-chunk message to it.""" client = setup_client() topic_id = create_topic(client) fetch_topic_info(client, topic_id) diff --git a/examples/consensus/topic_message_submit_transaction.py b/examples/consensus/topic_message_submit_transaction.py index 5fcaaf6a6..f03bf1a39 100644 --- a/examples/consensus/topic_message_submit_transaction.py +++ b/examples/consensus/topic_message_submit_transaction.py @@ -1,21 +1,23 @@ """ + +Example demonstrating topic message submit transaction. + uv run examples/consensus/topic_message_submit_transaction.py python examples/consensus/topic_message_submit_transaction.py - """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, AccountId, - PrivateKey, + Client, Network, - TopicMessageSubmitTransaction, - TopicCreateTransaction, + PrivateKey, ResponseCode, + TopicCreateTransaction, + TopicMessageSubmitTransaction, ) load_dotenv() @@ -23,7 +25,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -41,7 +43,7 @@ def setup_client(): def create_topic(client, operator_key): - """Create a new topic""" + """Create a new topic.""" print("\nSTEP 1: Creating a Topic...") try: topic_tx = ( @@ -62,7 +64,7 @@ def create_topic(client, operator_key): def submit_topic_message_transaction(client, topic_id, message, operator_key): - """Submit a message to the specified topic""" + """Submit a message to the specified topic.""" print("\nSTEP 2: Submitting message...") transaction = ( TopicMessageSubmitTransaction(topic_id=topic_id, message=message) @@ -84,9 +86,7 @@ def submit_topic_message_transaction(client, topic_id, message, operator_key): def main(): - """ - A example to create a topic and then submit a message to it. - """ + """A example to create a topic and then submit a message to it.""" message = "Hello, Hiero!" # Config Client diff --git a/examples/consensus/topic_update_transaction.py b/examples/consensus/topic_update_transaction.py index 2e0808800..3f8525c7d 100644 --- a/examples/consensus/topic_update_transaction.py +++ b/examples/consensus/topic_update_transaction.py @@ -1,21 +1,23 @@ """ + +Example demonstrating topic update transaction. + uv run examples/consensus/topic_update_transaction.py python examples/consensus/topic_update_transaction.py - """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, AccountId, - PrivateKey, - TopicUpdateTransaction, + Client, Network, - TopicCreateTransaction, + PrivateKey, ResponseCode, + TopicCreateTransaction, + TopicUpdateTransaction, ) load_dotenv() @@ -23,7 +25,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -41,7 +43,7 @@ def setup_client(): def create_topic(client, operator_key): - """Create a new topic""" + """Create a new topic.""" print("\nSTEP 1: Creating a Topic...") try: topic_tx = ( @@ -62,7 +64,7 @@ def create_topic(client, operator_key): def update_topic(new_memo): - """A example to create a topic and then update it""" + """A example to create a topic and then update it.""" # Config Client client, _, operator_key = setup_client() diff --git a/examples/contract/contract_balance_query.py b/examples/contract/contract_balance_query.py index 3db17d1c9..cdc925ff7 100644 --- a/examples/contract/contract_balance_query.py +++ b/examples/contract/contract_balance_query.py @@ -1,5 +1,7 @@ """ -Contract Balance Query Example + + +Contract Balance Query Example. This script demonstrates how to: 1. Set up a client connection to the Hedera network @@ -11,9 +13,8 @@ uv run -m examples.contract.contract_balance_query python -m examples.contract.contract_balance_query """ - -import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( @@ -22,11 +23,10 @@ CryptoGetAccountBalanceQuery, Hbar, ) - from hiero_sdk_python.contract.contract_id import ContractId +from hiero_sdk_python.response_code import ResponseCode from .contracts import SIMPLE_CONTRACT_BYTECODE -from hiero_sdk_python.response_code import ResponseCode load_dotenv() diff --git a/examples/contract/contract_bytecode_query.py b/examples/contract/contract_bytecode_query.py index 254aea29d..f43973657 100644 --- a/examples/contract/contract_bytecode_query.py +++ b/examples/contract/contract_bytecode_query.py @@ -1,4 +1,6 @@ """ + + Example demonstrating contract bytecode query on the network. This module shows how to query a contract bytecode on the network by: @@ -16,7 +18,6 @@ python -m examples.contract.contract_bytecode_query """ - import os import sys @@ -40,7 +41,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -54,7 +55,7 @@ def setup_client(): def create_contract_file(client): - """Create a file containing the simple contract bytecode""" + """Create a file containing the simple contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -74,7 +75,7 @@ def create_contract_file(client): def create_contract(client, file_id): - """Create a contract using the file""" + """Create a contract using the file.""" receipt = ( ContractCreateTransaction() .set_admin_key(client.operator_private_key.public_key()) @@ -99,10 +100,11 @@ def create_contract(client, file_id): def query_contract_bytecode(): """ Demonstrates querying a contract bytecode by: + 1. Setting up client with operator account 2. Creating a file containing contract bytecode 3. Creating a contract using the file - 4. Querying the contract bytecode + 4. Querying the contract bytecode. """ client = setup_client() diff --git a/examples/contract/contract_call_query.py b/examples/contract/contract_call_query.py index 3551d95c1..3dfc64b64 100644 --- a/examples/contract/contract_call_query.py +++ b/examples/contract/contract_call_query.py @@ -1,4 +1,6 @@ """ + + Example demonstrating contract call query on the network. This module shows how to query a contract call on the network by: @@ -16,7 +18,6 @@ python -m examples.contract.contract_call_query """ - import os import sys @@ -43,7 +44,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -57,7 +58,7 @@ def setup_client(): def create_contract_file(client): - """Create a file containing the stateful contract bytecode""" + """Create a file containing the stateful contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -77,8 +78,8 @@ def create_contract_file(client): def create_contract(client, file_id): - """Create a contract using the file with constructor parameters""" - initial_message = "Initial message from constructor".encode("utf-8") + """Create a contract using the file with constructor parameters.""" + initial_message = b"Initial message from constructor" constructor_params = ContractFunctionParameters().add_bytes32(initial_message) receipt = ( ContractCreateTransaction() @@ -103,10 +104,11 @@ def create_contract(client, file_id): def query_contract_call(): """ Demonstrates querying a contract call by: + 1. Setting up client with operator account 2. Creating a file containing stateful contract bytecode 3. Creating a contract using the file with constructor parameters - 4. Querying the contract call + 4. Querying the contract call. """ client = setup_client() diff --git a/examples/contract/contract_create_transaction_no_constructor_parameters.py b/examples/contract/contract_create_transaction_no_constructor_parameters.py index ede899dc5..4797ced67 100644 --- a/examples/contract/contract_create_transaction_no_constructor_parameters.py +++ b/examples/contract/contract_create_transaction_no_constructor_parameters.py @@ -1,4 +1,6 @@ """ + + Example demonstrating contract creation with constructor parameters on the network. This module shows how to create a stateful smart contract by: @@ -15,7 +17,6 @@ uv run -m examples.contract.contract_create_transaction_no_constructor_parameters """ - import os import sys @@ -41,7 +42,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -55,7 +56,7 @@ def setup_client(): def create_contract_file(client): - """Create a file containing the stateful contract bytecode""" + """Create a file containing the stateful contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -77,9 +78,10 @@ def create_contract_file(client): def contract_create_constructor(): """ Demonstrates creating a stateful contract with constructor parameters by: + 1. Setting up client with operator account 2. Creating a file containing stateful contract bytecode - 3. Creating a contract using the file with constructor parameters + 3. Creating a contract using the file with constructor parameters. """ client = setup_client() @@ -92,7 +94,7 @@ def contract_create_constructor(): # 2. Pass those bytes to add_bytes32() to properly format for the contract # NOTE: If message exceeds 32 bytes, it will raise an error. # If message is less than 32 bytes, it will be padded with zeros. - initial_message = "Initial message from constructor".encode("utf-8") + initial_message = b"Initial message from constructor" # Create ContractFunctionParameters object and add the bytes32 parameter # This will be passed to setConstructorParameters() when creating the contract diff --git a/examples/contract/contract_create_transaction_with_bytecode.py b/examples/contract/contract_create_transaction_with_bytecode.py index b9e0de044..573f6c05d 100644 --- a/examples/contract/contract_create_transaction_with_bytecode.py +++ b/examples/contract/contract_create_transaction_with_bytecode.py @@ -1,4 +1,6 @@ """ + + Example demonstrating contract creation on the network. This module shows how to create a smart contract by: @@ -14,7 +16,6 @@ python -m examples.contract.contract_create_transaction_with_bytecode """ - import os import sys @@ -36,7 +37,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -52,8 +53,9 @@ def setup_client(): def contract_create_with_bytecode(): """ Demonstrates creating a contract on the network by: + 1. Setting up client with operator account - 2. Creating a contract using the bytecode + 2. Creating a contract using the bytecode. """ client = setup_client() diff --git a/examples/contract/contract_create_transaction_with_constructor_parameters.py b/examples/contract/contract_create_transaction_with_constructor_parameters.py index 28cb5aa02..4db6c3721 100644 --- a/examples/contract/contract_create_transaction_with_constructor_parameters.py +++ b/examples/contract/contract_create_transaction_with_constructor_parameters.py @@ -1,4 +1,6 @@ """ + + Example demonstrating contract creation on the network. This module shows how to create a smart contract by: @@ -14,7 +16,6 @@ uv run -m examples.contract.contract_create_transaction_with_constructor_parameters python -m examples.contract.contract_create_transaction_with_constructor_parameters """ - import os import sys @@ -37,7 +38,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -51,7 +52,7 @@ def setup_client(): def create_contract_file(client): - """Create a file containing the contract bytecode""" + """Create a file containing the contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -73,9 +74,10 @@ def create_contract_file(client): def contract_create(): """ Demonstrates creating a contract on the network by: + 1. Setting up client with operator account 2. Creating a file containing contract bytecode - 3. Creating a contract using the file + 3. Creating a contract using the file. """ client = setup_client() diff --git a/examples/contract/contract_delete_transaction.py b/examples/contract/contract_delete_transaction.py index df31b70bb..bbc0ec13c 100644 --- a/examples/contract/contract_delete_transaction.py +++ b/examples/contract/contract_delete_transaction.py @@ -1,4 +1,6 @@ """ + + Example demonstrating contract deletion on the network. This module shows how to delete a smart contract by: @@ -18,7 +20,6 @@ uv run -m examples.contract.contract_delete_transaction python -m examples.contract.contract_delete_transaction """ - import os import sys @@ -46,7 +47,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -60,7 +61,7 @@ def setup_client(): def create_contract_file(client): - """Create a file containing the contract bytecode""" + """Create a file containing the contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -80,7 +81,7 @@ def create_contract_file(client): def create_contract(client, file_id, initial_balance): - """Create a contract using the file""" + """Create a contract using the file.""" receipt = ( ContractCreateTransaction() .set_admin_key(client.operator_private_key.public_key()) @@ -106,13 +107,14 @@ def create_contract(client, file_id, initial_balance): def contract_delete(): """ Demonstrates deleting a contract on the network by: + 1. Setting up client with operator account 2. Creating a file containing contract bytecode 3. Creating two contracts: one with balance, one for transfer 4. Deleting the contract and transferring the hbars to a transfer contract 5. Checking if the contract is deleted and the transfer contract has the hbars 6. Deleting the transfer contract and transferring the hbars to the operator account - 7. Checking if the transfer contract is deleted + 7. Checking if the transfer contract is deleted. """ client = setup_client() diff --git a/examples/contract/contract_execute_transaction.py b/examples/contract/contract_execute_transaction.py index c5671b8e6..7daf30ae5 100644 --- a/examples/contract/contract_execute_transaction.py +++ b/examples/contract/contract_execute_transaction.py @@ -1,4 +1,6 @@ """ + + Example demonstrating contract execute on the network. This module shows how to execute a contract on the network by: @@ -15,7 +17,6 @@ uv run -m examples.contract.contract_execute_transaction python -m examples.contract.contract_execute_transaction """ - import os import sys @@ -45,7 +46,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -59,7 +60,7 @@ def setup_client(): def create_contract_file(client): - """Create a file containing the stateful contract bytecode""" + """Create a file containing the stateful contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -79,8 +80,8 @@ def create_contract_file(client): def create_contract(client, file_id): - """Create a contract using the file with constructor parameters""" - initial_message = "This is the initial message!".encode("utf-8") + """Create a contract using the file with constructor parameters.""" + initial_message = b"This is the initial message!" constructor_params = ContractFunctionParameters().add_bytes32(initial_message) receipt = ( ContractCreateTransaction() @@ -105,7 +106,7 @@ def create_contract(client, file_id): def get_contract_message(client, contract_id): - """Get the message from the contract""" + """Get the message from the contract.""" # Query the contract function to verify that the message was set query = ( ContractCallQuery() @@ -127,12 +128,13 @@ def get_contract_message(client, contract_id): def execute_contract(): """ Demonstrates executing a contract by: + 1. Setting up client with operator account 2. Creating a file containing stateful contract bytecode 3. Creating a contract using the file with constructor parameters 4. Getting the current message from the contract 5. Executing a contract function to set the new message - 6. Querying the contract function to verify that the message was set + 6. Querying the contract function to verify that the message was set. """ client = setup_client() diff --git a/examples/contract/contract_execute_transaction_with_value.py b/examples/contract/contract_execute_transaction_with_value.py index 7a17dc9cd..723a065c9 100644 --- a/examples/contract/contract_execute_transaction_with_value.py +++ b/examples/contract/contract_execute_transaction_with_value.py @@ -1,4 +1,6 @@ """ + + Example demonstrating contract execute with HBAR value transfer on the network. This module shows how to execute a contract on the network by: @@ -39,7 +41,6 @@ - A receive() function for plain HBAR transfers - A setMessageAndPay() function that accepts HBAR while updating a message """ - import os import sys @@ -70,7 +71,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -84,7 +85,7 @@ def setup_client(): def create_contract_file(client): - """Create a file containing the stateful contract bytecode""" + """Create a file containing the stateful contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -104,8 +105,8 @@ def create_contract_file(client): def create_contract(client, file_id): - """Create a contract using the file with constructor parameters""" - initial_message = "Initial message from constructor".encode("utf-8") + """Create a contract using the file with constructor parameters.""" + initial_message = b"Initial message from constructor" constructor_params = ContractFunctionParameters().add_bytes32(initial_message) receipt = ( ContractCreateTransaction() @@ -132,11 +133,12 @@ def create_contract(client, file_id): def execute_contract_with_value(): """ Demonstrates executing a contract with HBAR value transfer by: + 1. Setting up client with operator account 2. Creating a file containing stateful contract bytecode 3. Creating a contract using the file 4. Executing a contract with HBAR value transfer - 5. Querying the contract info to verify the balance + 5. Querying the contract info to verify the balance. The set_payable_amount() method sends HBAR from the transaction signer to the contract. The contract must have either a receive() function declared as `receive() external payable` diff --git a/examples/contract/contract_info_query.py b/examples/contract/contract_info_query.py index 61c758287..bdcf9c5a8 100644 --- a/examples/contract/contract_info_query.py +++ b/examples/contract/contract_info_query.py @@ -1,4 +1,6 @@ """ + + Example demonstrating contract info query on the network. This module shows how to query a contract info on the network by: @@ -16,8 +18,8 @@ python -m examples.contract.contract_info_query """ - import sys + from hiero_sdk_python import Client, Duration from hiero_sdk_python.contract.contract_create_transaction import ( ContractCreateTransaction, @@ -32,7 +34,7 @@ def create_contract_file(client): - """Create a file containing the simple contract bytecode""" + """Create a file containing the simple contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -52,7 +54,7 @@ def create_contract_file(client): def create_contract(client, file_id): - """Create a contract using the file""" + """Create a contract using the file.""" receipt = ( ContractCreateTransaction() .set_admin_key(client.operator_private_key.public_key()) @@ -81,10 +83,11 @@ def create_contract(client, file_id): def query_contract_info(): """ Demonstrates querying a contract info by: + 1. Setting up client with operator account 2. Creating a file containing contract bytecode 3. Creating a contract using the file - 4. Querying the contract info + 4. Querying the contract info. """ client = Client.from_env() print(f"Operator: {client.operator_account_id}") diff --git a/examples/contract/contract_update_transaction.py b/examples/contract/contract_update_transaction.py index d41d9a76a..b03791f34 100644 --- a/examples/contract/contract_update_transaction.py +++ b/examples/contract/contract_update_transaction.py @@ -1,4 +1,6 @@ """ + + Example demonstrating comprehensive contract update operations on the network. This module shows how to update an existing smart contract using ALL available setters: @@ -14,7 +16,6 @@ uv run -m examples.contract.contract_update_transaction python -m examples.contract.contract_update_transaction """ - import datetime import os import sys @@ -44,7 +45,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -58,7 +59,7 @@ def setup_client(): def create_contract_file(client): - """Create a file containing the contract bytecode""" + """Create a file containing the contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -78,7 +79,7 @@ def create_contract_file(client): def create_initial_contract(client, file_id): - """Create the initial contract that we'll update later""" + """Create the initial contract that we'll update later.""" receipt = ( ContractCreateTransaction() .set_bytecode_file_id(file_id) @@ -101,11 +102,12 @@ def create_initial_contract(client, file_id): def contract_update(): """ Demonstrates updating a contract with ALL available setters by: + 1. Setting up client with operator account 2. Creating files containing contract bytecode 3. Creating an initial contract 4. Updating the contract using all available setters - 5. Querying the contract info + 5. Querying the contract info. """ client = setup_client() diff --git a/examples/contract/contracts/__init__.py b/examples/contract/contracts/__init__.py index 0ca4dfe8f..66d35c3ee 100644 --- a/examples/contract/contracts/__init__.py +++ b/examples/contract/contracts/__init__.py @@ -1,14 +1,16 @@ """ -This module contains the bytecode constants for the contracts + + +This module contains the bytecode constants for the contracts. + and configuration constants for the contracts. """ - from .contract_utils import ( # Bytecode constants; Configuration constants + CONSTRUCTOR_TEST_CONTRACT_BYTECODE, CONTRACT_DEPLOY_GAS, SIMPLE_CONTRACT_BYTECODE, - STATEFUL_CONTRACT_BYTECODE, - CONSTRUCTOR_TEST_CONTRACT_BYTECODE, SIMPLE_CONTRACT_RUNTIME_BYTECODE, + STATEFUL_CONTRACT_BYTECODE, ) __all__ = [ diff --git a/examples/contract/contracts/contract_utils.py b/examples/contract/contracts/contract_utils.py index f7327344d..cc5483858 100644 --- a/examples/contract/contracts/contract_utils.py +++ b/examples/contract/contracts/contract_utils.py @@ -1,5 +1,8 @@ """ + + This module provides utilities for loading and managing smart contract bytecode. + It contains bytecode constants for contracts and configuration constants for deployment. File Structure: @@ -25,7 +28,6 @@ - Each contract's bytecode is loaded into a constant (e.g. SIMPLE_CONTRACT_BYTECODE) - The _load_contract_bytecode() utility handles loading and validation """ - from pathlib import Path diff --git a/examples/contract/ethereum_transaction.py b/examples/contract/ethereum_transaction.py index 3698ab90b..413e0d477 100644 --- a/examples/contract/ethereum_transaction.py +++ b/examples/contract/ethereum_transaction.py @@ -1,4 +1,6 @@ """ + + Example demonstrating Ethereum transaction execution on the network. This module shows how to execute a contract using Ethereum transaction by: @@ -16,7 +18,6 @@ # Run from the project root directory python -m examples.contract.ethereum_transaction """ - import os import sys @@ -47,7 +48,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -62,6 +63,7 @@ def setup_client(): def create_alias_account(client): """ + Create an alias account for the ECDSA key by transferring HBAR to it. This creates a "hollow" account controlled by the generated ECDSA key. @@ -98,7 +100,7 @@ def create_alias_account(client): def create_contract_file(client): - """Create a file containing the stateful contract bytecode""" + """Create a file containing the stateful contract bytecode.""" file_receipt = ( FileCreateTransaction() .set_keys(client.operator_private_key.public_key()) @@ -118,8 +120,8 @@ def create_contract_file(client): def create_contract(client, file_id): - """Create a contract using the file with constructor parameters""" - initial_message = "Initial message from constructor".encode("utf-8") + """Create a contract using the file with constructor parameters.""" + initial_message = b"Initial message from constructor" constructor_params = ContractFunctionParameters().add_bytes32(initial_message) receipt = ( ContractCreateTransaction() @@ -144,7 +146,7 @@ def create_contract(client, file_id): def get_contract_message(client, contract_id): - """Get the message from the contract""" + """Get the message from the contract.""" # Query the contract function to verify that the message was set query = ( ContractCallQuery() @@ -227,13 +229,14 @@ def create_ethereum_transaction_data(contract_id, new_message, alias_private_key def execute_ethereum_transaction(): """ Demonstrates executing a contract using Ethereum transaction by: + 1. Setting up client with operator account 2. Creating an alias account for ECDSA key 3. Creating a file containing contract bytecode 4. Creating a contract using the file 5. Getting the current message from the contract 6. Executing the contract via Ethereum transaction to update the message - 7. Verifying the contract state was updated + 7. Verifying the contract state was updated. """ client = setup_client() @@ -248,8 +251,8 @@ def execute_ethereum_transaction(): initial_message = get_contract_message(client, contract_id) print(f"\nInitial contract message: '{initial_message}'") - # Prepare a new message to set in the contract (le than 32 bytes) - new_message = "Updated message via Eth tx!".encode("utf-8")[:32] + # Prepare a new message to set in the contract (less than 32 bytes) + new_message = b"Updated message via Eth tx!"[:32] new_message_string = new_message.decode("utf-8") # For display print(f"\nPreparing Ethereum transaction to set message: '{new_message_string}'") diff --git a/examples/crypto/private_key_der.py b/examples/crypto/private_key_der.py index 7637d09d7..7695f2f3d 100644 --- a/examples/crypto/private_key_der.py +++ b/examples/crypto/private_key_der.py @@ -1,5 +1,8 @@ """ -Example file: Demonstrating how to serialize a PrivateKey to DER (hex) + + +Example file: Demonstrating how to serialize a PrivateKey to DER (hex). + and then load it back. *WARNING* DER‐encoded private keys should not be printed or exposed in a real-world scenario. @@ -7,8 +10,6 @@ python examples/crypto/private_key_der.py """ - -from cryptography.exceptions import InvalidSignature from hiero_sdk_python.crypto.private_key import PrivateKey diff --git a/examples/crypto/private_key_ecdsa.py b/examples/crypto/private_key_ecdsa.py index c8b504d35..7af2fefa8 100644 --- a/examples/crypto/private_key_ecdsa.py +++ b/examples/crypto/private_key_ecdsa.py @@ -1,19 +1,23 @@ """ -Example file: Working with ECDSA (secp256k1) PrivateKey using the PrivateKey class -*WARNING* ECDSA seeds should not be printed or exposed in a real‑world scenario + + +Example file: Working with ECDSA (secp256k1) PrivateKey using the PrivateKey class. + +*WARNING* ECDSA seeds should not be printed or exposed in a real-world scenario. uv run examples/crypto/private_key_ecdsa.py python examples/crypto/private_key_ecdsa.py """ - from cryptography.exceptions import InvalidSignature + from hiero_sdk_python.crypto.private_key import PrivateKey def example_generate_ecdsa() -> None: """ - Demonstrates generating a new ECDSA (secp256k1) PrivateKey, + Demonstrates generating a new ECDSA (secp256k1) PrivateKey,. + signing data, and verifying with the associated PublicKey. """ print("=== ECDSA: Generate & Sign ===") @@ -42,6 +46,7 @@ def example_generate_ecdsa() -> None: def example_load_ecdsa_raw() -> None: """ Demonstrates creating an ECDSA (secp256k1) PrivateKey from raw 32 bytes (a scalar). + Then signs and verifies. """ print("=== ECDSA: Load from Raw ===") @@ -68,9 +73,7 @@ def example_load_ecdsa_raw() -> None: def example_load_ecdsa_from_hex() -> None: - """ - Demonstrates creating an ECDSA (secp256k1) PrivateKey from a hex-encoded 32-byte scalar. - """ + """Demonstrates creating an ECDSA (secp256k1) PrivateKey from a hex-encoded 32-byte scalar.""" print("=== ECDSA: Load from Hex ===") # 32-byte scalar in hex. Must not be zero; example: ecdsa_hex = "abcdef0000000000000000000000000000000000000000000000000000000001" @@ -96,6 +99,7 @@ def example_load_ecdsa_from_hex() -> None: def example_load_ecdsa_der() -> None: """ Demonstrates loading an ECDSA (secp256k1) private key from DER bytes. + TraditionalOpenSSL in hex form for demonstration. """ print("=== ECDSA: Load from DER ===") diff --git a/examples/crypto/private_key_ed25519.py b/examples/crypto/private_key_ed25519.py index eeaba2c8f..a9afe7cf6 100644 --- a/examples/crypto/private_key_ed25519.py +++ b/examples/crypto/private_key_ed25519.py @@ -1,19 +1,23 @@ """ -Example file: Working with Ed25519 PrivateKey using the PrivateKey class -*WARNING* Ed25519 seeds should not be printed or exposed in a real‑world scenario + + +Example file: Working with Ed25519 PrivateKey using the PrivateKey class. + +*WARNING* Ed25519 seeds should not be printed or exposed in a real-world scenario. uv run examples/crypto/private_key_ed25519.py python examples/crypto/private_key_ed25519.py """ - from cryptography.exceptions import InvalidSignature + from hiero_sdk_python.crypto.private_key import PrivateKey def example_generate_ed25519() -> None: """ - Demonstrates generating a brand new Ed25519 PrivateKey, signing data, + Demonstrates generating a brand new Ed25519 PrivateKey, signing data,. + and verifying the signature with its corresponding PublicKey. """ print("=== Ed25519: Generate & Sign ===") @@ -41,6 +45,7 @@ def example_generate_ed25519() -> None: def example_load_ed25519_raw() -> None: """ Demonstrates creating a PrivateKey from a 32-byte raw Ed25519 seed. + Then uses it for signing and verifying. """ print("=== Ed25519: Load from Raw ===") @@ -70,6 +75,7 @@ def example_load_ed25519_raw() -> None: def example_load_ed25519_from_hex() -> None: """ Demonstrates creating a PrivateKey from a hex-encoded string for Ed25519. + Must be 32 bytes in total, i.e. 64 hex characters. """ print("=== Ed25519: Load from Hex ===") @@ -97,6 +103,7 @@ def example_load_ed25519_from_hex() -> None: def example_load_ed25519_der() -> None: """ Demonstrates loading an Ed25519 private key from DER bytes (hex form). + In actual usage, you might read the raw DER bytes from a file (binary), then call from_der(...) or from_string_der(...). """ diff --git a/examples/crypto/public_key_der.py b/examples/crypto/public_key_der.py index 8a1f48e16..45e8715be 100644 --- a/examples/crypto/public_key_der.py +++ b/examples/crypto/public_key_der.py @@ -1,22 +1,22 @@ """ + + Example file: Working with DER-encoded SubjectPublicKeyInfo (SPKI) public keys. uv run examples/crypto/public_key_der.py python examples/crypto/public_key_der.py """ - -from cryptography.hazmat.primitives.asymmetric import ec, ed25519, utils -from cryptography.hazmat.primitives import serialization, hashes from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, ed25519, utils + from hiero_sdk_python.crypto.public_key import PublicKey, keccak256 def example_load_ecdsa_der() -> None: - """ - Demonstrate creating a secp256k1 ECDSA PublicKey from DER-encoded bytes. - """ - # Generate a ECDSA key pair. + """Demonstrate creating a secp256k1 ECDSA PublicKey from DER-encoded bytes.""" + # Generate an ECDSA key pair. private_key = ec.generate_private_key(ec.SECP256K1()) public_key = private_key.public_key() @@ -36,10 +36,8 @@ def example_load_ecdsa_der() -> None: def example_load_ed25519_der() -> None: - """ - Demonstrate creating an Ed25519 PublicKey from DER-encoded bytes. - """ - # Generate a Ed25519 key pair. + """Demonstrate creating an Ed25519 PublicKey from DER-encoded bytes.""" + # Generate an Ed25519 key pair. private_key = ed25519.Ed25519PrivateKey.generate() public_key = private_key.public_key() @@ -59,9 +57,7 @@ def example_load_ed25519_der() -> None: def example_verify_der_signature() -> None: - """ - Demonstrate verifying an ECDSA signature using a DER-encoded public key. - """ + """Demonstrate verifying an ECDSA signature using a DER-encoded public key.""" private_key = ec.generate_private_key(ec.SECP256K1()) public_key = private_key.public_key() diff --git a/examples/crypto/public_key_ecdsa.py b/examples/crypto/public_key_ecdsa.py index 013ebeae0..67290cce8 100644 --- a/examples/crypto/public_key_ecdsa.py +++ b/examples/crypto/public_key_ecdsa.py @@ -1,20 +1,21 @@ """ + + Example file: Working with an ECDSA (secp256k1) PublicKey using the PublicKey class. + uv run examples/crypto/public_key_ecdsa.py python examples/crypto/public_key_ecdsa.py """ - -from cryptography.hazmat.primitives.asymmetric import ec, utils -from cryptography.hazmat.primitives import hashes from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ec, utils + from hiero_sdk_python.crypto.public_key import PublicKey, keccak256 def example_load_compressed_ecdsa() -> None: - """ - Demonstrate creating a PublicKey object from a compressed 33-byte ECDSA hex. - """ + """Demonstrate creating a PublicKey object from a compressed 33-byte ECDSA hex.""" # A mock 33-byte compressed hex: compressed_pubkey = bytes.fromhex( "0281c2e57fecef82ff4f546dece3684acb6e2fe12a97af066348de81ccaf05d0a4" @@ -30,9 +31,7 @@ def example_load_compressed_ecdsa() -> None: def example_load_uncompressed_ecdsa_from_hex() -> None: - """ - Demonstrate creating an ECDSA (secp256k1) public key from an uncompressed 65-byte hex string. - """ + """Demonstrate creating an ECDSA (secp256k1) public key from an uncompressed 65-byte hex string.""" # Uncompressed secp256k1 public keys start with 0x04 and are 65 bytes total. uncompressed_hex = ( "04" @@ -52,9 +51,7 @@ def example_load_uncompressed_ecdsa_from_hex() -> None: def example_verify_ecdsa_signature() -> None: - """ - Demonstrate verifying a signature with an ECDSA secp256k1 public key. - """ + """Demonstrate verifying a signature with an ECDSA secp256k1 public key.""" # Generate a key pair to be able to sign private_key = ec.generate_private_key(ec.SECP256K1()) public_key = private_key.public_key() diff --git a/examples/crypto/public_key_ed25519.py b/examples/crypto/public_key_ed25519.py index 56deedd9d..941e184ad 100644 --- a/examples/crypto/public_key_ed25519.py +++ b/examples/crypto/public_key_ed25519.py @@ -1,17 +1,21 @@ """ -Example file: Working with an Ed25519 PublicKey using the PublicKey class + + +Example file: Working with an Ed25519 PublicKey using the PublicKey class. + uv run examples/crypto/public_key_ed25519.py python examples/crypto/public_key_ed25519.py """ - -from cryptography.hazmat.primitives.asymmetric import ed25519 from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives.asymmetric import ed25519 + from hiero_sdk_python.crypto.public_key import PublicKey def example_load_ed25519_from_raw() -> None: """ Demonstrate creating a PublicKey object from a 32-byte Ed25519 public key. + Please ensure to pass a public key not a private key. """ # Ed25519 public key bytes are always 32 bytes. @@ -31,7 +35,8 @@ def example_load_ed25519_from_raw() -> None: def example_load_ed25519_from_hex() -> None: """ - Demonstrate creating a PublicKey object from a 32-byte hex string + Demonstrate creating a PublicKey object from a 32-byte hex string. + representing an Ed25519 public key. """ # Must be 64 hex characters e.g. @@ -43,9 +48,7 @@ def example_load_ed25519_from_hex() -> None: def example_verify_ed25519_signature() -> None: - """ - Demonstrate verifying an Ed25519 signature. - """ + """Demonstrate verifying an Ed25519 signature.""" # Ed25519 is "EdDSA over Curve25519". # Key pair: private_key = ed25519.Ed25519PrivateKey.generate() diff --git a/examples/errors/max_attempts_error.py b/examples/errors/max_attempts_error.py index 227357582..faeeb176c 100644 --- a/examples/errors/max_attempts_error.py +++ b/examples/errors/max_attempts_error.py @@ -1,12 +1,13 @@ #!/usr/bin/env python3 """ + + Example demonstrating how to handle MaxAttemptsError in the Hiero SDK. run: uv run examples/errors/max_attempts_error.py python examples/errors/max_attempts_error.py """ - from hiero_sdk_python import ( Client, TransactionGetReceiptQuery, @@ -14,6 +15,7 @@ ) from hiero_sdk_python.exceptions import MaxAttemptsError + def main() -> None: # Initialize the client client = Client.from_env() diff --git a/examples/errors/precheck_error.py b/examples/errors/precheck_error.py index 20847a755..7f9e7da65 100644 --- a/examples/errors/precheck_error.py +++ b/examples/errors/precheck_error.py @@ -1,18 +1,16 @@ #!/usr/bin/env python3 """ + + Example demonstrating how to handle PrecheckError in the Hiero SDK. run: uv run examples/errors/precheck_error.py python examples/errors/precheck_error.py """ - +from hiero_sdk_python import AccountId, Client, TransferTransaction from hiero_sdk_python.exceptions import PrecheckError -from hiero_sdk_python import ( - Client, - TransferTransaction, - AccountId -) + def main() -> None: # Initialize the client diff --git a/examples/errors/receipt_status_error.py b/examples/errors/receipt_status_error.py index 93780ec8a..c7bbff3fd 100644 --- a/examples/errors/receipt_status_error.py +++ b/examples/errors/receipt_status_error.py @@ -1,19 +1,17 @@ #!/usr/bin/env python3 """ + + Example demonstrating how to handle ReceiptStatusError in the Hiero SDK. run: uv run examples/errors/receipt_status_error.py python examples/errors/receipt_status_error.py """ -from hiero_sdk_python import ( - Client, - ResponseCode, - TokenAssociateTransaction, - TokenId -) +from hiero_sdk_python import Client, ResponseCode, TokenAssociateTransaction, TokenId from hiero_sdk_python.exceptions import ReceiptStatusError + def main() -> None: client = Client.from_env() diff --git a/examples/file/file_append_transaction.py b/examples/file/file_append_transaction.py index e0ebc7fc7..220eda5d5 100644 --- a/examples/file/file_append_transaction.py +++ b/examples/file/file_append_transaction.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """ -File Append Example +File Append Example. This example demonstrates how to append content to an existing file on the network. It shows both single-chunk and multi-chunk append operations. @@ -9,20 +9,21 @@ uv run examples/file_append_transaction.py python examples/file_append_transaction.py """ -import sys import os +import sys + from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() from hiero_sdk_python import ( + AccountId, Client, + FileAppendTransaction, + FileCreateTransaction, Network, PrivateKey, - FileCreateTransaction, - AccountId, - FileAppendTransaction, ResponseCode, ) @@ -30,7 +31,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -45,7 +46,7 @@ def setup_client(): def create_file(client, file_private_key): - """Create a file with initial content""" + """Create a file with initial content.""" print("Creating file with initial content...") create_receipt = ( FileCreateTransaction() @@ -70,7 +71,7 @@ def create_file(client, file_private_key): def append_file_single(client, file_id, file_private_key): - """Append content to the file (single chunk)""" + """Append content to the file (single chunk).""" print("\nAppending content to file (single chunk)...") append_receipt = ( FileAppendTransaction() @@ -91,7 +92,7 @@ def append_file_single(client, file_id, file_private_key): def append_file_large(client, file_id, file_private_key): - """Append large content to the file (multi-chunk)""" + """Append large content to the file (multi-chunk).""" print("\nAppending large content (multi-chunk)...") large_content = b"Large content that will be split into multiple chunks. " * 100 @@ -121,9 +122,10 @@ def append_file_large(client, file_id, file_private_key): def main(): """ Demonstrates appending content to a file on the network by: + 1. Setting up client with operator account 2. Creating a file with initial content - 3. Appending additional content to the file + 3. Appending additional content to the file. """ client = setup_client() diff --git a/examples/file/file_contents_query.py b/examples/file/file_contents_query.py index a2c9f6e2b..6d70b90a3 100644 --- a/examples/file/file_contents_query.py +++ b/examples/file/file_contents_query.py @@ -1,9 +1,11 @@ """ + + This example demonstrates how to query file contents using the Python SDK. + uv run examples/file/file_contents_query.py python examples/file/file_contents_query.py """ - import os import sys @@ -20,7 +22,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -34,7 +36,7 @@ def setup_client(): def create_file(client: Client): - """Create a test file""" + """Create a test file.""" file_private_key = PrivateKey.generate_ed25519() receipt = ( @@ -62,9 +64,10 @@ def create_file(client: Client): def query_file_contents(): """ Demonstrates querying file contents by: + 1. Setting up client with operator account 2. Creating a test file - 3. Querying the file contents + 3. Querying the file contents. """ client = setup_client() diff --git a/examples/file/file_create_transaction.py b/examples/file/file_create_transaction.py index b30d90ad7..ea3e3591d 100644 --- a/examples/file/file_create_transaction.py +++ b/examples/file/file_create_transaction.py @@ -1,19 +1,22 @@ """ + + Run with: + uv run examples/file_create_transaction.py python examples/file_create_transaction.py """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, AccountId, - PrivateKey, + Client, Network, + PrivateKey, ) from hiero_sdk_python.file.file_create_transaction import FileCreateTransaction from hiero_sdk_python.response_code import ResponseCode @@ -24,7 +27,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -40,9 +43,10 @@ def setup_client(): def file_create(): """ Demonstrates creating a file on the network by: + 1. Setting up client with operator account 2. Creating a file with a private key - 3. Creating a new file + 3. Creating a new file. """ client = setup_client() diff --git a/examples/file/file_delete_transaction.py b/examples/file/file_delete_transaction.py index be4b60428..deec59360 100644 --- a/examples/file/file_delete_transaction.py +++ b/examples/file/file_delete_transaction.py @@ -1,11 +1,13 @@ """ + + This example demonstrates how to delete a file using the Python SDK. + Run with: uv run examples/file_delete_transaction.py python examples/file_delete_transaction.py """ - import os import sys @@ -24,7 +26,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -38,8 +40,7 @@ def setup_client(): def create_file(client: Client): - """Create a test file and return its ID along with the private key""" - + """Create a test file and return its ID along with the private key.""" file_private_key = PrivateKey.generate_ed25519() receipt = ( @@ -63,7 +64,7 @@ def create_file(client: Client): def query_file_info(client: Client, file_id: FileId): - """Query file info and display the results""" + """Query file info and display the results.""" info = FileInfoQuery().set_file_id(file_id).execute(client) print(info) @@ -72,10 +73,11 @@ def query_file_info(client: Client, file_id: FileId): def file_delete(): """ Demonstrates the complete file lifecycle by: + 1. Creating a file 2. Querying file info (before deletion) 3. Deleting the file - 4. Querying file info (after deletion) + 4. Querying file info (after deletion). """ # Setup client client = setup_client() diff --git a/examples/file/file_info_query.py b/examples/file/file_info_query.py index 315df3cf3..6441d6c91 100644 --- a/examples/file/file_info_query.py +++ b/examples/file/file_info_query.py @@ -1,9 +1,11 @@ """ + + This example demonstrates how to query file info using the Python SDK. + uv run examples/file/file_info_query.py python examples/file/file_info_query.py """ - import os import sys @@ -20,7 +22,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -34,7 +36,7 @@ def setup_client(): def create_file(client: Client): - """Create a test file""" + """Create a test file.""" file_private_key = PrivateKey.generate_ed25519() receipt = ( @@ -62,9 +64,10 @@ def create_file(client: Client): def query_file_info(): """ Demonstrates querying file info by: + 1. Setting up client with operator account 2. Creating a test file - 3. Querying the file info + 3. Querying the file info. """ client = setup_client() diff --git a/examples/file/file_update_transaction.py b/examples/file/file_update_transaction.py index 4d72cacf0..4cea7492f 100644 --- a/examples/file/file_update_transaction.py +++ b/examples/file/file_update_transaction.py @@ -1,10 +1,11 @@ """ + +Example demonstrating file update transaction. + Run: uv run examples/file_update_transaction.py python examples/file_update_transaction.py - """ - import os import sys @@ -22,7 +23,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -36,7 +37,7 @@ def setup_client(): def create_file(client): - """Create a test file""" + """Create a test file.""" file_private_key = PrivateKey.generate_ed25519() receipt = ( @@ -68,11 +69,12 @@ def query_file_info(client, file_id): def file_update(): """ Demonstrates querying file info by: + 1. Setting up client with operator account 2. Creating a test file 3. Querying the file info 4. Updating the file info - 5. Querying the file info again + 5. Querying the file info again. """ client = setup_client() diff --git a/examples/hbar.py b/examples/hbar.py index 783129892..b9cf3c78d 100644 --- a/examples/hbar.py +++ b/examples/hbar.py @@ -1,16 +1,16 @@ """ + +Example: Hbar. + uv run examples/hbar.py python examples/hbar.py """ - from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.hbar_unit import HbarUnit def demonstrate_factory_methods(): - """ - Demonstrates creating Hbar values using the convenient factory methods. - """ + """Demonstrates creating Hbar values using the convenient factory methods.""" print("\n=== Creating Hbar Using Factory Methods ===") # Creates an Hbar object representing 1 Gigabar (1,000,000,000 ℏ) @@ -53,9 +53,7 @@ def create_hbar_using_constructor(): def create_hbar_using_of(): - """ - Demonstrates creating Hbar using the of() method with explicit units. - """ + """Demonstrates creating Hbar using the of() method with explicit units.""" print("\n=== Creating Hbar Using of() Method ===") # Treated as 5 ℏ @@ -71,9 +69,7 @@ def create_hbar_using_of(): def create_hbar_from_tinybars(): - """ - Demonstrates using from_tinybars() to create Hbar values directly. - """ + """Demonstrates using from_tinybars() to create Hbar values directly.""" print("\n=== Creating from Tinybars ===") # Treated as tinyhbars @@ -110,9 +106,7 @@ def parse_hbar_from_string(): def demonstrate_conversion_methods(): - """ - Demonstrates usage of to(), to_tinybars(), and to_hbars(). - """ + """Demonstrates usage of to(), to_tinybars(), and to_hbars().""" print("\n=== Converting Hbar Values ===") h = Hbar(10) # 10 ℏ @@ -125,9 +119,7 @@ def demonstrate_conversion_methods(): def demonstrate_negation(): - """ - Demonstrates use of negated() method. - """ + """Demonstrates use of negated() method.""" print("\n=== Negating Hbar Values ===") h = Hbar(15) @@ -140,9 +132,7 @@ def demonstrate_negation(): def demonstrate_constants(): - """ - Demonstrates using ZERO, MAX, and MIN constants. - """ + """Demonstrates using ZERO, MAX, and MIN constants.""" print("\n=== Using Constants ===") # A constant value of zero hbars diff --git a/examples/logger/logging_example.py b/examples/logger/logging_example.py index be38fdcec..9808190ad 100644 --- a/examples/logger/logging_example.py +++ b/examples/logger/logging_example.py @@ -1,5 +1,7 @@ """ -Logging Example - Demonstrates logging functionality in the Hiero SDK + + +Logging Example - Demonstrates logging functionality in the Hiero SDK. This example shows how to: - Set up a client with custom logging @@ -10,18 +12,18 @@ uv run examples/logger/logging_example.py python examples/logger/logging_example.py """ - import os + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, - AccountId, - PrivateKey, AccountCreateTransaction, - Network, + AccountId, + Client, Logger, LogLevel, + Network, + PrivateKey, ) load_dotenv() @@ -84,7 +86,7 @@ def create_key(): # Generate new key to use with new account new_key = PrivateKey.generate() - print(f"Generated new key pair:") + print("Generated new key pair:") print(f" Private key: {new_key.to_string()}") print(f" Public key: {new_key.public_key().to_string()}") diff --git a/examples/nodes/node_create_transaction.py b/examples/nodes/node_create_transaction.py index 8585523b2..1f0c9a940 100644 --- a/examples/nodes/node_create_transaction.py +++ b/examples/nodes/node_create_transaction.py @@ -1,4 +1,6 @@ """ + + Demonstrates adding a node on the network. NOTE: This is a privileged transaction that can only be executed on solo but not on local-node. @@ -15,7 +17,6 @@ 1. GitHub repository with full setup instructions: https://github.com/hiero-ledger/solo 2. Official documentation with step-by-step guide: https://solo.hiero.org/v0.43.0/docs/step-by-step-guide/ """ - import sys from dotenv import load_dotenv @@ -37,7 +38,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" load_dotenv() network = Network(network="solo") client = Client(network) diff --git a/examples/nodes/node_delete_transaction.py b/examples/nodes/node_delete_transaction.py index 23dfc4663..471e8cc71 100644 --- a/examples/nodes/node_delete_transaction.py +++ b/examples/nodes/node_delete_transaction.py @@ -1,4 +1,6 @@ """ + + Example demonstrating node deletion on the network. NOTE: This is a privileged transaction that can only be executed on solo but not on local-node. @@ -15,7 +17,6 @@ 1. GitHub repository with full setup instructions: https://github.com/hiero-ledger/solo 2. Official documentation with step-by-step guide: https://solo.hiero.org/v0.43.0/docs/step-by-step-guide/ """ - import sys from dotenv import load_dotenv @@ -38,7 +39,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" load_dotenv() network = Network(network="solo") client = Client(network) @@ -109,9 +110,10 @@ def create_node(client): def node_delete(): """ Demonstrates node deletion functionality by: + 1. Setting up client with operator account 2. Creating a new node on the network - 3. Deleting the node + 3. Deleting the node. """ # Set up client with operator account client = setup_client() diff --git a/examples/nodes/node_update_transaction.py b/examples/nodes/node_update_transaction.py index 2e29cefec..bd1ec83cf 100644 --- a/examples/nodes/node_update_transaction.py +++ b/examples/nodes/node_update_transaction.py @@ -1,4 +1,6 @@ """ + + Example demonstrating node update on the network. NOTE: This is a privileged transaction that can only be executed on solo but not on local-node. @@ -15,7 +17,6 @@ 1. GitHub repository with full setup instructions: https://github.com/hiero-ledger/solo 2. Official documentation with step-by-step guide: https://solo.hiero.org/v0.43.0/docs/step-by-step-guide/ """ - import sys from dotenv import load_dotenv @@ -38,7 +39,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" load_dotenv() network = Network(network="solo") client = Client(network) @@ -162,10 +163,11 @@ def update_node(client, node_id, admin_key): def node_update(): """ Demonstrates node update functionality by: + 1. Setting up client with operator account 2. Creating a new node on the network 3. Updating the same node with new parameters - 4. Verifying successful update + 4. Verifying successful update. """ # Set up client with operator account client = setup_client() diff --git a/examples/prng_transaction.py b/examples/prng_transaction.py index 3b1df1524..30fdb6011 100644 --- a/examples/prng_transaction.py +++ b/examples/prng_transaction.py @@ -1,4 +1,6 @@ """ + + Example demonstrating PRNG (Pseudo-Random Number Generator) transaction functionality. The PRNG transaction is a transaction that generates a pseudo-random number. @@ -6,7 +8,6 @@ You can set the range for the PRNG transaction to generate a pseudo-random number within a range. If no range is set, the PRNG transaction will generate a 48 byte unsigned pseudo-random number. """ - import os import sys @@ -23,7 +24,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -37,7 +38,7 @@ def setup_client(): def prng_with_range(client, range_value): - """Generate a pseudo-random number within a specified range""" + """Generate a pseudo-random number within a specified range.""" receipt = PrngTransaction().set_range(range_value).execute(client) if receipt.status != ResponseCode.SUCCESS: @@ -54,7 +55,7 @@ def prng_with_range(client, range_value): def prng_without_range(client): - """Generate pseudo-random bytes without specifying a range""" + """Generate pseudo-random bytes without specifying a range.""" receipt = PrngTransaction().execute(client) if receipt.status != ResponseCode.SUCCESS: @@ -73,9 +74,10 @@ def prng_without_range(client): def prng_transaction(): """ Demonstrates PRNG transaction functionality by: + 1. Setting up client with operator account 2. Generating a random number within a range - 3. Generating random bytes without a range + 3. Generating random bytes without a range. """ client = setup_client() diff --git a/examples/protobuf_round_trip.py b/examples/protobuf_round_trip.py index c804c935d..01c5c2737 100644 --- a/examples/protobuf_round_trip.py +++ b/examples/protobuf_round_trip.py @@ -1,5 +1,7 @@ """ -Worked Example: Hedera Protobuf Round Trip + + +Worked Example: Hedera Protobuf Round Trip. This script demonstrates constructing, serializing, and deserializing Hedera protobuf messages without connecting to the network. It shows: @@ -11,9 +13,9 @@ This example accompanies the ProtoBuff Training documentation. """ from hiero_sdk_python.hapi.services import ( - query_pb2, - crypto_get_info_pb2, basic_types_pb2, + crypto_get_info_pb2, + query_pb2, response_pb2, ) diff --git a/examples/query/account_balance_query.py b/examples/query/account_balance_query.py index c7cda035d..001f448d6 100644 --- a/examples/query/account_balance_query.py +++ b/examples/query/account_balance_query.py @@ -1,5 +1,7 @@ """ -Query Balance Example + + +Query Balance Example. This script demonstrates how to: 1. Set up a client connection to the Hedera network @@ -12,18 +14,17 @@ python examples/query/account_balance_query.py """ - import sys import time from hiero_sdk_python import ( - Client, - PrivateKey, AccountCreateTransaction, - TransferTransaction, + Client, CryptoGetAccountBalanceQuery, - ResponseCode, Hbar, + PrivateKey, + ResponseCode, + TransferTransaction, ) @@ -77,7 +78,7 @@ def create_account(client, operator_key, initial_balance=Hbar(10)): receipt = transaction.execute(client) new_account_id = receipt.account_id - print(f"✓ Account created successfully") + print("✓ Account created successfully") print(f" Account ID: {new_account_id}") print( f" Initial balance: {initial_balance.to_hbars()} hbars ({initial_balance.to_tinybars()} tinybars)\n" @@ -144,9 +145,7 @@ def transfer_hbars(client, operator_id, operator_key, recipient_id, amount): def main(): - """ - Main workflow: Set up client, create account, query balance, and transfer HBAR. - """ + """Main workflow: Set up client, create account, query balance, and transfer HBAR.""" try: # Initialize client with operator credentials client, operator_id, operator_key = setup_client() diff --git a/examples/query/account_balance_query_2.py b/examples/query/account_balance_query_2.py index d5483de15..c5c30e588 100644 --- a/examples/query/account_balance_query_2.py +++ b/examples/query/account_balance_query_2.py @@ -1,33 +1,35 @@ # uv run examples/query/account_balance_query_2.py # python examples/query/account_balance_query_2.py -"""Example: Use CryptoGetAccountBalanceQuery to retrieve an account's -HBAR and token balances, including minting NFTs to the account.""" +""" +Example: Use CryptoGetAccountBalanceQuery to retrieve an account's. + +HBAR and token balances, including minting NFTs to the account. +""" import os import sys from hiero_sdk_python import ( - Client, - PrivateKey, - TokenCreateTransaction, AccountCreateTransaction, + AccountId, + Client, Hbar, + PrivateKey, ResponseCode, + TokenCreateTransaction, TokenInfoQuery, - TokenType, TokenMintTransaction, - AccountId, + TokenType, ) from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery from hiero_sdk_python.tokens.token_id import TokenId - key_type = os.getenv("KEY_TYPE", "ecdsa") def setup_client(): - """Setup Client""" + """Setup Client.""" try: client = Client.from_env() print(f"Client set up with operator id {client.operator_account_id}") @@ -38,7 +40,7 @@ def setup_client(): def create_account(client, name, initial_balance=Hbar(10)): - """Create a test account with initial balance""" + """Create a test account with initial balance.""" account_private_key = PrivateKey.generate(key_type) account_public_key = account_private_key.public_key() @@ -96,7 +98,7 @@ def create_and_mint_token(treasury_account_id, treasury_account_key, client): def get_account_balance(client: Client, account_id: AccountId): - """Get account balance using CryptoGetAccountBalanceQuery""" + """Get account balance using CryptoGetAccountBalanceQuery.""" print(f"Retrieving account balance for account id: {account_id} ...") try: # Use CryptoGetAccountBalanceQuery to get the account balance @@ -117,7 +119,7 @@ def get_account_balance(client: Client, account_id: AccountId): def compare_token_balances( client, treasury_id: AccountId, receiver_id: AccountId, token_id: TokenId ): - """Compare token balances between two accounts""" + """Compare token balances between two accounts.""" print( f"\n🔎 Comparing token balances for Token ID {token_id} " f"between accounts {treasury_id} and {receiver_id}..." @@ -134,11 +136,14 @@ def compare_token_balances( def main(): - """Main function to run the account balance query example + """ + + Main function to run the account balance query example. + 1-Create test account with intial balance 2- Create NFT collection with test account as treasury 3- Mint NFTs to the test account - 4- Retrieve and display account balances including token balances + 4- Retrieve and display account balances including token balances. """ client = setup_client() diff --git a/examples/query/account_info_query.py b/examples/query/account_info_query.py index 9b7df6c9f..9afb6c66e 100644 --- a/examples/query/account_info_query.py +++ b/examples/query/account_info_query.py @@ -1,32 +1,33 @@ """ + +Example demonstrating account info query. + uv run examples/query/account_info_query.py python examples/query/account_info_query.py - """ - import sys from hiero_sdk_python import ( + AccountCreateTransaction, Client, + Hbar, PrivateKey, - AccountCreateTransaction, ResponseCode, - Hbar, ) from hiero_sdk_python.query.account_info_query import AccountInfoQuery -from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction +from hiero_sdk_python.tokens.nft_id import NftId +from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_associate_transaction import ( TokenAssociateTransaction, ) +from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_grant_kyc_transaction import TokenGrantKycTransaction -from hiero_sdk_python.tokens.supply_type import SupplyType -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.token_mint_transaction import TokenMintTransaction -from hiero_sdk_python.tokens.nft_id import NftId +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" try: client = Client.from_env() operator_id = client.operator_account_id @@ -40,7 +41,7 @@ def setup_client(): def create_test_account(client, operator_key): - """Create a new test account for demonstration""" + """Create a new test account for demonstration.""" new_account_private_key = PrivateKey.generate_ed25519() new_account_public_key = new_account_private_key.public_key() @@ -67,7 +68,7 @@ def create_test_account(client, operator_key): def create_fungible_token(client, operator_id, operator_key): - """Create a fungible token for association with test account""" + """Create a fungible token for association with test account.""" receipt = ( TokenCreateTransaction() .set_token_name("FungibleToken") @@ -95,7 +96,7 @@ def create_fungible_token(client, operator_id, operator_key): def create_nft(client, account_id, account_private_key): - """Create a non-fungible token""" + """Create a non-fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleNFT") @@ -127,7 +128,7 @@ def create_nft(client, account_id, account_private_key): def mint_nft(client, nft_token_id, account_private_key): - """Mint a non-fungible token""" + """Mint a non-fungible token.""" receipt = ( TokenMintTransaction() .set_token_id(nft_token_id) @@ -147,7 +148,7 @@ def mint_nft(client, nft_token_id, account_private_key): def associate_token_with_account(client, token_id, account_id, account_key): - """Associate the token with the test account""" + """Associate the token with the test account.""" receipt = ( TokenAssociateTransaction() .set_account_id(account_id) @@ -167,7 +168,7 @@ def associate_token_with_account(client, token_id, account_id, account_key): def grant_kyc_for_token(client, account_id, token_id): - """Grant KYC for the token to the account""" + """Grant KYC for the token to the account.""" receipt = ( TokenGrantKycTransaction() .set_account_id(account_id) @@ -183,7 +184,7 @@ def grant_kyc_for_token(client, account_id, token_id): def display_account_info(info): - """Display basic account information""" + """Display basic account information.""" print(f"\nAccount ID: {info.account_id}") print(f"Contract Account ID: {info.contract_account_id}") print(f"Account Balance: {info.balance}") @@ -201,7 +202,7 @@ def display_account_info(info): def display_token_relationships(info): - """Display token relationships information""" + """Display token relationships information.""" print( f"\nToken Relationships ({len(info.token_relationships)} total) for account {info.account_id}:" ) @@ -222,6 +223,7 @@ def display_token_relationships(info): def query_account_info(): """ Demonstrates the account info query functionality by: + 1. Setting up client with operator account 2. Creating a new account 3. Querying account info and displaying account information @@ -230,7 +232,7 @@ def query_account_info(): 6. Granting KYC to the new account for the token 7. Querying account info again to see updated KYC status 8. Creating an NFT token with the new account as treasury and minting one NFT - 9. Querying final account info to see complete token relationships and NFT ownership + 9. Querying final account info to see complete token relationships and NFT ownership. """ client, operator_id, operator_key = setup_client() diff --git a/examples/query/payment_query.py b/examples/query/payment_query.py index 46c519f55..40725e95a 100644 --- a/examples/query/payment_query.py +++ b/examples/query/payment_query.py @@ -1,25 +1,26 @@ """ + +Example demonstrating payment query. + uv run examples/query/payment_query.py python examples/query/payment_query.py - """ - import sys from hiero_sdk_python import ( Client, ) -from hiero_sdk_python.tokens.token_type import TokenType -from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery from hiero_sdk_python.hbar import Hbar +from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" try: client = Client.from_env() operator_id = client.operator_account_id @@ -33,8 +34,7 @@ def setup_client(): def create_fungible_token(client, operator_id, operator_key): - """Create a fungible token""" - + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleFT") @@ -84,7 +84,7 @@ def demonstrate_zero_cost_balance_query(client, account_id): # Execute the query (should work without payment) print("\nExecuting query without payment...") result = query_no_payment.execute(client) - print(f"Query executed successfully!") + print("Query executed successfully!") print(f" Account balance (only hbars): {result.hbars}") # Case 2: Payment set - should return the set payment amount @@ -103,7 +103,7 @@ def demonstrate_zero_cost_balance_query(client, account_id): # Execute the query (should work with custom payment) print("\nExecuting query with custom payment...") result = query_with_payment.execute(client) - print(f"Query executed successfully!") + print("Query executed successfully!") print(f" Account balance (only hbars): {result.hbars}") @@ -130,7 +130,7 @@ def demonstrate_payment_required_queries(client, token_id): # Execute the query (should work with network-determined cost) print("\nExecuting query with network-determined cost...") result = query_no_payment.execute(client) - print(f"Query executed successfully!") + print("Query executed successfully!") print(f" Token info: {result}") # Case 2: Payment set - should return the set payment amount @@ -147,7 +147,7 @@ def demonstrate_payment_required_queries(client, token_id): # Execute the query (should work with custom payment) print("\nExecuting query with custom payment...") result = query_with_payment.execute(client) - print(f"Query executed successfully!") + print("Query executed successfully!") print(f" Token info: {result}") # Case 3: Compare network cost vs custom payment @@ -159,11 +159,12 @@ def demonstrate_payment_required_queries(client, token_id): def query_payment(): """ Demonstrates the query payment by: + 1. Setting up client with operator account 2. Creating a fungible token with the operator account as owner 3. Demonstrating queries that don't require payment (CryptoGetAccountBalanceQuery) 4. Demonstrating queries that do require payment (TokenInfoQuery) - 5. Comparing network-determined cost vs custom payment amount + 5. Comparing network-determined cost vs custom payment amount. """ client, operator_id, operator_key = setup_client() token_id = create_fungible_token(client, operator_id, operator_key) diff --git a/examples/query/token_info_query_fungible.py b/examples/query/token_info_query_fungible.py index 8c5593821..d63beb992 100644 --- a/examples/query/token_info_query_fungible.py +++ b/examples/query/token_info_query_fungible.py @@ -1,22 +1,24 @@ """ + +Example demonstrating token info query fungible. + uv run examples/query/token_info_query_fungible.py python examples/query/token_info_query_fungible.py """ - import sys from hiero_sdk_python import ( Client, ) -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" try: client = Client.from_env() operator_id = client.operator_account_id @@ -30,7 +32,7 @@ def setup_client(): def create_fungible_token(client, operator_id, operator_key): - """Create a fungible token""" + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleFT") @@ -64,9 +66,10 @@ def create_fungible_token(client, operator_id, operator_key): def query_token_info(): """ Demonstrates the token info query functionality by: + 1. Creating a fungible token 2. Querying the token's information using TokenInfoQuery - 3. Printing the token details of the TokenInfo object + 3. Printing the token details of the TokenInfo object. """ client, operator_id, operator_key = setup_client() token_id = create_fungible_token(client, operator_id, operator_key) diff --git a/examples/query/token_info_query_nft.py b/examples/query/token_info_query_nft.py index d8576bb13..6c924f71e 100644 --- a/examples/query/token_info_query_nft.py +++ b/examples/query/token_info_query_nft.py @@ -1,23 +1,24 @@ """ + +Example demonstrating token info query nft. + uv run examples/query/token_info_query_nft.py python examples/token_info_query_nft.py - """ - import sys from hiero_sdk_python import ( Client, ) -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" try: client = Client.from_env() operator_id = client.operator_account_id @@ -31,7 +32,7 @@ def setup_client(): def create_nft(client, operator_id, operator_key): - """Create a non-fungible token""" + """Create a non-fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleNFT") @@ -63,9 +64,10 @@ def create_nft(client, operator_id, operator_key): def query_token_info(): """ Demonstrates the token info query functionality by: - 1. Creating a NFT + + 1. Creating an NFT 2. Querying the token's information using TokenInfoQuery - 3. Printing the token details of the TokenInfo object + 3. Printing the token details of the TokenInfo object. """ client, operator_id, operator_key = setup_client() token_id = create_nft(client, operator_id, operator_key) diff --git a/examples/query/token_nft_info_query.py b/examples/query/token_nft_info_query.py index b87f37fa9..8496eab66 100644 --- a/examples/query/token_nft_info_query.py +++ b/examples/query/token_nft_info_query.py @@ -1,25 +1,26 @@ """ + +Example demonstrating token nft info query. + uv run examples/query/token_nft_info_query.py python examples/query/token_nft_info_query.py - """ - import sys from hiero_sdk_python import ( Client, ) -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.query.token_nft_info_query import TokenNftInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.nft_id import NftId from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_mint_transaction import TokenMintTransaction +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" try: client = Client.from_env() operator_id = client.operator_account_id @@ -33,7 +34,7 @@ def setup_client(): def create_nft(client, operator_id, operator_key): - """Create a non-fungible token""" + """Create a non-fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleNFT") @@ -63,7 +64,7 @@ def create_nft(client, operator_id, operator_key): def mint_nft(client, nft_token_id): - """Mint a non-fungible token""" + """Mint a non-fungible token.""" receipt = ( TokenMintTransaction() .set_token_id(nft_token_id) @@ -83,9 +84,10 @@ def mint_nft(client, nft_token_id): def query_nft_info(): """ Demonstrates the nft info query functionality by: + 1. Creating a nft 2. Minting a nft - 3. Querying the nft info + 3. Querying the nft info. """ client, operator_id, operator_key = setup_client() token_id = create_nft(client, operator_id, operator_key) diff --git a/examples/query/topic_info_query.py b/examples/query/topic_info_query.py index 8b508bc5f..7d6f3ec34 100644 --- a/examples/query/topic_info_query.py +++ b/examples/query/topic_info_query.py @@ -1,19 +1,21 @@ """ + +Example demonstrating topic info query. + uv run examples/query/topic_info_query.py python examples/query/topic_info_query.py - """ - import sys + from hiero_sdk_python import ( Client, - TopicInfoQuery, TopicCreateTransaction, + TopicInfoQuery, ) def create_topic(client, operator_key): - """Create a new topic""" + """Create a new topic.""" print("\nSTEP 1: Creating a Topic...") try: topic_tx = ( @@ -34,9 +36,7 @@ def create_topic(client, operator_key): def query_topic_info(): - """ - A full example that create a topic and query topic info for that topic. - """ + """A full example that create a topic and query topic info for that topic.""" # Config Client client = Client.from_env() print(f"Operator: {client.operator_account_id}") diff --git a/examples/query/topic_message_query.py b/examples/query/topic_message_query.py index 7275e1d76..0198a403c 100644 --- a/examples/query/topic_message_query.py +++ b/examples/query/topic_message_query.py @@ -1,9 +1,10 @@ """ + +Example demonstrating topic message query. + uv run examples/query/topic_message_query.py python examples/query/topic_message_query.py - """ - import sys import time from datetime import datetime, timezone @@ -16,7 +17,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" try: client = Client.from_env() operator_id = client.operator_account_id @@ -30,7 +31,7 @@ def setup_client(): def create_topic(client, operator_key): - """Create a new topic""" + """Create a new topic.""" print("\nSTEP 1: Creating a Topic...") try: topic_tx = ( @@ -51,9 +52,7 @@ def create_topic(client, operator_key): def query_topic_messages(): - """ - A full example that creates a topic and perform query topic messages. - """ + """A full example that creates a topic and perform query topic messages.""" # Config Client client, _, operator_key = setup_client() diff --git a/examples/query/transaction_get_receipt_query.py b/examples/query/transaction_get_receipt_query.py index 9d9955d50..535a5853c 100644 --- a/examples/query/transaction_get_receipt_query.py +++ b/examples/query/transaction_get_receipt_query.py @@ -1,24 +1,25 @@ """ + +Example demonstrating transaction get receipt query. + uv run examples/query/transaction_get_receipt_query.py python examples/query/transaction_get_receipt_query.py - """ - import sys from hiero_sdk_python import ( + AccountCreateTransaction, Client, - PrivateKey, - TransferTransaction, Hbar, - TransactionGetReceiptQuery, + PrivateKey, ResponseCode, - AccountCreateTransaction, + TransactionGetReceiptQuery, + TransferTransaction, ) def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" try: client = Client.from_env() operator_id = client.operator_account_id @@ -32,7 +33,7 @@ def setup_client(): def create_account(client, operator_key): - """Create a new recipient account""" + """Create a new recipient account.""" print("\nSTEP 1: Creating a new recipient account...") recipient_key = PrivateKey.generate() try: @@ -53,7 +54,6 @@ def create_account(client, operator_key): def _print_receipt_children(queried_receipt): """Pretty-print receipt status and any child receipts.""" - children = queried_receipt.children if not children: @@ -71,7 +71,6 @@ def _print_receipt_children(queried_receipt): def _print_receipt_duplicates(queried_receipt): """Pretty-print receipt status and any duplicate receipts.""" - duplicates = queried_receipt.duplicates if not duplicates: @@ -90,6 +89,7 @@ def _print_receipt_duplicates(queried_receipt): def query_receipt(): """ A full example that include account creation, Hbar transfer, and receipt querying. + Demonstrates include_child_receipts support (SDK API: set_include_children). """ # Config Client diff --git a/examples/query/transaction_record_query.py b/examples/query/transaction_record_query.py index fcf616b0c..7cd77594a 100644 --- a/examples/query/transaction_record_query.py +++ b/examples/query/transaction_record_query.py @@ -1,15 +1,16 @@ """ + +Example demonstrating transaction record query. + uv run examples/query/transaction_record_query.py python examples/query/transaction_record_query.py - """ - import sys from hiero_sdk_python import ( Client, - PrivateKey, Hbar, + PrivateKey, ) from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction from hiero_sdk_python.query.transaction_record_query import TransactionRecordQuery @@ -24,7 +25,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" try: client = Client.from_env() operator_id = client.operator_account_id @@ -38,7 +39,7 @@ def setup_client(): def create_account_transaction(client): - """Create a new account to get a transaction ID for record query""" + """Create a new account to get a transaction ID for record query.""" # Generate a new key pair for the account new_account_key = PrivateKey.generate_ed25519() @@ -67,7 +68,7 @@ def create_account_transaction(client): def create_fungible_token(client: "Client", account_id, account_private_key): - """Create a fungible token""" + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleFT") @@ -96,7 +97,7 @@ def create_fungible_token(client: "Client", account_id, account_private_key): def associate_token(client, token_id, receiver_id, receiver_private_key): - """Associate token with an account""" + """Associate token with an account.""" # Associate the token_id with the new account receipt = ( TokenAssociateTransaction() @@ -119,7 +120,7 @@ def associate_token(client, token_id, receiver_id, receiver_private_key): def transfer_tokens( client, treasury_id, treasury_private_key, receiver_id, token_id, amount=10 ): - """Transfer tokens to the receiver account so we can later reject them""" + """Transfer tokens to the receiver account so we can later reject them.""" # Transfer tokens to the receiver account receipt = ( TransferTransaction() @@ -141,14 +142,14 @@ def transfer_tokens( def print_transaction_record(record): - """Print the transaction record""" + """Print the transaction record.""" print(f"Transaction ID: {record.transaction_id}") print(f"Transaction Fee: {record.transaction_fee}") print(f"Transaction Hash: {record.transaction_hash.hex()}") print(f"Transaction Memo: {record.transaction_memo}") print(f"Transaction Account ID: {record.receipt.account_id}") - print(f"\nTransfers made in the transaction:") + print("\nTransfers made in the transaction:") for account_id, amount in record.transfers.items(): print(f" Account: {account_id}, Amount: {amount}") @@ -156,11 +157,12 @@ def print_transaction_record(record): def query_record(): """ Demonstrates the transaction record query functionality by performing the following steps: + 1. Creating a new account transaction to get a transaction ID 2. Querying and displaying the transaction record for account creation 3. Creating a fungible token and associating it with the new account 4. Transferring tokens from operator to new account - 5. Querying and displaying the transaction record for token transfer + 5. Querying and displaying the transaction record for token transfer. """ client, operator_id, operator_key = setup_client() @@ -185,7 +187,7 @@ def query_record(): print("Transaction record for token transfer:") print_transaction_record(transfer_record) - print(f"\nToken Transfer Record:") + print("\nToken Transfer Record:") for token_id, transfers in transfer_record.token_transfers.items(): print(f" Token ID: {token_id}") for account_id, amount in transfers.items(): diff --git a/examples/query/transaction_record_query_with_duplicates.py b/examples/query/transaction_record_query_with_duplicates.py index 54d4dc253..2e433d2e0 100644 --- a/examples/query/transaction_record_query_with_duplicates.py +++ b/examples/query/transaction_record_query_with_duplicates.py @@ -1,4 +1,6 @@ """ + + Demonstrates behavior when submitting duplicate transactions and querying records. Key points shown: @@ -10,16 +12,16 @@ Do NOT expect to see non-empty duplicates in this example — that's intentional. """ - import sys import time + from hiero_sdk_python import Client from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction from hiero_sdk_python.crypto.private_key import PrivateKey +from hiero_sdk_python.exceptions import PrecheckError from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.query.transaction_record_query import TransactionRecordQuery from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.exceptions import PrecheckError def main(): diff --git a/examples/schedule/schedule_create_transaction.py b/examples/schedule/schedule_create_transaction.py index 8fa5e7cbd..f7aed4e68 100644 --- a/examples/schedule/schedule_create_transaction.py +++ b/examples/schedule/schedule_create_transaction.py @@ -1,9 +1,11 @@ """ + + Example demonstrating account schedule creation. + uv run examples/schedule/schedule_create_transaction.py python examples/schedule/schedule_create_transaction.py """ - import datetime import os import sys @@ -25,7 +27,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -39,7 +41,7 @@ def setup_client(): def create_account(client): - """Create a test account""" + """Create a test account.""" account_private_key = PrivateKey.generate_ed25519() account_public_key = account_private_key.public_key() @@ -66,13 +68,13 @@ def create_account(client): def account_balance(client, account_id): - """Get the balance of an account""" + """Get the balance of an account.""" balance = CryptoGetAccountBalanceQuery(account_id).execute(client) print(f"Account balance: {balance.hbars} hbars") def schedule_transfer_transaction(client, account_id): - """Schedule a transfer transaction""" + """Schedule a transfer transaction.""" # Amount to transfer in tinybars amount = Hbar(1).to_tinybars() # Create a transfer transaction @@ -82,19 +84,19 @@ def schedule_transfer_transaction(client, account_id): .add_hbar_transfer(client.operator_account_id, amount) ) # Convert the transfer transaction into a scheduled transaction - schedule_tx = transfer_tx.schedule() - return schedule_tx + return transfer_tx.schedule() def schedule_account_create(): """ Demonstrates account schedule functionality by: + 1. Setting up client with operator account 2. Creating a test account 3. Scheduling a transfer transaction to move HBAR from the test account to the operator account 4. Signing and executing the scheduled transaction 5. Checking the account balance before and after the scheduled transaction - 6. Querying the transaction record to check if it was executed + 6. Querying the transaction record to check if it was executed. """ client = setup_client() diff --git a/examples/schedule/schedule_delete_transaction.py b/examples/schedule/schedule_delete_transaction.py index 5a8708820..b33b94ff4 100644 --- a/examples/schedule/schedule_delete_transaction.py +++ b/examples/schedule/schedule_delete_transaction.py @@ -1,9 +1,11 @@ """ + + Example demonstrating schedule deletion on the network. + uv run examples/schedule/schedule_delete_transaction.py python examples/schedule/schedule_delete_transaction.py """ - import datetime import os import sys @@ -30,7 +32,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -44,7 +46,7 @@ def setup_client(): def create_account(client): - """Create a test account""" + """Create a test account.""" account_private_key = PrivateKey.generate_ed25519() account_public_key = account_private_key.public_key() @@ -71,7 +73,7 @@ def create_account(client): def create_schedule(client, account_id, account_private_key): - """Create a scheduled transaction""" + """Create a scheduled transaction.""" # Amount to transfer in tinybars amount = Hbar(1).to_tinybars() @@ -118,10 +120,11 @@ def create_schedule(client, account_id, account_private_key): def schedule_delete(): """ Demonstrates schedule deletion functionality by: + 1. Setting up client with operator account 2. Creating a test account 3. Creating a scheduled transaction - 4. Deleting the scheduled transaction + 4. Deleting the scheduled transaction. """ client = setup_client() diff --git a/examples/schedule/schedule_info_query.py b/examples/schedule/schedule_info_query.py index d4130e5f2..3463330be 100644 --- a/examples/schedule/schedule_info_query.py +++ b/examples/schedule/schedule_info_query.py @@ -1,9 +1,11 @@ """ + + Example demonstrating schedule info query on the network. + uv run examples/schedule/schedule_info_query.py python examples/schedule/schedule_info_query.py """ - import datetime import os import sys @@ -11,12 +13,12 @@ from dotenv import load_dotenv from hiero_sdk_python import ( + AccountCreateTransaction, AccountId, Client, Hbar, Network, PrivateKey, - AccountCreateTransaction, ResponseCode, ScheduleInfoQuery, Timestamp, @@ -29,7 +31,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -43,7 +45,7 @@ def setup_client(): def create_account(client): - """Create a test account""" + """Create a test account.""" account_private_key = PrivateKey.generate_ed25519() account_public_key = account_private_key.public_key() @@ -70,7 +72,7 @@ def create_account(client): def create_schedule(client, account_id, account_private_key): - """Create a scheduled transaction""" + """Create a scheduled transaction.""" # Amount to transfer in tinybars amount = Hbar(1).to_tinybars() @@ -116,10 +118,11 @@ def create_schedule(client, account_id, account_private_key): def query_schedule_info(): """ Demonstrates querying a schedule info by: + 1. Setting up client with operator account 2. Creating a test account that will schedule the txn 3. Creating a scheduled transaction - 4. Querying the schedule info + 4. Querying the schedule info. """ client = setup_client() diff --git a/examples/schedule/schedule_sign_transaction.py b/examples/schedule/schedule_sign_transaction.py index c899f4a75..2bd8334aa 100644 --- a/examples/schedule/schedule_sign_transaction.py +++ b/examples/schedule/schedule_sign_transaction.py @@ -1,4 +1,6 @@ """ + + Example demonstrating Schedule Sign functionality. Execution rule: @@ -15,7 +17,6 @@ uv run examples/schedule/schedule_sign_transaction.py python examples/schedule/schedule_sign_transaction.py """ - import datetime import os import sys @@ -36,7 +37,7 @@ def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -50,7 +51,7 @@ def setup_client(): def create_account(client): - """Create a test account""" + """Create a test account.""" account_private_key = PrivateKey.generate_ed25519() account_public_key = account_private_key.public_key() @@ -77,7 +78,7 @@ def create_account(client): def create_schedule(client, account_id): - """Create a scheduled transaction""" + """Create a scheduled transaction.""" # Amount to transfer in tinybars amount = Hbar(1).to_tinybars() @@ -134,7 +135,7 @@ def _fmt_ts(ts): def query_schedule_info(client, schedule_id, required_inner_keys=None): - """Query and display schedule information (including missing signatures if known)""" + """Query and display schedule information (including missing signatures if known).""" info = ScheduleInfoQuery().set_schedule_id(schedule_id).execute(client) print("\nSchedule Info:") @@ -166,12 +167,13 @@ def query_schedule_info(client, schedule_id, required_inner_keys=None): def schedule_sign(): """ Demonstrates schedule sign functionality by: + 1. Setting up client with operator account 2. Creating a test account 3. Creating a scheduled transfer transaction 4. Querying the schedule info before signing 5. Signing the scheduled transaction to execute it - 6. Querying the schedule info after signing to verify execution + 6. Querying the schedule info after signing to verify execution. """ client = setup_client() diff --git a/examples/tls_query_balance.py b/examples/tls_query_balance.py index e00b8f92b..7a1741999 100644 --- a/examples/tls_query_balance.py +++ b/examples/tls_query_balance.py @@ -1,5 +1,6 @@ -""" -TLS Query Balance Example +r""" + +TLS Query Balance Example. Demonstrates how to connect to the Hedera network with TLS enabled. @@ -13,16 +14,16 @@ Run with: uv run examples/tls_query_balance.py """ - import os + from dotenv import load_dotenv from hiero_sdk_python import ( - Network, - Client, AccountId, - PrivateKey, + Client, CryptoGetAccountBalanceQuery, + Network, + PrivateKey, ) diff --git a/examples/tokens/account_allowance_approve_transaction.py b/examples/tokens/account_allowance_approve_transaction.py index 9b7bbb0e9..d1c31bcb5 100644 --- a/examples/tokens/account_allowance_approve_transaction.py +++ b/examples/tokens/account_allowance_approve_transaction.py @@ -1,13 +1,14 @@ """ + + Example demonstrating fungible token allowance approval and usage. + uv run examples/tokens/account_allowance_approve_transaction.py python examples/tokens/account_allowance_approve_transaction.py """ - import sys - from hiero_sdk_python import Client, Hbar, PrivateKey, TransactionId from hiero_sdk_python.account.account_allowance_approve_transaction import ( AccountAllowanceApproveTransaction, @@ -31,7 +32,7 @@ def setup_client(): def create_account(client): - """Create an account""" + """Create an account.""" account_private_key = PrivateKey.generate_ed25519() account_public_key = account_private_key.public_key() @@ -55,7 +56,7 @@ def create_account(client): def create_fungible_token(client): - """Create a fungible token""" + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("Test Token") @@ -80,7 +81,7 @@ def create_fungible_token(client): def associate_token_with_account(client, account_id, account_private_key, token_id): - """Associate token with account""" + """Associate token with account.""" receipt = ( TokenAssociateTransaction() .set_account_id(account_id) @@ -102,7 +103,7 @@ def associate_token_with_account(client, account_id, account_private_key, token_ def approve_token_allowance( client, token_id, owner_account_id, spender_account_id, amount ): - """Approve token allowance for spender""" + """Approve token allowance for spender.""" receipt = ( AccountAllowanceApproveTransaction() .approve_token_allowance(token_id, owner_account_id, spender_account_id, amount) @@ -120,7 +121,7 @@ def approve_token_allowance( def delete_token_allowance(client, token_id, owner_account_id, spender_account_id): - """Delete token allowance by setting amount to 0""" + """Delete token allowance by setting amount to 0.""" receipt = ( AccountAllowanceApproveTransaction() .approve_token_allowance(token_id, owner_account_id, spender_account_id, 0) @@ -145,7 +146,7 @@ def transfer_token_without_allowance( receiver_account_id, token_id, ): - """Transfer tokens without allowance""" + """Transfer tokens without allowance.""" print("Trying to transfer tokens without allowance...") owner_account_id = client.operator_account_id client.set_operator( @@ -173,13 +174,14 @@ def transfer_token_without_allowance( def token_allowance(): """ Demonstrates fungible token allowance functionality by: + 1. Setting up client with operator account 2. Creating spender and receiver accounts 3. Creating a fungible token and associating it with the receiver account 4. Approving token allowance for spender 5. Transferring tokens using the allowance 6. Deleting the allowance - 7. Attempting to transfer tokens without allowance (should fail) + 7. Attempting to transfer tokens without allowance (should fail). """ client = setup_client() diff --git a/examples/tokens/custom_fee_fixed.py b/examples/tokens/custom_fee_fixed.py index 4f474cf43..f833b0a53 100644 --- a/examples/tokens/custom_fee_fixed.py +++ b/examples/tokens/custom_fee_fixed.py @@ -1,18 +1,19 @@ """ + + Run with: + uv run examples/tokens/custom_fixed_fee.py python examples/tokens/custom_fixed_fee.py """ - import sys -from hiero_sdk_python.crypto.private_key import PrivateKey from hiero_sdk_python.client.client import Client +from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.custom_fixed_fee import CustomFixedFee -from hiero_sdk_python.hbar import Hbar +from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_type import TokenType @@ -24,12 +25,7 @@ def setup_client(): return client def custom_fixed_fee_example(): - """ - - Demonstrates how to create a token with a Custom Fixed Fee. - - """ - + """Demonstrates how to create a token with a Custom Fixed Fee.""" client = setup_client() print("\n--- Creating Custom Fixed Fee ---") diff --git a/examples/tokens/custom_fee_fractional.py b/examples/tokens/custom_fee_fractional.py index 0fe789539..b46b0e231 100644 --- a/examples/tokens/custom_fee_fractional.py +++ b/examples/tokens/custom_fee_fractional.py @@ -1,23 +1,25 @@ """ + + Run with: + python examples/tokens/custom_fractional_fee.py uv run examples/tokens/custom_fractional_fee.py """ - import sys +from hiero_sdk_python.account.account_id import AccountId +from hiero_sdk_python.client.client import Client +from hiero_sdk_python.query.token_info_query import TokenInfoQuery +from hiero_sdk_python.response_code import ResponseCode +from hiero_sdk_python.tokens.custom_fractional_fee import CustomFractionalFee +from hiero_sdk_python.tokens.fee_assessment_method import FeeAssessmentMethod +from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import ( TokenCreateTransaction, TokenParams, ) -from hiero_sdk_python.tokens.custom_fractional_fee import CustomFractionalFee -from hiero_sdk_python.tokens.fee_assessment_method import FeeAssessmentMethod -from hiero_sdk_python.query.token_info_query import TokenInfoQuery -from hiero_sdk_python.account.account_id import AccountId -from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.client.client import Client from hiero_sdk_python.tokens.token_type import TokenType -from hiero_sdk_python.tokens.supply_type import SupplyType def setup_client(): @@ -74,16 +76,14 @@ def print_fractional_fees(token_info, fractional_fee): if not token_info.custom_fees: print("No custom fees found.") return - else: - print("\n--- Custom Fractional Fee ---") - print(fractional_fee) + print("\n--- Custom Fractional Fee ---") + print(fractional_fee) def query_and_validate_fractional_fee(client: Client, token_id): """Fetch token info from Hedera and print the custom fractional fees.""" print("\nQuerying token info to validate fractional fee...") - token_info = TokenInfoQuery(token_id=token_id).execute(client) - return token_info + return TokenInfoQuery(token_id=token_id).execute(client) def main(): diff --git a/examples/tokens/custom_royalty_fee.py b/examples/tokens/custom_royalty_fee.py index b476c81b5..33cec8243 100644 --- a/examples/tokens/custom_royalty_fee.py +++ b/examples/tokens/custom_royalty_fee.py @@ -1,19 +1,18 @@ """ + + Run with: + uv run examples/tokens/custom_royalty_fee.py python examples/tokens/custom_royalty_fee.py """ - -import sys - -from hiero_sdk_python.crypto.private_key import PrivateKey from hiero_sdk_python.client.client import Client -from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.tokens.supply_type import SupplyType +from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.query.token_info_query import TokenInfoQuery +from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.custom_fixed_fee import CustomFixedFee from hiero_sdk_python.tokens.custom_royalty_fee import CustomRoyaltyFee -from hiero_sdk_python.hbar import Hbar +from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_type import TokenType @@ -47,7 +46,6 @@ def create_royalty_fee_object(client): def create_token_with_fee(client, royalty_fee): """Creates a token with the specified royalty fee attached.""" - print("\n--- Creating Token with Royalty Fee ---") transaction = ( TokenCreateTransaction() @@ -80,7 +78,6 @@ def create_token_with_fee(client, royalty_fee): def verify_token_fee(client, token_id): """Queries the network to verify the fee exists.""" - print("\n--- Verifying Fee on Network ---") token_info = TokenInfoQuery().set_token_id(token_id).execute(client) retrieved_fees = token_info.custom_fees diff --git a/examples/tokens/token_airdrop_claim_auto.py b/examples/tokens/token_airdrop_claim_auto.py index a267c4e70..5b60f486f 100644 --- a/examples/tokens/token_airdrop_claim_auto.py +++ b/examples/tokens/token_airdrop_claim_auto.py @@ -1,5 +1,7 @@ """ -Hedera Token Airdrop Example Script + + +Hedera Token Airdrop Example Script. This script demonstrates an end-to-end example for an account to automatically (no user action required) claim a set of airdrops. @@ -20,31 +22,30 @@ uv run examples/tokens/token_airdrop_claim_auto.py python examples/tokens/token_airdrop_claim_auto.py """ - # pylint: disable=import-error, # pylint: disable=too-many-arguments, # pylint: disable=too-many-positional-arguments, # pylint: disable=protected-access, # pylint: disable=broad-exception-caught -import sys -from typing import Iterable +from collections.abc import Iterable + from hiero_sdk_python import ( - Client, - AccountId, - PrivateKey, AccountCreateTransaction, - TokenCreateTransaction, - TokenMintTransaction, - TokenAirdropTransaction, - TokenType, - SupplyType, - NftId, + AccountId, + Client, CryptoGetAccountBalanceQuery, - ResponseCode, Hbar, + NftId, + PrivateKey, + ResponseCode, + SupplyType, + TokenAirdropTransaction, + TokenCreateTransaction, TokenId, + TokenMintTransaction, TokenNftInfoQuery, + TokenType, ) diff --git a/examples/tokens/token_airdrop_claim_signature_required.py b/examples/tokens/token_airdrop_claim_signature_required.py index 5e9a0cb35..4b3feb2cb 100644 --- a/examples/tokens/token_airdrop_claim_signature_required.py +++ b/examples/tokens/token_airdrop_claim_signature_required.py @@ -1,5 +1,7 @@ """ -Hedera Token Airdrop Example Script + + +Hedera Token Airdrop Example Script. This script demonstrates and end-to-end example for an account to claim a set of airdrops. @@ -21,39 +23,36 @@ uv run examples/tokens/token_airdrop_claim_signature_required.py python examples/tokens/token_airdrop_claim_signature_required.py """ - # pylint: disable=import-error, # pylint: disable=too-many-arguments, # pylint: disable=protected-access, # pylint: disable=broad-except -import sys -from typing import Iterable, List, Dict +from collections.abc import Iterable from hiero_sdk_python import ( - Client, - AccountId, - PrivateKey, AccountCreateTransaction, - TokenCreateTransaction, - TokenMintTransaction, - TokenAirdropTransaction, - TokenType, - SupplyType, - NftId, + AccountId, + Client, CryptoGetAccountBalanceQuery, - ResponseCode, Hbar, + NftId, + PendingAirdropId, + PrivateKey, + ResponseCode, + SupplyType, + TokenAirdropTransaction, + TokenClaimAirdropTransaction, + TokenCreateTransaction, TokenId, + TokenMintTransaction, TokenNftInfoQuery, - TokenClaimAirdropTransaction, - PendingAirdropId, - TransactionRecordQuery, - TransactionRecord, + TokenType, TransactionId, + TransactionRecord, + TransactionRecordQuery, ) - def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -64,9 +63,7 @@ def setup_client(): def create_receiver( client: Client, signature_required: bool = True, max_auto_assoc: int = 0 ): - """ - Creates a receiver account with specific configurations. - """ + """Creates a receiver account with specific configurations.""" receiver_key = PrivateKey.generate() receiver_public_key = receiver_key.public_key() @@ -104,9 +101,7 @@ def create_fungible_token( initial_supply: int = 50, max_supply: int = 1000, ): - """ - Creates a fungible token. - """ + """Creates a fungible token.""" try: receipt = ( TokenCreateTransaction() @@ -140,9 +135,7 @@ def create_nft_token( symbol: str = "MNT", max_supply: int = 100, ): - """ - Creates an NFT token. - """ + """Creates an NFT token.""" try: receipt = ( TokenCreateTransaction() @@ -174,9 +167,7 @@ def mint_nft_token( operator_key: PrivateKey, nft_token_id: TokenId, ): - """ - Mints an NFT token. - """ + """Mints an NFT token.""" try: receipt = ( TokenMintTransaction() @@ -201,11 +192,9 @@ def mint_nft_token( def get_token_association_status( - client: Client, receiver_id: AccountId, token_ids: List[TokenId] -) -> Dict[TokenId, bool]: - """ - Checks if the receiver account is associated with the given tokens. - """ + client: Client, receiver_id: AccountId, token_ids: list[TokenId] +) -> dict[TokenId, bool]: + """Checks if the receiver account is associated with the given tokens.""" try: # Query the receiver's balance, which includes token associations balance = ( @@ -229,9 +218,7 @@ def get_token_association_status( def log_fungible_balances(balances: dict, token_ids: Iterable[TokenId]): - """ - Logs the balances of fungible tokens. - """ + """Logs the balances of fungible tokens.""" print(" Fungible tokens:") for token_id in token_ids: amount = balances.get(token_id, 0) @@ -239,9 +226,7 @@ def log_fungible_balances(balances: dict, token_ids: Iterable[TokenId]): def log_nft_balances(client: Client, account_id: AccountId, nft_ids: Iterable[NftId]): - """ - Logs the ownership of NFTs. - """ + """Logs the ownership of NFTs.""" print(" NFTs:") owned_nfts = [] for nft_id in nft_ids: @@ -267,9 +252,7 @@ def log_balances( nft_ids: Iterable[NftId], prefix: str = "", ): - """ - Logs the balances of both the operator and receiver accounts. - """ + """Logs the balances of both the operator and receiver accounts.""" print(f"\n===== {prefix} Balances =====") try: @@ -312,10 +295,7 @@ def perform_airdrop( nft_ids: Iterable[NftId], ft_amount: int = 100, ): - """ - Performs an airdrop of fungible and NFT tokens. - """ - + """Performs an airdrop of fungible and NFT tokens.""" try: transaction = TokenAirdropTransaction() @@ -349,7 +329,7 @@ def perform_airdrop( def fetch_pending_airdrops( client: Client, transaction_id: TransactionId -) -> List[PendingAirdropId]: +) -> list[PendingAirdropId]: """ Retrieve all pending airdrop IDs generated by a specific transaction. @@ -379,7 +359,7 @@ def fetch_pending_airdrops( def claim_airdrop( - client: Client, receiver_key: PrivateKey, pending_airdrops: List[PendingAirdropId] + client: Client, receiver_key: PrivateKey, pending_airdrops: list[PendingAirdropId] ): """ Claims one or more pending airdrops on behalf of the receiver. @@ -410,9 +390,7 @@ def claim_airdrop( def main(): - """ - Main function to execute the airdrop claim example. - """ + """Main function to execute the airdrop claim example.""" # Set up client and derive operator credentials client = setup_client() operator_id = client.operator_account_id diff --git a/examples/tokens/token_airdrop_transaction.py b/examples/tokens/token_airdrop_transaction.py index 50876020a..f43295d97 100644 --- a/examples/tokens/token_airdrop_transaction.py +++ b/examples/tokens/token_airdrop_transaction.py @@ -1,29 +1,30 @@ """ + +Example demonstrating token airdrop transaction. + uv run examples/tokens/token_airdrop_transaction.py python examples/tokens/token_airdrop_transaction.py """ - import sys from hiero_sdk_python import ( + AccountCreateTransaction, Client, - PrivateKey, Hbar, - AccountCreateTransaction, - TokenCreateTransaction, + NftId, + PrivateKey, + ResponseCode, TokenAirdropTransaction, TokenAssociateTransaction, + TokenCreateTransaction, TokenMintTransaction, + TokenNftInfoQuery, TokenType, - ResponseCode, - NftId, TransactionRecordQuery, - TokenNftInfoQuery, ) from hiero_sdk_python.query.account_info_query import AccountInfoQuery - def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -32,7 +33,7 @@ def setup_client(): def create_account(client, operator_key): - """Create a new recipient account""" + """Create a new recipient account.""" print("\nCreating a new account...") recipient_key = PrivateKey.generate() @@ -55,7 +56,7 @@ def create_account(client, operator_key): def create_token(client, operator_id, operator_key): - """Create a fungible token""" + """Create a fungible token.""" print("\nCreating a token...") try: token_tx = ( @@ -78,7 +79,7 @@ def create_token(client, operator_id, operator_key): def create_nft(client, operator_key, operator_id): - """Create a NFT""" + """Create an NFT.""" print("\nCreating a nft...") try: nft_tx = ( @@ -101,7 +102,7 @@ def create_nft(client, operator_key, operator_id): def mint_nft(client, operator_key, nft_id): - """Mint the NFT with metadata""" + """Mint the NFT with metadata.""" print("\nMinting a nft...") try: mint_tx = TokenMintTransaction(token_id=nft_id, metadata=[b"NFT data"]) @@ -118,7 +119,7 @@ def mint_nft(client, operator_key, nft_id): def associate_tokens(client, recipient_id, recipient_key, tokens): - """Associate the token and nft with the recipient""" + """Associate the token and nft with the recipient.""" print("\nAssociating tokens to recipient...") try: assocciate_tx = TokenAssociateTransaction( @@ -150,7 +151,8 @@ def airdrop_tokens( client, operator_id, operator_key, recipient_id, token_id, nft_id, serial_number ): """ - Build and execute a TokenAirdropTransaction that transfers one fungible token + Build and execute a TokenAirdropTransaction that transfers one fungible token. + and the specified NFT serial. Returns the airdrop receipt. """ print(f"\nStep 6: Airdropping tokens to recipient {recipient_id}:") @@ -238,6 +240,7 @@ def verify_transaction_record( ): """ Verify the airdrop transaction record for expected token and NFT transfers. + Returns a dict summarizing results for further analysis. """ result = { @@ -290,9 +293,10 @@ def verify_post_airdrop_balances( ): """ Verify post-airdrop balances and NFT ownership to confirm successful transfer. + Uses AccountInfoQuery for robust token association and balance verification. Accepts a `balances_before` mapping with keys 'sender' and 'recipient'. - Returns (fully_verified_bool, details_dict) + Returns (fully_verified_bool, details_dict). """ sender_balances_before = balances_before.get("sender", {}) recipient_balances_before = balances_before.get("recipient", {}) @@ -482,7 +486,8 @@ def _print_final_summary( def token_airdrop(): """ - A full example that creates an account, a token, associate token, and + A full example that creates an account, a token, associate token, and. + finally perform token airdrop. """ # Setup Client diff --git a/examples/tokens/token_airdrop_transaction_cancel.py b/examples/tokens/token_airdrop_transaction_cancel.py index e940e63c6..2429d2f99 100644 --- a/examples/tokens/token_airdrop_transaction_cancel.py +++ b/examples/tokens/token_airdrop_transaction_cancel.py @@ -1,21 +1,23 @@ """ + +Example demonstrating token airdrop transaction cancel. + uv run examples/tokens/token_airdrop_transaction_cancel.py python examples/tokens/token_airdrop_transaction_cancel.py """ - import sys from hiero_sdk_python import ( - Client, - PrivateKey, AccountCreateTransaction, + Client, + CryptoGetAccountBalanceQuery, Hbar, - TokenCreateTransaction, + PrivateKey, + ResponseCode, TokenAirdropTransaction, - TransactionRecordQuery, TokenCancelAirdropTransaction, - CryptoGetAccountBalanceQuery, - ResponseCode, + TokenCreateTransaction, + TransactionRecordQuery, ) # Load environment variables from .env file diff --git a/examples/tokens/token_associate_transaction.py b/examples/tokens/token_associate_transaction.py index 75db451e5..e423d18c2 100644 --- a/examples/tokens/token_associate_transaction.py +++ b/examples/tokens/token_associate_transaction.py @@ -1,4 +1,7 @@ """ + +Example demonstrating token associate transaction. + uv run examples/tokens/token_associate_transaction.py python examples/tokens/token_associate_transaction.py @@ -6,22 +9,20 @@ This script shows the complete workflow: client setup, account creation, token creation, token association, and verification. """ - import sys from hiero_sdk_python import ( + AccountCreateTransaction, AccountInfoQuery, Client, - PrivateKey, Hbar, - AccountCreateTransaction, - TokenCreateTransaction, - TokenAssociateTransaction, + PrivateKey, ResponseCode, + TokenAssociateTransaction, + TokenCreateTransaction, ) - def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -140,7 +141,7 @@ def associate_token_with_account(client, token_id, account_id, account_key): f"❌ Token association failed with status: {ResponseCode(receipt.status).name}" ) sys.exit(1) - print(f"✅ Success! Token association complete.") + print("✅ Success! Token association complete.") print(f" Account {account_id} can now hold and transfer token {token_id}") except Exception as e: print(f"❌ Error associating token with account: {e}") @@ -152,8 +153,9 @@ def associate_two_tokens_mixed_types_with_set_token_ids( ): """ Associate two tokens using set_token_ids() with mixed types: + - first as TokenId - - second as string + - second as string. """ try: receipt = ( @@ -188,7 +190,8 @@ def associate_two_tokens_mixed_types_with_set_token_ids( def demonstrate_invalid_set_token_ids_usage(client, account_id, account_key): """ - Example 4: demonstrate that set_token_ids() rejects invalid types, + Example 4: demonstrate that set_token_ids() rejects invalid types,. + i.e. values that are neither TokenId nor string. """ print("`set_token_ids()` only accepts a list of TokenId or strings (also mixed)") @@ -245,19 +248,19 @@ def verify_token_association(client, account_id, token_id): if info.token_relationships: for relationship in info.token_relationships: if str(relationship.token_id) == str(token_id): - print(f"✅ Verification Successful!") + print("✅ Verification Successful!") print( f" Token {token_id} is associated with account {account_id}" ) print(f" Balance: {relationship.balance}") return True - print(f"❌ Verification Failed!") + print("❌ Verification Failed!") print(f" Token {token_id} is NOT associated with account {account_id}") if info.token_relationships: associated_tokens = [str(rel.token_id) for rel in info.token_relationships] print(f" Associated tokens found: {associated_tokens}") else: - print(f" No token associations found for this account") + print(" No token associations found for this account") return False except Exception as e: print(f"❌ Error verifying token association: {e}") @@ -311,7 +314,7 @@ def main(): ) # Step 7: Verify the token association - print(f"\nSTEP 7: Verifying token association...") + print("\nSTEP 7: Verifying token association...") is_associated = verify_token_association(client, account_id, token_id_0) is_associated = verify_token_association(client, account_id, token_id_1) is_associated = verify_token_association(client, account_id, token_id_2) diff --git a/examples/tokens/token_burn_transaction_fungible.py b/examples/tokens/token_burn_transaction_fungible.py index 3c076e7cd..6b9e99574 100644 --- a/examples/tokens/token_burn_transaction_fungible.py +++ b/examples/tokens/token_burn_transaction_fungible.py @@ -1,22 +1,19 @@ """ + +Example demonstrating token burn transaction fungible. + uv run examples/tokens/token_burn_transaction_fungible.py python examples/tokens/token_burn_transaction_fungible.py - """ - import sys -from hiero_sdk_python import ( - Client -) -from hiero_sdk_python.tokens.token_type import TokenType +from hiero_sdk_python import Client from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_burn_transaction import TokenBurnTransaction from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction - - +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): @@ -27,7 +24,7 @@ def setup_client(): def create_fungible_token(client, operator_id, operator_key): - """Create a fungible token""" + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleFT") @@ -56,7 +53,7 @@ def create_fungible_token(client, operator_id, operator_key): def get_token_info(client, token_id): - """Get token info for the token""" + """Get token info for the token.""" token_info = TokenInfoQuery().set_token_id(token_id).execute(client) print(f"Token supply: {token_info.total_supply}") @@ -65,11 +62,12 @@ def get_token_info(client, token_id): def token_burn_fungible(): """ Demonstrates the fungible token burn functionality by: + 1. Setting up client with operator account 2. Creating a fungible token with the operator account as owner 3. Getting initial token supply 4. Burning 50 tokens from the total supply - 5. Getting final token supply to verify burn + 5. Getting final token supply to verify burn. """ client = setup_client() operator_id = client.operator_account_id diff --git a/examples/tokens/token_burn_transaction_nft.py b/examples/tokens/token_burn_transaction_nft.py index 49d3e8682..e68ae8a7d 100644 --- a/examples/tokens/token_burn_transaction_nft.py +++ b/examples/tokens/token_burn_transaction_nft.py @@ -1,23 +1,20 @@ """ + +Example demonstrating token burn transaction nft. + uv run examples/tokens/token_burn_transaction_nft.py python examples/tokens/token_burn_transaction_nft.py - """ - import sys -from hiero_sdk_python import ( - Client -) -from hiero_sdk_python.tokens.token_type import TokenType +from hiero_sdk_python import Client from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_burn_transaction import TokenBurnTransaction from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_mint_transaction import TokenMintTransaction - - +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): @@ -28,7 +25,7 @@ def setup_client(): def create_nft(client, operator_id, operator_key): - """Create a non-fungible token""" + """Create a non-fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleNFT") @@ -57,7 +54,7 @@ def create_nft(client, operator_id, operator_key): def mint_nfts(client, nft_token_id, metadata_list): - """Mint a non-fungible token""" + """Mint a non-fungible token.""" receipt = ( TokenMintTransaction() .set_token_id(nft_token_id) @@ -75,7 +72,7 @@ def mint_nfts(client, nft_token_id, metadata_list): def get_token_info(client, token_id): - """Get token info for the token""" + """Get token info for the token.""" token_info = TokenInfoQuery().set_token_id(token_id).execute(client) print(f"Token supply: {token_info.total_supply}") @@ -84,12 +81,13 @@ def get_token_info(client, token_id): def token_burn_nft(): """ Demonstrates the NFT burn functionality by: + 1. Setting up client with operator account 2. Creating an NFT collection with the operator account as owner 3. Minting multiple NFTs with metadata 4. Getting initial token supply 5. Burning specific NFTs by serial number - 6. Getting final token supply to verify burn + 6. Getting final token supply to verify burn. """ client = setup_client() operator_id = client.operator_account_id diff --git a/examples/tokens/token_create_transaction_admin_key.py b/examples/tokens/token_create_transaction_admin_key.py index bd1b218ac..1e9edc06e 100644 --- a/examples/tokens/token_create_transaction_admin_key.py +++ b/examples/tokens/token_create_transaction_admin_key.py @@ -1,4 +1,6 @@ """ + + This example demonstrates the admin key privileges for token management using Hiero SDK Python. It shows: @@ -15,22 +17,19 @@ uv run examples/tokens/token_create_transaction_admin_key.py python examples/tokens/token_create_transaction_admin_key.py """ - import sys from hiero_sdk_python import ( Client, PrivateKey, TokenCreateTransaction, - TokenUpdateTransaction, TokenDeleteTransaction, TokenInfoQuery, + TokenUpdateTransaction, ) - from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.supply_type import SupplyType - +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): @@ -50,6 +49,7 @@ def generate_admin_key(): def create_token_with_admin_key(client, operator_id, operator_key, admin_key): """ Create a fungible token with only an admin key. + The admin key grants privileges to update token properties and delete the token. """ print("\nCreating a fungible token with admin key...") @@ -105,6 +105,7 @@ def demonstrate_admin_update_memo(client, token_id, admin_key): def demonstrate_failed_supply_key_addition(client, token_id, admin_key): """ Demonstrate that admin key cannot add a new supply key if none was present during creation. + This shows the limitation of admin key privileges. """ print(f"\nAttempting to add supply key to {token_id} (this should fail)...") @@ -129,9 +130,8 @@ def demonstrate_failed_supply_key_addition(client, token_id, admin_key): " Admin key cannot authorize adding keys that were not present during token creation." ) return True # Expected failure - else: - print("⚠️ Unexpectedly succeeded - this shouldn't happen") - return False + print("⚠️ Unexpectedly succeeded - this shouldn't happen") + return False except Exception as e: print(f"❌ As expected, adding supply key failed with exception: {e}") return True @@ -140,6 +140,7 @@ def demonstrate_failed_supply_key_addition(client, token_id, admin_key): def demonstrate_admin_key_update(client, token_id, admin_key, operator_key): """ Demonstrate updating the admin key itself using current admin key authorization. + This shows admin key can change itself. """ print(f"\nUpdating admin key for {token_id} to operator key...") @@ -167,6 +168,7 @@ def demonstrate_admin_key_update(client, token_id, admin_key, operator_key): def demonstrate_token_deletion(client, token_id, operator_key): """ Demonstrate deleting the token using admin key (now operator key). + Note: Since we updated admin key to operator_key, we use that. """ print(f"\nDeleting token {token_id} using admin key...") @@ -206,13 +208,13 @@ def get_token_info(client, token_id): def main(): """ Main function demonstrating admin key capabilities: + 1. Create token with admin key 2. Update token memo (admin privilege) 3. Attempt to add supply key (should fail) 4. Update admin key itself - 5. Delete token (admin privilege) + 5. Delete token (admin privilege). """ - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_create_transaction_freeze_key.py b/examples/tokens/token_create_transaction_freeze_key.py index 245747265..f20e07bfd 100644 --- a/examples/tokens/token_create_transaction_freeze_key.py +++ b/examples/tokens/token_create_transaction_freeze_key.py @@ -1,4 +1,7 @@ """ + +Example demonstrating token create transaction freeze key. + uv run examples/tokens/token_create_transaction_freeze_key.py python examples/tokens/token_create_transaction_freeze_key.py @@ -8,10 +11,8 @@ and verifying how transfers behave while frozen 3. (Bonus) Showing that tokens created with freezeDefault=True start accounts frozen """ - import sys from dataclasses import dataclass -from typing import Tuple from hiero_sdk_python import ( AccountCreateTransaction, @@ -210,6 +211,7 @@ def attempt_transfer( ): """ Try to transfer tokens from the treasury to a recipient and log the result. + Returns True when the transfer succeeds, False otherwise. """ print(f"\n➡️ Attempting transfer ({note}) ...") @@ -280,9 +282,7 @@ def demonstrate_freeze_default_flow( operator_key: PrivateKey, freeze_key: PrivateKey, ): - """ - Bonus: Show that freezeDefault=True starts new accounts frozen until explicitly unfrozen. - """ + """Bonus: Show that freezeDefault=True starts new accounts frozen until explicitly unfrozen.""" print("\nBONUS 🌟 Demonstrating freezeDefault=True behavior...") token_id = create_token_with_freeze_key( client, diff --git a/examples/tokens/token_create_transaction_fungible_finite.py b/examples/tokens/token_create_transaction_fungible_finite.py index b4b89bb87..26e495dfd 100644 --- a/examples/tokens/token_create_transaction_fungible_finite.py +++ b/examples/tokens/token_create_transaction_fungible_finite.py @@ -1,4 +1,6 @@ """ + + This is a simple example of how to create a finite fungible token using setting methods. It: @@ -20,13 +22,14 @@ """ import os import sys + from hiero_sdk_python import ( Client, PrivateKey, TokenCreateTransaction, ) -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.supply_type import SupplyType +from hiero_sdk_python.tokens.token_type import TokenType def parse_optional_key(key_str): diff --git a/examples/tokens/token_create_transaction_fungible_infinite.py b/examples/tokens/token_create_transaction_fungible_infinite.py index 6305580d2..4c2b3117e 100644 --- a/examples/tokens/token_create_transaction_fungible_infinite.py +++ b/examples/tokens/token_create_transaction_fungible_infinite.py @@ -1,4 +1,6 @@ """ + + This example creates an infinite fungible token using Hiero SDK Python. It: @@ -14,15 +16,14 @@ uv run examples/tokens/token_create_transaction_fungible_infinite.py python examples/tokens/token_create_transaction_fungible_infinite.py """ - - import sys + from hiero_sdk_python import ( Client, PrivateKey, + SupplyType, TokenCreateTransaction, TokenType, - SupplyType, ) @@ -44,7 +45,7 @@ def generate_keys(): def build_transaction(client, operator_id, admin_key, supply_key): """Build and freeze the infinite fungible token creation transaction.""" print("\nBuilding transaction to create an infinite fungible token...") - transaction = ( + return ( TokenCreateTransaction() .set_token_name("Infinite Fungible Token") .set_token_symbol("IFT") @@ -57,7 +58,6 @@ def build_transaction(client, operator_id, admin_key, supply_key): .set_supply_key(supply_key) .freeze_with(client) ) - return transaction def execute_transaction(transaction, client, operator_key, admin_key, supply_key): @@ -84,7 +84,6 @@ def execute_transaction(transaction, client, operator_key, admin_key, supply_key def create_token_fungible_infinite(): """Main function to create an infinite fungible token.""" - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_create_transaction_kyc_key.py b/examples/tokens/token_create_transaction_kyc_key.py index a2e9688f4..61ee96ae6 100644 --- a/examples/tokens/token_create_transaction_kyc_key.py +++ b/examples/tokens/token_create_transaction_kyc_key.py @@ -1,5 +1,7 @@ """ -Token KYC Key Demonstration + + +Token KYC Key Demonstration. This script demonstrates how to work with KYC (Know Your Customer) keys on Hedera tokens: 1. Creating a token WITHOUT a KYC key and attempting KYC operations (fails) @@ -19,19 +21,18 @@ python examples/tokens/token_create_transaction_kyc_key.py """ - - import sys import time from hiero_sdk_python import ( Client, - PrivateKey, Hbar, + PrivateKey, ResponseCode, ) from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction from hiero_sdk_python.hapi.services.basic_types_pb2 import TokenType +from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_associate_transaction import ( TokenAssociateTransaction, @@ -42,9 +43,6 @@ TokenRevokeKycTransaction, ) from hiero_sdk_python.transaction.transfer_transaction import TransferTransaction -from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery - - def setup_client(): @@ -95,6 +93,7 @@ def create_account(client, operator_key, initial_balance=Hbar(2)): def create_token_without_kyc_key(client, operator_id, operator_key): """ Demonstrate creating a token WITHOUT a KYC key. + This shows that KYC operations will fail for this token. Returns: @@ -140,6 +139,7 @@ def create_token_without_kyc_key(client, operator_id, operator_key): def attempt_kyc_without_key(client, token_id, account_id, operator_key): """ Attempt to grant KYC on a token that has no KYC key. + This should fail with an appropriate error. This demonstrates why having a KYC key is essential for KYC operations. @@ -163,12 +163,11 @@ def attempt_kyc_without_key(client, token_id, account_id, operator_key): print(f" KYC grant failed as expected with status: {status_name}") print(f" Reason: Token {token_id} has no KYC key defined\n") return False - elif receipt.status != ResponseCode.SUCCESS: + if receipt.status != ResponseCode.SUCCESS: print(f" KYC grant failed with unexpected status: {status_name}\n") return False - else: - print(f" Unexpected success! Status: {status_name}\n") - return True + print(f" Unexpected success! Status: {status_name}\n") + return True except Exception as e: print(f" Error attempting KYC grant: {e}\n") return False @@ -177,6 +176,7 @@ def attempt_kyc_without_key(client, token_id, account_id, operator_key): def create_token_with_kyc_key(client, operator_id, operator_key, kyc_private_key): """ Create a token WITH a KYC key. + This demonstrates the proper way to create a token that requires KYC. Returns: @@ -223,6 +223,7 @@ def create_token_with_kyc_key(client, operator_id, operator_key, kyc_private_key def associate_token_to_account(client, token_id, account_id, account_private_key): """ Associate a token with an account. + This is required before the account can receive or hold the token. """ try: @@ -253,6 +254,7 @@ def attempt_transfer_without_kyc( ): """ Attempt to transfer tokens to an account that has not been granted KYC. + Depending on token configuration, this may fail. Returns: @@ -286,21 +288,20 @@ def attempt_transfer_without_kyc( if receipt.status != ResponseCode.SUCCESS: print(f" Transfer failed with status: {status_name}") - print(f" Reason: Account may require KYC before receiving tokens\n") + print(" Reason: Account may require KYC before receiving tokens\n") return False - else: - print(f" Transfer succeeded with status: {status_name}") - # Check balance after transfer - balance_after = ( - CryptoGetAccountBalanceQuery(account_id=recipient_id) - .execute(client) - .token_balances - ) - recipient_balance_after = balance_after.get(token_id, 0) - print( - f"Recipient's token balance after transfer: {recipient_balance_after}\n" - ) - return True + print(f" Transfer succeeded with status: {status_name}") + # Check balance after transfer + balance_after = ( + CryptoGetAccountBalanceQuery(account_id=recipient_id) + .execute(client) + .token_balances + ) + recipient_balance_after = balance_after.get(token_id, 0) + print( + f"Recipient's token balance after transfer: {recipient_balance_after}\n" + ) + return True except Exception as e: print(f" Error during transfer attempt: {e}\n") return False @@ -309,6 +310,7 @@ def attempt_transfer_without_kyc( def grant_kyc_to_account(client, token_id, account_id, kyc_private_key): """ Grant KYC to an account for a specific token. + This allows the account to interact with the token (transfer, receive, etc). """ print("\n" + "=" * 70) @@ -338,6 +340,7 @@ def grant_kyc_to_account(client, token_id, account_id, kyc_private_key): def transfer_token_after_kyc(client, token_id, operator_id, recipient_id, operator_key): """ Transfer tokens to an account that HAS been granted KYC. + This should succeed. """ print("\n" + "=" * 70) @@ -388,6 +391,7 @@ def transfer_token_after_kyc(client, token_id, operator_id, recipient_id, operat def revoke_kyc_from_account(client, token_id, account_id, kyc_private_key): """ Revoke KYC from an account (optional bonus demonstration). + This prevents the account from further interacting with the token. """ print("\n" + "=" * 70) @@ -411,7 +415,7 @@ def revoke_kyc_from_account(client, token_id, account_id, kyc_private_key): return False print(f" KYC revoked for account {account_id} on token {token_id}") - print(f" The account can no longer transfer or receive this token\n") + print(" The account can no longer transfer or receive this token\n") return True except Exception as e: print(f" Error revoking KYC: {e}\n") @@ -421,10 +425,11 @@ def revoke_kyc_from_account(client, token_id, account_id, kyc_private_key): def main(): """ Main workflow demonstrating KYC key functionality: + 1. Create a token without KYC key and show KYC operations fail 2. Create a token with KYC key 3. Demonstrate successful KYC operations - 4. Show how KYC affects token transfers + 4. Show how KYC affects token transfers. """ try: # Setup @@ -437,7 +442,7 @@ def main(): print("Generating KYC key for demonstration") print("=" * 70) kyc_private_key = PrivateKey.generate("ed25519") - print(f" KYC key generated\n") + print(" KYC key generated\n") # ===== PART 1: Token WITHOUT KYC Key ===== token_without_kyc = create_token_without_kyc_key( @@ -468,7 +473,7 @@ def main(): ) # Try to transfer without KYC (may fail) - transfer_without_kyc_result = attempt_transfer_without_kyc( + attempt_transfer_without_kyc( client, token_with_kyc, operator_id, test_account_2, operator_key ) @@ -491,16 +496,16 @@ def main(): print("SUMMARY: KYC Key Demonstration Complete") print("=" * 70) print(f" Token without KYC key: {token_without_kyc}") - print(f" - KYC operations fail on this token (no KYC key defined)") + print(" - KYC operations fail on this token (no KYC key defined)") print(f"\n Token with KYC key: {token_with_kyc}") - print(f" - KYC can be granted/revoked using the KYC key") - print(f" - Accounts must have KYC before interacting with the token") - print(f"\n Key Takeaways:") - print(f" 1. KYC keys are essential for token-level KYC control") - print(f" 2. Without a KYC key, KYC operations cannot be performed") - print(f" 3. KYC keys must sign any KYC grant/revoke transaction") - print(f" 4. Previously granted KYC persists even if the key is removed") - print(f" 5. KYC is independent of other keys (freeze key, admin key, etc)") + print(" - KYC can be granted/revoked using the KYC key") + print(" - Accounts must have KYC before interacting with the token") + print("\n Key Takeaways:") + print(" 1. KYC keys are essential for token-level KYC control") + print(" 2. Without a KYC key, KYC operations cannot be performed") + print(" 3. KYC keys must sign any KYC grant/revoke transaction") + print(" 4. Previously granted KYC persists even if the key is removed") + print(" 5. KYC is independent of other keys (freeze key, admin key, etc)") print("=" * 70) except Exception as e: diff --git a/examples/tokens/token_create_transaction_max_automatic_token_associations_0.py b/examples/tokens/token_create_transaction_max_automatic_token_associations_0.py index 4d7d8f6d9..cd18b25e5 100644 --- a/examples/tokens/token_create_transaction_max_automatic_token_associations_0.py +++ b/examples/tokens/token_create_transaction_max_automatic_token_associations_0.py @@ -1,5 +1,8 @@ """ + + Example: demonstrate how max_automatic_token_associations=0 behaves. + The script walks through: 1. Creating a fungible token on Hedera testnet (default network). 2. Creating an account whose max automatic associations is zero. @@ -7,11 +10,9 @@ 4. Associating the token for that account. 5. Transferring again, this time succeeding. Run with: - uv run examples/tokens/token_create_transaction_max_automatic_token_associations_0 + uv run examples/tokens/token_create_transaction_max_automatic_token_associations_0. """ - import sys -from typing import Tuple from hiero_sdk_python import ( AccountCreateTransaction, @@ -29,7 +30,6 @@ from hiero_sdk_python.exceptions import PrecheckError from hiero_sdk_python.transaction.transaction_receipt import TransactionReceipt - TOKENS_TO_TRANSFER = 10 @@ -67,7 +67,7 @@ def create_demo_token( def create_max_account( client: Client, operator_key: PrivateKey -) -> Tuple[AccountId, PrivateKey]: +) -> tuple[AccountId, PrivateKey]: """Create an account whose max automatic associations equals zero.""" print( "\nSTEP 2: Creating account 'max' with max automatic associations set to 0..." @@ -178,7 +178,9 @@ def _response_code_name(status) -> str: def _as_response_code(value) -> ResponseCode: - """Ensure we always treat codes as ResponseCode enums. + """ + + Ensure we always treat codes as ResponseCode enums. Some transactions return raw integer codes rather than ResponseCode enums, so we normalize before accessing `.name`. diff --git a/examples/tokens/token_create_transaction_nft_finite.py b/examples/tokens/token_create_transaction_nft_finite.py index 90be4ffa0..216b4277d 100644 --- a/examples/tokens/token_create_transaction_nft_finite.py +++ b/examples/tokens/token_create_transaction_nft_finite.py @@ -1,4 +1,6 @@ """ + + This example creates a finite NFT using Hiero SDK Python. It: @@ -14,19 +16,17 @@ uv run examples/tokens/token_create_transaction_nft_finite python examples/tokens/token_create_transaction_nft_finite """ - import sys + from hiero_sdk_python import ( Client, PrivateKey, + SupplyType, TokenCreateTransaction, TokenType, - SupplyType, ) - - def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -45,7 +45,7 @@ def generate_keys(): def build_transaction(client, operator_id, admin_key, supply_key): """Build and freeze the finite NFT creation transaction.""" print("\nBuilding transaction to create a finite NFT...") - transaction = ( + return ( TokenCreateTransaction() .set_token_name("Finite NFT") .set_token_symbol("FNFT") @@ -58,7 +58,6 @@ def build_transaction(client, operator_id, admin_key, supply_key): .set_supply_key(supply_key) .freeze_with(client) ) - return transaction def execute_transaction(transaction, client, operator_key, admin_key, supply_key): diff --git a/examples/tokens/token_create_transaction_nft_infinite.py b/examples/tokens/token_create_transaction_nft_infinite.py index 9b37382f1..f7b6f71a5 100644 --- a/examples/tokens/token_create_transaction_nft_infinite.py +++ b/examples/tokens/token_create_transaction_nft_infinite.py @@ -1,17 +1,19 @@ """ + +Example demonstrating token create transaction nft infinite. + Usage: uv run examples/tokens/token_create_transaction_nft_infinite.py python examples/tokens/token_create_transaction_nft_infinite.py """ - - import sys + from hiero_sdk_python import ( Client, PrivateKey, + SupplyType, TokenCreateTransaction, TokenType, - SupplyType, ) @@ -21,11 +23,9 @@ def setup_client(): print(f"Client set up with operator id {client.operator_account_id}") return client -""" -2. Generate Keys On-the-Fly """ - - +2. Generate Keys On-the-Fly. +""" def keys_on_fly(): print("\nGenerating new admin and supply keys for the NFT...") admin_key = PrivateKey.generate_ed25519() @@ -34,11 +34,9 @@ def keys_on_fly(): return admin_key, supply_key -""" -3. Build and Execute Transaction """ - - +3. Build and Execute Transaction. +""" def transaction(client, operator_id, operator_key, admin_key, supply_key): try: print("\nBuilding transaction to create an infinite NFT...") @@ -70,9 +68,8 @@ def transaction(client, operator_id, operator_key, admin_key, supply_key): f"Success! Infinite non-fungible token created with ID: {receipt.token_id}" ) return receipt.token_id - else: - print("Token creation failed: Token ID not returned in receipt.") - sys.exit(1) + print("Token creation failed: Token ID not returned in receipt.") + sys.exit(1) except Exception as e: print(f"Token creation failed: {e}") @@ -82,8 +79,6 @@ def transaction(client, operator_id, operator_key, admin_key, supply_key): """ Creates an infinite NFT by generating admin and supply keys on the fly. """ - - def create_token_nft_infinite(): client = setup_client() operator_id = client.operator_account_id diff --git a/examples/tokens/token_create_transaction_pause_key.py b/examples/tokens/token_create_transaction_pause_key.py index 9fd163b11..029878470 100644 --- a/examples/tokens/token_create_transaction_pause_key.py +++ b/examples/tokens/token_create_transaction_pause_key.py @@ -1,4 +1,6 @@ """ + + This example demonstrates the pause key capabilities for token management using the Hiero Python SDK. It shows: @@ -15,24 +17,21 @@ Usage: uv run examples/token_create_transaction_pause_key.py """ - import sys from hiero_sdk_python import ( + AccountCreateTransaction, Client, + Hbar, PrivateKey, TokenCreateTransaction, TokenPauseTransaction, TokenUnpauseTransaction, TransferTransaction, - AccountCreateTransaction, - Hbar, ) - from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.supply_type import SupplyType - +from hiero_sdk_python.tokens.token_type import TokenType # ------------------------------------------------------- diff --git a/examples/tokens/token_create_transaction_supply_key.py b/examples/tokens/token_create_transaction_supply_key.py index f3d68949d..9f234c341 100644 --- a/examples/tokens/token_create_transaction_supply_key.py +++ b/examples/tokens/token_create_transaction_supply_key.py @@ -1,4 +1,6 @@ """ + + This example demonstrates the Purpose of the Supply Key for token management using Hiero SDK Python. It shows: @@ -14,21 +16,18 @@ Usage: uv run examples/tokens/token_create_transaction_supply_key.py """ - import sys from hiero_sdk_python import ( Client, PrivateKey, TokenCreateTransaction, - TokenMintTransaction, TokenInfoQuery, + TokenMintTransaction, ) - from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.supply_type import SupplyType - +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): @@ -40,6 +39,7 @@ def setup_client(): def create_token_no_supply_key(client, operator_id, operator_key): """ Create a FUNGIBLE token WITHOUT a supply key. + We use Fungible because creating an NFT without a supply key is forbidden (it would result in a permanently 0-supply, useless token). """ @@ -79,6 +79,7 @@ def create_token_no_supply_key(client, operator_id, operator_key): def demonstrate_mint_fail(client, token_id): """ Attempt to mint more tokens when no supply key exists. + This is expected to FAIL. """ print(f"Attempting to mint more to {token_id} (Expected to FAIL)...") @@ -104,9 +105,7 @@ def demonstrate_mint_fail(client, token_id): def create_token_with_supply_key(client, operator_id, operator_key): - """ - Create a Non-Fungible token (NFT) WITH a supply key. - """ + """Create a Non-Fungible token (NFT) WITH a supply key.""" print("\n--- Scenario 2: Token WITH Supply Key ---") # Generate a specific supply key @@ -151,6 +150,7 @@ def create_token_with_supply_key(client, operator_id, operator_key): def demonstrate_mint_success(client, token_id, supply_key): """ Mint a token using the valid supply key. + For NFTs, minting involve setting metadata for each unique serial number been created. """ print(f"Attempting to mint NFT to {token_id} using Supply Key...") @@ -184,9 +184,7 @@ def verify_token_info(client, token_id): def main(): - """ - Main execution flow. - """ + """Main execution flow.""" client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_create_transaction_token_fee_schedule_key.py b/examples/tokens/token_create_transaction_token_fee_schedule_key.py index 6719fc434..ae417cdd6 100644 --- a/examples/tokens/token_create_transaction_token_fee_schedule_key.py +++ b/examples/tokens/token_create_transaction_token_fee_schedule_key.py @@ -1,4 +1,7 @@ """ + +Example demonstrating token create transaction token fee schedule key. + uv run examples/tokens/token_create_transaction_token_fee_schedule_key.py Example: Demonstrating the fee_schedule_key in Token Creation @@ -13,23 +16,22 @@ Then, it attempts to update the custom fees for both tokens to demonstrate the difference. """ - import sys from hiero_sdk_python import Client, PrivateKey +from hiero_sdk_python.query.token_info_query import TokenInfoQuery +from hiero_sdk_python.response_code import ResponseCode +from hiero_sdk_python.tokens.custom_fixed_fee import CustomFixedFee +from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import ( TokenCreateTransaction, - TokenParams, TokenKeys, + TokenParams, ) -from hiero_sdk_python.tokens.token_type import TokenType -from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_fee_schedule_update_transaction import ( TokenFeeScheduleUpdateTransaction, ) -from hiero_sdk_python.tokens.custom_fixed_fee import CustomFixedFee -from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.query.token_info_query import TokenInfoQuery +from hiero_sdk_python.tokens.token_type import TokenType # Load environment variables diff --git a/examples/tokens/token_create_transaction_token_metadata.py b/examples/tokens/token_create_transaction_token_metadata.py index 2eb6d9fd6..4ffb3f08f 100644 --- a/examples/tokens/token_create_transaction_token_metadata.py +++ b/examples/tokens/token_create_transaction_token_metadata.py @@ -1,4 +1,6 @@ """ + + This example creates a fungible token with on-ledger metadata using Hiero SDK Python. It demonstrates: @@ -14,22 +16,19 @@ uv run examples/tokens/token_create_transaction_token_metadata.py python examples/tokens/token_create_transaction_token_metadata.py """ - import sys + from hiero_sdk_python import ( Client, PrivateKey, + SupplyType, TokenCreateTransaction, - TokenUpdateTransaction, TokenType, - SupplyType, + TokenUpdateTransaction, ) -from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode - - def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -45,9 +44,7 @@ def generate_metadata_key(): def create_token_without_metadata_key(client, operator_key, operator_id): - """ - Creating token with on-ledger metadata WITHOUT metadata_key (max 100 bytes) - """ + """Creating token with on-ledger metadata WITHOUT metadata_key (max 100 bytes).""" print("\nCreating token WITHOUT metadata_key") metadata = b"Initial on-ledger metadata" # < 100 bytes @@ -105,9 +102,7 @@ def try_update_metadata_without_key(client, operator_key, token_id): def create_token_with_metadata_key(client, metadata_key, operator_id, operator_key): - """ - Create token with metadata_key and on-ledger metadata (max 100 bytes) - """ + """Create token with metadata_key and on-ledger metadata (max 100 bytes).""" metadata = b"Example on-ledger token metadata" print("\nCreating token with metadata and metadata_key...") @@ -146,9 +141,7 @@ def create_token_with_metadata_key(client, metadata_key, operator_id, operator_k def update_metadata_with_key(client, token_id, metadata_key, operator_key): - """ - Update token metadata with metadata_key - """ + """Update token metadata with metadata_key.""" print(f"\nUpdating token {token_id} metadata WITH metadata_key...") updated_metadata = b"Updated metadata (with key)" @@ -176,7 +169,8 @@ def update_metadata_with_key(client, token_id, metadata_key, operator_key): def demonstrate_metadata_length_validation(client, operator_key, operator_id): """ - Demonstrate that metadata longer than 100 bytes trigger a ValueError + Demonstrate that metadata longer than 100 bytes trigger a ValueError. + in the TokenCreateTransaction.set_metadata() validation. """ print("\nDemonstrating metadata length validation (> 100 bytes)...") @@ -194,7 +188,7 @@ def demonstrate_metadata_length_validation(client, operator_key, operator_id): transaction.sign(operator_key) receipt = transaction.execute(client) if receipt.status == ResponseCode.SUCCESS: - print(f"❌ Unexpected success for this operation!") + print("❌ Unexpected success for this operation!") else: print( "Error: Expected ValueError for metadata > 100 bytes, but none was raised." @@ -209,11 +203,11 @@ def demonstrate_metadata_length_validation(client, operator_key, operator_id): def create_token_with_metadata(): """ Main function to create and update fungible token with metadata with two scenarios: + - create token WITHOUT metadata_key (expected to fail) - create token WITH metadat_key (expected to succed) - and validate metadata length + and validate metadata length. """ - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_create_transaction_wipe_key.py b/examples/tokens/token_create_transaction_wipe_key.py index 70e1395c3..e1c6688b5 100644 --- a/examples/tokens/token_create_transaction_wipe_key.py +++ b/examples/tokens/token_create_transaction_wipe_key.py @@ -1,4 +1,6 @@ """ + + This example demonstrates the Wipe Key privileges for token management using Hiero SDK Python. It shows: @@ -17,27 +19,23 @@ Usage: uv run examples/tokens/token_create_transaction_wipe_key.py """ - import sys from hiero_sdk_python import ( + AccountCreateTransaction, Client, + Hbar, + NftId, # <--- FIX 1: Added NftId import PrivateKey, - TokenCreateTransaction, - TokenWipeTransaction, TokenAssociateTransaction, - TransferTransaction, - AccountCreateTransaction, + TokenCreateTransaction, TokenInfoQuery, TokenMintTransaction, - Hbar, - NftId, # <--- FIX 1: Added NftId import + TokenWipeTransaction, + TransferTransaction, ) - from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.token_type import TokenType -from hiero_sdk_python.tokens.supply_type import SupplyType - def setup_client(): @@ -47,9 +45,7 @@ def setup_client(): return client def create_recipient_account(client): - """ - Helper: Create a new account to hold tokens(wiped ones) - """ + """Helper: Create a new account to hold tokens(wiped ones).""" private_key = PrivateKey.generate_ed25519() tx = ( AccountCreateTransaction() @@ -68,8 +64,7 @@ def create_recipient_account(client): def associate_and_transfer(client, token_id, recipient_id, recipient_key, amount): - """Helper: Associate token to recipient and transfer tokens to them""" - + """Helper: Associate token to recipient and transfer tokens to them.""" associate_tx = ( TokenAssociateTransaction() .set_account_id(recipient_id) @@ -217,7 +212,7 @@ def demonstrate_wipe_success(client, token_id, target_account_id, wipe_key): print(f"❌ Wipe failed with status: {ResponseCode(receipt.status).name}") return False - print(f"✅ Wipe Successful!") + print("✅ Wipe Successful!") return True @@ -230,6 +225,7 @@ def verify_supply(client, token_id): def demonstrate_nft_wipe_scenario(client, operator_id, operator_key, user_id, user_key): """ Scenario 3: Create an NFT, Mint it, Transfer it, and then Wipe it. + This demonstrates that Wipe Key works for NON_FUNGIBLE_UNIQUE tokens as well. """ print("\n--- Scenario 3: NFT Wipe with Wipe Key ---") @@ -280,16 +276,24 @@ def demonstrate_nft_wipe_scenario(client, operator_id, operator_key, user_id, us .add_token_id(nft_token_id) .freeze_with(client) .sign(user_key) - ).execute(client) + ) + associate_receipt = associate_tx.execute(client) + if associate_receipt.status != ResponseCode.SUCCESS: + print(f"❌ Association failed: {ResponseCode(associate_receipt.status).name}") + return + print("✅ Token associated.") # Transfer - # FIX 2: Use NftId(token_id, serial_number) transfer_tx = ( TransferTransaction() .add_nft_transfer(NftId(nft_token_id, serial_number), operator_id, user_id) - .execute(client) + .freeze_with(client) ) - print(f"✅ Transfer complete.") + transfer_receipt = transfer_tx.execute(client) + if transfer_receipt.status != ResponseCode.SUCCESS: + print(f"❌ Transfer failed: {ResponseCode(transfer_receipt.status).name}") + return + print("✅ Transfer complete.") # 4. Wipe the NFT from the User print(f"Attempting to WIPE NFT #{serial_number} from user {user_id}...") @@ -316,13 +320,13 @@ def demonstrate_nft_wipe_scenario(client, operator_id, operator_key, user_id, us def main(): """ Main execution flow: + 1. Setup Client 2. Create a recipient account 3. Scenario 1: Fail to wipe without key (Fungible) 4. Scenario 2: Successfully wipe with key (Fungible) - 5. Scenario 3: Successfully wipe with key (NFT) + 5. Scenario 3: Successfully wipe with key (NFT). """ - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_delete_transaction.py b/examples/tokens/token_delete_transaction.py index 2cc3b1284..1c46c2ce0 100644 --- a/examples/tokens/token_delete_transaction.py +++ b/examples/tokens/token_delete_transaction.py @@ -7,13 +7,12 @@ from hiero_sdk_python import ( Client, PrivateKey, + ResponseCode, TokenCreateTransaction, TokenDeleteTransaction, - ResponseCode, ) - def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -21,10 +20,12 @@ def setup_client(): return client def generate_admin_key(): - """Generate a new admin key within the script: - This key will be used to create the token with admin privileges """ + Generate a new admin key within the script: + + This key will be used to create the token with admin privileges. + """ print("\nGenerating a new admin key for the token...") admin_key = PrivateKey.generate(os.getenv("KEY_TYPE", "ed25519")) print("Admin key generated successfully.") @@ -32,7 +33,7 @@ def generate_admin_key(): def create_new_token(client, admin_key): - """Create the Token""" + """Create the Token.""" token_id_to_delete = None try: @@ -67,10 +68,7 @@ def create_new_token(client, admin_key): def delete_token(admin_key, token_id_to_delete, client): - """ - Delete the Token we just created - """ - + """Delete the Token we just created.""" try: print(f"\nSTEP 2: Deleting token {token_id_to_delete}...") delete_tx = ( @@ -99,6 +97,7 @@ def delete_token(admin_key, token_id_to_delete, client): def main(): """ 1. Call create_new_token() to create a new token and get its admin key, token ID, client, and operator key. + 2. Build a TokenDeleteTransaction using the token ID. 3. Freeze the transaction with the client. 4. Sign the transaction with both the operator key and the admin key. diff --git a/examples/tokens/token_dissociate_transaction.py b/examples/tokens/token_dissociate_transaction.py index 588388061..871c8cffb 100644 --- a/examples/tokens/token_dissociate_transaction.py +++ b/examples/tokens/token_dissociate_transaction.py @@ -1,24 +1,23 @@ # uv run examples/tokens/token_dissociate_transaction.py # python examples/tokens/token_dissociate_transaction.py -""" -A full example that creates an account, two tokens, associates them, and finally dissociates them. -""" +"""A full example that creates an account, two tokens, associates them, and finally dissociates them.""" import os import sys from hiero_sdk_python import ( + AccountCreateTransaction, + AccountInfoQuery, Client, - PrivateKey, Hbar, - AccountCreateTransaction, - TokenCreateTransaction, + PrivateKey, + ResponseCode, TokenAssociateTransaction, + TokenCreateTransaction, TokenDissociateTransaction, TokenType, - AccountInfoQuery, - ResponseCode, ) + def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -29,7 +28,7 @@ def setup_client(): def create_new_account(client, operator_id, operator_key): - """Create a new account to associate/dissociate with tokens""" + """Create a new account to associate/dissociate with tokens.""" print("\nSTEP 1: Creating a new account...") recipient_key = PrivateKey.generate(os.getenv("KEY_TYPE", "ed25519")) @@ -103,7 +102,6 @@ def token_associate( Note: Tokens must be associated with an account before they can be used or dissociated. Association is a prerequisite for holding, transferring, or later dissociating tokens. """ - print( f"\nSTEP 3: Associating NFT and fungible tokens with account {recipient_id}..." ) @@ -155,7 +153,6 @@ def token_dissociate( - For security or privacy reasons - To comply with business or regulatory requirements """ - print( f"\nSTEP 4: Dissociating NFT and fungible tokens from account {recipient_id}..." ) @@ -179,13 +176,13 @@ def token_dissociate( def main(): """ - 1-create new account + 1-create new account. + 2-create two tokens 3-associate the tokens with the new account 4-dissociate the tokens from the new account - 5-verify dissociation + 5-verify dissociation. """ - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_fee_schedule_update_transaction_fungible.py b/examples/tokens/token_fee_schedule_update_transaction_fungible.py index 9c707ee8e..573060802 100644 --- a/examples/tokens/token_fee_schedule_update_transaction_fungible.py +++ b/examples/tokens/token_fee_schedule_update_transaction_fungible.py @@ -1,24 +1,26 @@ -"""Example: Update Custom Fees for a Fungible Token +""" + +Example: Update Custom Fees for a Fungible Token. + uv run examples/tokens/token_fee_schedule_update_transaction_fungible.py python examples/tokens/token_fee_schedule_update_transaction_fungible.py """ - import sys from hiero_sdk_python import Client +from hiero_sdk_python.query.token_info_query import TokenInfoQuery +from hiero_sdk_python.response_code import ResponseCode +from hiero_sdk_python.tokens.custom_fixed_fee import CustomFixedFee +from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import ( TokenCreateTransaction, - TokenParams, TokenKeys, + TokenParams, ) -from hiero_sdk_python.tokens.token_type import TokenType -from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_fee_schedule_update_transaction import ( TokenFeeScheduleUpdateTransaction, ) -from hiero_sdk_python.tokens.custom_fixed_fee import CustomFixedFee -from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.query.token_info_query import TokenInfoQuery +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): diff --git a/examples/tokens/token_fee_schedule_update_transaction_nft.py b/examples/tokens/token_fee_schedule_update_transaction_nft.py index 644a5c240..c27d09f43 100644 --- a/examples/tokens/token_fee_schedule_update_transaction_nft.py +++ b/examples/tokens/token_fee_schedule_update_transaction_nft.py @@ -1,23 +1,26 @@ -"""Example: Update Custom Fees for an NFT -uv run examples/tokens/token_fee_schedule_update_transaction_nft.py -python examples/tokens/token_fee_schedule_update_transaction_nft.py""" +""" + +Example: Update Custom Fees for an NFT. +uv run examples/tokens/token_fee_schedule_update_transaction_nft.py +python examples/tokens/token_fee_schedule_update_transaction_nft.py +""" import sys from hiero_sdk_python import Client +from hiero_sdk_python.query.token_info_query import TokenInfoQuery +from hiero_sdk_python.response_code import ResponseCode +from hiero_sdk_python.tokens.custom_royalty_fee import CustomRoyaltyFee +from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import ( TokenCreateTransaction, - TokenParams, TokenKeys, + TokenParams, ) -from hiero_sdk_python.tokens.token_type import TokenType -from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_fee_schedule_update_transaction import ( TokenFeeScheduleUpdateTransaction, ) -from hiero_sdk_python.tokens.custom_royalty_fee import CustomRoyaltyFee -from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.query.token_info_query import TokenInfoQuery +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): diff --git a/examples/tokens/token_freeze_transaction.py b/examples/tokens/token_freeze_transaction.py index ed755631f..6365dd758 100644 --- a/examples/tokens/token_freeze_transaction.py +++ b/examples/tokens/token_freeze_transaction.py @@ -1,26 +1,28 @@ """ -Creates a freezeable token and demonstrates freezing and unfreezing + + +Creates a freezeable token and demonstrates freezing and unfreezing. + the token for the operator (treasury) account. uv run examples/tokens/token_freeze_transaction.py python examples/tokens/token_freeze_transaction.py """ - import os import sys from hiero_sdk_python import ( Client, PrivateKey, + ResponseCode, TokenCreateTransaction, TokenFreezeTransaction, TransferTransaction, - ResponseCode, ) def setup_client(): - """Setup client from environment variables""" + """Setup client from environment variables.""" client = Client.from_env() operator_id = client.operator_account_id operator_key = client.operator_private_key @@ -32,7 +34,7 @@ def setup_client(): def generate_freeze_key(): - """Generate a Freeze Key""" + """Generate a Freeze Key.""" print("\nSTEP 1: Generating a new freeze key...") freeze_key = PrivateKey.generate(os.getenv("KEY_TYPE", "ed25519")) print("✅ Freeze key generated.") @@ -40,7 +42,7 @@ def generate_freeze_key(): def create_freezeable_token(client, operator_id, operator_key): - """Create a token with the freeze key""" + """Create a token with the freeze key.""" freeze_key = generate_freeze_key() print("\nSTEP 2: Creating a new freezeable token...") @@ -72,7 +74,7 @@ def create_freezeable_token(client, operator_id, operator_key): def freeze_token(token_id, client, operator_id, freeze_key): - """Freeze the token for the operator account""" + """Freeze the token for the operator account.""" print(f"\nSTEP 3: Freezing token {token_id} for operator account {operator_id}...") try: @@ -95,7 +97,7 @@ def freeze_token(token_id, client, operator_id, freeze_key): def verify_freeze(token_id, client, operator_id, operator_key): - """Attempt a token transfer to confirm the account is frozen""" + """Attempt a token transfer to confirm the account is frozen.""" print("\nVerifying freeze: Attempting token transfer...") try: @@ -129,6 +131,7 @@ def verify_freeze(token_id, client, operator_id, operator_key): def main(): """ 1. Create a freezeable token with a freeze key. + 2. Freeze the token for the operator account using the freeze key. 3. Attempt a token transfer to verify the freeze (should fail). """ diff --git a/examples/tokens/token_grant_kyc_transaction.py b/examples/tokens/token_grant_kyc_transaction.py index e1766c4eb..8bcc3fd92 100644 --- a/examples/tokens/token_grant_kyc_transaction.py +++ b/examples/tokens/token_grant_kyc_transaction.py @@ -1,10 +1,10 @@ """ + +Example demonstrating token grant kyc transaction. + uv run examples/tokens/token_grant_kyc_transaction.py python examples/tokens/token_grant_kyc_transaction.py - """ - - import sys from hiero_sdk_python import ( @@ -12,15 +12,15 @@ PrivateKey, ) from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_associate_transaction import ( TokenAssociateTransaction, ) -from hiero_sdk_python.tokens.token_grant_kyc_transaction import TokenGrantKycTransaction from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction +from hiero_sdk_python.tokens.token_grant_kyc_transaction import TokenGrantKycTransaction +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): @@ -30,7 +30,7 @@ def setup_client(): return client def create_fungible_token(client, operator_id, operator_key, kyc_private_key): - """Create a fungible token""" + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleFT") @@ -62,7 +62,7 @@ def create_fungible_token(client, operator_id, operator_key, kyc_private_key): def associate_token(client, token_id, account_id, account_private_key): - """Associate a token with an account""" + """Associate a token with an account.""" associate_transaction = ( TokenAssociateTransaction() .set_account_id(account_id) @@ -83,7 +83,7 @@ def associate_token(client, token_id, account_id, account_private_key): def create_test_account(client): - """Create a new account for testing""" + """Create a new account for testing.""" # Generate private key for new account new_account_private_key = PrivateKey.generate() new_account_public_key = new_account_private_key.public_key() @@ -115,13 +115,13 @@ def create_test_account(client): def token_grant_kyc(): """ Demonstrates the token grant KYC functionality by: + 1. Setting up client with operator account 2. Creating a fungible token with KYC key 3. Creating a new account 4. Associating the token with the new account - 5. Granting KYC to the new account + 5. Granting KYC to the new account. """ - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_mint_transaction_fungible.py b/examples/tokens/token_mint_transaction_fungible.py index 7c07563b6..ffa81f798 100644 --- a/examples/tokens/token_mint_transaction_fungible.py +++ b/examples/tokens/token_mint_transaction_fungible.py @@ -1,21 +1,24 @@ """ + +Example demonstrating token mint transaction fungible. + uv run examples/tokens/token_mint_transaction_fungible.py python examples/tokens/token_mint_transaction_fungible.py Creates a mintable fungible token and then mints additional supply. """ - import os import sys from hiero_sdk_python import ( Client, PrivateKey, + ResponseCode, TokenCreateTransaction, - TokenMintTransaction, TokenInfoQuery, - ResponseCode, + TokenMintTransaction, ) + def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -33,9 +36,9 @@ def generate_supply_key(): def create_new_token(client): """ Create a fungible token that can have its supply changed (minted or burned). + This requires setting a supply key, which is a special key that authorizes supply changes. """ - operator_id = client.operator_account_id operator_key = client.operator_private_key @@ -77,12 +80,11 @@ def create_new_token(client): def token_mint_fungible(client, token_id, supply_key): """ - Mint more of a fungible token + Mint more of a fungible token. The token must have a supply key set during creation, which authorizes future minting or burning. Only the holder of the supply key can perform these actions. """ - mint_amount = 5000 # This is 50.00 tokens because decimals is 2 print(f"\nSTEP 3: Minting {mint_amount} more tokens for {token_id}...") @@ -115,12 +117,12 @@ def token_mint_fungible(client, token_id, supply_key): def main(): """ - 1. Create a new token with a supply key so its supply can be changed later + 1. Create a new token with a supply key so its supply can be changed later. + 2. Confirm the token's total supply before minting 3. Mint more tokens by submitting a TokenMintTransaction (signed by the supply key) - 4. Confirm the token's total supply after minting + 4. Confirm the token's total supply after minting. """ - client = setup_client() token_id, supply_key = create_new_token(client) token_mint_fungible(client, token_id, supply_key) diff --git a/examples/tokens/token_mint_transaction_non_fungible.py b/examples/tokens/token_mint_transaction_non_fungible.py index ca8752bb3..e19b84a8b 100644 --- a/examples/tokens/token_mint_transaction_non_fungible.py +++ b/examples/tokens/token_mint_transaction_non_fungible.py @@ -2,24 +2,25 @@ # python examples/tokens/token_mint_non_fungible.py """ -Create a Non-Fungible Token (NFT) Collection and Mint NFTs +Create a Non-Fungible Token (NFT) Collection and Mint NFTs. + uv run examples/token_mint_transaction_non_fungible.py python examples/token_mint_transaction_non_fungible.py """ - import os import sys from hiero_sdk_python import ( Client, PrivateKey, + ResponseCode, TokenCreateTransaction, + TokenInfoQuery, TokenMintTransaction, TokenType, - TokenInfoQuery, - ResponseCode, ) + def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -36,8 +37,7 @@ def generate_supply_key(): def create_nft_collection(): - """Create the NFT Collection (Token)""" - + """Create the NFT Collection (Token).""" client = setup_client() supply_key = generate_supply_key() @@ -69,12 +69,11 @@ def create_nft_collection(): def token_mint_non_fungible(client, token_id, supply_key): """ - Mint new NFTs with metadata + Mint new NFTs with metadata. The supply key authorizes minting new NFTs after the collection is created. Each NFT is assigned unique metadata, which can be used to identify or describe the token. """ - # Prepare the metadata for each NFT to be minted # Each entry in the list will become a unique NFT with its own metadata metadata_list = [ @@ -112,11 +111,12 @@ def token_mint_non_fungible(client, token_id, supply_key): def main(): """ - 1. Create a new NFT collection (token) with a supply key + 1. Create a new NFT collection (token) with a supply key. + 2. Prepare metadata for each NFT to be minted 3. Confirm total supply before minting 4. Mint the NFTs by submitting a TokenMintTransaction (signed by the supply key) - 5. Confirm total supply after minting + 5. Confirm total supply after minting. """ client, token_id, supply_key = create_nft_collection() token_mint_non_fungible(client, token_id, supply_key) diff --git a/examples/tokens/token_pause_transaction.py b/examples/tokens/token_pause_transaction.py index 5e36c150d..4e6e84668 100644 --- a/examples/tokens/token_pause_transaction.py +++ b/examples/tokens/token_pause_transaction.py @@ -1,21 +1,18 @@ """ + +Example demonstrating token pause transaction. + uv run examples/tokens/token_pause_transaction.py python examples/tokens/token_pause_transaction.py - """ - -import sys - -from hiero_sdk_python import Client, PrivateKey +from hiero_sdk_python import Client +from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction -from hiero_sdk_python.tokens.token_pause_transaction import TokenPauseTransaction from hiero_sdk_python.tokens.token_delete_transaction import TokenDeleteTransaction -from hiero_sdk_python.query.token_info_query import TokenInfoQuery - - +from hiero_sdk_python.tokens.token_pause_transaction import TokenPauseTransaction +from hiero_sdk_python.tokens.token_type import TokenType def setup_client(): @@ -26,6 +23,7 @@ def setup_client(): def assert_success(receipt, action: str): """ + Verify that a transaction or query succeeded, else raise. Args: @@ -42,7 +40,7 @@ def assert_success(receipt, action: str): def create_token(client, operator_id, admin_key, pause_key): - """Create a fungible token""" + """Create a fungible token.""" # Create fungible token create_token_transaction = ( TokenCreateTransaction() @@ -70,7 +68,7 @@ def create_token(client, operator_id, admin_key, pause_key): def pause_token(client, token_id, pause_key): - """Pause token""" + """Pause token.""" # Note: This requires the pause key that was specified during token creation pause_transaction = ( TokenPauseTransaction() @@ -86,15 +84,13 @@ def pause_token(client, token_id, pause_key): def check_pause_status(client, token_id): - """ - Query and print the current paused/unpaused status of a token. - """ + """Query and print the current paused/unpaused status of a token.""" info = TokenInfoQuery().set_token_id(token_id).execute(client) print(f"Token status is now: {info.pause_status.name}") def delete_token(client, token_id, admin_key): - """Delete token""" + """Delete token.""" # Note: This requires the admin key that was specified during token creation delete_transaction = ( TokenDeleteTransaction() @@ -112,10 +108,11 @@ def delete_token(client, token_id, admin_key): def token_pause(): """ Demonstrates the token pause functionality by: + 1. Creating a fungible token with pause and delete capability 2. Pausing the token 3. Verifying pause status - 4. Attempting (and failing) to delete the paused token because it is paused + 4. Attempting (and failing) to delete the paused token because it is paused. """ client = setup_client() operator_id = client.operator_account_id diff --git a/examples/tokens/token_reject_transaction_fungible_token.py b/examples/tokens/token_reject_transaction_fungible_token.py index 272e84af5..e552e4f6e 100644 --- a/examples/tokens/token_reject_transaction_fungible_token.py +++ b/examples/tokens/token_reject_transaction_fungible_token.py @@ -1,9 +1,10 @@ """ + +Example demonstrating token reject transaction fungible token. + uv run examples/tokens/token_reject_transaction_fungible_token.py python examples/tokens/token_reject_transaction_fungible_token.py - """ - import sys from hiero_sdk_python import ( @@ -12,7 +13,6 @@ TransferTransaction, ) from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery from hiero_sdk_python.response_code import ResponseCode @@ -22,6 +22,8 @@ ) from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_reject_transaction import TokenRejectTransaction +from hiero_sdk_python.tokens.token_type import TokenType + def setup_client(): client = Client.from_env() @@ -30,7 +32,7 @@ def setup_client(): return client def create_test_account(client): - """Create a new account for testing""" + """Create a new account for testing.""" # Generate private key for new account new_account_private_key = PrivateKey.generate_ed25519() new_account_public_key = new_account_private_key.public_key() @@ -58,7 +60,7 @@ def create_test_account(client): def create_fungible_token(client: "Client", treasury_id, treasury_private_key): - """Create a fungible token""" + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleFT") @@ -92,7 +94,7 @@ def create_fungible_token(client: "Client", treasury_id, treasury_private_key): def associate_token(client, receiver_id, token_id, receiver_private_key): - """Associate token with an account""" + """Associate token with an account.""" # Associate the token_id with the new account receipt = ( TokenAssociateTransaction() @@ -115,7 +117,7 @@ def associate_token(client, receiver_id, token_id, receiver_private_key): def transfer_tokens( client, treasury_id, treasury_private_key, receiver_id, token_id, amount=10 ): - """Transfer tokens to the receiver account so we can later reject them""" + """Transfer tokens to the receiver account so we can later reject them.""" # Transfer tokens to the receiver account receipt = ( TransferTransaction() @@ -135,7 +137,7 @@ def transfer_tokens( def get_token_balances(client, treasury_id, receiver_id, token_id): - """Get token balances for both accounts""" + """Get token balances for both accounts.""" token_balance = ( CryptoGetAccountBalanceQuery().set_account_id(treasury_id).execute(client) ) @@ -154,12 +156,13 @@ def get_token_balances(client, treasury_id, receiver_id, token_id): def token_reject_fungible(): """ Demonstrates the fungible token reject functionality by: + 1. Creating a new treasury account 2. Creating a new receiver account 3. Creating a fungible token with the treasury account as owner 4. Associating the token with the receiver account 5. Transferring tokens to the receiver account - 6. Rejecting the tokens from the receiver account + 6. Rejecting the tokens from the receiver account. """ client = setup_client() # Create treasury/sender account that will create and send tokens diff --git a/examples/tokens/token_reject_transaction_nft.py b/examples/tokens/token_reject_transaction_nft.py index 1ab4d0066..7ba6b91e4 100644 --- a/examples/tokens/token_reject_transaction_nft.py +++ b/examples/tokens/token_reject_transaction_nft.py @@ -1,9 +1,10 @@ """ + +Example demonstrating token reject transaction nft. + uv run examples/tokens/token_reject_transaction_nft.py python examples/tokens/token_reject_transaction_nft.py - """ - import sys from hiero_sdk_python import ( @@ -12,7 +13,6 @@ TransferTransaction, ) from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery from hiero_sdk_python.response_code import ResponseCode @@ -24,6 +24,8 @@ from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_mint_transaction import TokenMintTransaction from hiero_sdk_python.tokens.token_reject_transaction import TokenRejectTransaction +from hiero_sdk_python.tokens.token_type import TokenType + def setup_client(): client = Client.from_env() @@ -32,7 +34,7 @@ def setup_client(): return client def create_test_account(client): - """Create a new account for testing""" + """Create a new account for testing.""" # Generate private key for new account new_account_private_key = PrivateKey.generate_ed25519() new_account_public_key = new_account_private_key.public_key() @@ -60,7 +62,7 @@ def create_test_account(client): def create_nft(client, treasury_id, treasury_private_key): - """Create a non-fungible token""" + """Create a non-fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleNFT") @@ -94,7 +96,7 @@ def create_nft(client, treasury_id, treasury_private_key): def mint_nfts(client, nft_token_id, metadata_list, treasury_private_key): - """Mint a non-fungible token""" + """Mint a non-fungible token.""" receipt = ( TokenMintTransaction() .set_token_id(nft_token_id) @@ -118,7 +120,7 @@ def mint_nfts(client, nft_token_id, metadata_list, treasury_private_key): def associate_token(client, receiver_id, nft_token_id, receiver_private_key): - """Associate token with an account""" + """Associate token with an account.""" # Associate the token_id with the new account receipt = ( TokenAssociateTransaction() @@ -139,7 +141,7 @@ def associate_token(client, receiver_id, nft_token_id, receiver_private_key): def transfer_nfts(client, treasury_id, treasury_private_key, receiver_id, nft_ids): - """Transfer NFTs to the receiver account so we can later reject them""" + """Transfer NFTs to the receiver account so we can later reject them.""" # Transfer NFTs to the receiver account receipt = ( TransferTransaction() @@ -159,7 +161,7 @@ def transfer_nfts(client, treasury_id, treasury_private_key, receiver_id, nft_id def get_nft_balances(client, treasury_id, receiver_id, nft_token_id): - """Get NFT balances for both accounts""" + """Get NFT balances for both accounts.""" token_balance = ( CryptoGetAccountBalanceQuery().set_account_id(treasury_id).execute(client) ) @@ -178,13 +180,14 @@ def get_nft_balances(client, treasury_id, receiver_id, nft_token_id): def token_reject_nft(): """ Demonstrates the NFT token reject functionality by: + 1. Creating a new treasury account 2. Creating a new receiver account 3. Creating a non-fungible token 4. Minting two NFTs 5. Associating the NFT with the receiver account 6. Transferring the NFTs to the receiver account - 7. Rejecting the NFTs from the receiver account + 7. Rejecting the NFTs from the receiver account. """ client = setup_client() # Create treasury/sender account that will create and send tokens diff --git a/examples/tokens/token_revoke_kyc_transaction.py b/examples/tokens/token_revoke_kyc_transaction.py index ece877de0..358e9b1c1 100644 --- a/examples/tokens/token_revoke_kyc_transaction.py +++ b/examples/tokens/token_revoke_kyc_transaction.py @@ -1,9 +1,10 @@ """ -uv run examples/tokens/token_revoke_kyc_transaction.py.py -python examples/tokens/token_revoke_kyc_transaction.py.py -""" +Example demonstrating token revoke kyc transaction. +uv run examples/tokens/token_revoke_kyc_transaction.py +python examples/tokens/token_revoke_kyc_transaction.py +""" import sys from hiero_sdk_python import ( @@ -11,18 +12,19 @@ PrivateKey, ) from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_associate_transaction import ( TokenAssociateTransaction, ) +from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_grant_kyc_transaction import TokenGrantKycTransaction from hiero_sdk_python.tokens.token_revoke_kyc_transaction import ( TokenRevokeKycTransaction, ) -from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction +from hiero_sdk_python.tokens.token_type import TokenType + def setup_client(): client = Client.from_env() @@ -31,7 +33,7 @@ def setup_client(): return client def create_fungible_token(client, operator_id, operator_key, kyc_private_key): - """Create a fungible token""" + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleFT") @@ -63,7 +65,7 @@ def create_fungible_token(client, operator_id, operator_key, kyc_private_key): def associate_token(client, token_id, account_id, account_private_key): - """Associate a token with an account""" + """Associate a token with an account.""" associate_transaction = ( TokenAssociateTransaction() .set_account_id(account_id) @@ -84,7 +86,7 @@ def associate_token(client, token_id, account_id, account_private_key): def create_test_account(client): - """Create a new account for testing""" + """Create a new account for testing.""" # Generate private key for new account new_account_private_key = PrivateKey.generate() new_account_public_key = new_account_private_key.public_key() @@ -114,7 +116,7 @@ def create_test_account(client): def grant_kyc(client, token_id, account_id, kyc_private_key): - """Grant KYC to an account""" + """Grant KYC to an account.""" receipt = ( TokenGrantKycTransaction() .set_token_id(token_id) @@ -136,14 +138,14 @@ def grant_kyc(client, token_id, account_id, kyc_private_key): def token_revoke_kyc(): """ Demonstrates the token revoke KYC functionality by: + 1. Setting up client with operator account 2. Creating a fungible token with KYC key 3. Creating a new account 4. Associating the token with the new account 5. Granting KYC to the new account - 6. Revoking KYC from the new account + 6. Revoking KYC from the new account. """ - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_unfreeze_transaction.py b/examples/tokens/token_unfreeze_transaction.py index b4c5ccd2e..61f7b4510 100644 --- a/examples/tokens/token_unfreeze_transaction.py +++ b/examples/tokens/token_unfreeze_transaction.py @@ -1,24 +1,27 @@ """ -Creates a freezeable token, freezes it for the treasury account, + + +Creates a freezeable token, freezes it for the treasury account,. + and then unfreezes it. uv run examples/tokens/token_unfreeze_transaction.py python examples/tokens/token_unfreeze_transaction.py """ - import os import sys from hiero_sdk_python import ( Client, PrivateKey, + ResponseCode, TokenCreateTransaction, TokenFreezeTransaction, TokenUnfreezeTransaction, TransferTransaction, - ResponseCode, ) + def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -26,7 +29,7 @@ def setup_client(): return client def generate_freeze_key(): - """Generate a Freeze Key on the fly""" + """Generate a Freeze Key on the fly.""" print("\nSTEP 1: Generating a new freeze key...") freeze_key = PrivateKey.generate(os.getenv("KEY_TYPE", "ed25519")) print("✅ Freeze key generated.") @@ -34,8 +37,7 @@ def generate_freeze_key(): def create_freezable_token(client): - """Create a token with the freeze key""" - + """Create a token with the freeze key.""" operator_id = client.operator_account_id operator_key = client.operator_private_key @@ -64,7 +66,7 @@ def create_freezable_token(client): def freeze_token(token_id, client, operator_id, freeze_key): - """Freeze the token for the operator account""" + """Freeze the token for the operator account.""" print(f"\nSTEP 3: Freezing token {token_id} for operator account {operator_id}...") try: receipt = ( @@ -84,7 +86,7 @@ def freeze_token(token_id, client, operator_id, freeze_key): def unfreeze_token(token_id, client, operator_id, freeze_key, operator_key): - """Unfreeze the token for the operator account""" + """Unfreeze the token for the operator account.""" # Step 1: Unfreeze the token for the operator account print( f"\nSTEP 4: Unfreezing token {token_id} for operator account {operator_id}..." @@ -124,7 +126,10 @@ def unfreeze_token(token_id, client, operator_id, freeze_key, operator_key): def main(): - """Unfreeze the token for the operator account. + """ + + Unfreeze the token for the operator account. + 1. Freeze the token for the operator account (calls freeze_token()). 2. Unfreeze the token for the operator account using TokenUnfreezeTransaction. 3. Attempt a test transfer of 1 unit of the token to self to verify unfreeze. diff --git a/examples/tokens/token_unpause_transaction.py b/examples/tokens/token_unpause_transaction.py index d692219aa..0d2160965 100644 --- a/examples/tokens/token_unpause_transaction.py +++ b/examples/tokens/token_unpause_transaction.py @@ -1,24 +1,26 @@ """ + +Example demonstrating token unpause transaction. + uv run examples/tokens/token_unpause_transaction.py python examples/tokens/token_unpause_transaction.py - """ - import sys from hiero_sdk_python import ( - Client, AccountId, + Client, PrivateKey, ResponseCode, + TokenCreateTransaction, TokenId, + TokenInfoQuery, + TokenPauseTransaction, TokenType, - TokenCreateTransaction, TokenUnpauseTransaction, - TokenPauseTransaction, - TokenInfoQuery, ) + def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -30,7 +32,7 @@ def create_token( operator_id: AccountId, pause_key: PrivateKey, ): - """Create a fungible token""" + """Create a fungible token.""" print("\nCreating a token...") try: @@ -58,7 +60,7 @@ def create_token( def pause_token(client: Client, token_id: TokenId, pause_key: PrivateKey): - """Pause token""" + """Pause token.""" print("\nAttempting to pause the token...") try: diff --git a/examples/tokens/token_update_nfts_transaction_nfts.py b/examples/tokens/token_update_nfts_transaction_nfts.py index deeb04a80..8d95ca99d 100644 --- a/examples/tokens/token_update_nfts_transaction_nfts.py +++ b/examples/tokens/token_update_nfts_transaction_nfts.py @@ -1,26 +1,26 @@ """ + +Example demonstrating token update nfts transaction nfts. + uv run examples/tokens/token_update_transaction_nfts.py python examples/tokens/token_update_transaction_nfts.py - """ - import sys from hiero_sdk_python import ( Client, PrivateKey, ) -from hiero_sdk_python.tokens.token_type import TokenType +from hiero_sdk_python.query.token_nft_info_query import TokenNftInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.nft_id import NftId from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_mint_transaction import TokenMintTransaction +from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.token_update_nfts_transaction import ( TokenUpdateNftsTransaction, ) -from hiero_sdk_python.query.token_nft_info_query import TokenNftInfoQuery - def setup_client(): @@ -30,7 +30,7 @@ def setup_client(): return client def create_nft(client, operator_id, operator_key, metadata_key): - """Create a non-fungible token""" + """Create a non-fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleNFT") @@ -61,7 +61,7 @@ def create_nft(client, operator_id, operator_key, metadata_key): def mint_nfts(client, nft_token_id, metadata_list): - """Mint a non-fungible token""" + """Mint a non-fungible token.""" receipt = ( TokenMintTransaction() .set_token_id(nft_token_id) @@ -81,16 +81,15 @@ def mint_nfts(client, nft_token_id, metadata_list): def get_nft_info(client, nft_id): - """Get information about an NFT""" - info = TokenNftInfoQuery().set_nft_id(nft_id).execute(client) + """Get information about an NFT.""" + return TokenNftInfoQuery().set_nft_id(nft_id).execute(client) - return info def update_nft_metadata( client, nft_token_id, serial_numbers, new_metadata, metadata_private_key ): - """Update metadata for NFTs in a collection""" + """Update metadata for NFTs in a collection.""" receipt = ( TokenUpdateNftsTransaction() .set_token_id(nft_token_id) @@ -115,14 +114,14 @@ def update_nft_metadata( def token_update_nfts(): """ Demonstrates the NFT token update functionality by: + 1. Setting up client with operator account 2. Creating a non-fungible token with metadata key 3. Minting two NFTs with initial metadata 4. Checking the current NFT info 5. Updating metadata for the first NFT - 6. Verifying the updated NFT metadata + 6. Verifying the updated NFT metadata. """ - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_update_transaction_fungible.py b/examples/tokens/token_update_transaction_fungible.py index 920a4f23a..cd313294c 100644 --- a/examples/tokens/token_update_transaction_fungible.py +++ b/examples/tokens/token_update_transaction_fungible.py @@ -1,22 +1,24 @@ """ + +Example demonstrating token update transaction fungible. + uv run examples/tokens/token_update_transaction_fungible.py python examples/tokens/token_update_transaction_fungible.py - """ - import sys from hiero_sdk_python import ( Client, PrivateKey, ) -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction +from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.token_update_transaction import TokenUpdateTransaction + def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -25,7 +27,7 @@ def setup_client(): def create_fungible_token(client, operator_id, operator_key, metadata_key): """ - Create a fungible token + Create a fungible token. If we want to update metadata later using TokenUpdateTransaction: 1. Set a metadata_key and sign the update transaction with it, or @@ -66,10 +68,9 @@ def create_fungible_token(client, operator_id, operator_key, metadata_key): def get_token_info(client, token_id): - """Get information about a fungible token""" - info = TokenInfoQuery().set_token_id(token_id).execute(client) + """Get information about a fungible token.""" + return TokenInfoQuery().set_token_id(token_id).execute(client) - return info def update_token_data( @@ -80,7 +81,7 @@ def update_token_data( update_token_symbol, update_token_memo, ): - """Update metadata for a fungible token""" + """Update metadata for a fungible token.""" receipt = ( TokenUpdateTransaction() .set_token_id(token_id) @@ -97,17 +98,18 @@ def update_token_data( ) sys.exit(1) - print(f"Successfully updated token data") + print("Successfully updated token data") def token_update_fungible(): """ Demonstrates the fungible token update functionality by: + 1. Setting up client with operator account 2. Creating a fungible token with metadata key 3. Checking the current token info 4. Updating the token's metadata, name, symbol and memo - 5. Verifying the updated token info + 5. Verifying the updated token info. """ client = setup_client() operator_id = client.operator_account_id diff --git a/examples/tokens/token_update_transaction_key.py b/examples/tokens/token_update_transaction_key.py index 74702cea5..a3bbe6f6f 100644 --- a/examples/tokens/token_update_transaction_key.py +++ b/examples/tokens/token_update_transaction_key.py @@ -1,21 +1,22 @@ """ + +Example demonstrating token update transaction key. + uv run examples/tokens/token_update_transaction_key.py python examples/tokens/token_update_transaction_key.py - """ - import sys from hiero_sdk_python import ( Client, PrivateKey, ) -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode -from hiero_sdk_python.tokens.token_key_validation import TokenKeyValidation from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction +from hiero_sdk_python.tokens.token_key_validation import TokenKeyValidation +from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.token_update_transaction import TokenUpdateTransaction @@ -26,7 +27,7 @@ def setup_client(): return client def create_fungible_token(client, operator_id, admin_key, wipe_key): - """Create a fungible token""" + """Create a fungible token.""" receipt = ( TokenCreateTransaction() .set_token_name("MyExampleFT") @@ -59,10 +60,9 @@ def create_fungible_token(client, operator_id, admin_key, wipe_key): def get_token_info(client, token_id): - """Get information about a fungible token""" - info = TokenInfoQuery().set_token_id(token_id).execute(client) + """Get information about a fungible token.""" + return TokenInfoQuery().set_token_id(token_id).execute(client) - return info def update_wipe_key_full_validation(client, token_id, old_wipe_key): @@ -93,7 +93,7 @@ def update_wipe_key_full_validation(client, token_id, old_wipe_key): print(f"Token update failed with status: {ResponseCode(receipt.status).name}") sys.exit(1) - print(f"Successfully updated wipe key") + print("Successfully updated wipe key") # Query token info to verify wipe key update info = get_token_info(client, token_id) @@ -103,12 +103,12 @@ def update_wipe_key_full_validation(client, token_id, old_wipe_key): def token_update_key(): """ Demonstrates updating keys on a fungible token by: + 1. Setting up client with operator account 2. Creating a fungible token with admin and wipe keys 3. Checking the current token info and key values - 4. Updating the wipe key with full validation + 4. Updating the wipe key with full validation. """ - client = setup_client() operator_id = client.operator_account_id diff --git a/examples/tokens/token_update_transaction_nft.py b/examples/tokens/token_update_transaction_nft.py index a4eece992..8801a9229 100644 --- a/examples/tokens/token_update_transaction_nft.py +++ b/examples/tokens/token_update_transaction_nft.py @@ -1,22 +1,24 @@ """ + +Example demonstrating token update transaction nft. + uv run examples/tokens/token_update_transaction_nft.py python examples/tokens/token_update_transaction_nft.py - """ - import sys from hiero_sdk_python import ( Client, PrivateKey, ) -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.query.token_info_query import TokenInfoQuery from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.supply_type import SupplyType from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction +from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.token_update_transaction import TokenUpdateTransaction + def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -25,7 +27,7 @@ def setup_client(): def create_nft(client, operator_id, operator_key, metadata_key): """ - Create a non-fungible token + Create a non-fungible token. If we want to update metadata later using TokenUpdateTransaction: 1. Set a metadata_key and sign the update transaction with it, or @@ -64,10 +66,9 @@ def create_nft(client, operator_id, operator_key, metadata_key): def get_nft_info(client, nft_token_id): - """Get information about an NFT""" - info = TokenInfoQuery().set_token_id(nft_token_id).execute(client) + """Get information about an NFT.""" + return TokenInfoQuery().set_token_id(nft_token_id).execute(client) - return info def update_nft_data( @@ -78,7 +79,7 @@ def update_nft_data( update_token_symbol, update_token_memo, ): - """Update data for an NFT""" + """Update data for an NFT.""" receipt = ( TokenUpdateTransaction() .set_token_id(nft_token_id) @@ -95,19 +96,19 @@ def update_nft_data( ) sys.exit(1) - print(f"Successfully updated NFT data") + print("Successfully updated NFT data") def token_update_nft(): """ Demonstrates the NFT token update functionality by: + 1. Setting up client with operator account 2. Creating a non-fungible token with metadata key 3. Checking the current NFT info 4. Updating the token's metadata, name, symbol and memo - 5. Verifying the updated NFT info + 5. Verifying the updated NFT info. """ - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/tokens/token_wipe_transaction.py b/examples/tokens/token_wipe_transaction.py index d49f9f4dc..e3d070121 100644 --- a/examples/tokens/token_wipe_transaction.py +++ b/examples/tokens/token_wipe_transaction.py @@ -1,18 +1,17 @@ """ + +Example demonstrating token wipe transaction. + uv run examples/tokens/token_wipe_transaction.py python examples/tokens/token_wipe_transaction.py """ - -import os import sys from hiero_sdk_python import ( Client, - AccountId, PrivateKey, - Network, - TransferTransaction, TokenAssociateTransaction, + TransferTransaction, ) from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction from hiero_sdk_python.hbar import Hbar @@ -22,6 +21,7 @@ from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.tokens.token_wipe_transaction import TokenWipeTransaction + def setup_client(): client = Client.from_env() print(f"Network: {client.network.network}") @@ -29,7 +29,7 @@ def setup_client(): return client def create_test_account(client): - """Create a new account for testing""" + """Create a new account for testing.""" # Generate private key for new account new_account_private_key = PrivateKey.generate() new_account_public_key = new_account_private_key.public_key() @@ -59,7 +59,7 @@ def create_test_account(client): def create_token(client, operator_id, operator_key): - """Create a fungible token""" + """Create a fungible token.""" # Create fungible token # Note: The wipe key is required to perform token wipe operations transaction = ( @@ -94,7 +94,7 @@ def create_token(client, operator_id, operator_key): def associate_token(client, account_id, token_id, account_private_key): - """Associate a token with an account""" + """Associate a token with an account.""" # Associate the token with the new account # Note: Accounts must be associated with tokens before they can receive them associate_transaction = ( @@ -117,7 +117,7 @@ def associate_token(client, account_id, token_id, account_private_key): def transfer_tokens(client, token_id, operator_id, account_id, amount): - """Transfer tokens from operator to the specified account""" + """Transfer tokens from operator to the specified account.""" # Transfer tokens to the new account # Note: Negative amount for sender, positive for receiver transfer_transaction = ( @@ -138,7 +138,7 @@ def transfer_tokens(client, token_id, operator_id, account_id, amount): def wipe_tokens(client, token_id, account_id, amount): - """Wipe tokens from the specified account""" + """Wipe tokens from the specified account.""" # Wipe the tokens from the account # Note: This requires the wipe key that was specified during token creation transaction = ( @@ -161,13 +161,13 @@ def wipe_tokens(client, token_id, account_id, amount): def token_wipe(): """ Demonstrates the token wipe functionality by: + 1. Creating a new account 2. Creating a fungible token with wipe capability 3. Associating the token with the new account 4. Transferring tokens to the new account - 5. Wiping the tokens from the account + 5. Wiping the tokens from the account. """ - client = setup_client() operator_id = client.operator_account_id operator_key = client.operator_private_key diff --git a/examples/topic_info.py b/examples/topic_info.py index 7978d0999..1c52c0356 100644 --- a/examples/topic_info.py +++ b/examples/topic_info.py @@ -1,5 +1,7 @@ """ -**INTERNAL DEVELOPER REFERENCE** + + +**INTERNAL DEVELOPER REFERENCE**. This example is primarily for internal SDK developers and contributors. @@ -23,9 +25,8 @@ uv run examples/topic_info.py python examples/topic_info.py """ - -from hiero_sdk_python.consensus.topic_info import TopicInfo from hiero_sdk_python.account.account_id import AccountId +from hiero_sdk_python.consensus.topic_info import TopicInfo from hiero_sdk_python.crypto.private_key import PrivateKey from hiero_sdk_python.Duration import Duration from hiero_sdk_python.hapi.services import consensus_topic_info_pb2 @@ -89,7 +90,7 @@ def mock_ledger_id() -> bytes: def build_mock_topic_info() -> TopicInfo: """Manually construct a TopicInfo instance with mock data.""" - topic_info = TopicInfo( + return TopicInfo( memo="Example topic memo", running_hash=mock_running_hash(), sequence_number=42, @@ -103,7 +104,6 @@ def build_mock_topic_info() -> TopicInfo: fee_exempt_keys=None, custom_fees=[mock_custom_fee()], ) - return topic_info def build_topic_info_from_proto() -> TopicInfo: @@ -120,8 +120,7 @@ def build_topic_info_from_proto() -> TopicInfo: proto.ledger_id = mock_ledger_id() proto.custom_fees.append(mock_custom_fee()._to_topic_fee_proto()) - topic_info = TopicInfo._from_proto(proto) - return topic_info + return TopicInfo._from_proto(proto) def print_topic_info(topic: TopicInfo) -> None: diff --git a/examples/transaction/batch_transaction.py b/examples/transaction/batch_transaction.py index 6cc2d0d19..e25ef331f 100644 --- a/examples/transaction/batch_transaction.py +++ b/examples/transaction/batch_transaction.py @@ -1,5 +1,8 @@ """ -uv run examples/transaction/batch_transaction.py + +Example demonstrating batch transaction. + +uv run examples/transaction/batch_transaction.py. """ import os @@ -8,18 +11,18 @@ from dotenv import load_dotenv from hiero_sdk_python import ( + AccountCreateTransaction, AccountId, + BatchTransaction, Client, + CryptoGetAccountBalanceQuery, Network, PrivateKey, - AccountCreateTransaction, - CryptoGetAccountBalanceQuery, ResponseCode, TokenCreateTransaction, TokenFreezeTransaction, TokenType, TokenUnfreezeTransaction, - BatchTransaction, TransferTransaction, ) @@ -37,9 +40,7 @@ def get_balance(client, account_id, token_id): def setup_client(): - """ - Set up and configure a Hedera client for testnet operations. - """ + """Set up and configure a Hedera client for testnet operations.""" network_name = os.getenv("NETWORK", "testnet").lower() print(f"Connecting to Hedera {network_name} network!") @@ -60,9 +61,7 @@ def setup_client(): def create_account(client): - """ - Create a new recipient account. - """ + """Create a new recipient account.""" print("\nCreating new recipient account...") try: key = PrivateKey.generate() @@ -86,9 +85,7 @@ def create_account(client): def create_fungible_token(client, freeze_key): - """ - Create a fungible token with freeze_key. - """ + """Create a fungible token with freeze_key.""" print("\nCreating fungible token...") try: tx = ( @@ -115,9 +112,7 @@ def create_fungible_token(client, freeze_key): def freeze_token(client, account_id, token_id, freeze_key): - """ - Freeze token for an account. - """ + """Freeze token for an account.""" print(f"\nFreezing token for account {account_id}") try: tx = ( @@ -141,9 +136,7 @@ def freeze_token(client, account_id, token_id, freeze_key): def transfer_token(client, sender, recipient, token_id): - """ - Perform a token trasfer transaction. - """ + """Perform a token transfer transaction.""" print(f"\nTransferring token {token_id} from {sender} → {recipient}") try: tx = ( @@ -152,18 +145,15 @@ def transfer_token(client, sender, recipient, token_id): .add_token_transfer(token_id=token_id, account_id=recipient, amount=1) ) - receipt = tx.execute(client) + return tx.execute(client) - return receipt except Exception as e: print(f"Error transfering token: {e}") sys.exit(1) def perform_batch_tx(client, sender, recipient, token_id, freeze_key): - """ - Perform a batch transaction using PrivateKey as batch_key. - """ + """Perform a batch transaction using PrivateKey as batch_key.""" print( "\nPerforming batch transaction with PrivateKey (unfreeze → transfer → freeze)..." ) @@ -209,6 +199,7 @@ def perform_batch_tx(client, sender, recipient, token_id, freeze_key): def perform_batch_tx_with_public_key(client, sender, recipient, token_id, freeze_key): """ Perform a batch transaction using PublicKey as batch_key. + Demonstrates that batch_key can accept both PrivateKey and PublicKey. """ print( diff --git a/examples/transaction/custom_fee_limit.py b/examples/transaction/custom_fee_limit.py index 631ea27dc..3dc1de06a 100644 --- a/examples/transaction/custom_fee_limit.py +++ b/examples/transaction/custom_fee_limit.py @@ -1,24 +1,26 @@ """ + + Example: Using CustomFeeLimit with a revenue-generating topic. - Creates a topic that charges a fixed custom fee per message. - Submits a message with a CustomFeeLimit specifying how much the payer is willing to pay in custom fees for that message. """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, AccountId, - PrivateKey, + Client, + CustomFixedFee, Hbar, Network, + PrivateKey, TopicCreateTransaction, TopicMessageSubmitTransaction, - CustomFixedFee, ) from hiero_sdk_python.transaction.custom_fee_limit import CustomFeeLimit diff --git a/examples/transaction/transaction_freeze_manually.py b/examples/transaction/transaction_freeze_manually.py index be7e9a8f0..73f848bc2 100644 --- a/examples/transaction/transaction_freeze_manually.py +++ b/examples/transaction/transaction_freeze_manually.py @@ -1,5 +1,8 @@ """ -Demonstrates how to manually freeze, serialize, deserialize, + + +Demonstrates how to manually freeze, serialize, deserialize,. + sign, and execute a transaction using hiero_sdk_python. uv run examples/transaction/transaction_freeze_manually.py @@ -7,17 +10,18 @@ """ import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( AccountId, - PrivateKey, - TopicCreateTransaction, - TransactionId, Client, Network, + PrivateKey, + ResponseCode, + TopicCreateTransaction, Transaction, - ResponseCode + TransactionId, ) load_dotenv() @@ -28,9 +32,7 @@ NODE_ACCOUNT_ID = AccountId.from_string("0.0.3") def setup_client(): - """ - Initialize and return a Hedera Client using operator credentials. - """ + """Initialize and return a Hedera Client using operator credentials.""" if not OPERATOR_ID or not OPERATOR_KEY: raise RuntimeError("OPERATOR_ID or OPERATOR_KEY not set in .env") @@ -51,9 +53,7 @@ def setup_client(): return client def build_unsigned_tx(executor_client): - """ - Build a Transaction, manually freeze it for a specific node, and return serialized unsigned bytes. - """ + """Build a Transaction, manually freeze it for a specific node, and return serialized unsigned bytes.""" tx_id = TransactionId.generate(executor_client.operator_account_id) tx = ( @@ -72,9 +72,7 @@ def build_unsigned_tx(executor_client): return tx.to_bytes() def sign_and_execute(unsigned_bytes, executor_client): - """ - Deserialize, sign, and execute a transaction. - """ + """Deserialize, sign, and execute a transaction.""" try: # Deserialize tx = Transaction.from_bytes(unsigned_bytes) @@ -98,6 +96,7 @@ def sign_and_execute(unsigned_bytes, executor_client): def main(): """ 1. Set up a client. + 2. Create a Transaction and explicitly: - Set the TransactionId - Set the NodeAccountId (e.g. 0.0.3) diff --git a/examples/transaction/transaction_freeze_secondary_client.py b/examples/transaction/transaction_freeze_secondary_client.py index 146c520d0..93656e0bd 100644 --- a/examples/transaction/transaction_freeze_secondary_client.py +++ b/examples/transaction/transaction_freeze_secondary_client.py @@ -1,28 +1,30 @@ """ -Demonstrate Manually freezing using secondary client, serializing, deserializing, signing, + + +Demonstrate Manually freezing using secondary client, serializing, deserializing, signing,. + and executing a Hedera transaction using hiero_sdk_python. uv run examples/transaction/transaction_freeze_secondary_client.py python examples/transaction/transaction_freeze_secondary_client.py """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( + AccountCreateTransaction, AccountId, - PrivateKey, - TopicCreateTransaction, - TransactionId, Client, Network, + PrivateKey, + ResponseCode, + TopicCreateTransaction, Transaction, - AccountCreateTransaction, - ResponseCode + TransactionId, ) - load_dotenv() NETWORK_NAME = os.getenv("NETWORK", "testnet").lower() @@ -31,9 +33,7 @@ def setup_client(): - """ - Initialize and return the primary Hedera client using operator credentials. - """ + """Initialize and return the primary Hedera client using operator credentials.""" if not OPERATOR_ID or not OPERATOR_KEY: raise RuntimeError("OPERATOR_ID or OPERATOR_KEY not set in .env") @@ -54,9 +54,7 @@ def setup_client(): return client def create_secondary_client(executor_client): - """ - Create a secondary account and client. - """ + """Create a secondary account and client.""" private_key = PrivateKey.generate() receipt = ( @@ -77,7 +75,8 @@ def create_secondary_client(executor_client): def build_unsigned_bytes(executor_client, secondary_client): """ - Build a TopicCreateTransaction, manually freeze it using a secondary client, + Build a TopicCreateTransaction, manually freeze it using a secondary client,. + and return the serialized unsigned transaction bytes. """ tx_id = TransactionId.generate(executor_client.operator_account_id) @@ -98,7 +97,8 @@ def build_unsigned_bytes(executor_client, secondary_client): def sign_and_execute(unsigned_bytes, executor_client): """ - Deserialize a transaction from bytes, sign it using the executor client, + Deserialize a transaction from bytes, sign it using the executor client,. + and execute it on the Hedera network. """ try: @@ -122,6 +122,7 @@ def sign_and_execute(unsigned_bytes, executor_client): def main(): """ 1. Setup an executor client. + 2. Created secondary client used to manually freeze a transaction. 3. Create a Transaction and explicitly: - Set the TransactionId diff --git a/examples/transaction/transaction_freeze_without_operator.py b/examples/transaction/transaction_freeze_without_operator.py index b84b52d69..f20577d70 100644 --- a/examples/transaction/transaction_freeze_without_operator.py +++ b/examples/transaction/transaction_freeze_without_operator.py @@ -1,5 +1,8 @@ """ -Demonstrate manually freezing with client having no operator set, + + +Demonstrate manually freezing with client having no operator set,. + serializing, signing, and executing a transaction. uv run examples/transaction/transaction_freeze_without_operator.py @@ -7,20 +10,20 @@ """ import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( AccountId, - PrivateKey, - TopicCreateTransaction, - TransactionId, Client, Network, + PrivateKey, + ResponseCode, + TopicCreateTransaction, Transaction, - ResponseCode + TransactionId, ) - load_dotenv() NETWORK_NAME = os.getenv("NETWORK", "testnet").lower() @@ -29,9 +32,7 @@ def setup_client(): - """ - Initialize and return the primary Hedera client using operator credentials. - """ + """Initialize and return the primary Hedera client using operator credentials.""" if not OPERATOR_ID or not OPERATOR_KEY: raise RuntimeError("OPERATOR_ID or OPERATOR_KEY not set in .env") @@ -54,16 +55,14 @@ def setup_client(): def create_client_without_operator(): - """ - Create a client without an operator. - """ - secondary_client = Client(Network(NETWORK_NAME)) + """Create a client without an operator.""" + return Client(Network(NETWORK_NAME)) - return secondary_client def build_unsigned_bytes(executor_client, secondary_client): """ - Build a TopicCreateTransaction, manually freeze it using a secondary client, + Build a TopicCreateTransaction, manually freeze it using a secondary client,. + and return the serialized unsigned transaction bytes. """ tx_id = TransactionId.generate(executor_client.operator_account_id) @@ -84,7 +83,8 @@ def build_unsigned_bytes(executor_client, secondary_client): def sign_and_execute(unsigned_bytes, executor_client): """ - Deserialize a transaction from bytes, sign it using the executor client, + Deserialize a transaction from bytes, sign it using the executor client,. + and execute it on the Hedera network. """ try: @@ -108,6 +108,7 @@ def sign_and_execute(unsigned_bytes, executor_client): def main(): """ 1. Setup an executor client. + 2. Create a secondary client without an operator. 3. Create a Transaction and explicitly: - Set the TransactionId diff --git a/examples/transaction/transaction_to_bytes.py b/examples/transaction/transaction_to_bytes.py index b727c1d93..f1ce84c86 100644 --- a/examples/transaction/transaction_to_bytes.py +++ b/examples/transaction/transaction_to_bytes.py @@ -1,4 +1,6 @@ """ + + Example demonstrating transaction byte serialization and deserialization. This example shows how to: @@ -11,18 +13,18 @@ uv run examples/transaction/transaction_to_bytes.py python examples/transaction/transaction_to_bytes.py """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, AccountId, - PrivateKey, + Client, Network, - TransferTransaction, + PrivateKey, Transaction, + TransferTransaction, ) load_dotenv() diff --git a/examples/transaction/transfer_transaction_fungible.py b/examples/transaction/transfer_transaction_fungible.py index 550eeba95..a14a51b71 100644 --- a/examples/transaction/transfer_transaction_fungible.py +++ b/examples/transaction/transfer_transaction_fungible.py @@ -1,24 +1,26 @@ """ + +Example demonstrating transfer transaction fungible. + uv run examples/transaction/transfer_transaction_fungible.py python examples/transaction/transfer_transaction_fungible.py - """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, - AccountId, - PrivateKey, - Network, - TransferTransaction, AccountCreateTransaction, - Hbar, - TokenCreateTransaction, + AccountId, + Client, CryptoGetAccountBalanceQuery, + Hbar, + Network, + PrivateKey, TokenAssociateTransaction, + TokenCreateTransaction, + TransferTransaction, ) load_dotenv() @@ -29,7 +31,7 @@ # CLIENT SETUP # -------------------------- def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) @@ -50,7 +52,7 @@ def setup_client(): # ACCOUNT CREATION # -------------------------- def create_account(client, operator_key): - """Create a new recipient account""" + """Create a new recipient account.""" print("\nSTEP 1: Creating a new recipient account...") recipient_key = PrivateKey.generate() try: @@ -154,8 +156,9 @@ def transfer_transaction(client, operator_id, operator_key, recipient_id, token_ # -------------------------- def main(): """ - A full example to create a new recipent account, a fungible token, and - transfer the token to that account + A full example to create a new recipient account, a fungible token, and. + + transfer the token to that account. """ # Config Client client, operator_id, operator_key = setup_client() diff --git a/examples/transaction/transfer_transaction_gigabar.py b/examples/transaction/transfer_transaction_gigabar.py index 502dd15da..150269e41 100644 --- a/examples/transaction/transfer_transaction_gigabar.py +++ b/examples/transaction/transfer_transaction_gigabar.py @@ -1,10 +1,11 @@ -"""Example of transferring HBAR using the GIGABAR unit. +""" + +Example of transferring HBAR using the GIGABAR unit. Usage: uv run examples/transaction/transfer_transaction_gigabar.py python examples/transaction/transfer_transaction_gigabar.py """ - import os import sys @@ -118,7 +119,9 @@ def get_balance(client, account_id, when=""): def main(): - """Run example demonstrating large-value transfers using GIGABAR units. + """ + + Run example demonstrating large-value transfers using GIGABAR units. Steps: 1. Setup client. diff --git a/examples/transaction/transfer_transaction_hbar.py b/examples/transaction/transfer_transaction_hbar.py index 44782466d..49167ab8c 100644 --- a/examples/transaction/transfer_transaction_hbar.py +++ b/examples/transaction/transfer_transaction_hbar.py @@ -1,10 +1,11 @@ -"""Example of transferring HBAR using the Hiero Python SDK. +""" + +Example of transferring HBAR using the Hiero Python SDK. Usage: uv run examples/transaction/transfer_transaction_hbar.py python examples/transaction/transfer_transaction_hbar.py """ - import os import sys @@ -115,7 +116,9 @@ def get_balance(client, account_id, when=""): def main(): - """Run a full example to create a new recipient account and transfer hbar to that account. + """ + + Run a full example to create a new recipient account and transfer hbar to that account. Steps: 1. Setup client with operator credentials. diff --git a/examples/transaction/transfer_transaction_nft.py b/examples/transaction/transfer_transaction_nft.py index bc108d1fb..4625145bc 100644 --- a/examples/transaction/transfer_transaction_nft.py +++ b/examples/transaction/transfer_transaction_nft.py @@ -1,22 +1,23 @@ """ + +Example demonstrating transfer transaction nft. + uv run examples/transaction/transfer_transaction_nft.py python examples/transaction/transfer_transaction_nft.py - """ - import os import sys + from dotenv import load_dotenv from hiero_sdk_python import ( - Client, AccountId, - PrivateKey, + Client, Network, + PrivateKey, TransferTransaction, ) from hiero_sdk_python.account.account_create_transaction import AccountCreateTransaction -from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.hbar import Hbar from hiero_sdk_python.response_code import ResponseCode from hiero_sdk_python.tokens.nft_id import NftId @@ -26,13 +27,14 @@ ) from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_mint_transaction import TokenMintTransaction +from hiero_sdk_python.tokens.token_type import TokenType load_dotenv() network_name = os.getenv("NETWORK", "testnet").lower() def setup_client(): - """Initialize and set up the client with operator account""" + """Initialize and set up the client with operator account.""" # Initialize network and client network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") @@ -48,7 +50,7 @@ def setup_client(): def create_test_account(client): - """Create a new account for testing""" + """Create a new account for testing.""" # Generate private key for new account new_account_private_key = PrivateKey.generate() new_account_public_key = new_account_private_key.public_key() @@ -78,7 +80,7 @@ def create_test_account(client): def create_nft(client, operator_id, operator_key): - """Create a non-fungible token""" + """Create a non-fungible token.""" transaction = ( TokenCreateTransaction() .set_token_name("MyExampleNFT") @@ -110,7 +112,7 @@ def create_nft(client, operator_id, operator_key): def mint_nft(client, nft_token_id, operator_key): - """Mint a non-fungible token""" + """Mint a non-fungible token.""" transaction = ( TokenMintTransaction() .set_token_id(nft_token_id) @@ -130,7 +132,7 @@ def mint_nft(client, nft_token_id, operator_key): def associate_nft(client, account_id, token_id, account_private_key): - """Associate a non-fungible token with an account""" + """Associate a non-fungible token with an account.""" # Associate the token_id with the new account associate_transaction = ( TokenAssociateTransaction() @@ -152,7 +154,7 @@ def associate_nft(client, account_id, token_id, account_private_key): def transfer_nft_token(client, nft_id, sender_id, receiver_id): - """Transfer the NFT from the sender to the receiver account""" + """Transfer the NFT from the sender to the receiver account.""" # Transfer nft to the new account transfer_transaction = ( TransferTransaction() @@ -173,11 +175,12 @@ def transfer_nft_token(client, nft_id, sender_id, receiver_id): def main(): """ Demonstrates the nft transfer functionality by: + 1. Creating a new account 2. Creating a nft 3. Minting a nft 4. Associating the nft with the new account - 5. Transferring the nft to the new account + 5. Transferring the nft to the new account. """ client, operator_id, operator_key = setup_client() account_id, new_account_private_key = create_test_account(client) diff --git a/examples/transaction/transfer_transaction_tinybar.py b/examples/transaction/transfer_transaction_tinybar.py index a832b01ff..4de758162 100644 --- a/examples/transaction/transfer_transaction_tinybar.py +++ b/examples/transaction/transfer_transaction_tinybar.py @@ -1,10 +1,11 @@ -"""Example of transferring tinybars using legacy integer and modern Hbar object approaches. +""" + +Example of transferring tinybars using legacy integer and modern Hbar object approaches. Usage: uv run examples/transaction/transfer_transaction_tinybar.py python examples/transaction/transfer_transaction_tinybar.py """ - import os import sys @@ -139,7 +140,9 @@ def get_balance(client, account_id, when=""): def main(): - """Run example showing both integer and object-based tinybar transfers. + """ + + Run example showing both integer and object-based tinybar transfers. Steps: 1. Setup client. diff --git a/src/hiero_sdk_python/utils/crypto_utils.py b/src/hiero_sdk_python/utils/crypto_utils.py index 43dab440c..6559849a7 100644 --- a/src/hiero_sdk_python/utils/crypto_utils.py +++ b/src/hiero_sdk_python/utils/crypto_utils.py @@ -29,8 +29,19 @@ def keccak256(data: bytes) -> bytes: def compress_point_unchecked(x: int, y: int) -> bytes: """ - Compress an (x, y) for secp256k1 (or similar). 33 bytes: [0x02 or 0x03] + x(32). - sign bit of y => 0x03 if odd, 0x02 if even + Compress an elliptic curve point to SEC1 compressed format. + + Converts an (x, y) coordinate pair for secp256k1 into a 33-byte + compressed representation: [prefix byte] + [x coordinate as 32 bytes]. + + The prefix byte is 0x02 if y is even, or 0x03 if y is odd. + + Args: + x: The x coordinate of the elliptic curve point. + y: The y coordinate of the elliptic curve point. + + Returns: + bytes: A 33-byte compressed point representation. """ prefix = 0x02 | (y & 1) return bytes([prefix]) + x.to_bytes(32, "big") diff --git a/tests/unit/endpoint_test.py b/tests/unit/endpoint_test.py index 1a8bfd124..73cefc718 100644 --- a/tests/unit/endpoint_test.py +++ b/tests/unit/endpoint_test.py @@ -4,52 +4,54 @@ pytestmark = pytest.mark.unit -def test_getter_setter(): +def test_getter_setter(): """Test for Endpoint constructor, getters, and setters with fluent interface.""" - + endpoint = Endpoint(address=None, port=None, domain_name=None) - + # Test fluent interface (method chaining) - result = endpoint.set_address(b'127.0.1.1') + result = endpoint.set_address(b"127.0.1.1") assert result is endpoint, "set_address should return self for method chaining" - + result = endpoint.set_port(77777) assert result is endpoint, "set_port should return self for method chaining" - + result = endpoint.set_domain_name("redpanda.com") assert result is endpoint, "set_domain_name should return self for method chaining" - + # Protect against breaking changes - verify attributes exist - assert hasattr(endpoint, 'get_address'), "Missing get_address method" - assert hasattr(endpoint, 'get_port'), "Missing get_port method" - assert hasattr(endpoint, 'get_domain_name'), "Missing get_domain_name method" - - assert endpoint.get_address() == b'127.0.1.1' + assert hasattr(endpoint, "get_address"), "Missing get_address method" + assert hasattr(endpoint, "get_port"), "Missing get_port method" + assert hasattr(endpoint, "get_domain_name"), "Missing get_domain_name method" + + assert endpoint.get_address() == b"127.0.1.1" assert endpoint.get_port() == 77777 assert endpoint.get_domain_name() == "redpanda.com" + def test_serialization_roundtrip(): """ Verifies that all fields survive a full round-trip conversion: Endpoint -> Protobuf -> Endpoint. """ - original = Endpoint(address=b'192.168.1.1', port=8080, domain_name="example.com") - + original = Endpoint(address=b"192.168.1.1", port=8080, domain_name="example.com") + # Perform round-trip proto = original._to_proto() roundtrip = Endpoint._from_proto(proto) - + assert roundtrip.get_address() == original.get_address() assert roundtrip.get_port() == original.get_port() assert roundtrip.get_domain_name() == original.get_domain_name() + def test_constructor_with_values(): """Test Endpoint constructor with actual values.""" - endpoint = Endpoint(address=b'192.168.1.1', port=8080, domain_name="example.com") + endpoint = Endpoint(address=b"192.168.1.1", port=8080, domain_name="example.com") # Protect against breaking changes assert isinstance(endpoint, Endpoint), "Constructor must return Endpoint instance" - assert endpoint.get_address() == b'192.168.1.1' + assert endpoint.get_address() == b"192.168.1.1" assert endpoint.get_port() == 8080 assert endpoint.get_domain_name() == "example.com" @@ -64,73 +66,79 @@ def test_constructor_with_values(): ) def test_from_proto_port_mapping(input_port, expected_port): """Tests port mapping logic when converting Protobuf ServiceEndpoint to Endpoint. - + Port mapping rules: - Port 0 or 50111 maps to 50211 (legacy/default behavior) - Other ports pass through unchanged """ - + mock_proto = MagicMock() mock_proto.port = input_port mock_proto.ipAddressV4 = b"127.0.1.1" mock_proto.domain_name = "redpanda.com" - + endpoint = Endpoint._from_proto(mock_proto) - + # Verify port mapping assert endpoint.get_port() == expected_port - + # Verify all fields are mapped correctly (not just port) assert endpoint.get_address() == b"127.0.1.1", "Address must be mapped from proto" - assert endpoint.get_domain_name() == "redpanda.com", "Domain name must be mapped from proto" - + assert ( + endpoint.get_domain_name() == "redpanda.com" + ), "Domain name must be mapped from proto" + # Protect against breaking changes - PRIORITY 1 assert isinstance(endpoint, Endpoint), "Must return Endpoint instance" -@pytest.mark.parametrize(("field_to_none", "attr_name", "expected_default"), [ - ("address", "ipAddressV4", b""), - ("port", "port", 0), - ("domain_name", "domain_name", "") -]) + +@pytest.mark.parametrize( + ("field_to_none", "attr_name", "expected_default"), + [ + ("address", "ipAddressV4", b""), + ("port", "port", 0), + ("domain_name", "domain_name", ""), + ], +) def test_to_proto_with_none_values(field_to_none, attr_name, expected_default): """ - Ensures that when a field is None, _to_proto assigns the + Ensures that when a field is None, _to_proto assigns the standard Protobuf default instead of crashing. """ # Create endpoint with all values set - params = {"address": b'127.0.0.1', "port": 50211, "domain_name": "hiero.org"} - + params = {"address": b"127.0.0.1", "port": 50211, "domain_name": "hiero.org"} + # Nullify one specific field params[field_to_none] = None endpoint = Endpoint(**params) - + # Act proto = endpoint._to_proto() - + # Assert: Check that the specific attribute is the proto default assert getattr(proto, attr_name) == expected_default -def test_to_proto(): - """Verifies that an Endpoint instance can be correctly serialized back into +def test_to_proto(): + """Verifies that an Endpoint instance can be correctly serialized back into a Protobuf ServiceEndpoint object with all fields intact.""" - endpoint = Endpoint(address=b'127.0.1.1', port=77777, domain_name="redpanda.com") + endpoint = Endpoint(address=b"127.0.1.1", port=77777, domain_name="redpanda.com") proto = endpoint._to_proto() - assert proto.ipAddressV4 == b'127.0.1.1' + assert proto.ipAddressV4 == b"127.0.1.1" assert proto.port == 77777 assert proto.domain_name == "redpanda.com" -def test_str(): +def test_str(): """Tests the human-readable string representation of the Endpoint.""" - endpoint = Endpoint(address=b'127.0.1.1', port=77777, domain_name="redpanda.com") + endpoint = Endpoint(address=b"127.0.1.1", port=77777, domain_name="redpanda.com") result = str(endpoint) - + # Verify return type assert isinstance(result, str), "String representation should return a string" - assert result == '127.0.1.1:77777' + assert result == "127.0.1.1:77777" def test_str_with_none_values(): @@ -139,25 +147,26 @@ def test_str_with_none_values(): with pytest.raises(AttributeError): str(endpoint) -@pytest.mark.parametrize("invalid_data", [ - {"port": 77777, "domain_name": "test.com"}, - {"ip_address_v4": "127.0.0.1", "domain_name": "test.com"}, - {"ip_address_v4": "127.0.0.1", "port": 77777}, -]) + +@pytest.mark.parametrize( + "invalid_data", + [ + {"port": 77777, "domain_name": "test.com"}, + {"ip_address_v4": "127.0.0.1", "domain_name": "test.com"}, + {"ip_address_v4": "127.0.0.1", "port": 77777}, + ], +) def test_from_dict_missing_fields(invalid_data): """Test that from_dict raises ValueError when required fields are missing.""" with pytest.raises(ValueError, match="JSON data must contain"): Endpoint.from_dict(invalid_data) + def test_from_dict_success(): - """ Tests successful creation of an Endpoint from a dictionary (JSON format) """ - data = { - "ip_address_v4": "127.0.0.1", - "port": 77777, - "domain_name": "redpanda.com" - } + """Tests successful creation of an Endpoint from a dictionary (JSON format)""" + data = {"ip_address_v4": "127.0.0.1", "port": 77777, "domain_name": "redpanda.com"} endpoint = Endpoint.from_dict(data) - + assert endpoint.get_address() == b"127.0.0.1" assert endpoint.get_port() == 77777 - assert endpoint.get_domain_name() == "redpanda.com" \ No newline at end of file + assert endpoint.get_domain_name() == "redpanda.com"