Skip to content

HTTP API Client

TronPy uses TRON HTTP API to communicate with TRON nodes. The main client class is Tron.

Creating client

Refer Quickstart for creating clients.

Calling query APIs

The Tron wraps many query APIs and utility functions. You can query the chain using a instance.

>>> 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.....................'}

Using TronGrid API Key

You can register an API Key at TronGrid.

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"]))  # Use mainnet(trongrid) with multiple api_key

Use HTTP Proxy

from tronpy import Tron
from tronpy.providers import HTTPProvider

provider = HTTPProvider(api_key="API KEY HERE")
provider.sess.proxies = {"https": "....", "http": "..."}
client = Tron(provider)

API reference

Tron

Tron(provider: HTTPProvider = None, *, network: str = 'mainnet', conf: dict = None)

The TRON API Client.

Parameters:

  • provider

    (HTTPProvider, default: None ) –

    An HTTPProvider object, can be configured to use private node

  • network

    (str, default: 'mainnet' ) –

    Which network to connect, one of "mainnet", "shasta", "nile", or "tronex"

Methods:

Attributes:

Source code in tronpy/tron.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
def __init__(self, provider: HTTPProvider = None, *, network: str = "mainnet", conf: dict = None):
    self.conf = DEFAULT_CONF
    """The config dict."""

    if conf is not None:
        self.conf = dict(DEFAULT_CONF, **conf)
        if provider is not None and self.conf["timeout"] != DEFAULT_CONF["timeout"]:
            raise ValueError("timeout value should be set in provider")

    if provider is None:
        self.provider = HTTPProvider(conf_for_name(network), self.conf["timeout"])
    elif isinstance(provider, (HTTPProvider,)):
        self.provider = provider
    else:
        raise TypeError("provider is not a HTTPProvider")

    self._trx = Trx(self)

conf instance-attribute

conf = DEFAULT_CONF

The config dict.

is_address class-attribute instance-attribute

is_address = staticmethod(keys.is_address)

Is object a TRON address, both hex format and base58check format.

is_base58check_address class-attribute instance-attribute

is_base58check_address = staticmethod(keys.is_base58check_address)

Is object an address in base58check format.

is_hex_address class-attribute instance-attribute

is_hex_address = staticmethod(keys.is_hex_address)

Is object an address in hex str format.

to_base58check_address class-attribute instance-attribute

to_base58check_address = staticmethod(keys.to_base58check_address)

Convert address of any format to a base58check format.

to_canonical_address class-attribute instance-attribute

to_canonical_address = staticmethod(keys.to_base58check_address)

Convert address of any format to a base58check format.

to_hex_address class-attribute instance-attribute

to_hex_address = staticmethod(keys.to_hex_address)

Convert address of any format to a hex format.

trx property

trx: Trx

Helper object to send various transactions.

generate_address

generate_address(priv_key=None) -> dict

Generate a random address.

Source code in tronpy/tron.py
636
637
638
639
640
641
642
643
644
645
def generate_address(self, priv_key=None) -> dict:
    """Generate a random address."""
    if priv_key is None:
        priv_key = PrivateKey.random()
    return {
        "base58check_address": priv_key.public_key.to_base58check_address(),
        "hex_address": priv_key.public_key.to_hex_address(),
        "private_key": priv_key.hex(),
        "public_key": priv_key.public_key.hex(),
    }

generate_address_from_mnemonic

generate_address_from_mnemonic(
    mnemonic: str, passphrase: str = "", account_path: str = TRON_DEFAULT_PATH
)

Generate address from a mnemonic.

Parameters:

  • mnemonic

    (str) –

    space-separated list of BIP39 mnemonic seed words

  • passphrase

    (str, default: '' ) –

    Optional passphrase used to encrypt the mnemonic

  • account_path

    (str, default: TRON_DEFAULT_PATH ) –

    Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation.

Source code in tronpy/tron.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
def generate_address_from_mnemonic(self, mnemonic: str, passphrase: str = "", account_path: str = TRON_DEFAULT_PATH):
    """
    Generate address from a mnemonic.

    :param str mnemonic: space-separated list of BIP39 mnemonic seed words
    :param str passphrase: Optional passphrase used to encrypt the mnemonic
    :param str account_path: Specify an alternate HD path for deriving the seed using
        BIP32 HD wallet key derivation.
    """
    seed = seed_from_mnemonic(mnemonic, passphrase)
    key = key_from_seed(seed, account_path)
    priv_key = PrivateKey(key)
    return {
        "base58check_address": priv_key.public_key.to_base58check_address(),
        "hex_address": priv_key.public_key.to_hex_address(),
        "private_key": priv_key.hex(),
        "public_key": priv_key.public_key.hex(),
    }

generate_address_with_mnemonic

generate_address_with_mnemonic(
    passphrase: str = "",
    num_words: int = 12,
    language: str = "english",
    account_path: str = TRON_DEFAULT_PATH,
)

Create a new address and related mnemonic.

Creates a new address, and returns it alongside the mnemonic that can be used to regenerate it using any BIP39-compatible wallet.

Parameters:

  • passphrase

    (str, default: '' ) –

    Extra passphrase to encrypt the seed phrase

  • num_words

    (int, default: 12 ) –

    Number of words to use with seed phrase. Default is 12 words. Must be one of [12, 15, 18, 21, 24].

  • language

    (str, default: 'english' ) –

    Language to use for BIP39 mnemonic seed phrase.

  • account_path

    (str, default: TRON_DEFAULT_PATH ) –

    Specify an alternate HD path for deriving the seed using BIP32 HD wallet key derivation.

Source code in tronpy/tron.py
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
def generate_address_with_mnemonic(
    self, passphrase: str = "", num_words: int = 12, language: str = "english", account_path: str = TRON_DEFAULT_PATH
):
    r"""
    Create a new address and related mnemonic.

    Creates a new address, and returns it alongside the mnemonic that can be used to regenerate it using any BIP39-compatible wallet.

    :param str passphrase: Extra passphrase to encrypt the seed phrase
    :param int num_words: Number of words to use with seed phrase. Default is 12 words.
                          Must be one of [12, 15, 18, 21, 24].
    :param str language: Language to use for BIP39 mnemonic seed phrase.
    :param str account_path: Specify an alternate HD path for deriving the seed using
        BIP32 HD wallet key derivation.
    """  # noqa: E501
    mnemonic = generate_mnemonic(num_words, language)
    return self.generate_address_from_mnemonic(mnemonic, passphrase, account_path), mnemonic

generate_zkey

generate_zkey() -> dict

Generate a random shielded address.

Source code in tronpy/tron.py
689
690
691
def generate_zkey(self) -> dict:
    """Generate a random shielded address."""
    return self.provider.make_request("wallet/getnewshieldedaddress")

get_account

get_account(addr: TAddress) -> dict

Get account info from an address.

Source code in tronpy/tron.py
731
732
733
734
735
736
737
def get_account(self, addr: TAddress) -> dict:
    """Get account info from an address."""

    ret = self.provider.make_request("wallet/getaccount", {"address": keys.to_base58check_address(addr), "visible": True})
    if ret:
        return ret
    raise AddressNotFound("account not found on-chain")

get_account_asset_balance

get_account_asset_balance(addr: TAddress, token_id: int | str) -> int

Get TRC10 token balance of an account. Result is in raw amount.

Source code in tronpy/tron.py
778
779
780
781
782
783
784
def get_account_asset_balance(self, addr: TAddress, token_id: int | str) -> int:
    """Get TRC10 token balance of an account. Result is in raw amount."""
    if int(token_id) < 1000000 or int(token_id) > 1999999:
        raise ValueError("invalid token_id range")

    balances = self.get_account_asset_balances(addr)
    return balances.get(str(token_id), 0)

get_account_asset_balances

get_account_asset_balances(addr: TAddress) -> dict

Get all TRC10 token balances of an account.

Source code in tronpy/tron.py
773
774
775
776
def get_account_asset_balances(self, addr: TAddress) -> dict:
    """Get all TRC10 token balances of an account."""
    info = self.get_account(addr)
    return {p["key"]: p["value"] for p in info.get("assetV2", {}) if p["value"] > 0}

get_account_balance

get_account_balance(addr: TAddress) -> Decimal

Get TRX balance of an account. Result in TRX.

Source code in tronpy/tron.py
750
751
752
753
754
def get_account_balance(self, addr: TAddress) -> Decimal:
    """Get TRX balance of an account. Result in `TRX`."""

    info = self.get_account(addr)
    return Decimal(info.get("balance", 0)) / 1_000_000

get_account_permission

get_account_permission(addr: TAddress) -> dict

Get account's permission info from an address. Can be used in account_permission_update.

Source code in tronpy/tron.py
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
def get_account_permission(self, addr: TAddress) -> dict:
    """Get account's permission info from an address. Can be used in `account_permission_update`."""

    addr = keys.to_base58check_address(addr)
    # will check account existence
    info = self.get_account(addr)
    # For old accounts prior to AccountPermissionUpdate, these fields are not set.
    # So default permission is for backward compatibility.
    default_witness = None
    if info.get("is_witness", None):
        default_witness = {
            "type": "Witness",
            "id": 1,
            "permission_name": "witness",
            "threshold": 1,
            "keys": [{"address": addr, "weight": 1}],
        }
    return {
        "owner": info.get(
            "owner_permission",
            {"permission_name": "owner", "threshold": 1, "keys": [{"address": addr, "weight": 1}]},
        ),
        "actives": info.get(
            "active_permission",
            [
                {
                    "type": "Active",
                    "id": 2,
                    "permission_name": "active",
                    "threshold": 1,
                    "operations": "7fff1fc0033e0100000000000000000000000000000000000000000000000000",
                    "keys": [{"address": addr, "weight": 1}],
                }
            ],
        ),
        "witness": info.get("witness_permission", default_witness),
    }

get_account_resource

get_account_resource(addr: TAddress) -> dict

Get resource info of an account.

Source code in tronpy/tron.py
739
740
741
742
743
744
745
746
747
748
def get_account_resource(self, addr: TAddress) -> dict:
    """Get resource info of an account."""

    ret = self.provider.make_request(
        "wallet/getaccountresource",
        {"address": keys.to_base58check_address(addr), "visible": True},
    )
    if ret:
        return ret
    raise AddressNotFound("account not found on-chain")

get_address_from_passphrase

get_address_from_passphrase(passphrase: str) -> dict

Get an address from a passphrase, compatiable with wallet/createaddress.

Source code in tronpy/tron.py
684
685
686
687
def get_address_from_passphrase(self, passphrase: str) -> dict:
    """Get an address from a passphrase, compatiable with `wallet/createaddress`."""
    priv_key = PrivateKey.from_passphrase(passphrase.encode())
    return self.generate_address(priv_key)

get_asset

get_asset(asset_id: int = None, issuer: TAddress = None) -> dict

Get TRC10(asset) info by asset's id or issuer.

Source code in tronpy/tron.py
982
983
984
985
986
987
988
989
990
991
def get_asset(self, asset_id: int = None, issuer: TAddress = None) -> dict:
    """Get TRC10(asset) info by asset's id or issuer."""
    if asset_id and issuer:
        return ValueError("either query by id or issuer")
    if asset_id:
        return self.provider.make_request("wallet/getassetissuebyid", {"value": asset_id, "visible": True})
    return self.provider.make_request(
        "wallet/getassetissuebyaccount",
        {"address": keys.to_base58check_address(issuer), "visible": True},
    )

get_asset_from_name

get_asset_from_name(name: str) -> dict

Get asset info from its abbr name, might fail if there're duplicates.

Source code in tronpy/tron.py
 993
 994
 995
 996
 997
 998
 999
1000
def get_asset_from_name(self, name: str) -> dict:
    """Get asset info from its abbr name, might fail if there're duplicates."""
    assets = [asset for asset in self.list_assets() if asset["abbr"] == name]
    if assets:
        if len(assets) == 1:
            return assets[0]
        raise ValueError("duplicated assets with the same name", [asset["id"] for asset in assets])
    raise AssetNotFound

get_bandwidth

get_bandwidth(addr: TAddress) -> int

Query the bandwidth of the account

Source code in tronpy/tron.py
756
757
758
759
760
761
762
763
764
def get_bandwidth(self, addr: TAddress) -> int:
    """Query the bandwidth of the account"""
    ret = self.provider.make_request(
        "wallet/getaccountnet", {"address": keys.to_base58check_address(addr), "visible": True}
    )
    if ret:
        # (freeNetLimit - freeNetUsed) + (NetLimit - NetUsed)
        return ret["freeNetLimit"] - ret.get("freeNetUsed", 0) + ret.get("NetLimit", 0) - ret.get("NetUsed", 0)
    raise AddressNotFound("account not found on-chain")

get_block

get_block(id_or_num: None | str | int = None, *, visible: bool = True) -> dict

Get block from a block id or block number.

Parameters:

  • id_or_num

    (None | str | int, default: None ) –

    Block number, or Block hash(id), or None (default) to get the latest block.

  • visible

    (bool, default: True ) –

    Use visible=False to get non-base58check addresses and strings instead of hex strings.

Source code in tronpy/tron.py
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
def get_block(self, id_or_num: None | str | int = None, *, visible: bool = True) -> dict:
    """Get block from a block id or block number.

    :param id_or_num: Block number, or Block hash(id), or ``None`` (default) to get the latest block.
    :param visible: Use ``visible=False`` to get non-base58check addresses and strings instead of hex strings.
    """

    if isinstance(id_or_num, (int,)):
        block = self.provider.make_request("wallet/getblockbynum", {"num": id_or_num, "visible": visible})
    elif isinstance(id_or_num, (str,)):
        block = self.provider.make_request("wallet/getblockbyid", {"value": id_or_num, "visible": visible})
    elif id_or_num is None:
        block = self.provider.make_request("wallet/getnowblock", {"visible": visible})
    else:
        raise TypeError(f"can not infer type of {id_or_num}")

    if "Error" in (block or {}):
        raise BugInJavaTron(block)
    if block:
        return block
    raise BlockNotFound

get_can_delegated_max_size

get_can_delegated_max_size(address: TAddress, resource: str = 'ENERGY') -> dict

Query the amount of delegatable resources share of the specified resource type for an address

Args: address (TAddress): resource (str, optional): Resource type, can be "ENERGY" or "BANDWIDTH". Defaults to "ENERGY".

Returns: dict: Response data

Source code in tronpy/tron.py
835
836
837
838
839
840
841
842
843
844
845
846
847
848
def get_can_delegated_max_size(self, address: TAddress, resource: str = "ENERGY") -> dict:
    """Query the amount of delegatable resources share of the specified resource type for an address

    Args:
        address (TAddress):
        resource (str, optional): Resource type, can be ``"ENERGY"`` or ``"BANDWIDTH"``. Defaults to "ENERGY".

    Returns:
        dict: Response data
    """
    return self.provider.make_request(
        "wallet/getcandelegatedmaxsize",
        {"owner_address": keys.to_base58check_address(address), "type": 1 if resource == "ENERGY" else 0, "visible": True},
    )

get_chain_parameters

get_chain_parameters() -> dict

List all chain parameters, values that can be changed via proposal.

Source code in tronpy/tron.py
976
977
978
def get_chain_parameters(self) -> dict:
    """List all chain parameters, values that can be changed via proposal."""
    return self.provider.make_request("wallet/getchainparameters", {"visible": True}).get("chainParameter", [])

get_contract

get_contract(addr: TAddress) -> Contract

Get a contract object.

Source code in tronpy/tron.py
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
def get_contract(self, addr: TAddress) -> Contract:
    """Get a contract object."""
    addr = keys.to_base58check_address(addr)
    info = self.provider.make_request("wallet/getcontract", {"value": addr, "visible": True})

    try:
        self._handle_api_error(info)
    except ApiError as e:
        # your java's null pointer exception sucks
        raise AddressNotFound("contract address not found") from e

    return Contract(
        addr=addr,
        bytecode=info.get("bytecode", ""),
        name=info.get("name", ""),
        abi=info.get("abi", {}).get("entrys", []),
        origin_energy_limit=info.get("origin_energy_limit", 0),
        user_resource_percent=info.get("consume_user_resource_percent", 100),
        origin_address=info.get("origin_address", ""),
        code_hash=info.get("code_hash", ""),
        client=self,
    )

get_contract_as_shielded_trc20

get_contract_as_shielded_trc20(addr: TAddress) -> ShieldedTRC20

Get a Shielded TRC20 Contract object.

Source code in tronpy/tron.py
1058
1059
1060
1061
def get_contract_as_shielded_trc20(self, addr: TAddress) -> ShieldedTRC20:
    """Get a Shielded TRC20 Contract object."""
    contract = self.get_contract(addr)
    return ShieldedTRC20(contract)

get_contract_info

get_contract_info(addr: TAddress) -> dict

Queries a contract's information from the blockchain

Source code in tronpy/tron.py
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
def get_contract_info(self, addr: TAddress) -> dict:
    """Queries a contract's information from the blockchain"""
    addr = keys.to_base58check_address(addr)
    info = self.provider.make_request("wallet/getcontractinfo", {"value": addr, "visible": True})

    try:
        self._handle_api_error(info)
    except ApiError as e:
        raise AddressNotFound("contract address not found") from e

    return info

get_delegated_resource_account_index_v2

get_delegated_resource_account_index_v2(addr: TAddress) -> dict

Query the resource delegation index by an account

Source code in tronpy/tron.py
850
851
852
853
854
855
856
857
858
def get_delegated_resource_account_index_v2(self, addr: TAddress) -> dict:
    """Query the resource delegation index by an account"""
    return self.provider.make_request(
        "wallet/getdelegatedresourceaccountindexv2",
        {
            "value": keys.to_base58check_address(addr),
            "visible": True,
        },
    )

get_delegated_resource_v2

get_delegated_resource_v2(fromAddr: TAddress, toAddr: TAddress) -> dict

Query the amount of delegatable resources share of the specified resource type for an address

Source code in tronpy/tron.py
824
825
826
827
828
829
830
831
832
833
def get_delegated_resource_v2(self, fromAddr: TAddress, toAddr: TAddress) -> dict:
    """Query the amount of delegatable resources share of the specified resource type for an address"""
    return self.provider.make_request(
        "wallet/getdelegatedresourcev2",
        {
            "fromAddress": keys.to_base58check_address(fromAddr),
            "toAddress": keys.to_base58check_address(toAddr),
            "visible": True,
        },
    )

get_energy

get_energy(address: str) -> int

Query the energy of the account

Source code in tronpy/tron.py
766
767
768
769
770
771
def get_energy(self, address: str) -> int:
    """Query the energy of the account"""
    account_info = self.get_account_resource(address)
    energy_limit = account_info.get("EnergyLimit", 0)
    energy_used = account_info.get("EnergyUsed", 0)
    return energy_limit - energy_used

get_estimated_energy

get_estimated_energy(
    owner_address: TAddress,
    contract_address: TAddress,
    function_selector: str,
    parameter: str,
) -> int

Returns an estimated energy of calling a contract from the chain.

Source code in tronpy/tron.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
def get_estimated_energy(
    self,
    owner_address: TAddress,
    contract_address: TAddress,
    function_selector: str,
    parameter: str,
) -> int:
    """Returns an estimated energy of calling a contract from the chain."""
    params = {
        "owner_address": keys.to_base58check_address(owner_address),
        "contract_address": keys.to_base58check_address(contract_address),
        "function_selector": function_selector,
        "parameter": parameter,
        "visible": True,
    }
    ret = self.provider.make_request("wallet/estimateenergy", params)
    self._handle_api_error(ret)
    return ret["energy_required"]

get_latest_block

get_latest_block() -> dict

Get latest block.

Source code in tronpy/tron.py
877
878
879
def get_latest_block(self) -> dict:
    """Get latest block."""
    return self.provider.make_request("wallet/getnowblock", {"visible": True})

get_latest_block_id

get_latest_block_id() -> str

Get latest block id in hex.

Source code in tronpy/tron.py
881
882
883
884
885
def get_latest_block_id(self) -> str:
    """Get latest block id in hex."""

    info = self.provider.make_request("wallet/getnodeinfo")
    return info["block"].split(",ID:", 1)[-1]

get_latest_block_number

get_latest_block_number() -> int

Get latest block number. Implemented via wallet/getnodeinfo, which is faster than wallet/getnowblock.

Source code in tronpy/tron.py
887
888
889
890
891
def get_latest_block_number(self) -> int:
    """Get latest block number. Implemented via `wallet/getnodeinfo`, which is faster than `wallet/getnowblock`."""

    info = self.provider.make_request("wallet/getnodeinfo")
    return int(info["block"].split(",ID:", 1)[0].replace("Num:", "", 1))

get_latest_solid_block_id

get_latest_solid_block_id() -> str

Get latest solid block id in hex.

Source code in tronpy/tron.py
865
866
867
868
869
def get_latest_solid_block_id(self) -> str:
    """Get latest solid block id in hex."""

    info = self.provider.make_request("wallet/getnodeinfo")
    return info["solidityBlock"].split(",ID:", 1)[-1]

get_latest_solid_block_number

get_latest_solid_block_number() -> int

Get latest solid block number. Implemented via wallet/getnodeinfo, which is faster than walletsolidity/getnowblock.

Source code in tronpy/tron.py
871
872
873
874
875
def get_latest_solid_block_number(self) -> int:
    """Get latest solid block number. Implemented via `wallet/getnodeinfo`,
    which is faster than `walletsolidity/getnowblock`."""
    info = self.provider.make_request("wallet/getnodeinfo")
    return int(info["solidityBlock"].split(",ID:", 1)[0].replace("Num:", "", 1))

get_node_info

get_node_info() -> dict

Get current API node' info.

Source code in tronpy/tron.py
971
972
973
974
def get_node_info(self) -> dict:
    """Get current API node' info."""

    return self.provider.make_request("wallet/getnodeinfo", {"visible": True})

get_solid_transaction_info

get_solid_transaction_info(txn_id: str) -> dict

Get transaction receipt info from a transaction id, must be in solid block.

Source code in tronpy/tron.py
939
940
941
942
943
944
945
946
947
948
949
def get_solid_transaction_info(self, txn_id: str) -> dict:
    """Get transaction receipt info from a transaction id, must be in solid block."""

    if len(txn_id) != 64:
        raise BadHash("wrong transaction hash length")

    ret = self.provider.make_request("walletsolidity/gettransactioninfobyid", {"value": txn_id, "visible": True})
    self._handle_api_error(ret)
    if ret:
        return ret
    raise TransactionNotFound

get_transaction

get_transaction(txn_id: str) -> dict

Get transaction from a transaction id.

Source code in tronpy/tron.py
915
916
917
918
919
920
921
922
923
924
925
def get_transaction(self, txn_id: str) -> dict:
    """Get transaction from a transaction id."""

    if len(txn_id) != 64:
        raise BadHash("wrong transaction hash length")

    ret = self.provider.make_request("wallet/gettransactionbyid", {"value": txn_id, "visible": True})
    self._handle_api_error(ret)
    if ret:
        return ret
    raise TransactionNotFound

get_transaction_info

get_transaction_info(txn_id: str) -> dict

Get transaction receipt info from a transaction id.

Source code in tronpy/tron.py
927
928
929
930
931
932
933
934
935
936
937
def get_transaction_info(self, txn_id: str) -> dict:
    """Get transaction receipt info from a transaction id."""

    if len(txn_id) != 64:
        raise BadHash("wrong transaction hash length")

    ret = self.provider.make_request("wallet/gettransactioninfobyid", {"value": txn_id, "visible": True})
    self._handle_api_error(ret)
    if ret:
        return ret
    raise TransactionNotFound

get_zkey_from_sk

get_zkey_from_sk(sk: str, d: str = None) -> dict

Get the shielded address from sk(spending key) and d(diversifier).

Source code in tronpy/tron.py
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
def get_zkey_from_sk(self, sk: str, d: str = None) -> dict:
    """Get the shielded address from sk(spending key) and d(diversifier)."""
    if len(sk) != 64:
        raise BadKey("32 byte sk required")
    if d and len(d) != 22:
        raise BadKey("11 byte d required")

    esk = self.provider.make_request("wallet/getexpandedspendingkey", {"value": sk})
    ask = esk["ask"]
    nsk = esk["nsk"]
    ovk = esk["ovk"]
    ak = self.provider.make_request("wallet/getakfromask", {"value": ask})["value"]
    nk = self.provider.make_request("wallet/getnkfromnsk", {"value": nsk})["value"]

    ivk = self.provider.make_request("wallet/getincomingviewingkey", {"ak": ak, "nk": nk})["ivk"]

    if d is None:
        d = self.provider.make_request("wallet/getdiversifier")["d"]

    ret = self.provider.make_request("wallet/getzenpaymentaddress", {"ivk": ivk, "d": d})
    pkD = ret["pkD"]
    payment_address = ret["payment_address"]

    return {
        "sk": sk,
        "ask": ask,
        "nsk": nsk,
        "ovk": ovk,
        "ak": ak,
        "nk": nk,
        "ivk": ivk,
        "d": d,
        "pkD": pkD,
        "payment_address": payment_address,
    }

list_assets

list_assets() -> list

List all TRC10 tokens(assets).

Source code in tronpy/tron.py
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
def list_assets(self) -> list:
    """List all TRC10 tokens(assets)."""
    ret = self.provider.make_request("wallet/getassetissuelist", {"visible": True})
    assets = ret["assetIssue"]
    for asset in assets:
        asset["id"] = int(asset["id"])
        asset["owner_address"] = keys.to_base58check_address(asset["owner_address"])
        asset["name"] = bytes.fromhex(asset["name"]).decode()
        if "abbr" in asset:
            asset["abbr"] = bytes.fromhex(asset["abbr"]).decode()
        else:
            asset["abbr"] = ""
        if "description" in asset:
            asset["description"] = bytes.fromhex(asset["description"]).decode("utf8", "replace")
        else:
            asset["description"] = ""
        asset["url"] = bytes.fromhex(asset["url"]).decode()
    return assets

list_nodes

list_nodes() -> list

List all nodes that current API node is connected to.

Source code in tronpy/tron.py
962
963
964
965
966
967
968
969
def list_nodes(self) -> list:
    """List all nodes that current API node is connected to."""
    # NOTE: visible parameter is ignored
    ret = self.provider.make_request("wallet/listnodes", {"visible": True})
    nodes = ret.get("nodes", [])
    for node in nodes:
        node["address"]["host"] = bytes.fromhex(node["address"]["host"]).decode()
    return nodes

list_witnesses

list_witnesses() -> list

List all witnesses, including SR, SRP, and SRC.

Source code in tronpy/tron.py
953
954
955
956
957
958
959
960
def list_witnesses(self) -> list:
    """List all witnesses, including SR, SRP, and SRC."""
    # NOTE: visible parameter is ignored
    ret = self.provider.make_request("wallet/listwitnesses", {"visible": True})
    witnesses = ret.get("witnesses", [])
    for witness in witnesses:
        witness["address"] = keys.to_base58check_address(witness["address"])
    return witnesses

HTTPProvider

HTTPProvider(
    endpoint_uri: str | dict = None,
    timeout: float = DEFAULT_TIMEOUT,
    api_key: str | list[str] = None,
    jw_token: str = None,
)

An HTTP Provider for API request.

Parameters:

  • endpoint_uri

    (str | dict, default: None ) –

    HTTP API URL base. Default value is "https://api.trongrid.io/". Can also be configured via the TRONPY_HTTP_PROVIDER_URI environment variable.

  • timeout

    (float, default: DEFAULT_TIMEOUT ) –

    HTTP timeout in seconds.

  • api_key

    (str | list[str], default: None ) –

    TronGRID API Key in str, or list of str.

  • jw_token

    (str, default: None ) –

    TronGRID JWT Credentials in str.

Attributes:

  • timeout –

    Request timeout in second.

Source code in tronpy/providers/http.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def __init__(
    self,
    endpoint_uri: str | dict = None,
    timeout: float = DEFAULT_TIMEOUT,
    api_key: str | list[str] = None,
    jw_token: str = None,
):
    super().__init__()

    if endpoint_uri is None:
        self.endpoint_uri = os.environ.get("TRONPY_HTTP_PROVIDER_URI", "https://api.trongrid.io/")
    elif isinstance(endpoint_uri, (dict,)):
        self.endpoint_uri = endpoint_uri["fullnode"]
    elif isinstance(endpoint_uri, (str,)):
        self.endpoint_uri = endpoint_uri
    else:
        raise TypeError(f"unknown endpoint uri {endpoint_uri}")

    if "trongrid" in self.endpoint_uri:
        self.use_api_key = True
        if isinstance(api_key, (str,)):
            self._api_keys = [api_key]
        elif isinstance(api_key, (list,)) and api_key:
            self._api_keys = api_key
        else:
            self._api_keys = DEFAULT_API_KEYS.copy()

        self._default_api_keys = self._api_keys.copy()
    else:
        self.use_api_key = False
    self.jw_token = jw_token

    self.sess = requests.session()
    self.sess.headers["User-Agent"] = f"Tronpy/{VERSION}"

    self.timeout = timeout
    """Request timeout in second."""

timeout instance-attribute

timeout = timeout

Request timeout in second.