Wallet operations¶
Complete examples for wallet management, security, and transaction signing using the Akash Python SDK.
Overview¶
The AkashWallet class provides complete wallet functionality for the Akash Network, including secure key management, transaction signing, and address derivation.
API reference
See Wallet API for complete method documentation and advanced wallet features
Wallet creation¶
Generate new wallet¶
from akash import AkashWallet
def create_new_wallet():
"""Generate a new wallet with random entropy"""
wallet = AkashWallet.generate()
print(f"Address: {wallet.address}")
print(f"Mnemonic: {wallet.mnemonic}")
return wallet
new_wallet = create_new_wallet()
Generate with custom entropy¶
from akash import AkashWallet
import secrets
def create_wallet_with_entropy():
"""Generate wallet with custom entropy for advanced users"""
custom_entropy = secrets.randbits(128)
wallet = AkashWallet.generate(entropy=custom_entropy)
print(f"Generated with custom entropy: {wallet.address}")
return wallet
entropy_wallet = create_wallet_with_entropy()
Wallet import¶
Import from mnemonic¶
from akash import AkashWallet
def import_from_mnemonic():
"""Import existing wallet from mnemonic phrase"""
mnemonic = "poverty torch street hybrid estate message increase play negative vibrant transfer six police tiny garment congress survey tired used audit dolphin focus abstract appear"
wallet = AkashWallet.from_mnemonic(mnemonic)
print(f"Default path: {wallet.address}")
wallet2 = AkashWallet.from_mnemonic(mnemonic, derivation_path="m/44'/118'/0'/0/1")
print(f"Custom path: {wallet2.address}")
wallet3 = AkashWallet.from_mnemonic(mnemonic, derivation_path="m/44'/118'/1'/0/0")
print(f"Account 1: {wallet3.address}")
print(f"All addresses unique: {len({wallet.address, wallet2.address, wallet3.address}) == 3}")
return wallet
imported_wallet = import_from_mnemonic()
Import from private key¶
from akash import AkashWallet
def import_from_private_key():
"""Import wallet from raw private key"""
temp_wallet = AkashWallet.generate()
private_key_bytes = temp_wallet.private_key_bytes
print(f"Original address: {temp_wallet.address}")
restored_wallet = AkashWallet.from_private_key(private_key_bytes)
print(f"Restored address: {restored_wallet.address}")
print(f"Addresses match: {temp_wallet.address == restored_wallet.address}")
return restored_wallet
key_wallet = import_from_private_key()
Custom derivation paths¶
from akash import AkashWallet
def derivation_path_examples():
"""Demonstrate different derivation path patterns"""
mnemonic = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
print("derivation path examples:")
print("-" * 50)
paths = [
("m/44'/118'/0'/0/0", "Default Cosmos/Akash"),
("m/44'/118'/0'/0/1", "Same account, address 1"),
("m/44'/118'/0'/0/2", "Same account, address 2"),
("m/44'/118'/1'/0/0", "Account 1, first address"),
("m/44'/118'/2'/0/0", "Account 2, first address"),
("m/44'/60'/0'/0/0", "Coin type 60"),
("m/44'/0'/0'/0/0", "Coin type 0")
]
wallets = {}
for path, description in paths:
try:
wallet = AkashWallet.from_mnemonic(mnemonic, derivation_path=path)
wallets[path] = wallet
print(f"{path:20} {description:25} {wallet.address}")
except Exception as e:
print(f"{path:20} {description:25} ERROR: {e}")
addresses = [w.address for w in wallets.values()]
unique_addresses = len(set(addresses))
print(f"\nGenerated {len(addresses)} addresses, {unique_addresses} unique")
return wallets
derivation_wallets = derivation_path_examples()
Wallet properties¶
Basic wallet information¶
from akash import AkashWallet
def show_wallet_info():
"""Display comprehensive wallet information"""
wallet = AkashWallet.from_mnemonic(
"poverty torch street hybrid estate message increase play negative vibrant transfer six police tiny garment congress survey tired used audit dolphin focus abstract appear"
)
print("Wallet information:")
print("-" * 50)
print(f"Address: {wallet.address}")
print(f"Has mnemonic: {wallet.mnemonic is not None}")
print(f"Public key (hex): {wallet.public_key_bytes.hex()}")
print(f"Private key available: {hasattr(wallet, 'private_key_bytes')}")
print(f"\nAddress validation:")
print(f"Valid Akash address: {AkashWallet.validate_address(wallet.address)}")
print(f"Invalid address: {AkashWallet.validate_address('invalid_address')}")
return wallet
wallet_info = show_wallet_info()
Validate multiple addresses¶
from akash import AkashWallet
def validate_addresses():
"""Validate multiple address formats"""
test_addresses = [
"akash1qnnhhgzxj24f2kld5yhy4v4h4s9r295ak5gjw4",
"cosmos1qnnhhgzxj24f2kld5yhy4v4h4s9r295ak5gjw4",
"invalid_address",
"akash1invalid",
""
]
print("Address validation results:")
print("-" * 50)
for addr in test_addresses:
is_valid = AkashWallet.validate_address(addr)
status = "✓ Valid" if is_valid else "✗ Invalid"
display_addr = addr[:30] + "..." if len(addr) > 30 else addr
print(f"{display_addr:35} {status}")
validate_addresses()
Message signing¶
Sign and verify messages¶
from akash import AkashWallet
def message_signing_demo():
"""Demonstrate message signing and verification"""
wallet = AkashWallet.generate()
print("Message signing demo:")
print("-" * 50)
print(f"Wallet: {wallet.address}")
message = "Hello Akash Network!"
signature = wallet.sign_message(message)
print(f"Message: {message}")
print(f"Signature: {signature}")
is_valid = wallet.verify_signature(message, signature)
print(f"Signature valid: {is_valid}")
wrong_message = "Different message"
is_valid_wrong = wallet.verify_signature(wrong_message, signature)
print(f"Wrong message valid: {is_valid_wrong}")
return signature
signature = message_signing_demo()
Sign transaction data¶
from akash import AkashWallet
def transaction_signing_demo():
"""Demonstrate transaction signing"""
wallet = AkashWallet.generate()
tx_data = {
"chain_id": "akashnet-2",
"account_number": "12345",
"sequence": "1",
"fee": {"amount": "5000", "denom": "uakt"},
"memo": "Test transaction",
"msgs": [{
"type": "cosmos-sdk/MsgSend",
"value": {
"from_address": wallet.address,
"to_address": "akash1recipient...",
"amount": [{"denom": "uakt", "amount": "1000000"}]
}
}]
}
print("Transaction signing demo:")
print("-" * 50)
import json
tx_json = json.dumps(tx_data, sort_keys=True)
tx_signature = wallet.sign_message(tx_json)
print(f"Transaction signature: {tx_signature[:50]}...")
print("Transaction ready for broadcast")
return tx_signature
tx_sig = transaction_signing_demo()
Secure storage¶
Keystore encryption¶
from akash import AkashWallet
import getpass
import os
import tempfile
def keystore_demo():
"""Demonstrate secure keystore functionality"""
print("Keystore demo:")
print("-" * 50)
wallet = AkashWallet.generate()
print(f"Created wallet: {wallet.address}")
with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as tmp:
keystore_path = tmp.name
try:
password = "demo_password_123"
keystore_data = wallet.to_keystore(password)
with open(keystore_path, 'w') as f:
f.write(keystore_data)
print(f"Wallet encrypted and saved to keystore")
loaded_wallet = AkashWallet.from_keystore(keystore_path, password)
print(f"Wallet loaded from keystore: {loaded_wallet.address}")
addresses_match = wallet.address == loaded_wallet.address
print(f"Addresses match: {addresses_match}")
if addresses_match:
print("✓ Keystore encryption/decryption successful")
else:
print("✗ Keystore encryption/decryption failed")
except Exception as e:
print(f"Keystore error: {e}")
finally:
if os.path.exists(keystore_path):
os.remove(keystore_path)
print("Temporary keystore file cleaned up")
keystore_demo()
Environment variable storage¶
from akash import AkashWallet
import os
def env_storage_demo():
"""Demonstrate environment variable wallet storage"""
print("Environment storage demo:")
print("-" * 50)
wallet = AkashWallet.generate()
original_address = wallet.address
os.environ['WALLET_MNEMONIC'] = wallet.mnemonic
print("Mnemonic stored in environment variable")
stored_mnemonic = os.environ.get('WALLET_MNEMONIC')
if stored_mnemonic:
restored_wallet = AkashWallet.from_mnemonic(stored_mnemonic)
print(f"Original address: {original_address}")
print(f"Restored address: {restored_wallet.address}")
print(f"Match: {original_address == restored_wallet.address}")
if 'WALLET_MNEMONIC' in os.environ:
del os.environ['WALLET_MNEMONIC']
print("Environment variable cleaned up")
print("\nNote: Environment variables are not secure for production!")
print("Use keystore encryption for production applications.")
env_storage_demo()
Balance and account operations¶
Check wallet balance¶
from akash import AkashClient, AkashWallet
def check_wallet_balance():
"""Check wallet balance on Akash Network"""
wallet = AkashWallet.from_mnemonic(
"poverty torch street hybrid estate message increase play negative vibrant transfer six police tiny garment congress survey tired used audit dolphin focus abstract appear"
)
client = AkashClient("https://akash-rpc.polkachu.com:443")
print(f"Checking balance for: {wallet.address}")
print("-" * 50)
try:
balance = client.bank.get_balance(wallet.address, "uakt")
if balance:
balance_akt = client.bank.calculate_akt_amount(balance)
print(f"Balance: {balance_akt:.6f} AKT ({balance} uakt)")
else:
print("Balance: 0 AKT")
all_balances = client.bank.get_all_balances(wallet.address)
if all_balances:
print(f"\nAll balances:")
for denom, amount in all_balances.items():
print(f"{denom}: {amount}")
except Exception as e:
print(f"Error checking balance: {e}")
check_wallet_balance()
API reference
See Bank API for balance query methods and denomination handling
Get account information¶
from akash import AkashClient, AkashWallet
def get_account_info():
"""Get detailed account information"""
wallet = AkashWallet.from_mnemonic(
"poverty torch street hybrid estate message increase play negative vibrant transfer six police tiny garment congress survey tired used audit dolphin focus abstract appear"
)
client = AkashClient("https://akash-rpc.polkachu.com:443")
print(f"Account info for: {wallet.address}")
print("-" * 50)
try:
account_info = client.bank.get_account_info(wallet.address)
if account_info:
print(f"Account number: {account_info.get('account_number', 'N/A')}")
print(f"Sequence: {account_info.get('sequence', 'N/A')}")
print(f"Account type: {account_info.get('type', 'N/A')}")
delegations = client.staking.get_delegations(wallet.address)
print(f"Active delegations: {len(delegations) if delegations else 0}")
if delegations:
for delegation in delegations[:3]:
validator = delegation.get('delegation', {}).get('validator_address', 'N/A')
amount = delegation.get('balance', {}).get('amount', '0')
print(f"{validator[:20]}...: {amount} uakt")
except Exception as e:
print(f"Error getting account info: {e}")
get_account_info()
API reference
See Staking API for delegation queries and validator operations
Transaction broadcasting¶
Send tokens¶
from akash import AkashClient, AkashWallet
def send_tokens_example():
"""Example of sending tokens using wallet"""
wallet = AkashWallet.from_mnemonic(
"poverty torch street hybrid estate message increase play negative vibrant transfer six police tiny garment congress survey tired used audit dolphin focus abstract appear"
)
client = AkashClient("https://akash-rpc.polkachu.com:443")
print("Token transfer example:")
print("-" * 50)
print(f"From: {wallet.address}")
recipient = wallet.address
amount = "1000"
memo = "SDK test transfer"
print(f"To: {recipient}")
print(f"Amount: {amount} uakt")
print(f"Memo: {memo}")
try:
result = client.bank.send(
wallet=wallet,
to_address=recipient,
amount=amount,
denom="uakt",
memo=memo
)
if result.success:
print(f"✓ Transaction successful!")
print(f"tx hash: {result.tx_hash}")
print(f"Block height: {result.height if hasattr(result, 'height') else 'N/A'}")
else:
print(f"✗ Transaction failed:")
print(f"Error: {result.raw_log if hasattr(result, 'raw_log') else result}")
except Exception as e:
print(f"Error sending transaction: {e}")
# send_tokens_example()