andelf / tronpy Goto Github PK
View Code? Open in Web Editor NEWTRON Python Client Library.
License: MIT License
TRON Python Client Library.
License: MIT License
Could it be possible signing a transaction with multisignature permission? I've seen that with the sign function, signing is only possible via private key.
Thanks
Hello,
I have an issue sending from a multisign address, what cause to get that error?
on the web i can send by using that private key but using tronpy, It seems i miss something
what is the correct way?
contract.functions.transfer(TC2r7dPEfMaMt8ToJ3rQ7SuVhX391cFhv5, 100_000_000)
.with_owner("TGihHToJJ9B1NFi2Vx5bTM8muRmsbdAaJ8") # address of the private key
.fee_limit(20_000_000)
.build()
.sign(priv_key)
print(txn.txid)
print(txn.broadcast().wait())
tronpy.exceptions.BadKey: ('provided private key is not in the permission list', 'provided TGihHToJJ9B1NFi2Vx5bTM8muRmsbdAaJ8', "required {'keys': [{'address': '4163cdf133fcf4beb05881fb4b5d2b0ccf938a52af', 'w
eight': 1}], 'threshold': 1, 'permission_name': 'owner'}")
how to send all balance of TRX?
when i want send using balance as amout, that alwalys fail.
balance = client.get_account_balance(address)
Looking into the TRC20 or ERC20 token.
How do we query the transaction note/memo from specific hash_id or transaction_id ?
Got error tronpy.exceptions.AddressNotFound: account not found on-chain
When I try to get Balance of address.
Code :
from tronpy import Tron
from pprint import pprint
client = Tron(network='nile')
address=client.generate_address()['base58check_address']
pprint(client.get_account_balance(address))
Traceback :
Traceback (most recent call last):
File "tron.py", line 9, in <module>
pprint(client.get_account_balance(address))
File "G:\BOT\tipbot\env\lib\site-packages\tronpy\tron.py", line 517, in get_account_balance
info = self.get_account(addr)
File "G:\BOT\tipbot\env\lib\site-packages\tronpy\tron.py", line 501, in get_account
raise AddressNotFound("account not found on-chain")
tronpy.exceptions.AddressNotFound: account not found on-chain
I tried to create a trx transaction on shasta network and passing correct private key using tronweb for python but it's giving this error
{'code': 'SIGERROR',
'txid': '44212bea170d07e2c83c5a4c1ba96e6617165474401f8af1e2a7f3c6f09257d6',
'message': 'Validate signature error: bc9d036b9f7f2a1d1b9688aafef323484b4bc0836faedb52168b4d6f47c780824840d8a9c3904863453b69e875f62106743aecf9d2c912d4911ca00839632aea1c is signed by TNBWAv3eDZ3W9c61etU34DEy2X1kx5v6m5 but it is not contained of permission.'}
my script is as follows
from tronapi import Tron
import json
full_node = 'https://api.shasta.trongrid.io'
solidity_node = 'https://api.shasta.trongrid.io'
event_server = 'https://api.shasta.trongrid.io'
tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server)
tron.private_key = private_key
tron.default_address = sender_address
txn = tron.trx.send_transaction(to=receiver_address, amount=amount, options={
'from': sender_address,
'message': memo_text
})
txn = (
contract.functions.transfer(to, amounts)
.with_owner(address)
.fee_limit(5_000_000)
.build()
.sign(key1)
.inspect()
.broadcast()
)
see
https://tronscan.org/#/transaction/a1abdd2dd4b319abbe690225f237eaa309eb07522574b7657c72e7a8be0f3027
i see it always extra 345 Bandwidth but how to deal it
tronpy.exceptions.ValidationError: contract validate error : account does not exist
Traceback (most recent call last):
File "E:/PycharmProjects/MBE/common/http_client.py", line 134, in
test.get_user_addr_balance('TTMEUk3Y3nGx6HTfbCrEPct6KQNJcV7Wnz')
File "E:/PycharmProjects/MBE/common/http_client.py", line 17, in get_user_addr_balance
response = self.client.get_account_balance(addr)
File "E:\PycharmProjects\MBE\venv\lib\site-packages\tronpy\tron.py", line 548, in get_account_balance
info = self.get_account(addr)
File "E:\PycharmProjects\MBE\venv\lib\site-packages\tronpy\tron.py", line 532, in get_account
raise AddressNotFound("account not found on-chain")
tronpy.exceptions.AddressNotFound: account not found on-chain
TTMEUk3Y3nGx6HTfbCrEPct6KQNJcV7Wnz can be logged in
Hi @andelf. I noticed that logic was added two weeks ago to parse event logs, but there hasn't been a release since these changes. Could you please publish a new version when you can?
Secondly, I noticed that the Contract
class doesn't have a field for code_hash
, which is one of the keys returned in each contract object by Tron nodes. According to the Tron docs, it's the hash of the bytecode for the contract. See here for more.
Thanks!
Hello budy, how are you?
I had a problem with your library when trying to call the contract builder. When I create my contract in Solidity and compile it, it generates the abi and the byte code for me. However, an error is returned saying that my constructor does not exist. I noticed that in line 156 in the file 'contract.py' you check if the type is equal to "Constructor" but the generated abi is with the letter 'C' lowercase. I suggest replacing the line with:
method_abi['type'] == "constructor"
Thanks in advance!
Had an Issue were I was getting Transaction Expired when creating a transaction. After going through the documentation I had to modify the TransactionBuilder class by addding set_expiration below:
def set_expiration(self, expiration: int) -> "TransactionBuilder":
self._raw_data['expiration'] = current_timestamp() + expiration
return self
Is there a reason why the option to set expiration was added?
Currently, using Trongrid request Shasta/Nile testnet does not require an API Key.
Whether Tronpy supports API Key Settings of official TRON nodes
See-also: #14
I Believe that the key-address pair is correct? 🤔
>>> from tronpy import Tron
>>> from tronpy.keys import PrivateKey
>>>
>>> client = Tron(network='nile')
>>> # Private key of TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3
>>> priv_key = PrivateKey(bytes.fromhex("8888888888888888888888888888888888888888888888888888888888888888"))
>>>
>>> txn = (
... client.trx.transfer("TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000)
... .memo("test memo")
... .build()
... .inspect()
... .sign(priv_key)
... .broadcast()
... )
{'permission': {'keys': [{'address': '4162f94e9ac9349bccc61bfe66ddade6292702ecb6',
'weight': 1},
{'address': '417e5f4552091a69125d5dfcb7b8c2659029395bdf',
'weight': 1}],
'permission_name': 'owner',
'threshold': 2},
'raw_data': {'contract': [{'parameter': {'type_url': 'type.googleapis.com/protocol.TransferContract',
'value': {'amount': 1000,
'owner_address': '4162f94e9ac9349bccc61bfe66ddade6292702ecb6',
'to_address': '41d8dd39e2dea27a40001884901735e3940829bb44'}},
'type': 'TransferContract'}],
'data': '74657374206d656d6f',
'expiration': 1642777410792,
'ref_block_bytes': '84a7',
'ref_block_hash': 'f2c34569be1693be',
'timestamp': 1642777350792},
'signature': [],
'txID': '371b97a79c326eca1260695d3b58502d3b704662fd037b583e19dab76354f1f0'}
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/stuff/tronpy/tronpy/tron.py", line 170, in broadcast
return TransactionRet(self._client.broadcast(self), client=self._client, method=self._method)
File "/stuff/tronpy/tronpy/tron.py", line 902, in broadcast
self._handle_api_error(payload)
File "/stuff/tronpy/tron.py", line 542, in _handle_api_error
raise BadSignature(msg)
tronpy.exceptions.BadSignature: Validate signature error: sig error
Could you show an example of message verify in tronpy? I sign messages like this:
const original_message = "hello" const signedtxn = await tronWeb.trx.sign(original_message);
Slash in the first of this line cause instead of the url like to https://example.com/trx-fullnode/wallet/broadcasttransaction convert to https://example.com/wallet/broadcasttransaction
Line 869 in 9e869fb
Hello,
I am trying to decode TriggerSmartContract data parameter but getting error "Padding bytes were not empty"
trx_abi.decode_abi(['address', 'uint256'], bytes.fromhex(param['data']))
please tell me how can I decode.
'httpx==0.16.1' -- it's too strict version.
So it's impossible to use tronpy in the projects with other deps which also use httpx as deps. httpx is 0.18.2 now
Hello Sir.
I couldn't find any way to select a token and Transfer it via tronpy Please Help me.
The field "name" definitely does not exist in class ContractConstructor.
Line 216 in 531cd31
Hi everyone! Did anyone using tronpy in production experience something like a memory leak?
From my tests using aiohttp memory usage was more stable than with httpx, so maybe we should replace it?
Traceback (most recent call last):
File "C:/projects/bitcoin/python_tron_api/study/example_wallet2.py", line 40, in
asyncio.run(transfer())
File "C:\vnstudio\lib\asyncio\runners.py", line 43, in run
return loop.run_until_complete(main)
File "C:\vnstudio\lib\asyncio\base_events.py", line 573, in run_until_complete
return future.result()
File "C:/projects/bitcoin/python_tron_api/study/example_wallet2.py", line 33, in transfer
txn_ret = await txn.sign(priv_key).broadcast()
File "C:\projects\bitcoin\python_tron_api\tronpy\async_tron.py", line 185, in broadcast
return AsyncTransactionRet(await self._client.broadcast(self), client=self._client, method=self._method)
File "C:\projects\bitcoin\python_tron_api\tronpy\async_tron.py", line 898, in broadcast
self._handle_api_error(payload)
File "C:\projects\bitcoin\python_tron_api\tronpy\async_tron.py", line 524, in _handle_api_error
raise BadSignature(msg)
tronpy.exceptions.BadSignature: Validate signature error: sig error
get_account_balance function get only TRX.
How can I get other tokens in the account?
Freezing balance on nile stopped working, returned error with tronpy 0.3.0 (and 0.2.x):
Contract validate error : freeze v2 is open, old freeze is closed
<tronpy.tron.Tron object at 0x0000018C27137FA0>
client.generate_zkey()
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\wallet\venv\lib\site-packages\tronpy\tron.py", line 498, in generate_zkey
return self.provider.make_request("wallet/getnewshieldedaddress")
File "C:\Users\wallet\venv\lib\site-packages\tronpy\providers\http.py", line 80, in make_request
resp.raise_for_status()
File "C:\Users\wallet\venv\lib\site-packages\requests\models.py", line 1021, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://api.trongrid.io/wallet/getnewshieldedaddress
When I try to send a transaction, the script shows that the transaction has expired and nothing helps me(at async version same error)
def transfer(self,dist_address: str,amount: float=0.0,memo: str="",fee: float=0.0)->dict:
"""Transfer trx to another wallet"""
while True:
try:
txn =(self.blockchain.trx.transfer(self.address, dist_address, int(amount*1_000_000))
#.fee_limit(int(fee*1_000_000))
#.with_owner(self.address)
.build()
.sign(self.priv_key)
.broadcast()
).wait(timeout=60)
if 'id' in txn.keys() and txn['id']:
return True,txn['id']
except Exception as e:
print(e)
time.sleep(2)
continue
I get this error when updating httpx to its latest version, which is needed by other libraries
tronpy 0.2.6 requires httpx<0.17.0,>=0.16.1, but you have httpx 0.23.0 which is incompatible.
This project is not sponsored by BitcartCC.
Why there's a link on README?
I want to know if code below in the section .sign(priv_key) is it sign the transaction locally offline and just broadcast it or not?
what is the safe way to send trc20 token>?
`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()
.inspect()
.sign(priv_key)
.broadcast()
)
print(txn)
print(txn.wait())
Python: 3.7
tronpy: 0.1.5
error:
>> tronpy.Tron().get_block(24223718)
{'Error': 'class com.alibaba.fastjson.JSONException : unclosed string : _'}
I found only block 24223718
have problems.
I've reported this to Tron offical telegram group, no reply yet.
But:
tron.py:
def get_block(self, id_or_num: Union[None, str, int] = None) -> dict:
"""Get block from a block id or block number."""
if isinstance(id_or_num, (int,)):
block = self.provider.make_request("wallet/getblockbynum", {"num": id_or_num, "visible": True})
elif isinstance(id_or_num, (str,)):
block = self.provider.make_request("wallet/getblockbyid", {"value": id_or_num, "visible": True})
elif id_or_num is None:
block = self.provider.make_request("wallet/getnowblock", {"visible": True})
else:
raise TypeError("can not infer type of {}".format(id_or_num))
if block:
return block
else:
raise BlockNotFound
"wallet/getblockbynum", "wallet/getblockbyid", "wallet/getnowblock" do not have the "visible" parameter now (maybe exists before)
ref: https://developers.tron.network/reference#walletgetblockbynum
Hello,
Can you explain me the ways for getting address from private key ?
Thanks
from tronpy import Tron
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/site-packages/tronpy/__init__.py", line 1, in <module>
from tronpy.tron import Tron
File "/usr/local/lib/python3.8/site-packages/tronpy/tron.py", line 8, in <module>
from tronpy.contract import Contract, ShieldedTRC20, ContractMethod
File "/usr/local/lib/python3.8/site-packages/tronpy/contract.py", line 5, in <module>
from tronpy.abi import trx_abi
File "/usr/local/lib/python3.8/site-packages/tronpy/abi.py", line 4, in <module>
from eth_abi.registry import BaseEquals
File "/usr/local/lib/python3.8/site-packages/eth_abi/registry.py", line 15, in <module>
from . import (
File "/usr/local/lib/python3.8/site-packages/eth_abi/grammar.py", line 9, in <module>
from eth_abi.exceptions import (
ImportError: cannot import name 'ABITypeError' from 'eth_abi.exceptions' (/usr/local/lib/python3.8/site-packages/eth_abi/exceptions.py)
I want to know, how can I get the balance of trx20 tokens of an address and get the list of transactions of a certain address, which bothered me for 2 months, I'm sorry I didn't find them from the source code and documentation
Hello,
I just want remembering you to implement a method that claim tron rewards (for voting for super representatives) .
Thank you,
This is my function:
async def create_account():
async with AsyncTron(provider=AsyncHTTPProvider(api_key=[tronAPI1, tronAPI2, tronAPI3])) as client:
print(client)
Exception ignored in: <function AsyncClient.del at 0x0000021029ED0820>
Traceback (most recent call last):
File "C:\Python38\lib\site-packages\httpx_client.py", line 1780, in del
if self._state == ClientState.OPENED:
AttributeError: 'AsyncClient' object has no attribute '_state'
I earnestly ask you to translate the project under eth-abi>=3.0.1
My private node can get the latest block,
client = Tron(HTTPProvider("my_address"))
client.get_latest_block_number()
Works fine, but client.generate_address() throws an error
The error message displayed is: account not found on-chain
I think it has something to do with me not filling in the api, but how does the private full node get the api?
From the examples it seems like everybody joins test network
clien = Toron(network='nile')
however, I want to know how to connect to main Tron network, so if i generate the wallet, I can check it in tronscan?
File "/usr/local/lib/python3.9/dist-packages/tronpy/tron.py", line 153, in broadcast
return TransactionRet(self._client.broadcast(self), client=self._client, method=self._method)
File "/usr/local/lib/python3.9/dist-packages/tronpy/tron.py", line 826, in broadcast
self._handle_api_error(payload)
File "/usr/local/lib/python3.9/dist-packages/tronpy/tron.py", line 474, in _handle_api_error
raise UnknownError(msg, payload["code"])
tronpy.exceptions.UnknownError: ('Error: Index: 0', 'OTHER_ERROR')
NOTE: This library should not be used in production settings, see Security for more details.
Hello!
Is there any way to get raw_data_hex before broadcasting transaction?
I need that to calculate estimated net usage and find out if address net limit is enough for free transaction. Or may be there is another way to check if transaction will be free or not?
Thanks!
Will tronpy support Tron Stake 2.0(Now Nile has already opened functional test for Stake 2.0)?
ref:
tronprotocol/tips#484
https://coredevs.medium.com/what-is-stake-2-0-e04f59b948a6
Python: 3.7.8
tronpy: 0.1.3(0.1.2测试没问题)
tron.py 777行 def trigger_const_smart_contract_function
内
msg = ret['result']['message']
KeyError: 'message'
USDT-转帐
TransactionRet: {'result': True, 'txid': '0b9c085adefee7a40b98c905eedf1ea6a7310ea7f23a17c55c1ee5cc5c21b977'}
TransactionInfo:
{'id': '0b9c085adefee7a40b98c905eedf1ea6a7310ea7f23a17c55c1ee5cc5c21b977', 'fee': 146310, 'blockNumber': 23267640, 'blockTimeStamp': 1600078473000, 'contractResult': ['0000000000000000000000000000000000000000000000000000000000000000'], 'contract_address': 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', 'receipt': {'energy_fee': 146310, 'energy_usage_total': 14631, 'net_usage': 383, 'result': 'SUCCESS'}, 'log': [{'address': 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t', 'topics': ['ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef', '000000000000000000000000651e3e99bc10b26731696cc674e487dd2e3c532d', '0000000000000000000000004dbaaf85d6d476dbd73fd361cfa315dd8474b81a'], 'data': '0000000000000000000000000000000000000000000000000000000000002710'}]}
I run a Tron Full Node to generate new address, send(transfer) and get received by address transactions list (like bitcoin). But I don't know what is difference between tronpy and wallet-cli?
What is difference between client = Tron()
and client = Tron(HTTPProvider("http://127.0.0.1:8090"))
?
If I can do this works using client = Tron()
, so what is benefit of launch a tron node?
txn = (
... contract.functions.transfer('to address ', 1_000)
... .with_owner('address ') # address of the private key
... .fee_limit(5_000_000)
... .build()
... .sign(priv_key)
... )
An error:
Traceback (most recent call last):
File "zz.py", line 16, in
.sign(priv_key)
NameError: name 'priv_key' is not defined
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.