Skip to content

Commit 366c783

Browse files
authored
fix: example scripts and README update (#154)
* fixed example scripts and readme Signed-off-by: nadinedelia <nadine.loepfe@swirldslabs.com> * added commas Signed-off-by: nadinedelia <nadine.loepfe@swirldslabs.com> --------- Signed-off-by: nadinedelia <nadine.loepfe@swirldslabs.com>
1 parent d215878 commit 366c783

14 files changed

+753
-465
lines changed

CHANGELOG.md

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,18 @@ All notable changes to this project will be documented in this file.
44
This project adheres to [Semantic Versioning](https://semver.org).
55
This changelog is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
66

7-
## [Unreleased]
7+
## [0.1.3]
8+
### Added
9+
- a lot of Transactions
10+
11+
### Changed
12+
- Example scripts updated
13+
- README updated
14+
15+
### Removed
16+
17+
18+
## [0.1.1]
819
### Added
920
- RELEASE.md
1021
- CONTRIBUTING.md

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ Other installation methods can be found [here](https://docs.astral.sh/uv/getting
5555
2. Clone this repository:
5656

5757
```bash
58-
git clone https://github.com/hiero-ledger/hiero_sdk_python.git
58+
git clone https://github.com/hiero-ledger/hiero-sdk-python.git
5959
cd hiero-sdk-python
6060
```
6161

@@ -95,8 +95,8 @@ Create a .env file in the root of your project with the following (replace with
9595

9696
```
9797
OPERATOR_ID=0.0.1234xx
98-
OPERATOR_KEY=302e020100300506032b657004220420...
99-
ADMIN_KEY=302a300506032b65700321009308ecfdf...
98+
OPERATOR_KEY=af20e47d590300506032b657004220420...
99+
ADMIN_KEY=af20e47d59032b65700321009308ecfdf...
100100
SUPPLY_KEY =302a300506032b6570032100c5e4af5..."
101101
FREEZE_KEY=302a300306072b65700321009308ecfdf...
102102
RECIPIENT_ID=0.0.789xx

examples/token_associate.py

Lines changed: 75 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,36 +7,92 @@
77
AccountId,
88
PrivateKey,
99
Network,
10-
TokenId,
10+
Hbar,
11+
AccountCreateTransaction,
12+
TokenCreateTransaction,
1113
TokenAssociateTransaction,
1214
)
1315

16+
# Load environment variables from .env file
1417
load_dotenv()
1518

16-
def associate_token():
17-
network = Network(network='testnet')
18-
client = Client(network)
1919

20-
recipient_id = AccountId.from_string(os.getenv('OPERATOR_ID'))
21-
recipient_key = PrivateKey.from_string_ed25519(os.getenv('OPERATOR_KEY'))
22-
token_id = TokenId.from_string('TOKEN_ID') # Update as needed
20+
def create_and_associate_token():
21+
"""
22+
A full example that creates an account, creates a token,
23+
and associates the token with the new account.
24+
"""
25+
# 1. Setup Client
26+
# =================================================================
27+
print("Connecting to Hedera testnet...")
28+
client = Client(Network(network='testnet'))
2329

24-
client.set_operator(recipient_id, recipient_key)
30+
try:
31+
operator_id = AccountId.from_string(os.getenv('OPERATOR_ID'))
32+
operator_key = PrivateKey.from_string_ed25519(os.getenv('OPERATOR_KEY'))
33+
client.set_operator(operator_id, operator_key)
34+
except (TypeError, ValueError):
35+
print("❌ Error: Please check OPERATOR_ID and OPERATOR_KEY in your .env file.")
36+
sys.exit(1)
2537

26-
transaction = (
27-
TokenAssociateTransaction()
28-
.set_account_id(recipient_id)
29-
.add_token_id(token_id)
30-
.freeze_with(client)
31-
.sign(recipient_key)
32-
)
38+
print(f"Using operator account: {operator_id}")
39+
40+
# 2. Create a new account to associate the token with
41+
# =================================================================
42+
print("\nSTEP 1: Creating a new account...")
43+
recipient_key = PrivateKey.generate_ed25519()
44+
recipient_public_key = recipient_key.public_key()
3345

3446
try:
35-
receipt = transaction.execute(client)
36-
print("Token association successful.")
47+
tx = (
48+
AccountCreateTransaction()
49+
.set_key(recipient_public_key)
50+
.set_initial_balance(Hbar.from_tinybars(100_000_000)) # 1 Hbar
51+
)
52+
receipt = tx.execute(client)
53+
recipient_id = receipt.accountId
54+
print(f"✅ Success! Created new account with ID: {recipient_id}")
3755
except Exception as e:
38-
print(f"Token association failed: {str(e)}")
56+
print(f"❌ Error creating new account: {e}")
3957
sys.exit(1)
4058

59+
60+
# 3. Create a new token
61+
# =================================================================
62+
print("\nSTEP 2: Creating a new fungible token...")
63+
try:
64+
tx = (
65+
TokenCreateTransaction()
66+
.set_token_name("My Associable Token")
67+
.set_token_symbol("MAT")
68+
.set_initial_supply(1_000_000)
69+
.set_treasury_account_id(operator_id)
70+
)
71+
receipt = tx.execute(client)
72+
token_id = receipt.tokenId
73+
print(f"✅ Success! Created token with ID: {token_id}")
74+
except Exception as e:
75+
print(f"❌ Error creating token: {e}")
76+
sys.exit(1)
77+
78+
# 4. Associate the token with the new account
79+
# =================================================================
80+
print(f"\nSTEP 3: Associating token {token_id} with account {recipient_id}...")
81+
try:
82+
# Note: The operator pays for this transaction, but the recipient must sign it.
83+
tx = (
84+
TokenAssociateTransaction()
85+
.set_account_id(recipient_id)
86+
.add_token_id(token_id)
87+
.freeze_with(client) # Freeze against the client (operator)
88+
.sign(recipient_key) # The recipient *must* sign to approve the association
89+
)
90+
receipt = tx.execute(client)
91+
print(f"✅ Success! Token association complete.")
92+
except Exception as e:
93+
print(f"❌ Error associating token: {e}")
94+
sys.exit(1)
95+
96+
4197
if __name__ == "__main__":
42-
associate_token()
98+
create_and_associate_token()
Lines changed: 26 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,16 @@
11
"""
22
This is a simple example of how to create a finite fungible token using setting methods.
3-
43
It:
54
1. Loads environment variables.
65
2. Sets up a client and creates a token with the given parameters.
76
3. Executes the token creation and prints the result.
8-
97
Required environment variables:
108
- OPERATOR_ID, OPERATOR_KEY (mandatory)
119
- ADMIN_KEY, SUPPLY_KEY, FREEZE_KEY, PAUSE_KEY (optional)
12-
1310
Dependencies:
1411
- dotenv
1512
- hiero_sdk_python
1613
"""
17-
1814
# Adapt imports and paths as appropriate
1915
import os
2016
import sys
@@ -25,33 +21,34 @@
2521
PrivateKey,
2622
TokenCreateTransaction,
2723
Network,
28-
TokenType,
29-
SupplyType
30-
)
31-
24+
)
25+
from hiero_sdk_python.tokens.token_type import TokenType
26+
from hiero_sdk_python.tokens.supply_type import SupplyType
3227
# Load environment variables from .env file
3328
load_dotenv()
34-
3529
def create_token_fungible_finite():
3630
"""Function to create a finite fungible token."""
37-
3831
# Network Setup
3932
network = Network(network='testnet')
4033
client = Client(network)
4134

42-
# Operator credentials (must be present)
4335
operator_id = AccountId.from_string(os.getenv('OPERATOR_ID'))
4436
operator_key = PrivateKey.from_string_ed25519(os.getenv('OPERATOR_KEY'))
4537

46-
# Optional Token Keys
47-
admin_key = PrivateKey.from_string_ed25519(os.getenv('ADMIN_KEY'))# Optional
48-
supply_key = PrivateKey.from_string_ed25519(os.getenv('SUPPLY_KEY'))# Optional
49-
freeze_key = PrivateKey.from_string_ed25519(os.getenv('FREEZE_KEY'))# Optional
50-
pause_key = PrivateKey.from_string_ed25519(os.getenv('PAUSE_KEY'))# Optional
51-
38+
def parse_optional_key(key_str):
39+
if not key_str or key_str.startswith('<') or key_str.endswith('>'):
40+
return None
41+
try:
42+
return PrivateKey.from_string_ed25519(key_str)
43+
except:
44+
return None
45+
46+
admin_key = parse_optional_key(os.getenv('ADMIN_KEY'))
47+
supply_key = parse_optional_key(os.getenv('SUPPLY_KEY'))
48+
freeze_key = parse_optional_key(os.getenv('FREEZE_KEY'))
49+
pause_key = parse_optional_key(os.getenv('PAUSE_KEY'))
5250
# Set the operator for the client
5351
client.set_operator(operator_id, operator_key)
54-
5552
# Create the token creation transaction
5653
# In this example, we set up a default empty token create transaction, then set the values
5754
transaction = (
@@ -64,34 +61,33 @@ def create_token_fungible_finite():
6461
.set_token_type(TokenType.FUNGIBLE_COMMON)
6562
.set_supply_type(SupplyType.FINITE)
6663
.set_max_supply(100)
67-
.set_admin_key(admin_key) # Optional
68-
.set_supply_key(supply_key) # Optional
69-
.set_freeze_key(freeze_key) # Optional
70-
.set_pause_key(pause_key) # Optional
7164
.freeze_with(client) # Freeze the transaction. Returns self so we can sign.
7265
)
73-
66+
67+
# Add optional keys only if they exist
68+
if admin_key:
69+
transaction.set_admin_key(admin_key)
70+
if supply_key:
71+
transaction.set_supply_key(supply_key)
72+
if freeze_key:
73+
transaction.set_freeze_key(freeze_key)
74+
if pause_key:
75+
transaction.set_pause_key(pause_key)
7476
# Required signature by treasury (operator)
7577
transaction.sign(operator_key)
76-
7778
# Sign with adminKey if provided
7879
if admin_key:
7980
transaction.sign(admin_key)
80-
8181
try:
82-
8382
# Execute the transaction and get the receipt
8483
receipt = transaction.execute(client)
85-
8684
if receipt and receipt.tokenId:
8785
print(f"Finite fungible token created with ID: {receipt.tokenId}")
8886
else:
8987
print("Finite fungible token creation failed: Token ID not returned in receipt.")
9088
sys.exit(1)
91-
9289
except Exception as e:
9390
print(f"Token creation failed: {str(e)}")
9491
sys.exit(1)
95-
9692
if __name__ == "__main__":
97-
create_token_fungible_finite()
93+
create_token_fungible_finite()

0 commit comments

Comments
 (0)