### Deploy a Simple Smart Contract Source: https://github.com/andelf/tronpy/blob/master/docs/contract.md Deploy a contract by providing its bytecode and ABI. Ensure you have the necessary private key and client setup. The transaction is built, signed, and then broadcast. ```python from tronpy import Tron, Contract from tronpy.keys import PrivateKey client = Tron(network='nile') priv_key = PrivateKey(bytes.fromhex("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")) bytecode = "608060405234801561001057600080fd5b5060c78061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c806360fe47b11460375780636d4ce63c146062575b600080fd5b606060048036036020811015604b57600080fd5b8101908080359060200190929190505050607e565b005b60686088565b6040518082815260200191505060405180910390f35b8060008190555050565b6000805490509056fea2646970667358221220c8daade51f673e96205b4a991ab6b94af82edea0f4b57be087ab123f03fc40f264736f6c63430006000033" abi = [ { "inputs": [], "name": "get", "outputs": [{"internalType": "uint256", "name": "retVal", "type": "uint256"}], "stateMutability": "view", "type": "function", } ] cntr = Contract(name="SimpleStore", bytecode=bytecode, abi=abi) txn = ( client.trx.deploy_contract('TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu', cntr) .fee_limit(5_000_000) .build() .sign(priv_key) ) print(txn) result = txn.broadcast().wait() print(result) print('Created:', result['contract_address']) created_cntr = client.get_contract(result['contract_address']) ``` -------------------------------- ### Install TronPy with Mnemonic Support Source: https://github.com/andelf/tronpy/blob/master/docs/hdwallet.md Install the tronpy library with the necessary dependencies for mnemonic functionality. ```bash > pip3 install tronpy[mnemonic] ``` -------------------------------- ### Install TronPy Source: https://github.com/andelf/tronpy/blob/master/docs/quickstart.md Install TronPy using pip. Python 3.6+ is required. ```console pip3 install tronpy ``` -------------------------------- ### Create HD Wallet with AsyncTron Source: https://github.com/andelf/tronpy/blob/master/docs/hdwallet.md Asynchronously generate a new HD wallet, including its mnemonic code and address details, using the AsyncTron client. This example demonstrates setting a passphrase and the number of words for the mnemonic. ```python import asyncio from tronpy import AsyncTron async def create_hd_wallet(passphrase, num_of_words): async with AsyncTron(network='nile') as client: print(client) first_index_wallet_details, mnemonic_code = client.generate_address_with_mnemonic(passphrase=passphrase, num_words=num_of_words) print(mnemonic_code) # > 'abandon length scan lesson mammal elite noodle ...omitted...' print(first_index_wallet_details) # > {'base58check_address': 'TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3', 'hex_address': '41c71498123f6de4698410712e5f5c96ae42978776', 'private_key': '.................omitted.....................', 'public_key': '..................omitted.....................'} return passphrase, mnemonic_code, first_index_wallet_details['base58check_address'] ``` -------------------------------- ### Perform Async TRX Transfer Source: https://github.com/andelf/tronpy/blob/master/docs/async.md Demonstrates how to initiate and broadcast a TRX transfer using the AsyncTron client. Ensure you have the necessary private key and network configuration. The example shows building, signing, and broadcasting a transaction, then waiting for its confirmation. ```python import asyncio from tronpy import AsyncTron from tronpy.keys import PrivateKey # private key of TMisHYBVvFHwKXHPYTqo8DhrRPTbWeAM6z priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) async def transfer(): async with AsyncTron(network='nile') as client: print(client) txb = ( client.trx.transfer("TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000) .memo("test memo") .fee_limit(100_000_000) ) txn = await txb.build() print(txn) txn_ret = await txn.sign(priv_key).broadcast() print(txn_ret) # > {'result': True, 'txid': 'edc2a625752b9c71fdd0d68117802860c6adb1a45c19fd631a41757fa334d72b'} print(await txn_ret.wait()) # > {'id': 'edc2a625752b9c71fdd0d68117802860c6adb1a45c19fd631a41757fa334d72b', 'blockNumber': 10163821, # > 'blockTimeStamp': 1603368072000, 'contractResult': [''], 'receipt': {'net_usage': 283}} if __name__ == '__main__': asyncio.run(transfer()) ``` -------------------------------- ### Const Call Example (TRC20 BalanceOf) Source: https://github.com/andelf/tronpy/blob/master/docs/contract.md Demonstrates how to perform a constant call to a smart contract to retrieve the balance of a TRC20 token for a given address. This method is suitable for functions marked as 'pure' or 'view'. ```APIDOC ## Const Call Example (TRC20 BalanceOf) ### Description This example shows how to use a constant call to get the balance of a TRC20 token. Constant calls are used for contract functions that do not modify the blockchain state (marked as `pure` or `view`). ### Usage ```python from tronpy import Tron client = Tron(network='nile') cntr = client.get_contract("THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia") # Get the decimals of the token to correctly display the balance precision = cntr.functions.decimals() # Get the balance for a specific address balance = cntr.functions.balanceOf('TJRabPrwbZy45sbavfcjinPJC18kjpRTv8') / 10 ** precision print(f'Balance: {balance}') ``` ### Contract Functions (Example) ``` function allowance(address _owner, address _spender) view returns (uint256 remaining) function approve(address _spender, uint256 _amount) returns (bool success) function balanceOf(address _owner) view returns (uint256 balance) function decimals() view returns (uint8 ) function name() view returns (string ) function owner() view returns (address ) function symbol() view returns (string ) function totalSupply() view returns (uint256 theTotalSupply) function transfer(address _to, uint256 _amount) returns (bool success) function transferFrom(address _from, address _to, uint256 _amount) returns (bool success) ``` ``` -------------------------------- ### Trigger Call Example (TRC20 Transfer) Source: https://github.com/andelf/tronpy/blob/master/docs/contract.md Illustrates how to execute a trigger call to a smart contract to perform an action, such as transferring tokens. Trigger calls require signing and broadcasting a transaction. ```APIDOC ## Trigger Call Example (TRC20 Transfer) ### Description This example demonstrates how to perform a trigger call to transfer tokens using a smart contract. Trigger calls involve building, signing, and broadcasting a transaction. ### Method ```python contract.functions.transfer(address _to, uint256 _amount) ``` ### Usage ```python from tronpy import Tron from tronpy.keys import PrivateKey client = Tron(network='nile') contract = client.get_contract('THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia') # Assuming 'priv_key' is your private key object # priv_key = PrivateKey(bytes.fromhex('YOUR_PRIVATE_KEY_HEX')) txn = ( contract.functions.transfer('TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA', 1_000) .with_owner('TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu') # Address associated with the private key .fee_limit(5_000_000) .build() .sign(priv_key) ) # Broadcast the transaction response = txn.broadcast() print(response) # Wait for transaction confirmation and get the result result = txn.broadcast().result() print(f'Transaction Result: {result}') ``` ### Request Example ```json { "result": true, "txid": "63609d84524b754a97c111eec152700f273979bb00dad993d8dcce5848b4dd9a" } ``` ### Response Example (Success) ```json { "id": "63609d84524b754a97c111eec152700f273979bb00dad993d8dcce5848b4dd9a", "blockNumber": 6609475, "blockTimeStamp": 1592539509000, "contractResult": ["0000000000000000000000000000000000000000000000000000000000000001"], "contract_address": "THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia", "receipt": { "energy_usage": 13062, "energy_usage_total": 13062, "net_usage": 344, "result": "SUCCESS" }, "log": [ { "address": "THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia", "topics": [ "ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", "00000000000000000000000046a23e25df9a0f6c18729dda9ad1af3b6a131160", "000000000000000000000000d8dd39e2dea27a40001884901735e3940829bb44" ], "data": "00000000000000000000000000000000000000000000000000000000000003e8" } ] } ``` ``` -------------------------------- ### Smart Contract View/Pure Calls Source: https://context7.com/andelf/tronpy/llms.txt Query smart contract state without initiating a transaction. Results are automatically decoded. This example shows how to get a contract instance on the Nile testnet. ```python from tronpy import Tron from tronpy.exceptions import AddressNotFound client = Tron(network="nile") # TRC20 contract on Nile testnet cntr = client.get_contract("THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia") ``` -------------------------------- ### Asynchronous TRON Transaction with AsyncTron Source: https://github.com/andelf/tronpy/blob/master/README.md This example demonstrates how to perform a TRON transaction asynchronously using the `AsyncTron` client. It requires importing `asyncio` and `PrivateKey`. The client is managed using an `async with` statement. ```python import asyncio from tronpy import AsyncTron from tronpy.keys import PrivateKey # private key of TMisHYBVvFHwKXHPYTqo8DhrRPTbWeAM6z priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) async def transfer(): async with AsyncTron(network='nile') as client: print(client) txb = ( client.trx.transfer("TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000) .memo("test memo") .fee_limit(100_000_000) ) txn = await txb.build() print(txn) txn_ret = await txn.sign(priv_key).broadcast() print(txn_ret) # > {'result': True, 'txid': 'edc2a625752b9c71fdd0d68117802860c6adb1a45c19fd631a41757fa334d72b'} print(await txn_ret.wait()) # > {'id': 'edc2a625752b9c71fdd0d68117802860c6adb1a45c19fd631a41757fa334d72b', 'blockNumber': 10163821, 'blockTimeStamp': 1603368072000, 'contractResult': [''], 'receipt': {'net_usage': 283}} if __name__ == '__main__': asyncio.run(transfer()) ``` -------------------------------- ### Async Client Operations Source: https://context7.com/andelf/tronpy/llms.txt Examples of using the asynchronous client for common TRON operations like checking account balance, transferring TRX, and interacting with smart contracts. ```APIDOC ## Async Client Operations This section demonstrates how to use the `AsyncTron` client for asynchronous operations on the TRON network. ### Method `AsyncTron` client methods (e.g., `get_account_balance`, `trx.transfer`, `get_contract`) ### Parameters - **network** (string) - Required - The TRON network to connect to (e.g., "nile"). - **address** (string) - Required for `get_account_balance` - The TRON address to query. - **from_address** (string) - Required for `trx.transfer` - The sender's TRON address. - **to_address** (string) - Required for `trx.transfer` - The recipient's TRON address. - **amount** (integer) - Required for `trx.transfer` - The amount of TRX to transfer. - **memo** (string) - Optional for `trx.transfer` - A memo for the transaction. - **fee_limit** (integer) - Required for `trx.transfer` - The fee limit for the transaction. - **contract_address** (string) - Required for `get_contract` - The address of the smart contract. ### Request Example ```python import asyncio from tronpy import AsyncTron from tronpy.keys import PrivateKey priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) async def main(): async with AsyncTron(network="nile") as client: # Account balance balance = await client.get_account_balance("TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3") print(f"Balance: {balance} TRX") # Transfer TRX txb = ( client.trx.transfer( "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000_000, ) .memo("async transfer") .fee_limit(100_000_000) ) txn = await txb.build() ret = await txn.sign(priv_key).broadcast() print("txid:", ret.txid) receipt = await ret.wait() print("receipt:", receipt) # Smart contract const call contract = await client.get_contract("THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia") symbol = contract.functions.symbol() print("Symbol:", symbol) asyncio.run(main()) ``` ### Response - **balance** (integer) - The account balance in TRX. - **txid** (string) - The transaction ID. - **receipt** (object) - The transaction receipt. - **symbol** (string) - The smart contract symbol. ``` -------------------------------- ### Get Account Information Source: https://context7.com/andelf/tronpy/llms.txt Retrieve various account details like balance, bandwidth, and energy. Handles cases where an account might not be activated on-chain. ```python from tronpy import Tron from tronpy.exceptions import AddressNotFound # Assuming 'client' is an initialized Tron instance and 'addr' is a valid TRON address # Example for getting account info: try: account = client.get_account(addr) print(account.get("balance", 0)) # raw SUN balance except AddressNotFound: print("Account not yet activated on-chain") # Example for getting TRX balance in TRX (Decimal): balance = client.get_account_balance(addr) print(f"Balance: {balance} TRX") # Example for getting available bandwidth: bw = client.get_bandwidth(addr) print(f"Bandwidth: {bw}") # Example for getting available energy: energy = client.get_energy(addr) print(f"Energy: {energy}") # Example for getting resource details: resources = client.get_account_resource(addr) print(resources) ``` -------------------------------- ### TRX Transfer Source: https://context7.com/andelf/tronpy/llms.txt Guides on performing TRX transfers between addresses. It specifies that amounts should be in SUN (1 TRX = 1,000,000 SUN) and demonstrates the builder pattern for constructing, signing, and broadcasting transactions. ```APIDOC ## TRX Transfer Transfer TRX between addresses; amount is in SUN (1 TRX = 1,000,000 SUN). ```python from tronpy import Tron from tronpy.keys import PrivateKey client = Tron(network="nile") priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) txn = ( client.trx.transfer( "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", # from "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", # to 1_000_000, # 1 TRX in SUN ) .memo("payment for services") .build() .sign(priv_key) ) ret = txn.broadcast() print(ret.txid) # transaction hash receipt = ret.wait(timeout=30) # {'id': '...', 'blockNumber': 12345678, 'blockTimeStamp': ..., # 'contractResult': [''], 'receipt': {'net_usage': 283}} ``` ``` -------------------------------- ### Client Initialization Source: https://context7.com/andelf/tronpy/llms.txt Demonstrates how to create Tron and AsyncTron client instances connected to different TRON networks (mainnet, testnet, private nodes) and configure provider options. ```APIDOC ## Client Initialization Create a `Tron` (or `AsyncTron`) client connected to mainnet, a testnet, or a private node. ```python from tronpy import Tron from tronpy.providers import HTTPProvider # Mainnet (default) client = Tron() # Testnet: "nile", "shasta", or "tronex" client = Tron(network="nile") # Private node with custom timeout and fee limit client = Tron( HTTPProvider("http://127.0.0.1:8090", timeout=20.0), conf={"fee_limit": 10_000_000}, ) # Async client as context manager import asyncio from tronpy import AsyncTron async def main(): async with AsyncTron(network="nile") as client: block = await client.get_latest_block() print(block["blockID"]) asyncio.run(main()) ``` ``` -------------------------------- ### Get Latest Block Information Source: https://github.com/andelf/tronpy/blob/master/docs/quickstart.md Retrieve information about the latest block on the connected TRON network. ```python >>> client.get_block() {'blockID': '000000000064ac1f04aa38427cb78fb537c6b13115f2e6ed225625990af01a3f', 'block_header': {'raw_data': {'number': 6597663, 'parentHash': '000000000064ac1e8be0ae18b26a066e04d2895948d1a318ded6add9f0712641', 'timestamp': 1592503713000, 'txTrieRoot': '0000000000000000000000000000000000000000000000000000000000000000', 'version': 16, 'witness_address': '41e98ec1e5d55585f19cd9759d494af777d7041e0e'}, 'witness_signature': '7aa9ece51dc0e82b683570b2c9b792a5b1e298d52c6adb109cb3abb487a87948552007bd7baab6c8c539e9d105e324e6cb40da650e87595b4da08329b405083101'}} ``` -------------------------------- ### Async HD Wallet Main Execution Flow Source: https://github.com/andelf/tronpy/blob/master/docs/hdwallet.md Demonstrates the main execution flow for asynchronous HD wallet operations, including creating a wallet and deriving subsequent addresses. It verifies that different account indices yield different wallet addresses. ```python async def main(): passphrase, mnemonic_code, wallet_address = await create_hd_wallet('superSecret', 24) wallet_details = await derive_hd_wallet(mnemonic_code, passphrase, account_number=0, account_index=0) print(wallet_address == wallet_details['base58check_address']) # > True wallet_details = await derive_hd_wallet(mnemonic_code, passphrase, account_number=0, account_index=1) print(wallet_address == wallet_details['base58check_address']) # > False if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Connect to TRON Mainnet Source: https://github.com/andelf/tronpy/blob/master/docs/quickstart.md Initialize a Tron client connected to the default mainnet provider. ```python from tronpy import Tron client = Tron() # The default provider, mainnet ``` -------------------------------- ### Initialize Tron Client Source: https://context7.com/andelf/tronpy/llms.txt Instantiate a Tron or AsyncTron client connected to a specific TRON network (mainnet, testnet, or private node). For private nodes, a custom HTTPProvider with timeout and fee limit can be configured. AsyncTron clients can be used as context managers. ```python from tronpy import Tron from tronpy.providers import HTTPProvider # Mainnet (default) client = Tron() # Testnet: "nile", "shasta", or "tronex" client = Tron(network="nile") # Private node with custom timeout and fee limit client = Tron( HTTPProvider("http://127.0.0.1:8090", timeout=20.0), conf={"fee_limit": 10_000_000}, ) ``` ```python import asyncio from tronpy import AsyncTron async def main(): async with AsyncTron(network="nile") as client: block = await client.get_latest_block() print(block["blockID"]) asyncio.run(main()) ``` -------------------------------- ### Connect to TRON Testnets Source: https://github.com/andelf/tronpy/blob/master/docs/quickstart.md Initialize a Tron client connected to a preset testnet. Available testnets include 'nile', 'shasta', and 'tronex'. ```python from tronpy import Tron client = Tron(network="nile") # The Nile Testnet is preset # or "shasta", "tronex" ``` -------------------------------- ### Account Queries Source: https://context7.com/andelf/tronpy/llms.txt Shows how to query account information, including balance, TRX balance, bandwidth, energy, and general resource details. ```APIDOC ## Account Queries Fetch account balance, TRX balance, bandwidth, energy, and resource info. ```python from tronpy import Tron from tronpy.exceptions import AddressNotFound client = Tron() addr = "TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH" ``` -------------------------------- ### PrivateKey and Signing Source: https://context7.com/andelf/tronpy/llms.txt Details on creating, importing, and using `PrivateKey` objects for signing messages and transactions. Includes methods for random key generation, import from hex, and derivation from a passphrase. ```APIDOC ## PrivateKey and Signing Create, import, and use private keys to sign messages and transactions. ```python from tronpy.keys import PrivateKey # Random key priv = PrivateKey.random() # From hex priv = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) # From passphrase (sha256 of passphrase) priv = PrivateKey.from_passphrase(b"my secret passphrase") # Sign a raw message sig = priv.sign_msg(b"hello tron") print(sig.hex()) # 130-char hex string print(sig.tronweb_hex()) # TronWeb-compatible format (v+27) # Verify pub = priv.public_key assert pub.verify_msg(b"hello tron", sig) # Recover signer address from signature recovered_pub = sig.recover_public_key_from_msg(b"hello tron") print(recovered_pub.to_base58check_address()) ``` ``` -------------------------------- ### Offline Transaction Building Source: https://context7.com/andelf/tronpy/llms.txt Constructs and signs transactions without requiring a live node connection. The `ref_block_id` must be obtained beforehand, and the transaction can be broadcast later when online. Requires `pip install tronpy[offline]`. ```python from tronpy import Tron from tronpy.keys import PrivateKey # ref_block_id must be obtained from a node in advance REF_BLOCK_ID = "000000000064ac1f04aa38427cb78fb537c6b13115f2e6ed225625990af01a3f" client = Tron(network="nile") priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) txn = ( client.trx.transfer( "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000_000, ) .build(offline=True, ref_block_id=REF_BLOCK_ID) .sign(priv_key) ) # Serialise and transmit later print(txn) # JSON representation txn.broadcast() # submit when online ``` -------------------------------- ### Deploy a New Smart Contract Source: https://context7.com/andelf/tronpy/llms.txt Compile and deploy a new smart contract to the TRON network. Requires contract bytecode and ABI definition. The deployment transaction is signed and broadcast, and the contract address is returned. ```python from tronpy import Tron, Contract from tronpy.keys import PrivateKey client = Tron(network="nile") priv_key = PrivateKey(bytes.fromhex("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")) bytecode = ( "608060405234801561001057600080fd5b5060c78061001f6000396000f3fe" "6080604052348015600f57600080fd5b506004361060325760003560e01c80" "6360fe47b11460375780636d4ce63c146062575b600080fd5b606060048036" "03602081101560... (truncated)" ) abi = [ {"inputs": [{"name": "x", "type": "uint256"}], "name": "set", "outputs": [], "stateMutability": "nonpayable", "type": "function"}, {"inputs": [], "name": "get", "outputs": [{"name": "retVal", "type": "uint256"}], "stateMutability": "view", "type": "function"}, ] cntr = Contract(name="SimpleStore", bytecode=bytecode, abi=abi) txn = ( client.trx.deploy_contract("TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu", cntr) .fee_limit(5_000_000) .build() .sign(priv_key) ) result = txn.broadcast().wait() print("Contract deployed at:", result["contract_address"]) # Interact with newly deployed contract deployed = client.get_contract(result["contract_address"]) print("Value:", deployed.functions.get()) ``` -------------------------------- ### Use TronGrid API Key Source: https://github.com/andelf/tronpy/blob/master/docs/client.md Initialize the Tron client with an API key from TronGrid for authentication. Supports single or multiple API keys. ```python from tronpy import Tron from tronpy.providers import HTTPProvider client = Tron(HTTPProvider(api_key="Your api_key here")) # Use mainnet(trongrid) with a single api_key # or client = Tron(HTTPProvider(api_key=["key1", "key2", "key3"])) ``` -------------------------------- ### PrivateKey and Signing Source: https://context7.com/andelf/tronpy/llms.txt Manage private keys by creating random ones, importing from hex, or deriving from a passphrase. Sign messages and verify signatures using the public key. Recover the signer's address from a message signature. ```python from tronpy.keys import PrivateKey # Random key priv = PrivateKey.random() # From hex priv = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) # From passphrase (sha256 of passphrase) priv = PrivateKey.from_passphrase(b"my secret passphrase") # Sign a raw message sig = priv.sign_msg(b"hello tron") print(sig.hex()) # 130-char hex string print(sig.tronweb_hex()) # TronWeb-compatible format (v+27) # Verify pub = priv.public_key assert pub.verify_msg(b"hello tron", sig) # Recover signer address from signature recovered_pub = sig.recover_public_key_from_msg(b"hello tron") print(recovered_pub.to_base58check_address()) ``` -------------------------------- ### Create, Sign, and Broadcast TRX Transfer Source: https://github.com/andelf/tronpy/blob/master/docs/trx.md Demonstrates the method chaining approach to create a TRX transfer transaction, add a memo, build, sign with a private key, and then broadcast it. Use this for standard TRX transfers. ```python from tronpy import Tron from tronpy.keys import PrivateKey client = Tron(network='nile') priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) txn = ( client.trx.transfer("TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000) .memo("test memo") .build() .sign(priv_key) ) print(txn.txid) print(txn.broadcast().wait()) ``` -------------------------------- ### Using TronGrid API Key Source: https://github.com/andelf/tronpy/blob/master/docs/client.md Instructions on how to configure the Tron client to use a TronGrid API key for authentication. ```APIDOC ## Using TronGrid API Key ### Description You can register an API Key at [TronGrid](https://www.trongrid.io/) to authenticate your requests. ### Configuration #### Single API Key ```python from tronpy import Tron from tronpy.providers import HTTPProvider client = Tron(HTTPProvider(api_key="Your api_key here")) # Use mainnet(trongrid) with a single api_key ``` #### Multiple API Keys ```python from tronpy import Tron from tronpy.providers import HTTPProvider client = Tron(HTTPProvider(api_key=["key1", "key2", "key3"])) ``` ``` -------------------------------- ### Account Queries Source: https://context7.com/andelf/tronpy/llms.txt Fetch account details such as balance, TRX balance, bandwidth, energy, and general resource information. Handles potential AddressNotFound exceptions. ```python from tronpy import Tron from tronpy.exceptions import AddressNotFound client = Tron() addr = "TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH" ``` -------------------------------- ### Async Client Operations Source: https://context7.com/andelf/tronpy/llms.txt Demonstrates asynchronous operations using AsyncTron, including fetching account balances, transferring TRX, and interacting with smart contracts. Requires an active asyncio event loop. ```python import asyncio from tronpy import AsyncTron from tronpy.keys import PrivateKey priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) async def main(): async with AsyncTron(network="nile") as client: # Account balance balance = await client.get_account_balance("TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3") print(f"Balance: {balance} TRX") # Transfer TRX txb = ( client.trx.transfer( "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000_000, ) .memo("async transfer") .fee_limit(100_000_000) ) txn = await txb.build() ret = await txn.sign(priv_key).broadcast() print("txid:", ret.txid) receipt = await ret.wait() print("receipt:", receipt) # Smart contract const call contract = await client.get_contract("THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia") symbol = contract.functions.symbol() print("Symbol:", symbol) asyncio.run(main()) ``` -------------------------------- ### Freeze/Unfreeze Balance (Stake 2.0) Source: https://context7.com/andelf/tronpy/llms.txt Manage TRX staking for energy or bandwidth. Includes freezing, unfreezing, withdrawing stake, and delegating resources. Requires a private key for signing. ```python from tronpy import Tron from tronpy.keys import PrivateKey client = Tron(network="nile") priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) owner = "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3" # Freeze 10 TRX (10_000_000 SUN) for ENERGY txn = ( client.trx.freeze_balance(owner, amount=10_000_000, resource="ENERGY") .build() .sign(priv_key) ) txn.broadcast().wait() # Unfreeze 10 TRX from ENERGY stake txn = ( client.trx.unfreeze_balance(owner, resource="ENERGY", unfreeze_balance=10_000_000) .build() .sign(priv_key) ) txn.broadcast().wait() # After 14 days, withdraw expired unfreeze balance txn = client.trx.withdraw_stake_balance(owner).build().sign(priv_key) txn.broadcast().wait() # Delegate BANDWIDTH to another account (Stake 2.0) txn = ( client.trx.delegate_resource( owner, receiver="TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", balance=5_000_000, resource="BANDWIDTH", lock=False, ) .build() .sign(priv_key) ) txn.broadcast().wait() ``` -------------------------------- ### Asynchronous TRON Transaction with Manual Client Closing Source: https://github.com/andelf/tronpy/blob/master/README.md This snippet shows how to use the `AsyncTron` client with a manually managed `AsyncClient` from `httpx`. It demonstrates setting up the provider and closing the client explicitly. Remember to import `AsyncClient`, `Timeout`, `AsyncHTTPProvider`, and `CONF_NILE`. ```python from httpx import AsyncClient, Timeout from tronpy.providers.async_http import AsyncHTTPProvider from tronpy.defaults import CONF_NILE async def transfer(): _http_client = AsyncClient(limits=Limits(max_connections=100, max_keepalive_connections=20), timeout=Timeout(timeout=10, connect=5, read=5)) provider = AsyncHTTPProvider(CONF_NILE, client=_http_client) client = AsyncTron(provider=provider) print(client) priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) txb = ( client.trx.transfer("TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000) .memo("test memo") .fee_limit(100_000_000) ) txn = await txb.build() print(txn) txn_ret = await txn.sign(priv_key).broadcast() print(txn_ret) print(await txn_ret.wait()) await client.close() if __name__ == '__main__': asyncio.run(transfer()) ``` -------------------------------- ### Query TRON Chain APIs Source: https://github.com/andelf/tronpy/blob/master/docs/client.md Instantiate the Tron client and use its methods to query chain data like block numbers, block IDs, account balances, and asset balances. Also demonstrates generating a new TRON address. ```python >>> from tronpy import Tron >>> client = Tron() >>> client.get_latest_block_number() 20746184 >>> client.get_latest_block_id() '00000000013c8fc9a74d2ef9111d2216b9bec4b0fbf44e2e77711dde0e535f8e' >>> client.get_account_balance('TTzPiwbBedv7E8p4FkyPyeqq4RVoqRL3TW') Decimal('286820.078511') >>> client.get_account_asset_balance('TCrahg7N9cB1SwN21WzVMqxCptbRdvQata', 1002928) 989937719235000000 >>> client.generate_address() {'base58check_address': 'TU7r98aQ3XTHuM9NLwnyVmdCH7gAZDYqxt', 'hex_address': '41c71498123f6de4698410712e5f5c96ae42978776', 'private_key': '.................omitted.....................', 'public_key': '..................omitted.....................'} ``` -------------------------------- ### Generate HD Wallet and TRON Keys Source: https://context7.com/andelf/tronpy/llms.txt Generate BIP39 mnemonics and derive TRON keys via BIP32. This allows for creating new wallets with a specified number of words and language, outputting the mnemonic, address, and private key. ```python from tronpy import Tron # Install extra: pip install tronpy[mnemonic] client = Tron() # Create new wallet with mnemonic addr_info, mnemonic = client.generate_address_with_mnemonic( num_words=12, language="english", ) print("Mnemonic :", mnemonic) print("Address :", addr_info["base58check_address"]) print("PrivKey :", addr_info["private_key"]) ``` -------------------------------- ### Address Utilities Source: https://context7.com/andelf/tronpy/llms.txt Generate new addresses, derive from mnemonics (requires `tronpy[mnemonic]`), restore from mnemonics, and convert between base58check and hex address formats. Also demonstrates creating an address from a private key. ```python from tronpy import Tron from tronpy.keys import PrivateKey, to_base58check_address, to_hex_address, is_address client = Tron() # Generate a random address addr_info = client.generate_address() # {'base58check_address': 'TXyz...', 'hex_address': '41...', 'private_key': '...', 'public_key': '...'} # Generate address + mnemonic together (install tronpy[mnemonic]) addr_info, mnemonic = client.generate_address_with_mnemonic(num_words=12) print("Mnemonic:", mnemonic) print("Address:", addr_info["base58check_address"]) # Restore address from existing mnemonic restored = client.generate_address_from_mnemonic( "word1 word2 ... word12", passphrase="", account_path="m/44'/195'/0'/0/0", ) # Address format conversions b58 = to_base58check_address("410000000000000000000000000000000000000001") hex_addr = to_hex_address("TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH") print(is_address("TLyqzVGLV1srkB7dToTAEqgDSfPtXRJZYH")) # True # From private key directly priv = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888")) print(priv.public_key.to_base58check_address()) ``` -------------------------------- ### Query Node and Chain Information with TronPy Source: https://context7.com/andelf/tronpy/llms.txt Use this snippet to inspect network-level information such as node status, chain parameters, and witnesses. Ensure the Tron client is initialized. ```python from tronpy import Tron client = Tron() # Current node info node_info = client.get_node_info() print("Solid block:", node_info["solidityBlock"]) # Governance chain parameters params = client.get_chain_parameters() for p in params[:5]: print(p["key"], "=", p["value"]) # All Super Representatives witnesses = client.list_witnesses() for w in sorted(witnesses, key=lambda x: x.get("voteCount", 0), reverse=True)[:3]: print(w["address"], w.get("voteCount", 0)) # Connected peer nodes nodes = client.list_nodes() print(f"Connected to {len(nodes)} peers") ``` -------------------------------- ### Generate Address from Mnemonic Source: https://context7.com/andelf/tronpy/llms.txt Demonstrates how to restore or generate a TRON address from a mnemonic phrase using a specified account path. ```APIDOC ## Generate Address from Mnemonic This function allows you to derive a TRON address from a given mnemonic phrase and an account derivation path. ### Method `client.generate_address_from_mnemonic()` ### Parameters - **mnemonic** (string) - Required - The mnemonic phrase. - **passphrase** (string) - Optional - The passphrase for the mnemonic. - **account_path** (string) - Required - The derivation path for the account. ### Request Example ```python restored = client.generate_address_from_mnemonic( mnemonic="abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", passphrase="", account_path="m/44'/195'/0'/0/0", ) print("Restored address:", restored["base58check_address"]) ``` ### Response - **base58check_address** (string) - The generated TRON address. ``` -------------------------------- ### Use HTTP Proxy Source: https://github.com/andelf/tronpy/blob/master/docs/client.md Demonstrates how to configure the Tron client to use an HTTP proxy for network requests. ```APIDOC ## Use HTTP Proxy ### Description Configure the Tron client to route its HTTP requests through a proxy server. ### Configuration ```python from tronpy import Tron from tronpy.providers import HTTPProvider provider = HTTPProvider(api_key="API KEY HERE") provider.sess.proxies = {"https": "....", "http": "..."} client = Tron(provider) ``` ``` -------------------------------- ### Use HTTP Proxy Source: https://github.com/andelf/tronpy/blob/master/docs/client.md Configure the HTTP provider to use an HTTP proxy for network requests. Ensure the proxy URL is correctly specified. ```python from tronpy import Tron from tronpy.providers import HTTPProvider provider = HTTPProvider(api_key="API KEY HERE") provider.sess.proxies = {"https": "....", "http": "..."} client = Tron(provider) ```