Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand All @@ -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)

Expand Down
27 changes: 16 additions & 11 deletions examples/query/account_balance_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
python examples/query/account_balance_query.py

"""

import os
import sys
import time
Expand All @@ -30,7 +31,8 @@
)

load_dotenv()
network_name = os.getenv('NETWORK', 'testnet').lower()
network_name = os.getenv("NETWORK", "testnet").lower()


def setup_client():
"""
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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 = (
Expand Down Expand Up @@ -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)
Expand All @@ -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")

Expand Down
58 changes: 33 additions & 25 deletions examples/query/account_balance_query_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,27 +19,27 @@
TokenInfoQuery,
TokenType,
TokenMintTransaction,

)
from hiero_sdk_python.query.account_balance_query import CryptoGetAccountBalanceQuery
from hiero_sdk_python.tokens.token_id import TokenId


# 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}")
Expand All @@ -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)
Expand All @@ -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"]
Expand All @@ -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")
Expand All @@ -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} "
Expand All @@ -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
Expand All @@ -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()
Loading