Giter VIP home page Giter VIP logo

tron-api-python's Introduction

TRON API for Python

A Python API for interacting with the Tron (TRX)

image

image

image

image

image

Codacy Badge


A Command-Line Interface framework

You can install it in a system-wide location via pip:

sudo pip3 install tronapi

Or install it locally using virtualenv:

virtualenv -p /usr/bin/python3 ~/tronapi
source ~/tronapi/bin/activate
pip3 install tronapi

Usage

Specify the API endpoints:

Smart Contract

from tronapi import Tron
from solc import compile_source

full_node = 'https://api.trongrid.io'
solidity_node = 'https://api.trongrid.io'
event_server = 'https://api.trongrid.io'

tron = Tron(full_node=full_node,
        solidity_node=solidity_node,
        event_server=event_server)

# or default (tron = Tron())


# Solidity source code
contract_source_code = '''
pragma solidity ^0.4.25;

contract Hello {
    string public message;

    function Hello(string initialMessage) public {
        message = initialMessage;
    }

    function setMessage(string newMessage) public {
        message = newMessage;
    }
}

'''

compiled_sol = compile_source(contract_source_code)
contract_interface = compiled_sol['<stdin>:Hello']

hello = tron.trx.contract(
    abi=contract_interface['abi'],
    bytecode=contract_interface['bin']
)

# Submit the transaction that deploys the contract
tx = hello.deploy(
    fee_limit=10**9,
    call_value=0,
    consume_user_resource_percent=1
)

Base Example

from tronapi import Tron
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger()

full_node = 'https://api.trongrid.io'
solidity_node = 'https://api.trongrid.io'
event_server = 'https://api.trongrid.io'

tron = Tron(full_node=full_node,
        solidity_node=solidity_node,
        event_server=event_server)

account = tron.create_account
is_valid = bool(tron.trx.is_address(account.address.hex))

logger.debug('Generated account: ')
logger.debug('- Private Key: ' + account.private_key)
logger.debug('- Public Key: ' + account.public_key)
logger.debug('- Address: ')
logger.debug('-- Base58: ' + account.address.base58)
logger.debug('-- Hex: ' + account.address.hex)
logger.debug('-- isValid: ' + str(is_valid))
logger.debug('-----------')

transaction = tron.trx.get_transaction('757a14cef293c69b1cf9b9d3d19c2e40a330c640b05c6ffa4d54609a9628758c')

logger.debug('Transaction: ')
logger.debug('- Hash: ' + transaction['txID'])
logger.debug('- Transaction: ' + json.dumps(transaction, indent=2))
logger.debug('-----------')

# Events
event_result = tron.trx.get_event_result('TGEJj8eus46QMHPgWQe1FJ2ymBXRm96fn1', 0, 'Notify')

logger.debug('Event result:')
logger.debug('Contract Address: TGEJj8eus46QMHPgWQe1FJ2ymBXRm96fn1')
logger.debug('Event Name: Notify')
logger.debug('Block Number: 32162')
logger.debug('- Events: ' + json.dumps(event_result, indent=2))

More samples and snippets are available at examples.

Documentation

Documentation is available at docs.

Donations

TRON: TRWBqiqoFZysoAeyR1J35ibuyc8EvhUAoY

tron-api-python's People

Contributors

0xjayshen avatar ansmirnov avatar goedgar avatar jjconti avatar lemenkov avatar luchevoi avatar moliholy avatar serderovsh avatar sonicskye avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tron-api-python's Issues

Receiving revert response from contract trigger

I am running below code to trigger TronBet contract

parameters=[{'type': 'uint256', 'value': rollvalue}, {'type': 'uint256', 'value': direction}]#, {'type': 'uint64', 'value': "roll"}] parameters=[{"value":rollvalue,"type":"uint256"},{"value":direction,"type":"uint256"}] tx=tron.transaction_builder.trigger_smart_contract('TEEXEWrkMFKapSMJ6mErg39ELFKDqEs6w3','GoodLuck',fee_limit,bet_value,parameters)#,'TQR27jXR4dHdDtjE63MnnUQvecK97rop2y') #print(tx) #tx=tx['transaction'] tx=tron.trx.sign(tx)#,True) tron.trx.broadcast(tx)

Everything goes fine but contract is not triggered. When I enquire trx then I get below info

{'ret': [{'contractRet': 'REVERT'}], 'signature': ['0219801893a402337d882c09e598780579d9c21a6ab1d7cdd21ca452e50fbd884830f2892998bdfab2360240b3007aaf6cd29ad76b2005886d547d307f36a8bf1b'], 'txID': '32308a59ebd4b6442fb49f1914e6e5c7636fb0144eefd79f0e75f981f9ab159d', 'raw_data': {'contract': [{'parameter': {'value': {'data': '16bd160c00000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000000', 'owner_address': '419e737d5db19beafc2a9a813211cc73add2d3a872', 'contract_address': '412ec5f63da00583085d4c2c5e8ec3c8d17bde5e28', 'call_value': 10000000}, 'type_url': 'type.googleapis.com/protocol.TriggerSmartContract'}, 'type': 'TriggerSmartContract'}], 'ref_block_bytes': 'cf50', 'ref_block_hash': 'c25f1caca6eb80d0', 'expiration': 1546335174000, 'fee_limit': 600000, 'timestamp': 1546335116934}}

So it is reverted. Code failed to trigger the contract.

Please check. What is wrong and how to fix it

Mac, pip install tronapi, ImportError: No module named eth_account

After installed tronapi by sudo pip install tronapi, and run python account.py in examples documents, showing error:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    from tronapi import Tron
  File "/Volumes/D/coins/tron/tron-robot/tronapi/__init__.py", line 11, in <module>
    from eth_account import Account  # noqa: E402
ImportError: No module named eth_account

I checked installation logs, shows
Requirement already satisfied: eth-account<0.4.0,>=0.2.1 in /usr/local/lib/python3.7/site-packages (from tronapi) (0.3.0)
What should I do ?
Thank you

Initial Update

The bot created this issue to inform you that pyup.io has been set up on this repo.
Once you have closed it, the bot will open pull requests for updates as soon as they are available.

'NotFoundError' on get_transactions_to_address

Hi,

i'm currently executing this:

account = Tron().create_account

tron = Tron(**{"private_key": account.private_key, "default_address": account.address.hex})

address = tron.default_address.hex
transactions = tron.trx.get_transactions_to_address(address=address)

But i get this error on the last line:

tronapi.exceptions.NotFoundError: (404, '{"error":{"code":404,"status":"Not Found"}}', {'error': {'code': 404, 'status': 'Not Found'}}, 'https://api.trongrid.io/walletextension/gettransactionstothis')

But if i execute https://developers.tron.network/reference#transaction-information-by-account-address directly then it works.

Support setting permission_id in trx.sign for multisig

When trying to do multi-signature using an 'active' permission you need to be able to set the Permission_id in the transaction's contract e.g.

create_tx["raw_data"]["contract"][0]["Permission_id"] = 2

However, the problem here is that the transaction's raw data, and therefore the txID will need to be changed as a result of updating the transaction.

TronWeb handles this situation by taking a permissionId argument to its trx.multisign function, which if >0 where the transaction's contract doesn't have a Permission_id already, causes TronWeb to add the Permission_id to the contract before POSTing the transaction to wallet/getsignweight which then returns an updated transaction (in transaction.transaction) containing a corrected txID, which can then be signed.

This is how the code might look using tronapi to do the signing after this issue is fixed (in this case the wallet/getsignweight is only done on the first call to trx.sign):

create_tx = tron.transaction_builder.send_transaction('to', 1, 'from')
tron.private_key = 'first private_key'
signed1_tx = tron.trx.sign(create_tx, multisig=true, permission_id=2)
tron.private_key = 'second private_key'
signed2_tx = tron.trx.sign(signed1_tx, multisig=true, permission_id=2)
response = tron.trx.broadcast(signed2_tx)

Something like this should be added to your examples scripts to show how multisign should be used.

how transaction serialization and deserialization?

here I encounter another question. As ethereum uses RLP for serializing data. Does tron uses GoogleProtocol to serialize data ?

How the process is in tron-pathonapi?
where can i find solution ? or can you tell me some idea about how to serialization and deserialization locally?
I am really suffering from it ,looking forward to your reply.

Thanks a lot!

May be a raw_transaction json bug?

owner_address = transaction['raw_data']['contract'][0]['parameter']['value']['owner_address']

Some contract trigger json is

`{
    "result": {
        "result": true
    },
    "transaction": {
        "visible": false,
        "txID": "3ac31ba736c67e68620c3a6ddd76beb2134c8d796e041f8128149af3b5e7f153",
        "raw_data": {
            "contract": [
                {
                    "parameter": {
                        "value": {
                            "data": "0a23b56b",
                            "owner_address": "41f70c351d1a1e2431ced562ebe3f6041d9713c490",
                            "contract_address": "41bbf3f996cbbca9653209ea4ee888d2c1bbbb3451",
                            "call_value": 19
                        },
                        "type_url": "type.googleapis.com/protocol.TriggerSmartContract"
                    },
                    "type": "TriggerSmartContract"
                }
            ],
            "ref_block_bytes": "9b4f",
            "ref_block_hash": "eea9cbc2ef529d14",
            "expiration": 1578740379000,
            "fee_limit": 30000,
            "timestamp": 1578740320550
        },
        "raw_data_hex": "0a029b4f2208eea9cbc2ef529d1440f8da89a2f92d5a6f081f126b0a31747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e54726967676572536d617274436f6e747261637412360a1541f70c351d1a1e2431ced562ebe3f6041d9713c490121541e3cf5eefe3a2abf35a344ae8a3b2f4bb29810cbd181322040a23b56b70a69286a2f92d9001b0ea01"
    }
}

so, may be line 575 improve better?
owner_address = transaction['transaction']['raw_data']['contract'][0]['parameter']['value']['owner_address']

Missing functionality for interacting with contracts?

There seems to be code to deploy a contract but nothing to interact with it. You can get by by passing the "parameter" argument in as a keyword argument when creating a contract,, although there's some massaging that needs to be done to get it in the right format, which I haven't gotten around to implementing yet (or does it already exist somewhere?).

Likewise, there's no function that calls /wallet/triggersmartcontract although, one can work around it like so:

    return tron.manager.request('/wallet/triggersmartcontract', {
        'contract_address': contract_address,
        'owner_address': host.address.hex,
        'function_selector': function_name,
        'fee_limit': 1000000,
        'call_value': 0,
        'parameter': params
    })

There's appears to exist a ContractFunction class that comes back if you do contract.all_functions(), but it's not clear to me how its intended to be used. I can see in tron web that the parameters are encoded using parameters = abiCoder.encode(types, values).replace(/^(0x)/, '') but I'm not seeing any similar functionality here.

Can't Install

pip3 install tronapi

Collecting tronapi
Using cached https://files.pythonhosted.org/packages/32/c4/82fed9d23d9087b41ece9788b47a53fbe8be93af1464291ee302fde536b0/tronapi-3.1.3.tar.gz
Ignoring toolz: markers 'implementation_name == "pypy"' don't match your environment
Collecting cytoolz<1.0.0,>=0.9.0; implementation_name == "cpython" (from tronapi)
Using cached https://files.pythonhosted.org/packages/36/f4/9728ba01ccb2f55df9a5af029b48ba0aaca1081bbd7823ea2ee223ba7a42/cytoolz-0.9.0.1.tar.gz
Collecting eth-abi<3.0.0,>=2.0.0b4 (from tronapi)
Using cached https://files.pythonhosted.org/packages/d1/a1/61039ba8de300a053bd72c891c67dbcc5253c288c98dd204dea3e2cccb36/eth_abi-2.0.0b7-py3-none-any.whl
Collecting eth-account<0.4.0,>=0.2.1 (from tronapi)
Using cached https://files.pythonhosted.org/packages/a3/d8/6118bc0e00d6ec092bb02b012989d1018893755eb84da53266412ac359e3/eth_account-0.3.0-py3-none-any.whl

Collecting eth-utils<2.0.0,>=1.3.0 (from tronapi)
Could not find a version that satisfies the requirement eth-utils<2.0.0,>=1.3.0 (from tronapi) (from versions: 0.7.0, 0.7.1, 0.7.2, 0.7.3, 0.7.4, 0.8.0, 0.8.1, 1.0.0b1, 1.0.0b2, 1.0.1, 1.0.2, 1.0.3, 1.1.1, 1.1.2, 1.2.0, 1.2.1)
No matching distribution found for eth-utils<2.0.0,>=1.3.0 (from tronapi)

what's transaction detail?

i find method of offline_sign(),but i don't know the detail of parameter(transaction),can you help me?
I don't find detail in trx document.In addition,do you know how to mul-sign in trx?It looks like you should be good at eth and ripple,i can mul-sign in eth and ripple.Do they have anything in common?trx can use solidity too.

tronapi web3 Incompatible

pip3 install web3

Looking in indexes: http://mirrors.cloud.aliyuncs.com/pypi/simple/
Collecting web3
Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/84/7b/8dfe018c0b94a68f88d98ff39c11471ac55ffbcb22cd7ab41010c1476a75/web3-4.8.2-py3-none-any.whl (124kB)
100% |████████████████████████████████| 133kB 87.2MB/s
Requirement already satisfied: hexbytes<1.0.0,>=0.1.0 in /usr/local/lib/python3.7/site-packages (from web3) (0.1.0)
Requirement already satisfied: eth-utils<2.0.0,>=1.2.0 in /usr/local/lib/python3.7/site-packages (from web3) (1.4.1)
Requirement already satisfied: requests<3.0.0,>=2.16.0 in /usr/local/lib/python3.7/site-packages (from web3) (2.21.0)
Requirement already satisfied: lru-dict<2.0.0,>=1.1.6 in /usr/local/lib/python3.7/site-packages (from web3) (1.1.6)
Requirement already satisfied: eth-account<0.4.0,>=0.2.1 in /usr/local/lib/python3.7/site-packages (from web3) (0.3.0)
Collecting eth-abi<2.0.0,>=1.2.0 (from web3)
Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/e9/ef/5af786a32ae7ac3aece6489400ea2cee6b2ede7a7b3955e6f55a59442d12/eth_abi-1.3.0-py3-none-any.whl
Requirement already satisfied: eth-hash[pycryptodome]<1.0.0,>=0.2.0 in /usr/local/lib/python3.7/site-packages (from web3) (0.2.0)
Requirement already satisfied: cytoolz<1.0.0,>=0.9.0; implementation_name == "cpython" in /usr/local/lib/python3.7/site-packages (from web3) (0.9.0.1)
Requirement already satisfied: websockets<7.0.0,>=6.0.0 in /usr/local/lib/python3.7/site-packages (from web3) (6.0)
Requirement already satisfied: eth-typing<3.0.0,>=1.0.0 in /usr/local/lib/python3.7/site-packages (from eth-utils<2.0.0,>=1.2.0->web3) (2.0.0)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/site-packages (from requests<3.0.0,>=2.16.0->web3) (3.0.4)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.7/site-packages (from requests<3.0.0,>=2.16.0->web3) (1.24.1)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/site-packages (from requests<3.0.0,>=2.16.0->web3) (2018.11.29)
Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.7/site-packages (from requests<3.0.0,>=2.16.0->web3) (2.8)
Requirement already satisfied: eth-keys<0.3.0,>=0.2.0b3 in /usr/local/lib/python3.7/site-packages (from eth-account<0.4.0,>=0.2.1->web3) (0.2.1)
Requirement already satisfied: eth-keyfile<0.6.0,>=0.5.0 in /usr/local/lib/python3.7/site-packages (from eth-account<0.4.0,>=0.2.1->web3) (0.5.1)
Requirement already satisfied: attrdict<3,>=2.0.0 in /usr/local/lib/python3.7/site-packages (from eth-account<0.4.0,>=0.2.1->web3) (2.0.1)
Requirement already satisfied: eth-rlp<1,>=0.1.2 in /usr/local/lib/python3.7/site-packages (from eth-account<0.4.0,>=0.2.1->web3) (0.1.2)
Requirement already satisfied: parsimonious<0.9.0,>=0.8.0 in /usr/local/lib/python3.7/site-packages (from eth-abi<2.0.0,>=1.2.0->web3) (0.8.1)
Requirement already satisfied: pycryptodome<4,>=3.6.6; extra == "pycryptodome" in /usr/local/lib/python3.7/site-packages (from eth-hash[pycryptodome]<1.0.0,>=0.2.0->web3) (3.7.3)
Requirement already satisfied: toolz>=0.8.0 in /usr/local/lib/python3.7/site-packages (from cytoolz<1.0.0,>=0.9.0; implementation_name == "cpython"->web3) (0.9.0)
Requirement already satisfied: six in /usr/local/lib/python3.7/site-packages (from attrdict<3,>=2.0.0->eth-account<0.4.0,>=0.2.1->web3) (1.12.0)
Requirement already satisfied: rlp<2,>=0.6.0 in /usr/local/lib/python3.7/site-packages (from eth-rlp<1,>=0.1.2->eth-account<0.4.0,>=0.2.1->web3) (1.1.0)
tronapi 3.1.3 has requirement eth-abi<3.0.0,>=2.0.0b4, but you'll have eth-abi 1.3.0 which is incompatible.
Installing collected packages: eth-abi, web3
Found existing installation: eth-abi 2.0.0b5
Uninstalling eth-abi-2.0.0b5:
Successfully uninstalled eth-abi-2.0.0b5
Successfully installed eth-abi-1.3.0 web3-4.8.2

pip3 install tronapi
Looking in indexes: http://mirrors.cloud.aliyuncs.com/pypi/simple/
Requirement already satisfied: tronapi in /usr/local/lib/python3.7/site-packages (3.1.3)
Collecting eth-abi<3.0.0,>=2.0.0b4 (from tronapi)
Downloading http://mirrors.cloud.aliyuncs.com/pypi/packages/63/0d/416f32bf6a4ce2b929c1749f0efaf5b33b6ed80d3928869b48dd458f018e/eth_abi-2.0.0b5-py3-none-any.whl
Requirement already satisfied: eth-account<0.4.0,>=0.2.1 in /usr/local/lib/python3.7/site-packages (from tronapi) (0.3.0)
Requirement already satisfied: eth-utils<2.0.0,>=1.3.0 in /usr/local/lib/python3.7/site-packages (from tronapi) (1.4.1)
Requirement already satisfied: trx-utils in /usr/local/lib/python3.7/site-packages (from tronapi) (1.0.4)
Requirement already satisfied: hexbytes<1.0.0,>=0.1.0 in /usr/local/lib/python3.7/site-packages (from tronapi) (0.1.0)
Requirement already satisfied: requests<3.0.0,>=2.16.0 in /usr/local/lib/python3.7/site-packages (from tronapi) (2.21.0)
Requirement already satisfied: pycryptodome in /usr/local/lib/python3.7/site-packages (from tronapi) (3.7.3)
Requirement already satisfied: base58 in /usr/local/lib/python3.7/site-packages (from tronapi) (1.0.3)
Requirement already satisfied: ecdsa in /usr/local/lib/python3.7/site-packages (from tronapi) (0.13)
Requirement already satisfied: attrdict in /usr/local/lib/python3.7/site-packages (from tronapi) (2.0.1)
Requirement already satisfied: cytoolz<1.0.0,>=0.9.0 in /usr/local/lib/python3.7/site-packages (from tronapi) (0.9.0.1)
Requirement already satisfied: eth-typing<3.0.0,>=2.0.0 in /usr/local/lib/python3.7/site-packages (from eth-abi<3.0.0,>=2.0.0b4->tronapi) (2.0.0)
Requirement already satisfied: parsimonious<0.9.0,>=0.8.0 in /usr/local/lib/python3.7/site-packages (from eth-abi<3.0.0,>=2.0.0b4->tronapi) (0.8.1)
Requirement already satisfied: eth-keys<0.3.0,>=0.2.0b3 in /usr/local/lib/python3.7/site-packages (from eth-account<0.4.0,>=0.2.1->tronapi) (0.2.1)
Requirement already satisfied: eth-keyfile<0.6.0,>=0.5.0 in /usr/local/lib/python3.7/site-packages (from eth-account<0.4.0,>=0.2.1->tronapi) (0.5.1)
Requirement already satisfied: eth-rlp<1,>=0.1.2 in /usr/local/lib/python3.7/site-packages (from eth-account<0.4.0,>=0.2.1->tronapi) (0.1.2)
Requirement already satisfied: eth-hash<1.0.0,>=0.1.0 in /usr/local/lib/python3.7/site-packages (from eth-utils<2.0.0,>=1.3.0->tronapi) (0.2.0)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/site-packages (from requests<3.0.0,>=2.16.0->tronapi) (2018.11.29)
Requirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.7/site-packages (from requests<3.0.0,>=2.16.0->tronapi) (2.8)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.7/site-packages (from requests<3.0.0,>=2.16.0->tronapi) (1.24.1)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.7/site-packages (from requests<3.0.0,>=2.16.0->tronapi) (3.0.4)
Requirement already satisfied: six in /usr/local/lib/python3.7/site-packages (from attrdict->tronapi) (1.12.0)
Requirement already satisfied: toolz>=0.8.0 in /usr/local/lib/python3.7/site-packages (from cytoolz<1.0.0,>=0.9.0->tronapi) (0.9.0)
Requirement already satisfied: rlp<2,>=0.6.0 in /usr/local/lib/python3.7/site-packages (from eth-rlp<1,>=0.1.2->eth-account<0.4.0,>=0.2.1->tronapi) (1.1.0)
web3 4.8.2 has requirement eth-abi<2.0.0,>=1.2.0, but you'll have eth-abi 2.0.0b5 which is incompatible.
Installing collected packages: eth-abi
Found existing installation: eth-abi 1.3.0
Uninstalling eth-abi-1.3.0:
Successfully uninstalled eth-abi-1.3.0
Successfully installed eth-abi-2.0.0b5

File "checkblock.py", line 14, in
from web3 import Web3
File "/usr/local/lib/python3.7/site-packages/web3/init.py", line 8, in
from web3.main import Web3 # noqa: E402
File "/usr/local/lib/python3.7/site-packages/web3/main.py", line 16, in
from web3.eth import Eth
File "/usr/local/lib/python3.7/site-packages/web3/eth.py", line 13, in
from web3.contract import (
File "/usr/local/lib/python3.7/site-packages/web3/contract.py", line 33, in
from web3.utils.abi import (
File "/usr/local/lib/python3.7/site-packages/web3/utils/abi.py", line 10, in
from eth_abi.abi import (
ImportError: cannot import name 'collapse_type' from 'eth_abi.abi' (/usr/local/lib/python3.7/site-packages/eth_abi/abi.py)

attrdict==2.0.1
base58==1.0.3
bitcoin==1.1.39
blockcypher==1.0.73
certifi==2018.11.29
chardet==3.0.4
cytoolz==0.9.0.1
ecdsa==0.13
eth-abi==2.0.0b5
eth-account==0.3.0
eth-hash==0.2.0
eth-keyfile==0.5.1
eth-keys==0.2.1
eth-rlp==0.1.2
eth-typing==2.0.0
eth-utils==1.4.1
hexbytes==0.1.0
idna==2.8
lru-dict==1.1.6
parsimonious==0.8.1
pycryptodome==3.7.3
python-dateutil==2.2
requests==2.21.0
rlp==1.1.0
six==1.12.0
toolz==0.9.0
tronapi==3.1.3
trx-utils==1.0.4
urllib3==1.24.1
web3==4.8.2
websockets==6.0

No module named 'tronapi.providers'

Traceback (most recent call last):
File "alert.py", line 1, in
from tronapi import Tron
File "/usr/local/lib/python3.6/site-packages/tronapi/init.py", line 12, in
from tronapi.providers.http import HttpProvider # noqa: E402
ModuleNotFoundError: No module named 'tronapi.providers'

Energy and bandwith

How can i get value energy and bandwith on python tron api? is it possible?

TRC10 SELL transaction for poloniex

Hi I'm use this lib for work with polonium api and make transactions to exchange
every transactions is working except sell trc10 tokens

I.m use this code for make transaction

            order_symbol_Poloniex = 1002000

            buy_Trc10 = self.tron.transaction_builder.trigger_smart_contract(
                contract_address=trc10Contract,
                function_selector='sellOrder(trcToken,uint256,uint256,uint256)',
                fee_limit=10000000,
                token_id=1002000,
                token_value=0,
                parameters=[
                    {'type': 'int256', 'value': order_symbol_Poloniex},
                    {'type': 'int256', 'value': order_quantity_Poloniex},
                    {'type': 'int256', 'value': value_2symbol_Poloniex},
                    {'type': 'int256', 'value': order_price_Poloniex},])
            buy_Trc10_sign = buy_Trc10['transaction']
            buy_Trc10_signb = Trx(self.tron)
            buy_Trc10_signb.sign_and_broadcast(buy_Trc10_sign)
            return buy_Trc10 ```

but if token_id or token_value there then 0  I got exception


```File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tronapi/transactionbuilder.py", line 595, in trigger_smart_contract
    data.token_id = int(token_id)
AttributeError: 'dict' object has no attribute 'token_id'````

all transactions have fail status 

where is mistake?

Receiving KeyError: 'raw_data'

I wished to send a bet transaction to tronbot. I used below code for that
fee_limit =1000000000 multplier =1000000000 bet_value=10*multplier direction=0 rollvalue=50 parameters=[{"value":rollvalue,"type":"uint256"},{"value":direction,"type":"uint256"}] tx=tron.transaction_builder.trigger_smart_contract('TEEXEWrkMFKapSMJ6mErg39ELFKDqEs6w3','GoodLuck',fee_limit,bet_value,parameters,'TQR27jXR4dHdDtjE63MnnUQvecK97rop2y')

It produced below tx
{'result': {'result': True}, 'txid': '5deb501b657bc386aa2f015d175c2d1258aacf9f9c6a3bc3b57456e9d423ccb5', 'transaction': {'txID': '47a1328cb6f34b213f5abb9306fc67eeba7cd72feed24890d2372dd2fe370d9d', 'raw_data': {'contract': [{'parameter': {'value': {'data': '16bd160c00000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000000', 'owner_address': '419a536539b2bbdbadb5d2d45afcc1979065b4370c', 'contract_address': '412ec5f63da00583085d4c2c5e8ec3c8d17bde5e28', 'call_value': 10000000000}, 'type_url': 'type.googleapis.com/protocol.TriggerSmartContract'}, 'type': 'TriggerSmartContract'}], 'ref_block_bytes': '6014', 'ref_block_hash': '968c383e5d721d14', 'expiration': 1546249266000, 'fee_limit': 1000000000, 'timestamp': 1546249209653}}}

but when used "tx=tron.trx.sign(tx,True)" command to sign it then it gives above error.

Please see what is the issue or suggest how can i solve it. Thanks a lot

full error is given below

owner_address = transaction['raw_data']['contract'][0]['parameter']['value']['owner_address']

KeyError: 'raw_data'

Problem when send token

When I create a transaction to send a token, I get an error.

python3.6 test_new_api_tx.py
Traceback (most recent call last):
File "test_new_api_tx.py", line 14, in
send = tron.trx.send_token('TMESRzqhmeDeEGfNU636BKHsEUJCxW9mpJ',1,'TronLottery')
File "/usr/local/lib/python3.6/dist-packages/tronapi/trx.py", line 369, in send_token
account
File "/usr/local/lib/python3.6/dist-packages/tronapi/transactionbuilder.py", line 73, in send_token
raise InvalidTronError('Invalid amount provided')
tronapi.exceptions.InvalidTronError: Invalid amount provided

But TRC10 tokens use type integer. Therefore, if you correct a couple of lines of code in the kernel, the transaction is created successfully. Please correct the new release. Thank you!

tronapi/transactionbuilder.py:

    def send_token(self, to, amount, token_id, account):
    """Transfer Token

    Args:
        to (str): is the recipient address
        amount (float): is the amount of token to transfer
        token_id (str): Token Name(NOT SYMBOL)
        account: (str): is the address of the withdrawal account

    Returns:
        Token transfer Transaction raw data

    """
    if not self.tron.isAddress(to):
        raise InvalidTronError('Invalid recipient address provided')

    #if not isinstance(amount, float) or amount <= 0:
    if not is_integer(amount) or amount <= 0: <<<<<<<<<<<<<<<<<<<<<NEW
        raise InvalidTronError('Invalid amount provided')

    if not is_string(token_id) or not len(token_id):
        raise InvalidTronError('Invalid token ID provided')

    if not self.tron.isAddress(account):
        raise InvalidTronError('Invalid origin address provided')

    _to = self.tron.address.to_hex(to)
    _from = self.tron.address.to_hex(account)
    _token_id = self.tron.toHex(text=token_id)

    if _to == _from:
        raise TronError('Cannot transfer TRX to the same account')

    return self.tron.manager.request('/wallet/transferasset', {
        'to_address': _to,
        'owner_address': _from,
        'asset_name': _token_id,
        #'amount': self.tron.toSun(amount)
        'amount': amount    <<<<<<<<<<<<<<<<<<<<<NEW

})

:(

For a while working with this library and I can say that in addition to the existing bugs, it is not very convenient. Why is the Tron class, which is used to grant permissions to the tron account, named this way (Tron)? Why such a class has methods toBytes, to Int, to Hex and others, if it would be more logical to use them not on behalf of the object, but at least on behalf of the class (classmethod)?

Verify message Tronlink

Good afternoon, show me please an example of verification of the message signed tronlink. After signing I get a string of this type:

0x267363b76ac81738e22272c01e212483402f43474f8ac175420d563703470ce74486c6188f9da9ef27bad17ed7ef63797d11337be8b147fe1093de62cca66a7f1c

пытаюсь делать так:
tron.trx.verify_message(message=tron.toHex('123'), signed_message='0x267363b76ac81738e22272c01e212483402f43474f8ac175420d563703470ce74486c6188f9da9ef27bad17ed7ef63797d11337be8b147fe1093de62cca66a7f1c', address='TAQByCrjDDWrMWdDJqTFs5sPnvGb85q1cy')
but in response I get an error

"Unsupported type: The primitive argument must be one of: bytes,"
TypeError: Unsupported type: The primitive argument must be one of: bytes,bytearray, int or bool and not str

SIGERROR

Signing a raw transaction using tron.trx.sign() on version 3.0.5 (previously tron.trx.offline_sign() on version 3.0.2) returns SIGERROR
{'code': 'SIGERROR', 'message': 'validate signature error'}

API does not give Tether balance for any address

I am using below code to get token balance for an address:

`full_node = 'https://api.trongrid.io'
solidity_node = 'https://api.trongrid.io'
event_server = 'https://api.trongrid.io'

tron = Tron(full_node=full_node,
solidity_node=solidity_node,
event_server=event_server)

tron.private_key = 'my private key'
#tron.default_address = 'TQR27jXR4dHdDtjE63MnnUQvecK97rop2y'

account_info = tron.trx.get_account('TNaRAoLUyYEV2uF7GUrzSjRQTU8v5ZJ5VR')

print(account_info)
print(pd.DataFrame(account_info["asset"]))`

it does provide a dataframe of assets but tether balance is not there. And checked that this address has tether balance.

Pls help me out. thnx

Can I use Python to make a tron abi decoder?

I would like to read this result where is from trc usdt documents.
link:Trc usdt

constant_result is Hex type
Hex: 0000000000000000000000000000000000000000000000000000000000000020000000000
000000000000000000000000000000000000000000000000000000a5465746865722055534
400000000000000000000000000000000000000000000
Convert to decimal:Tether USD

trigger_smart_contract call_value and fee_limit values

When using the trigger_smart_contract function, are you expecting us to pass you the value already converted to SUN or do you do the conversion to SUN in your code? Best I can tell by looking at your code, you expect us to pass you the value in SUN.

eth-abi

Tell me you wrote that the problem was fixed, but dependencies still have the version "eth-abi> = 2.0.0b6, <3.0.0" and it turns python-api out does not work with web3

ModuleNotFoundError: No module named 'eth_abi.codec'

runtime error in function "TRIGGER_SMART_CONTRACT". AttributeError: 'AttributeDict' instance has no attribute 'hex'

hello,
thanks for the work you've done. Can you help with the problem, I'm new to the tron. I am running this script:

`from tronapi import Tron

tron = Tron()
tron.transaction_builder.trigger_smart_contract(
... contract_address = '41790f699c1fc02d1633b6c5687e0b8bd5ee2eb2c9',
... function_selector = 'returnAllAuctions()',
... fee_limit = 30000,
... issuer_address = 'TMTDUvyNMZr9vCD33wQHSytojUrNcANqy4',
... call_value=0,
... parameters=[]
... )
`

Unable to verify TronLink/TronWeb.js signed message in tron-api

Javascript Code for Signing Message:

const original_message = "557e3517549cf8ed47d8b205654ea2a7"
const signedtxn = await tronWeb.trx.sign(original_message);
// result 0x862e16c28684bed7162e9a1dd34962882d887610de6c775054ffbad989baec65707b2ba898366c02e9f20730bc2daf54bb7e6d33d77c64f8930f8c9365f5993a1b

Python Code for Verifying Signed Message

from tronapi import Tron
from hexbytes import HexBytes

tron = Tron()

class signed_message:
     # signedtxn variable in javascript
    signature = HexBytes('0x862e16c28684bed7162e9a1dd34962882d887610de6c775054ffbad989baec65707b2ba898366c02e9f20730bc2daf54bb7e6d33d77c64f8930f8c9365f5993a1b')

original_message = "557e3517549cf8ed47d8b205654ea2a7"
address = "<!-- Tron Base58 Address in TronLink/TronWeb -->"
tron.trx.verify_message(original_message, signed_message, address=address)

I am getting this error
ValueError: Signature does not match

how to use multisign?

hello, i'm insterested in this program, and i'm wondering if there are implement of multisign, or api that i can use?
looking forward to your reply ~ thank you

Still receiving revert error

Hello serderovsh,

I upgraded all the installations including tronapi but I still see the same problem. That transactions are being reverted. pls see latest as done just now
{'ret': [{'contractRet': 'REVERT'}], 'signature': ['8e7742b4ad0645f53a5c8002edd5460d86b1e194741a661651f0b63fec994c6f2bc8fb7c24be18b68958786874086a01a46ef56ece9aadb19bdf621c3c2b495c1c'], 'txID': 'a8091842b1a0c7eeca9c41f9579669ab2e7ee5901ba6e0d6d635d40ffffb3565', 'raw_data': {'contract': [{'parameter': {'value': {'data': '16bd160c00000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000000', 'owner_address': '419e737d5db19beafc2a9a813211cc73add2d3a872', 'contract_address': '412ec5f63da00583085d4c2c5e8ec3c8d17bde5e28', 'call_value': 10000000}, 'type_url': 'type.googleapis.com/protocol.TriggerSmartContract'}, 'type': 'TriggerSmartContract'}], 'ref_block_bytes': '4bc6', 'ref_block_hash': '3ef538e20d4c9c06', 'expiration': 1548241557000, 'fee_limit': 600000, 'timestamp': 1548241501491}}

could you please check to do it with tronbet or dice. I am getting this error for both of them I tried.

I appreciate all the help you provide.

Thanks and Regards,

Transaction expiration

Hi,

I'm using this repository for Tron transaction. I found that expiration time for each transaction is set to 60 seconds in Java source codes. How can I increase expiration time using tron-api-python?
If it's not possible in python, how can I solve it anyway?

output :
[{'code': 'TRANSACTION_EXPIRATION_ERROR', 'message': 'transaction expired'}]

problem when send transaction

code

tron = Tron(full_node=full_node,
        solidity_node=solidity_node,
        event_server=event_server)
balance = tron.trx.get_balance(address="418f48df84f242a7828ccb07e1ad6d087490277c9b")
# result = tron.trx.get_transaction('TxId')
tron.private_key = '3a1d6b03cd151bfbaa360fdaedb9943d275a7a0a86e3f1ebdee77e715485f8a7'
tron.default_address = '418f48df84f242a7828ccb07e1ad6d087490277c9b'

# added message
send = tron.trx.send_transaction('41a858daf83d105dd94c6e9cca1b50894c9c773b17', 1000.0, {})

then

Traceback (most recent call last):
  File "/Users/jay/Desktop/selfcode/trx/try.py", line 27, in <module>
    send = tron.trx.send_transaction('41a858daf83d105dd94c6e9cca1b50894c9c773b17', 1000.0, {})
  File "/Users/jay/anaconda3/envs/wallet/lib/python3.6/site-packages/tronapi/trx.py", line 344, in send_transaction
    sign = self.sign(tx)
  File "/Users/jay/anaconda3/envs/wallet/lib/python3.6/site-packages/tronapi/trx.py", line 486, in sign
    address = self.tron.address.from_private_key(self.tron.private_key).hex.lower()
  File "/Users/jay/anaconda3/envs/wallet/lib/python3.6/site-packages/tronapi/base/account.py", line 35, in from_private_key
    return PrivateKey(private_key).address
  File "/Users/jay/anaconda3/envs/wallet/lib/python3.6/site-packages/tronapi/base/account.py", line 46, in __init__
    _private = unhexlify(bytes(private_key, encoding='utf8'))
TypeError: encoding without a string argument

what should i do,I tried a lot about methods of str and bytes

Python36 create account error

File "C:\Python\Python36-32\lib\site-packages\tronapi\common\account.py", line 96, in address
'base58': to_base58.decode()
AttributeError: 'str' object has no attribute 'decode'

fix for python3:
'base58': to_base58

passing an array as an argument to the contract method

tell me how to be, I can’t solve the problem, there is a method in the contract that takes arrays as parameters:

function_selector='pay_royaltie(address [], uint256[], uint256[])',

how do I generate transaction data correctly, i do so:

row_trans = tron.transaction_builder.trigger_smart_contract(
    contract_address=CONTRACT_TRX,
    function_selector='pay_royaltie(address [], uint256[], uint256[])',
    # fee_limit=30000,
    call_value=25000000000,
    parameters=[
        [{'type': 'address', 'value': 'TmklXhXjgXTj87trNujkWFuXtQP8sCWZZV'}],
        [{'type': 'int256', 'value': 2}],
        [{'type': 'int256', 'value': int(3)}],
    ]
)

and half tea the next mistake:

raise ValueError('Invalid parameter type provided: ' + abi['type'])
TypeError: list indices must be integers or slices, not str in transactionbuilder.py", line 563, in trigger_smart_contract

Examples do not show how to include owner details

I find that the documentation/examples do not mention how to create the tron instance with contract owner information. After reading the source code I was able to figure out the following code and it works. Without this, I kept getting errors during the contract deploy step.

test_url = 'https://api.shasta.trongrid.io'
tron = Tron(full_node=test_url, solidity_node=test_url, event_server=test_url,
            private_key='af2389b556*****',        # my private key
            default_address='TQB3j6w7****')     # my tron address

Any chance to update the document to include the following information?

Mistabke in to_tron and from_tron

Maybe wrong.
I mean.

    @staticmethod
    def to_tron(amount):
        """Преобразовываем сумму в формат Tron
        Args:
            amount (float): Сумма
        """
        return math.floor(amount * 1e6)

    @staticmethod
    def from_tron(amount):
        """Преобразовываем сумму из формата Tron
        Args:
            amount (int): Сумма
        """
        return abs(amount) / pow(10, 6)

Is it opposite?
to_tron is abs(amount) / pow(10, 6)
from_tron is math.floor(amount * 1e6)

Add origin_energy_limit

This is currently supported using the existing code base due to the way keyword arguments are passed in:

with open("HelloWorldtron.json") as FILE:
    contract = json.load(FILE)

contract = ContractConstructor(
    tron,
    abi=contract['abi'],
    bytecode=to_bytes(text=contract['bytecode'])
)
tx = contract.transact(
    fee_limit=10**9,
    call_value=0,
    origin_energy_limit=9999
)

sign = tron.trx.sign(tx)
result = tron.trx.broadcast(sign)

However, if omitted (which it is in all examples), then the transaction will get rejected by a network running java-tron 3.2 or higher with an ambiguous CONTRACT_VALIDATE_ERROR. Validation should be added as well, such as:

        # Maximum energy consumption limit
        origin_energy_limit = kwargs.setdefault('origin_energy_limit ', 0)

        ...

        if not is_integer(origin_energy_limit) or origin_energy_limit < 0 or origin_energy_limit > 10 ** 9:
            raise ValueError('Invalid energy limit provided')

Bug in tronapi.trx.Trx.verify_message/sign.

Code example
TRON_SETTINGS = {
    'full_node': 'https://api.shasta.trongrid.io',
    'solidity_node': 'https://api.shasta.trongrid.io',
    'event_server': 'https://api.shasta.trongrid.io',
}

tron = tronapi.Tron(**TRON_SETTINGS)

account = tron.create_account  # XXX: create_account is property.
tron.private_key = account.private_key
tron.default_address = account.address.base58

message = tron.toHex(text='hello')
signed = tron.trx.sign(message)

tron.trx.verify_message(message, signed)

Result is always ValueError: Signature does not match.

I've inspected tronapi.trx.Trx.sign and tronapi.trx.Trx.verify_message and found that they have different code for header definition:

tronapi.trx.Trx.sign
            # Determine which header to attach to the message
            # before encrypting or decrypting
            header = TRX_MESSAGE_HEADER if use_tron else ETH_MESSAGE_HEADER
            header += str(len(transaction))

            message_hash = self.tron.keccak(text=header+transaction)
tronapi.trx.Trx.verify_message
        # Determine which header to attach to the message
        # before encrypting or decrypting
        header = TRX_MESSAGE_HEADER if use_tron else ETH_MESSAGE_HEADER

        message_hash = self.tron.keccak(text=header+message)

Adding header += str(len(message)) string into tronapi.trx.Trx.verify_message fixes the problem.

Get transactions to an address

I'm trying to extract what transactions have been sent to an address by using the tron.trx.get_transactions_related and tron.trx.get_transactions_to_address functions but when I do these, they error out.

tron.trx.get_transactions_to_address(addr)
2019-05-19 10:26:21,576 - DEBUG - Resetting dropped connection: api.trongrid.io
2019-05-19 10:26:22,138 - DEBUG - https://api.trongrid.io:443 "GET /walletextension/gettransactionstothis HTTP/1.1" 302 26
2019-05-19 10:26:22,246 - DEBUG - https://api.trongrid.io:443 "GET /404 HTTP/1.1" 404 43
Traceback (most recent call last):
File "", line 1, in
File "/root/tron_tx/lib/python3.6/site-packages/tronapi/trx.py", line 293, in get_transactions_to_address
return self.get_transactions_related(address, 'to', limit, offset)
File "/root/tron_tx/lib/python3.6/site-packages/tronapi/trx.py", line 275, in get_transactions_related
}, 'get')
File "/root/tron_tx/lib/python3.6/site-packages/tronapi/manager.py", line 122, in request
return self.solidity_node.request(url, json=params, method=method)
File "/root/tron_tx/lib/python3.6/site-packages/tronapi/providers/http.py", line 89, in request
**self.get_request_kwargs(),
File "/root/tron_tx/lib/python3.6/site-packages/tronapi/providers/http.py", line 126, in _request
raise exc_cls(response.status_code, text, json, kwargs.get('url'))
tronapi.exceptions.NotFoundError: (404, '{"error":{"code":404,"status":"Not Found"}}', {'error': {'code': 404, 'status': 'Not Found'}}, 'https://api.trongrid.io/walletextension/gettransactionstothis')

How to transfer trc20 token?

While we can transfer trc20 tokens via extensions but I could not find a code to transfer by python, do you have any idea?

How can i transaction TRC20 tokens?

send_token is used for trc10 , i want to trans trc20 ? the main issue is how do i use the tron-api-python to call trc20 contract interface.
can you help me?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.