diff --git a/CHANGELOG.md b/CHANGELOG.md index 143042957..ed40df694 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,7 +37,7 @@ This changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.1. - Add PR inactivity reminder bot for stale pull requests `.github/workflows/pr-inactivity-reminder-bot.yml` - Add comprehensive training documentation for _Executable class `docs/sdk_developers/training/executable.md` - Added empty `docs/maintainers/good_first_issues.md` file for maintainers to write Good First Issue guidelines (#1034) --Added new `.github/ISSUE_TEMPLATE/04_good_first_issue_candidate.yml` file (1068)(https://github.com/hiero-ledger/hiero-sdk-python/issues/1068) +- Added new `.github/ISSUE_TEMPLATE/04_good_first_issue_candidate.yml` file (1068)(https://github.com/hiero-ledger/hiero-sdk-python/issues/1068) - Enhanced `.github/ISSUE_TEMPLATE/01_good_first_issue.yml` with welcoming message and acceptance criteria sections to guide contributors in creating quality GFIs (#1052) - Add workflow to notify team about P0 issues `bot-p0-issues-notify-team.yml` @@ -54,6 +54,7 @@ This changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.1. `examples.yml` → `pr-check-examples.yml`, `test.yml` → `pr-check-test.yml` (#1043) - Cleaned up `token_airdrop_claim_auto` example for pylint compliance (no functional changes). (#1079) +- Formatted `examples/query` using black (#1082)(https://github.com/hiero-ledger/hiero-sdk-python/issues/1082) - Update team notification script and workflow for P0 issues 'p0_issues_notify_team.js' - Rename test files across the repository to ensure they consistently end with _test.py (#1055) diff --git a/examples/query/account_balance_query.py b/examples/query/account_balance_query.py index dfd56bc12..419f1773f 100644 --- a/examples/query/account_balance_query.py +++ b/examples/query/account_balance_query.py @@ -12,6 +12,7 @@ python examples/query/account_balance_query.py """ + import os import sys import time @@ -30,7 +31,8 @@ ) load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + def setup_client(): """ @@ -47,12 +49,13 @@ def setup_client(): print(f"Connecting to Hedera {network_name} network!") client = Client(network) - operator_id_str = os.getenv('OPERATOR_ID') - operator_key_str = os.getenv('OPERATOR_KEY') + operator_id_str = os.getenv("OPERATOR_ID") + operator_key_str = os.getenv("OPERATOR_KEY") if not operator_id_str or not operator_key_str: raise ValueError( - "OPERATOR_ID and OPERATOR_KEY environment variables must be set") + "OPERATOR_ID and OPERATOR_KEY environment variables must be set" + ) operator_id = AccountId.from_string(operator_id_str) operator_key = PrivateKey.from_string(operator_key_str) @@ -82,9 +85,7 @@ def create_account(client, operator_key, initial_balance=Hbar(10)): # Create the account creation transaction transaction = AccountCreateTransaction( - key=new_account_public_key, - initial_balance=initial_balance, - memo="New Account" + key=new_account_public_key, initial_balance=initial_balance, memo="New Account" ).freeze_with(client) # Sign and execute the transaction @@ -95,7 +96,8 @@ def create_account(client, operator_key, initial_balance=Hbar(10)): print(f"✓ 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") + f" Initial balance: {initial_balance.to_hbars()} hbars ({initial_balance.to_tinybars()} tinybars)\n" + ) return new_account_id, new_account_private_key @@ -136,7 +138,8 @@ def transfer_hbars(client, operator_id, operator_key, recipient_id, amount): str: The status of the transfer transaction. """ print( - f"Transferring {amount.to_tinybars()} tinybars ({amount.to_hbars()} hbars) from {operator_id} to {recipient_id}...") + f"Transferring {amount.to_tinybars()} tinybars ({amount.to_hbars()} hbars) from {operator_id} to {recipient_id}..." + ) # Create transfer transaction transfer_transaction = ( @@ -166,7 +169,8 @@ def main(): # Create a new account with initial balance new_account_id, new_account_private_key = create_account( - client, operator_key, initial_balance=Hbar(10)) + client, operator_key, initial_balance=Hbar(10) + ) # Query and display the initial balance print("=" * 60) @@ -182,7 +186,8 @@ def main(): print("=" * 60) transfer_amount = Hbar(5) transfer_status = transfer_hbars( - client, operator_id, operator_key, new_account_id, transfer_amount) + client, operator_id, operator_key, new_account_id, transfer_amount + ) print(f"Transfer transaction status: {transfer_status}") print("=" * 60 + "\n") diff --git a/examples/query/account_balance_query_2.py b/examples/query/account_balance_query_2.py index bcadb8a12..9a6fd3e21 100644 --- a/examples/query/account_balance_query_2.py +++ b/examples/query/account_balance_query_2.py @@ -19,7 +19,6 @@ TokenInfoQuery, TokenType, TokenMintTransaction, - ) from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery from hiero_sdk_python.tokens.token_id import TokenId @@ -27,19 +26,20 @@ # Load environment variables from .env file load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() -key_type = os.getenv('KEY_TYPE', 'ecdsa') +network_name = os.getenv("NETWORK", "testnet").lower() +key_type = os.getenv("KEY_TYPE", "ecdsa") + def setup_client(): - """Setup Client """ + """Setup Client""" network = Network(network_name) print(f"Connecting to Hedera {network_name} network!") client = Client(network) # Get the operator account from the .env file try: - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) # Set the operator (payer) account for the client client.set_operator(operator_id, operator_key) print(f"Client set up with operator id {client.operator_account_id}") @@ -48,6 +48,7 @@ def setup_client(): print("Error: Please check OPERATOR_ID and OPERATOR_KEY in your .env file.") sys.exit(1) + def create_account(client, name, initial_balance=Hbar(10)): """Create a test account with initial balance""" account_private_key = PrivateKey.generate(key_type) @@ -70,6 +71,7 @@ def create_account(client, name, initial_balance=Hbar(10)): print(f"{name} account created with id: {account_id}") return account_id, account_private_key + def create_and_mint_token(treasury_account_id, treasury_account_key, client): """Create an NFT collection and mint metadata_list (default 3 items).""" metadata_list = [b"METADATA_A", b"METADATA_B", b"METADATA_C"] @@ -79,35 +81,39 @@ def create_and_mint_token(treasury_account_id, treasury_account_key, client): token_id = ( TokenCreateTransaction() - .set_token_name("My Awesome NFT").set_token_symbol("MANFT") + .set_token_name("My Awesome NFT") + .set_token_symbol("MANFT") .set_token_type(TokenType.NON_FUNGIBLE_UNIQUE) .set_treasury_account_id(treasury_account_id) .set_initial_supply(0) .set_supply_key(supply_key) .freeze_with(client) - .sign(treasury_account_key).sign(supply_key).execute(client) + .sign(treasury_account_key) + .sign(supply_key) + .execute(client) ).token_id - TokenMintTransaction() \ - .set_token_id(token_id).set_metadata(metadata_list) \ - .freeze_with(client).sign(supply_key).execute(client) + TokenMintTransaction().set_token_id(token_id).set_metadata( + metadata_list + ).freeze_with(client).sign(supply_key).execute(client) - total_supply = TokenInfoQuery().set_token_id(token_id).execute(client).total_supply + total_supply = ( + TokenInfoQuery().set_token_id(token_id).execute(client).total_supply + ) print(f"✅ Created NFT {token_id} — total supply: {total_supply}") return token_id except (ValueError, TypeError, RuntimeError, ConnectionError) as error: print(f"❌ Error creating token: {error}") sys.exit(1) + def get_account_balance(client: Client, account_id: AccountId): """Get account balance using CryptoGetAccountBalanceQuery""" print(f"Retrieving account balance for account id: {account_id} ...") try: # Use CryptoGetAccountBalanceQuery to get the account balance account_balance = ( - CryptoGetAccountBalanceQuery() - .set_account_id(account_id) - .execute(client) + CryptoGetAccountBalanceQuery().set_account_id(account_id).execute(client) ) print("✅ Account balance retrieved successfully!") print(f"💰 HBAR Balance for {account_id}: {account_balance.hbars} hbars") @@ -120,10 +126,11 @@ def get_account_balance(client: Client, account_id: AccountId): print(f"Error retrieving account balance: {error}") sys.exit(1) -#OPTIONAL comparison function -def compare_token_balances(client, treasury_id: AccountId, - receiver_id: AccountId, - token_id: TokenId): + +# OPTIONAL comparison function +def compare_token_balances( + client, treasury_id: AccountId, receiver_id: AccountId, token_id: TokenId +): """Compare token balances between two accounts""" print( f"\n🔎 Comparing token balances for Token ID {token_id} " @@ -139,6 +146,7 @@ def compare_token_balances(client, treasury_id: AccountId, print(f"🏷️ Token balance for Treasury ({treasury_id}): {treasury_token_balance}") print(f"🏷️ Token balance for Receiver ({receiver_id}): {receiver_token_balance}") + def main(): """Main function to run the account balance query example 1-Create test account with intial balance @@ -151,14 +159,14 @@ def main(): test_account_id, test_account_key = create_account(client, "Test Account") # Create the tokens with the test account as the treasury so minted tokens # will be owned by the test account and show up in its token balances. - token_id = create_and_mint_token( - test_account_id, - test_account_key, - client) + token_id = create_and_mint_token(test_account_id, test_account_key, client) # Retrieve and display account balance for the test account get_account_balance(client, test_account_id) - #OPTIONAL comparison of token balances between test account and operator account - compare_token_balances(client, test_account_id, client.operator_account_id, token_id) + # OPTIONAL comparison of token balances between test account and operator account + compare_token_balances( + client, test_account_id, client.operator_account_id, token_id + ) + if __name__ == "__main__": main() diff --git a/examples/query/account_info_query.py b/examples/query/account_info_query.py index 78b85ca54..fb61c79b0 100644 --- a/examples/query/account_info_query.py +++ b/examples/query/account_info_query.py @@ -3,6 +3,7 @@ python examples/query/account_info_query.py """ + import os import sys from dotenv import load_dotenv @@ -18,7 +19,9 @@ ) 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.token_associate_transaction import TokenAssociateTransaction +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.supply_type import SupplyType from hiero_sdk_python.tokens.token_type import TokenType @@ -27,7 +30,8 @@ load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + def setup_client(): """Initialize and set up the client with operator account""" @@ -35,18 +39,19 @@ def setup_client(): print(f"Connecting to the Hedera {network} network!") client = Client(network) - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) client.set_operator(operator_id, operator_key) print(f"Client set up with operator id {client.operator_account_id}") return client, operator_id, operator_key + def create_test_account(client, operator_key): """Create a new test account for demonstration""" new_account_private_key = PrivateKey.generate_ed25519() new_account_public_key = new_account_private_key.public_key() - + receipt = ( AccountCreateTransaction() .set_key(new_account_public_key) @@ -56,16 +61,19 @@ def create_test_account(client, operator_key): .sign(operator_key) .execute(client) ) - + if receipt.status != ResponseCode.SUCCESS: - print(f"Account creation failed with status: {ResponseCode(receipt.status).name}") + print( + f"Account creation failed with status: {ResponseCode(receipt.status).name}" + ) sys.exit(1) - + new_account_id = receipt.account_id print(f"\nTest account created with ID: {new_account_id}") - + return new_account_id, new_account_private_key + def create_fungible_token(client, operator_id, operator_key): """Create a fungible token for association with test account""" receipt = ( @@ -83,16 +91,17 @@ def create_fungible_token(client, operator_id, operator_key): .set_kyc_key(operator_key) .execute(client) ) - + if receipt.status != ResponseCode.SUCCESS: print(f"Token creation failed with status: {ResponseCode(receipt.status).name}") sys.exit(1) - + token_id = receipt.token_id print(f"\nFungible token created with ID: {token_id}") - + return token_id + def create_nft(client, account_id, account_private_key): """Create a non-fungible token""" receipt = ( @@ -109,21 +118,22 @@ def create_nft(client, account_id, account_private_key): .set_supply_key(account_private_key) .set_freeze_key(account_private_key) .freeze_with(client) - .sign(account_private_key) # Sign with the account private key + .sign(account_private_key) # Sign with the account private key .execute(client) ) - + # Check if nft creation was successful if receipt.status != ResponseCode.SUCCESS: print(f"NFT creation failed with status: {ResponseCode(receipt.status).name}") sys.exit(1) - + # Get token ID from receipt nft_token_id = receipt.token_id print(f"\nNFT created with ID: {nft_token_id}") - + return nft_token_id + def mint_nft(client, nft_token_id, account_private_key): """Mint a non-fungible token""" receipt = ( @@ -131,18 +141,19 @@ def mint_nft(client, nft_token_id, account_private_key): .set_token_id(nft_token_id) .set_metadata(b"My NFT Metadata 1") .freeze_with(client) - .sign(account_private_key) # Sign with the account private key + .sign(account_private_key) # Sign with the account private key .execute(client) ) - + if receipt.status != ResponseCode.SUCCESS: print(f"NFT minting failed with status: {ResponseCode(receipt.status).name}") sys.exit(1) - + print(f"\nNFT minted with serial number: {receipt.serial_numbers[0]}") - + return NftId(nft_token_id, receipt.serial_numbers[0]) + def associate_token_with_account(client, token_id, account_id, account_key): """Associate the token with the test account""" receipt = ( @@ -153,13 +164,16 @@ def associate_token_with_account(client, token_id, account_id, account_key): .sign(account_key) .execute(client) ) - + if receipt.status != ResponseCode.SUCCESS: - print(f"Token association failed with status: {ResponseCode(receipt.status).name}") + print( + f"Token association failed with status: {ResponseCode(receipt.status).name}" + ) sys.exit(1) - + print(f"Token {token_id} associated with account {account_id}") + def grant_kyc_for_token(client, account_id, token_id): """Grant KYC for the token to the account""" receipt = ( @@ -168,13 +182,14 @@ def grant_kyc_for_token(client, account_id, token_id): .set_token_id(token_id) .execute(client) ) - + if receipt.status != ResponseCode.SUCCESS: print(f"KYC grant failed with status: {ResponseCode(receipt.status).name}") sys.exit(1) - + print(f"\nKYC granted for token_id: {token_id}") + def display_account_info(info): """Display basic account information""" print(f"\nAccount ID: {info.account_id}") @@ -184,17 +199,20 @@ def display_account_info(info): print(f"Is Deleted: {info.is_deleted}") print(f"Receiver Signature Required: {info.receiver_signature_required}") print(f"Owned NFTs: {info.owned_nfts}") - + print(f"Public Key: {info.key.to_string()}") - + print(f"Expiration Time: {info.expiration_time}") print(f"Auto Renew Period: {info.auto_renew_period}") - + print(f"Proxy Received: {info.proxy_received}") + def display_token_relationships(info): """Display token relationships information""" - print(f"\nToken Relationships ({len(info.token_relationships)} total) for account {info.account_id}:") + print( + f"\nToken Relationships ({len(info.token_relationships)} total) for account {info.account_id}:" + ) if info.token_relationships: for i, relationship in enumerate(info.token_relationships, 1): print(f" Token {i}:") @@ -208,6 +226,7 @@ def display_token_relationships(info): else: print(" No token relationships found") + def query_account_info(): """ Demonstrates the account info query functionality by: @@ -222,41 +241,41 @@ def query_account_info(): 9. Querying final account info to see complete token relationships and NFT ownership """ client, operator_id, operator_key = setup_client() - + # Create a new account account_id, account_private_key = create_test_account(client, operator_key) - + # Query the account info and display account information info = AccountInfoQuery(account_id).execute(client) print("\nAccount info query completed successfully!") display_account_info(info) - + # Create a fungible token token_id = create_fungible_token(client, operator_id, operator_key) - + # Associate the token with the account associate_token_with_account(client, token_id, account_id, account_private_key) - + # Query the account info and display token relationships info = AccountInfoQuery(account_id).execute(client) print("\nToken info query completed successfully!") display_token_relationships(info) - + # Grant KYC for the token print(f"\nGrant KYC for token: {token_id}") grant_kyc_for_token(client, account_id, token_id) - + # Query the account info again and see the kyc status has been updated to GRANTED info = AccountInfoQuery(account_id).execute(client) print("\nAccount info query completed successfully!") display_token_relationships(info) - + # Create an NFT token with the new account as the owner nft_token_id = create_nft(client, account_id, account_private_key) - + # Mint an NFT to the account mint_nft(client, nft_token_id, account_private_key) - + # Query the account info again and see that the account has 1 owned NFT # and the token relationship has been updated to include the NFT # NOTE: the newest token is the first in the list @@ -264,5 +283,6 @@ def query_account_info(): display_account_info(info) display_token_relationships(info) + if __name__ == "__main__": - query_account_info() \ No newline at end of file + query_account_info() diff --git a/examples/query/payment_query.py b/examples/query/payment_query.py index 5b8d9eb66..4a9f3c7ab 100644 --- a/examples/query/payment_query.py +++ b/examples/query/payment_query.py @@ -3,6 +3,7 @@ python examples/query/payment_query.py """ + import os import sys from dotenv import load_dotenv @@ -23,7 +24,8 @@ load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + def setup_client(): """Initialize and set up the client with operator account""" @@ -31,16 +33,17 @@ def setup_client(): print(f"Connecting to Hedera {network_name} network!") client = Client(network) - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) client.set_operator(operator_id, operator_key) print(f"Client set up with operator id {client.operator_account_id}") return client, operator_id, operator_key + def create_fungible_token(client, operator_id, operator_key): """Create a fungible token""" - + receipt = ( TokenCreateTransaction() .set_token_name("MyExampleFT") @@ -55,41 +58,44 @@ def create_fungible_token(client, operator_id, operator_key): .set_supply_key(operator_key) .execute(client) ) - + if receipt.status != ResponseCode.SUCCESS: - print(f"Fungible token creation failed with status: {ResponseCode.get_name(receipt.status)}") + print( + f"Fungible token creation failed with status: {ResponseCode.get_name(receipt.status)}" + ) sys.exit(1) - + token_id = receipt.token_id print(f"Fungible token created with ID: {token_id}") - + return token_id + def demonstrate_zero_cost_balance_query(client, account_id): """ Demonstrate cost calculation for queries that don't require payment. - + CryptoGetAccountBalanceQuery is an example of a query that doesn't require payment. For such queries: - get_cost() returns 0 Hbar when no payment is set - get_cost() returns the set payment amount when payment is set """ print("\nQueries that DON'T require payment:\n") - + # Case 1: No payment set - should return 0 Hbar cost print("When no payment is set:") query_no_payment = CryptoGetAccountBalanceQuery().set_account_id(account_id) - + cost_no_payment = query_no_payment.get_cost(client) print(f"Cost: {cost_no_payment} Hbar") print("Expected: 0 Hbar (payment not required)") - + # Execute the query (should work without payment) print("\nExecuting query without payment...") result = query_no_payment.execute(client) print(f"Query executed successfully!") print(f" Account balance (only hbars): {result.hbars}") - + # Case 2: Payment set - should return the set payment amount print("\nWhen custom payment is set:") custom_payment = Hbar(2) @@ -98,67 +104,67 @@ def demonstrate_zero_cost_balance_query(client, account_id): .set_account_id(account_id) .set_query_payment(custom_payment) ) - + cost_with_payment = query_with_payment.get_cost(client) print(f"Cost: {cost_with_payment} Hbar") print(f"Expected: {custom_payment} Hbar") - + # 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(f" Account balance (only hbars): {result.hbars}") + def demonstrate_payment_required_queries(client, token_id): """ Demonstrate cost calculation for queries that require payment. - + TokenInfoQuery is an example of a query that requires payment. For such queries: - get_cost() asks the network for the actual cost when no payment is set - get_cost() returns the set payment amount when payment is set """ print("\nQueries that DO require payment:\n") - + # Case 1: No payment set - should ask network for cost print("When no payment is set:") query_no_payment = TokenInfoQuery().set_token_id(token_id) - + print("Asking network for query cost...") cost_from_network = query_no_payment.get_cost(client) print(f"Cost: {cost_from_network} Hbar") print("This is the actual cost calculated by the network") - + # 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(f" Token info: {result}") - + # Case 2: Payment set - should return the set payment amount print("\nWhen custom payment is set:") custom_payment = Hbar(2) query_with_payment = ( - TokenInfoQuery() - .set_token_id(token_id) - .set_query_payment(custom_payment) + TokenInfoQuery().set_token_id(token_id).set_query_payment(custom_payment) ) - + cost_with_payment = query_with_payment.get_cost(client) print(f"Cost: {cost_with_payment} Hbar") print(f"Expected: {custom_payment} Hbar") - + # 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(f" Token info: {result}") - + # Case 3: Compare network cost vs custom payment print("\nCost comparison:") print(f"Network-determined cost: {cost_from_network} Hbar") print(f"Custom payment: {custom_payment} Hbar") + def query_payment(): """ Demonstrates the query payment by: @@ -170,9 +176,10 @@ def query_payment(): """ client, operator_id, operator_key = setup_client() token_id = create_fungible_token(client, operator_id, operator_key) - + demonstrate_zero_cost_balance_query(client, operator_id) demonstrate_payment_required_queries(client, token_id) + if __name__ == "__main__": query_payment() diff --git a/examples/query/token_info_query_fungible.py b/examples/query/token_info_query_fungible.py index dd640893c..aee3b615f 100644 --- a/examples/query/token_info_query_fungible.py +++ b/examples/query/token_info_query_fungible.py @@ -22,7 +22,8 @@ load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + def setup_client(): """Initialize and set up the client with operator account""" @@ -30,13 +31,14 @@ def setup_client(): print(f"Connecting to Hedera {network_name} network!") client = Client(network) - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) client.set_operator(operator_id, operator_key) print(f"Client set up with operator id {client.operator_account_id}") return client, operator_id, operator_key + def create_fungible_token(client, operator_id, operator_key): """Create a fungible token""" receipt = ( @@ -54,18 +56,21 @@ def create_fungible_token(client, operator_id, operator_key): .set_freeze_key(operator_key) .execute(client) ) - + # Check if token creation was successful if receipt.status != ResponseCode.SUCCESS: - print(f"Fungible token creation failed with status: {ResponseCode(receipt.status).name}") + print( + f"Fungible token creation failed with status: {ResponseCode(receipt.status).name}" + ) sys.exit(1) - + # Get token ID from receipt token_id = receipt.token_id print(f"Fungible token created with ID: {token_id}") - + return token_id + def query_token_info(): """ Demonstrates the token info query functionality by: @@ -75,9 +80,10 @@ def query_token_info(): """ client, operator_id, operator_key = setup_client() token_id = create_fungible_token(client, operator_id, operator_key) - + info = TokenInfoQuery().set_token_id(token_id).execute(client) print(f"Fungible token info: {info}") + if __name__ == "__main__": query_token_info() diff --git a/examples/query/token_info_query_nft.py b/examples/query/token_info_query_nft.py index c0eac6596..694ce386b 100644 --- a/examples/query/token_info_query_nft.py +++ b/examples/query/token_info_query_nft.py @@ -3,6 +3,7 @@ python examples/token_info_query_nft.py """ + import os import sys @@ -22,7 +23,8 @@ load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + def setup_client(): """Initialize and set up the client with operator account""" @@ -30,13 +32,14 @@ def setup_client(): print(f"Connecting to Hedera {network_name} network!") client = Client(network) - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) client.set_operator(operator_id, operator_key) print(f"Client set up with operator id {client.operator_account_id}") return client, operator_id, operator_key + def create_nft(client, operator_id, operator_key): """Create a non-fungible token""" receipt = ( @@ -54,18 +57,19 @@ def create_nft(client, operator_id, operator_key): .set_freeze_key(operator_key) .execute(client) ) - + # Check if nft creation was successful if receipt.status != ResponseCode.SUCCESS: print(f"NFT creation failed with status: {ResponseCode(receipt.status).name}") sys.exit(1) - + # Get token ID from receipt nft_token_id = receipt.token_id print(f"NFT created with ID: {nft_token_id}") - + return nft_token_id + def query_token_info(): """ Demonstrates the token info query functionality by: @@ -75,9 +79,10 @@ def query_token_info(): """ client, operator_id, operator_key = setup_client() token_id = create_nft(client, operator_id, operator_key) - + info = TokenInfoQuery().set_token_id(token_id).execute(client) print(f"Non-fungible token info: {info}") + if __name__ == "__main__": query_token_info() diff --git a/examples/query/token_nft_info_query.py b/examples/query/token_nft_info_query.py index 160194266..b95ad6d1a 100644 --- a/examples/query/token_nft_info_query.py +++ b/examples/query/token_nft_info_query.py @@ -3,6 +3,7 @@ python examples/query/token_nft_info_query.py """ + import os import sys from dotenv import load_dotenv @@ -23,7 +24,8 @@ load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + def setup_client(): """Initialize and set up the client with operator account""" @@ -32,13 +34,14 @@ def setup_client(): client = Client(network) # Set up operator account - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) client.set_operator(operator_id, operator_key) print(f"Client set up with operator id {client.operator_account_id}") return client, operator_id, operator_key + def create_nft(client, operator_id, operator_key): """Create a non-fungible token""" receipt = ( @@ -56,18 +59,19 @@ def create_nft(client, operator_id, operator_key): .set_freeze_key(operator_key) .execute(client) ) - + # Check if nft creation was successful if receipt.status != ResponseCode.SUCCESS: print(f"NFT creation failed with status: {ResponseCode(receipt.status).name}") sys.exit(1) - + # Get token ID from receipt nft_token_id = receipt.token_id print(f"NFT created with ID: {nft_token_id}") - + return nft_token_id + def mint_nft(client, nft_token_id): """Mint a non-fungible token""" receipt = ( @@ -76,15 +80,16 @@ def mint_nft(client, nft_token_id): .set_metadata(b"My NFT Metadata 1") .execute(client) ) - + if receipt.status != ResponseCode.SUCCESS: print(f"NFT minting failed with status: {ResponseCode(receipt.status).name}") sys.exit(1) - + print(f"NFT minted with serial number: {receipt.serial_numbers[0]}") - + return NftId(nft_token_id, receipt.serial_numbers[0]) + def query_nft_info(): """ Demonstrates the nft info query functionality by: @@ -95,9 +100,10 @@ def query_nft_info(): client, operator_id, operator_key = setup_client() token_id = create_nft(client, operator_id, operator_key) nft_id = mint_nft(client, token_id) - + info = TokenNftInfoQuery(nft_id=nft_id).execute(client) print(f"NFT info: {info}") + if __name__ == "__main__": query_nft_info() diff --git a/examples/query/topic_info_query.py b/examples/query/topic_info_query.py index 827d58128..71471246b 100644 --- a/examples/query/topic_info_query.py +++ b/examples/query/topic_info_query.py @@ -3,6 +3,7 @@ python examples/query/topic_info_query.py """ + import os import sys from dotenv import load_dotenv @@ -13,11 +14,12 @@ AccountId, PrivateKey, TopicInfoQuery, - TopicCreateTransaction + TopicCreateTransaction, ) load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + def setup_client(): """Initialize and set up the client with operator account""" @@ -26,24 +28,24 @@ def setup_client(): client = Client(network) try: - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) - client.set_operator(operator_id, operator_key) - print(f"Client set up with operator id {client.operator_account_id}") + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) + client.set_operator(operator_id, operator_key) + print(f"Client set up with operator id {client.operator_account_id}") - return client, operator_id, operator_key + return client, operator_id, operator_key except (TypeError, ValueError): print("❌ Error: Creating client, Please check your .env file") sys.exit(1) + def create_topic(client, operator_key): """Create a new topic""" print("\nSTEP 1: Creating a Topic...") try: topic_tx = ( TopicCreateTransaction( - memo="Python SDK created topic", - admin_key=operator_key.public_key() + memo="Python SDK created topic", admin_key=operator_key.public_key() ) .freeze_with(client) .sign(operator_key) @@ -57,13 +59,14 @@ def create_topic(client, operator_key): print(f"❌ Error: Creating topic: {e}") sys.exit(1) + def query_topic_info(): """ A full example that create a topic and query topic info for that topic. """ # Config Client client, _, operator_key = setup_client() - + # Create a new Topic topic_id = create_topic(client, operator_key) @@ -73,5 +76,6 @@ def query_topic_info(): topic_info = query.execute(client) print("✅ Success! Topic Info:", topic_info) + if __name__ == "__main__": query_topic_info() diff --git a/examples/query/topic_message_query.py b/examples/query/topic_message_query.py index 0341667c7..7ca6b382a 100644 --- a/examples/query/topic_message_query.py +++ b/examples/query/topic_message_query.py @@ -1,8 +1,9 @@ """ -uv run examples/query/topic_message_query.py -python examples/query/topic_message_query.py +uv run examples/query/topic_message_query.py +python examples/query/topic_message_query.py """ + import os import time import sys @@ -15,11 +16,13 @@ AccountId, PrivateKey, TopicCreateTransaction, - TopicMessageQuery + TopicMessageQuery, ) load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + + def setup_client(): """Initialize and set up the client with operator account""" network = Network(network_name) @@ -28,8 +31,8 @@ def setup_client(): client = Client(network) try: - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) client.set_operator(operator_id, operator_key) print(f"Client set up with operator id {client.operator_account_id}") @@ -38,14 +41,14 @@ def setup_client(): print("❌ Error: Creating client, Please check your .env file") sys.exit(1) + def create_topic(client, operator_key): """Create a new topic""" print("\nSTEP 1: Creating a Topic...") try: topic_tx = ( TopicCreateTransaction( - memo="Python SDK created topic", - admin_key=operator_key.public_key() + memo="Python SDK created topic", admin_key=operator_key.public_key() ) .freeze_with(client) .sign(operator_key) @@ -59,18 +62,20 @@ def create_topic(client, operator_key): print(f"❌ Error: Creating topic: {e}") sys.exit(1) + def query_topic_messages(): """ A full example that creates a topic and perform query topic messages. """ # Config Client client, _, operator_key = setup_client() - + # Create Topic topic_id = create_topic(client, operator_key) # Query Topic Messages print("\nSTEP 2: Query Topic Messages...") + def on_message_handler(topic_message): print(f"Received topic message: {topic_message}") @@ -81,25 +86,24 @@ def on_error_handler(e): topic_id=topic_id, start_time=datetime.now(timezone.utc), limit=0, - chunking_enabled=True + chunking_enabled=True, ) handle = query.subscribe( - client, - on_message=on_message_handler, - on_error=on_error_handler + client, on_message=on_message_handler, on_error=on_error_handler ) print("Subscription started. Will auto-cancel after 10 seconds or on Ctrl+C...") try: - startTime = time.time(); + startTime = time.time() while time.time() - startTime < 10: - time.sleep(1); + time.sleep(1) except KeyboardInterrupt: print("✋ Ctrl+C detected. Cancelling subscription...") finally: handle.cancel() print("✅ Subscription cancelled. Exiting.") + if __name__ == "__main__": query_topic_messages() diff --git a/examples/query/transaction_get_receipt_query.py b/examples/query/transaction_get_receipt_query.py index 74b5f5fee..ea6187e79 100644 --- a/examples/query/transaction_get_receipt_query.py +++ b/examples/query/transaction_get_receipt_query.py @@ -3,6 +3,7 @@ python examples/query/transaction_get_receipt_query.py """ + import os import sys from dotenv import load_dotenv @@ -16,11 +17,12 @@ Hbar, TransactionGetReceiptQuery, ResponseCode, - AccountCreateTransaction + AccountCreateTransaction, ) load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + def setup_client(): """Initialize and set up the client with operator account""" @@ -29,8 +31,8 @@ def setup_client(): client = Client(network) try: - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) client.set_operator(operator_id, operator_key) print(f"Client set up with operator id {client.operator_account_id}") @@ -54,11 +56,12 @@ def create_account(client, operator_key): recipient_id = receipt.account_id print(f"✅ Success! Created a new recipient account with ID: {recipient_id}") return recipient_id, recipient_key - + except Exception as e: print(f"Error creating new account: {e}") sys.exit(1) + def query_receipt(): """ A full example that include account creation, Hbar transfer, and receipt querying @@ -83,13 +86,18 @@ def query_receipt(): receipt = transaction.execute(client) transaction_id = transaction.transaction_id print(f"Transaction ID: {transaction_id}") - print(f"✅ Success! Transfer transaction status: {ResponseCode(receipt.status).name}") + print( + f"✅ Success! Transfer transaction status: {ResponseCode(receipt.status).name}" + ) # Query Transaction Receipt print("\nSTEP 3: Querying transaction receipt...") receipt_query = TransactionGetReceiptQuery().set_transaction_id(transaction_id) queried_receipt = receipt_query.execute(client) - print(f"✅ Success! Queried transaction status: {ResponseCode(queried_receipt.status).name}") + print( + f"✅ Success! Queried transaction status: {ResponseCode(queried_receipt.status).name}" + ) + if __name__ == "__main__": query_receipt() diff --git a/examples/query/transaction_record_query.py b/examples/query/transaction_record_query.py index 0d8e3b2d8..cb7cde2ef 100644 --- a/examples/query/transaction_record_query.py +++ b/examples/query/transaction_record_query.py @@ -3,6 +3,7 @@ python examples/query/transaction_record_query.py """ + import os import sys from dotenv import load_dotenv @@ -18,14 +19,17 @@ from hiero_sdk_python.query.transaction_record_query import TransactionRecordQuery 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_associate_transaction import ( + TokenAssociateTransaction, +) from hiero_sdk_python.tokens.token_create_transaction import TokenCreateTransaction from hiero_sdk_python.tokens.token_type import TokenType from hiero_sdk_python.transaction.transfer_transaction import TransferTransaction load_dotenv() -network_name = os.getenv('NETWORK', 'testnet').lower() +network_name = os.getenv("NETWORK", "testnet").lower() + def setup_client(): """Initialize and set up the client with operator account""" @@ -34,18 +38,19 @@ def setup_client(): client = Client(network) # Set up operator account - operator_id = AccountId.from_string(os.getenv('OPERATOR_ID', '')) - operator_key = PrivateKey.from_string(os.getenv('OPERATOR_KEY', '')) + operator_id = AccountId.from_string(os.getenv("OPERATOR_ID", "")) + operator_key = PrivateKey.from_string(os.getenv("OPERATOR_KEY", "")) client.set_operator(operator_id, operator_key) print(f"Client set up with operator id {client.operator_account_id}") return client, operator_id, operator_key + def create_account_transaction(client): """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() - + # Create the account receipt = ( AccountCreateTransaction() @@ -53,21 +58,24 @@ def create_account_transaction(client): .set_initial_balance(Hbar(1)) .execute(client) ) - + # Check if account creation was successful if receipt.status != ResponseCode.SUCCESS: - print(f"Account creation failed with status: {ResponseCode(receipt.status).name}") + print( + f"Account creation failed with status: {ResponseCode(receipt.status).name}" + ) sys.exit(1) - + # Get the new account ID and transaction ID from receipt new_account_id = receipt.account_id transaction_id = receipt.transaction_id - + print(f"Account created with ID: {new_account_id}") - + return new_account_id, new_account_key, transaction_id -def create_fungible_token(client: 'Client', account_id, account_private_key): + +def create_fungible_token(client: "Client", account_id, account_private_key): """Create a fungible token""" receipt = ( TokenCreateTransaction() @@ -83,16 +91,19 @@ def create_fungible_token(client: 'Client', account_id, account_private_key): .set_supply_key(account_private_key) .execute(client) ) - + if receipt.status != ResponseCode.SUCCESS: - print(f"Fungible token creation failed with status: {ResponseCode(receipt.status).name}") + print( + f"Fungible token creation failed with status: {ResponseCode(receipt.status).name}" + ) sys.exit(1) - + token_id = receipt.token_id print(f"\nFungible token created with ID: {token_id}") - + return token_id + def associate_token(client, token_id, receiver_id, receiver_private_key): """Associate token with an account""" # Associate the token_id with the new account @@ -101,17 +112,22 @@ def associate_token(client, token_id, receiver_id, receiver_private_key): .set_account_id(receiver_id) .add_token_id(token_id) .freeze_with(client) - .sign(receiver_private_key) # Has to be signed here by receiver's key + .sign(receiver_private_key) # Has to be signed here by receiver's key .execute(client) ) - + if receipt.status != ResponseCode.SUCCESS: - print(f"Token association failed with status: {ResponseCode(receipt.status).name}") + print( + f"Token association failed with status: {ResponseCode(receipt.status).name}" + ) sys.exit(1) - + print(f"Token successfully associated with account: {receiver_id}") -def transfer_tokens(client, treasury_id, treasury_private_key, receiver_id, token_id, amount=10): + +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 receipt = ( @@ -122,16 +138,17 @@ def transfer_tokens(client, treasury_id, treasury_private_key, receiver_id, toke .sign(treasury_private_key) .execute(client) ) - + # Check if transfer was successful if receipt.status != ResponseCode.SUCCESS: print(f"Transfer failed with status: {ResponseCode(receipt.status).name}") sys.exit(1) - + print(f"Successfully transferred {amount} tokens to receiver account {receiver_id}") - + return receipt + def print_transaction_record(record): """Print the transaction record""" print(f"Transaction ID: {record.transaction_id}") @@ -139,11 +156,12 @@ def print_transaction_record(record): 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:") for account_id, amount in record.transfers.items(): print(f" Account: {account_id}, Amount: {amount}") + def query_record(): """ Demonstrates the transaction record query functionality by performing the following steps: @@ -154,22 +172,20 @@ def query_record(): 5. Querying and displaying the transaction record for token transfer """ client, operator_id, operator_key = setup_client() - + # Create a transaction to get a transaction ID new_account_id, new_account_key, transaction_id = create_account_transaction(client) - - record = ( - TransactionRecordQuery() - .set_transaction_id(transaction_id) - .execute(client) - ) + + record = TransactionRecordQuery().set_transaction_id(transaction_id).execute(client) print("Transaction record for account creation:") print_transaction_record(record) - + token_id = create_fungible_token(client, operator_id, operator_key) associate_token(client, token_id, new_account_id, new_account_key) - transfer_receipt = transfer_tokens(client, operator_id, operator_key, new_account_id, token_id) - + transfer_receipt = transfer_tokens( + client, operator_id, operator_key, new_account_id, token_id + ) + transfer_record = ( TransactionRecordQuery() .set_transaction_id(transfer_receipt.transaction_id) @@ -177,12 +193,13 @@ def query_record(): ) print("Transaction record for token transfer:") print_transaction_record(transfer_record) - + print(f"\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(): print(f" Account: {account_id}, Amount: {amount}") + if __name__ == "__main__": query_record()