def instantiate_tronapi(pk, net): node_url = generate_tron_url(network=net) tron = Tron(full_node=node_url, solidity_node=node_url, event_server=node_url, private_key=pk) tron.private_key = pk tron.default_address = tron.address.from_private_key( tron.private_key).base58 return tron
def dashboard(): user = User.query.filter_by(username=session["user"]["username"]).first() tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server) tron.private_key = user.private_key tron.default_address = session["user"]["address"] balance = tron.trx.get_balance() / 1000000 if request.method == "POST": amount = request.form.get("amount").strip() address = request.form.get("address").strip() password = request.form.get("password") try: amount = float(amount) except: flash("You have supplied an invalid withdrawal amount", "danger") return redirect(url_for("dashboard")) if amount > balance: flash("You cannot withdraw more than your account balance", "danger") return redirect(url_for("dashboard")) if not tron.isAddress(address): flash("The withdrawal address provided is not valid", "danger") return redirect(url_for("dashboard")) if address == session["user"]["address"]: flash("You cannot withdraw to your own wallet", "danger") return redirect(url_for("dashboard")) if encrypt_password(password) != user.password: flash("The account password provided is not valid", "danger") return redirect(url_for("dashboard")) try: transaction = tron.trx.send(address, amount) if transaction["result"]: flash( f"Your withdrawal was successfully created, you can track your transaction <a href='https://tronscan.org/#/transaction/{transaction['txid']}' target='_blank'>here</a>", "success") return redirect(url_for("dashboard")) else: raise Exception() except: flash("An error occured when processing your withdrawal", "danger") return redirect(url_for("dashboard")) transactions = requests.get( f"https://api.trongrid.io/v1/accounts/{session['user']['address']}/transactions" ).json()["data"] return render_template("dashboard.html", balance=balance, transactions=transactions)
def register(): if request.method == "POST": email = request.form.get("email").strip().lower() username = request.form.get("username").strip().lower() password = request.form.get("password") if User.query.filter((User.email == email) | (User.username == username)).first(): flash("The account you are trying to create already exists", "danger") return redirect(url_for("register")) tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server) account = tron.create_account private_key = account.private_key address = account.address.base58 db.session.add( User(email=email, username=username, password=encrypt_password(password), private_key=private_key, address=address)) db.session.commit() flash("You have successfully registered your account", "success") return redirect(url_for("login")) return render_template("register.html")
def post(self): try: address = self.get_argument("address") if len(address) != 34 or (not str(address).startswith('T')): raise Exception("invalid address") trx = Trx( Tron(full_node=TRON_RPC_URL, solidity_node=TRON_RPC_URL, event_server=TRON_RPC_URL)) account_info = trx.get_account(address=address) if 'balance' in account_info: decBalance = Decimal( account_info['balance']) / Decimal('1000000') fmtBalance = str( decBalance.quantize(Decimal("0.000000"), getattr(decimal, 'ROUND_DOWN'))) else: fmtBalance = '0.000000' self.write( json.dumps(BaseHandler.success_ret_with_data(fmtBalance), default=decimal_default)) pass except Exception as e: self.write( json.dumps(BaseHandler.error_ret_with_data("error: %s" % e))) logging.error("error:{0} in {1}".format(e, get_linenumber()))
def post(self): try: trx = Trx( Tron(full_node=TRON_RPC_URL, solidity_node=TRON_RPC_URL, event_server=TRON_RPC_URL)) src_acct = self.get_argument("src_acct") dst_acct = self.get_argument("dst_acct") stramount = self.get_argument("amount") src_acct = src_acct.strip() dst_acct = dst_acct.strip() stramount = stramount.strip() if len(src_acct) != 34 or (not str(src_acct).startswith('T')): raise Exception("invalid src address") if len(dst_acct) != 34 or (not str(dst_acct).startswith('T')): raise Exception("invalid dst address") amount = float(stramount) tx = trx.tron.transaction_builder.send_transaction( to=dst_acct, amount=amount, account=src_acct) self.modify_expiration(tx) tx['signature'] = ['this_is_placeholder_for_signature'] rsp_data = { 'raw_trx_json_str': json.dumps(tx), 'digest': tx['txID'] } logging.info(f'{rsp_data}') self.write( json.dumps(BaseHandler.success_ret_with_data(rsp_data), default=decimal_default)) pass except Exception as e: logging.error("TRX_CreateRawTransaction: {}".format(e)) self.write( json.dumps(BaseHandler.error_ret_with_data("error: %s" % e))) pass
async def send_trx(self, from_address, private_key, to_address, amount): account = Tron(private_key=private_key, default_address=from_address) account_api = Trx(account) amount_sun = amount * 1e6 tx = await self._request('POST', '/wallet/createtransaction', owner_address=self.to_hex( from_address.encode()), to_address=self.to_hex(to_address.encode()), amount=int(amount_sun)) signed_tx = account_api.sign(tx) return await self._request('POST', '/wallet/broadcasttransaction', **signed_tx)
async def send_token(self, from_address, private_key, to_address, token_id, amount): account = Tron(private_key=private_key, default_address=from_address) account_api = Trx(account) amount_sun = amount * 1e6 tx = await self._request( 'POST', '/wallet/transferasset', owner_address=self.to_hex(from_address.encode()), to_address=self.to_hex(to_address.encode()), amount=int(amount_sun), asset_name=codecs.encode(str(token_id).encode(), 'hex').decode()) signed_tx = account_api.sign(tx) return await self._request('POST', '/wallet/broadcasttransaction', **signed_tx)
def post(self): try: address = self.get_argument("address") if len(address) != 34 or (not str(address).startswith('T')): raise Exception("invalid address") trx = Trx( Tron(full_node=TRON_RPC_URL, solidity_node=TRON_RPC_URL, event_server=TRON_RPC_URL)) account_info = trx.get_account(address=address) if 'balance' in account_info: decBalance = Decimal( account_info['balance']) / Decimal('1000000') fmtBalance = decBalance.quantize( Decimal("0.000000"), getattr(decimal, 'ROUND_DOWN')) else: fmtBalance = '0.000000' is_active = 'create_time' in account_info #账户是否已经激活 rsp_data = { 'address': address, 'balance': str(fmtBalance), 'active': is_active #其他代币资产信息可以根据资产id进行获取, 如TRC20-USDT , 此是后话 } logging.info(f'{rsp_data}') self.write( json.dumps(BaseHandler.success_ret_with_data(rsp_data), default=decimal_default)) pass except Exception as e: self.write( json.dumps(BaseHandler.error_ret_with_data("error: %s" % e))) logging.error("error:{0} in {1}".format(e, get_linenumber()))
def post(self): trx = Trx( Tron(full_node=TRON_RPC_URL, solidity_node=TRON_RPC_URL, event_server=TRON_RPC_URL)) try: signed_trx = self.get_argument_from_json("data") order_id = self.get_argument_from_json("orderId") is_exist, txid, tx_json = self.get_order_from_db(order_id) if is_exist: self.write( json.dumps(BaseHandler.success_ret_with_data(tx_json), default=decimal_default)) return signed_trx_jsonobj = json.loads(signed_trx) ret = trx.broadcast(signed_trx_jsonobj) if 'result' in ret and ret['result'] == True: self.write( json.dumps(BaseHandler.success_ret_with_data(ret), default=decimal_default)) #如果广播成功, 则插入数据库 if ret['result'] == True: self.insert_txid_into_db(order_id=order_id, txid=ret['transaction']['txID'], tx_json_str=json.dumps(ret)) else: errmsg = json.dumps(ret) self.write(json.dumps(BaseHandler.error_ret_with_data(errmsg))) except Exception as e: logging.error("TRX_SendRawTransaction: {}".format(e)) self.write( json.dumps(BaseHandler.error_ret_with_data("error: %s" % e))) pass
def process(self, symbol: str = 'TRX') -> list: #每次只查部分地址, 以防http超时 strSql = f"""SELECT address FROM tb_trx_active_addrs WHERE `symbol`='{symbol}' AND `balance` >= 1 ORDER BY `balance` DESC LIMIT 25;""" sqlRet = sql.run(strSql) addrs = [] for item in sqlRet: if "address" in item: if item['address'] not in addrs: addrs.append(item["address"]) trx = Trx( Tron(full_node=TRON_RPC_URL, solidity_node=TRON_RPC_URL, event_server=TRON_RPC_URL)) retList = [] for addr in addrs: account_info = trx.get_account(address=addr) if 'balance' in account_info: decBalance = Decimal( account_info['balance']) / Decimal('1000000') fmtBalance = decBalance.quantize( Decimal("0.000000"), getattr(decimal, 'ROUND_DOWN')) else: fmtBalance = '0.000000' if Decimal(fmtBalance) < Decimal('1.0'): logging.info( f"{addr}'s balance({fmtBalance}) is less than 1.0TRX, skip it." ) continue retList.append({ 'address': addr, 'balance': str(fmtBalance), 'symbol': symbol }) return retList
def __init__(self): self.N_BLOCK_COUNT_EACH_TIME = 5 self.tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server) self.api = Trx(tron=self.tron) # self.connected = self.tron.is_connected() self.addrs = self._GetExDepositAddrsFromDB() logging.info("len(addrs) : {}".format(len(self.addrs))) #使用 dict提高查询速度 self.hex_addrs = set() for addr in self.addrs: self.hex_addrs.add( str(self.tron.address.to_hex(address=addr)).lower()) logging.info("hex_addr: {}".format(self.hex_addrs)) pass
def execute(self, bot, update, args): user = update.effective_user exists = self.get_resource("user_exists.sql") if self.execute_global_sql(exists, user.id)["data"][0][0] == 1: # Update user details updusr = self.get_resource("update_user.sql") result = self.execute_global_sql(updusr, user.username, user.first_name, user.last_name, user.language_code, user.id) logging.info(f"Updated User: {user} {result}") sql = self.get_global_resource("select_address.sql") res = self.execute_global_sql(sql, user.id) if not res["success"]: msg = f"Something went wrong. Please contact @Wikioshi the owner of this bot" update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN) return address = res["data"][0][1] logging.info( f"User already exists - Address: {address} - {update}") else: tron = Tron() account = tron.create_account address = account.address.base58 privkey = account.private_key logging.info( f"Created Address: {address} - Private Key: {privkey} - Update: {update}" ) insert = self.get_resource("insert_address.sql") result = self.execute_global_sql(insert, user.id, address, privkey) logging.info(f"Insert Address: {user} {result}") insert = self.get_resource("insert_user.sql") result = self.execute_global_sql(insert, user.id, user.username, user.first_name, user.last_name, user.language_code, address) logging.info(f"Insert User: {user} {result}") about = self.get_resource(self.ABOUT_FILE) about = about.replace("{{address}}", address) if user.username: about = about.replace("{{warning}}", "") else: warning = f"*ATTENTION! You need a username to be able to receive tips. Set one in " \ f"your Telegram profile and execute the /{self.get_handle()} command again*\n\n" about = about.replace("{{warning}}", warning) message = update.message.reply_text(about, parse_mode=ParseMode.MARKDOWN) if bot.get_chat(update.message.chat_id).type == Chat.PRIVATE: remove_time = self.config.get("private_remove_after") else: remove_time = self.config.get("public_remove_after") if message: self.run_job(self._remove_msg, datetime.now() + timedelta(seconds=remove_time), context=f"{message.chat_id}_{message.message_id}")
def __init__(self, full_node: BaseProvider, solidity_node: BaseProvider, event_server: str): self.tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server) self.trx: Trx = self.tron.trx
from splitjoin import split, join, natural_sort DB_DEFAULT_PATH = os.path.join(os.path.dirname(__file__), dbName) DEFAULT_TOKEN_NAME = 'TOKEN' DEFAULT_ADDRESS = 'ADDRESS' #define constants # the maximum payload is 2350 because every two characters represents one byte data #_MAX_PAYLOAD = 4700 MAX_PAYLOAD = 2350 TX_SIZE = 300 TEMP_FOLDER = os.path.join(os.path.dirname(__file__), 'tmp') TEMP_FOLDER_READ = os.path.join(os.path.dirname(__file__), 'tmpread') RESULT_FOLDER = os.path.join(os.path.dirname(__file__), 'results') tron = Tron(full_node=fullNode, solidity_node=solidityNode, event_server=eventServer) shastaTron = Tron(full_node=shastaFullNode, solidity_node=shastaSolidityNode, event_server=shastaEventServer) # @dev dbconnect connects to a database stated in DB_DEFAULT_PATH # https://stackabuse.com/a-sqlite-tutorial-with-python/ def dbconnect(dbPath=DB_DEFAULT_PATH): con = sqlite3.connect(dbPath) return con # @dev genaccounts generate a number of accounts and store them to taccounts table in the database
constants, views, helpers ) from tronapi_bot.helpers import ( text_simple, get_contract_type, currency ) from tronapi_bot.keyboards import ( reply_markup_p1 ) # initial tron-api-python tron = Tron( full_node=constants.TRON_FULL_NODE, solidity_node=constants.TRON_SOLIDITY_NODE ) # Enabled logging logging.basicConfig( level=logging.DEBUG, format=constants.LOG_FORMATTER ) logger = logging.getLogger() CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3) def validate(bot, update, args): """Check TRON address"""
level=logging.DEBUG) else: logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG) config = TronConfigParser() config.read('config.conf') checkPing = int(config['DEFAULT']['PING_INTERVAL']) # Init DB client db.start(config['DATABASE']['DB_NAME'], config['DATABASE']['DB_USERNAME'], config['DATABASE']['DB_PASSWORD'], config['DATABASE']['DB_HOST'], config['DATABASE']['DB_PORT'], config['DATABASE']['DB_AUTHDB']) # Start Tron API tron = Tron(full_node=config['API']['FULL_NODE'], solidity_node=config['API']['SOLIDITY_NODE'], event_server=config['API']['EVENT_SERVER']) track_list = config['TRACK']['ADDRESSES'].split(',') def run_sync(bInit, bEnd): for n in range(bInit, bEnd + 1): logging.info('Downloading Block...') block = tron.trx.get_block(n) if 'transactions' not in block: continue # check all transactions for transaction in block['transactions']: if 'contract' not in transaction['raw_data']: continue # check all contracts in transaction
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/' private_key = sys.argv[1] default_address = sys.argv[2] contract_address = sys.argv[3] insertHash = sys.argv[4] tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server, private_key=private_key, default_address=default_address) HTTPhash = tron.transaction_builder.trigger_smart_contract( contract_address = contract_address, function_selector = 'insertHash(string)', fee_limit=2000000, call_value=0, parameters=[ {'type': 'string', 'value': insertHash} ]) sign = tron.trx.sign(HTTPhash["transaction"]) submission = tron.trx.broadcast(sign) print(submission)
from flask import Flask, request import tronapi from tronapi import Tron full_node = 'https://api.trongrid.io' solidity_node = 'https://api.trongrid.io' event_server = 'https://api.trongrid.io' PK = "eb8d0c4600b27603170610f322d9f4b9904fbcfb3f40701eb432a4e9958f41c2" tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server) def setTronPK(pk): tron.private_key = pk tron.default_address = tron.address.from_private_key(pk).base58 setTronPK(PK) app = Flask(__name__) def myfunc(add): txn = tron.trx.send_token(PA, 10 * 100000 * 6, "1003134") return "ok" app.route('/')
def main(): 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' privkey = "你的私钥" tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server, private_key=privkey) trx = Trx(tron) from_addr = 'TPcUx2iwjomVzmX3CHDDYmnEPJFTVeyqqS' to_addr = 'TDUjsjJzQABwVv8DnLVDZ778uKQ7X5Fs7E' options = { 'from' : from_addr } amount = float(0.123) # receipt = trx.send_transaction( to=to_addr, amount=amount, options=options ) #构造交易 tx = trx.tron.transaction_builder.send_transaction( to_addr, amount, options['from'] ) if False: sign = trx.sign(tx) sleep(61) # 休眠 61秒 广播时报错: {'code': 'TRANSACTION_EXPIRATION_ERROR', 'message': 'transaction expired'} result = trx.broadcast(sign) pprint(result) return old_expiration_hex = my_encode_int64(tx['raw_data']['expiration']) #改变 raw_data.expiration, 增加一个小时 tx['raw_data']['expiration'] += 3600 * 1000 new_expiration_hex = my_encode_int64(tx['raw_data']['expiration']) #也要改变 raw_data_hex 中相应的字段 # tmp_hex = tx['raw_data_hex'][30:] # tx['raw_data_hex'] = tx['raw_data_hex'][0:30] raw_data_hex = str(tx['raw_data_hex']) index = raw_data_hex.find(old_expiration_hex) logger.info( "index : {}".format( index) ) new_raw_data_hex = raw_data_hex.replace(old_expiration_hex, new_expiration_hex) old_txid = hashlib.sha256( unhexlify( tx['raw_data_hex'] )).hexdigest() new_txid = hashlib.sha256( unhexlify( new_raw_data_hex) ).hexdigest() if old_txid == tx['txID'] : logger.info('txid 比对成功!') else: logger.info('txid比对失败!') tx['txID'] = new_txid sign = trx.sign(tx) my_sig = new_ecsign( unhexlify( new_txid), unhexlify( privkey) ) logger.info( type(hexlify(my_sig)) ) logger.info( type(sign['signature'][0] )) logger.info( "我的签名: {}".format( str(hexlify(my_sig), encoding='latin') )) logger.info("原始签名: {}".format( sign['signature'][0] )) if sign['signature'][0] == str(hexlify(my_sig), encoding='latin'): logger.info('签名对比成功!') else: logger.info('签名对比失败') sleep(61) #休眠 61秒, 来测试修改 expiration的效果 result = trx.broadcast(sign) pprint(result) #测试成功 txid为: 8c2b0a40812be8bcee3f92587e6824dc5a6035572cffe13707211821085ea7d3 pass
import time import signal from tronapi import Tron from tronapi import HttpProvider # pip install tronapi env.touch() full_node = HttpProvider("https://api.trongrid.io") solidity_node = HttpProvider("https://api.trongrid.io") event_server = HttpProvider("https://api.trongrid.io") tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server) tron.default_block = "latest" def main(): gl.config = Config(gl.basic_file) ok: bool = gl.config.InitConfig() if not ok: logging.error("Failed to init config, \ please recheck config files and contents.") return config = gl.config if config.BlockNum < 0: logging.error("BlockNum must not less than 0, \ please recheck config files and contents.")
import logging 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/' private_key = 'da146374a75310b9666e834ee4ad0866d6f4035967bfc76217c5a495fff9f0d0' tron = Tron(full_node, solidity_node, event_server) account = tron.create_account is_valid = bool(tron.isAddress(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('-----------')
from tronapi import Tron from tronapi import HttpProvider full_node = HttpProvider('https://api.trongrid.io') solidity_node = HttpProvider('https://api.trongrid.io') event_server = HttpProvider('https://api.trongrid.io') tron = Tron(full_node, solidity_node, event_server) tron.toSun(1) # result: 1000000 tron.fromSun(1000000) # result: 1
def getTronBlockCount(url): tron = Tron(full_node=url, solidity_node=url, event_server=url) current_block = tron.trx.get_current_block() return current_block['block_header']['raw_data']['number']
import json import logging 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/' private_key = 'da146374a75310b9666e834ee4ad0866d6f4035967bfc76217c5a495fff9f0d0' tron = Tron(full_node, solidity_node, event_server) account = tron.create_account is_valid = bool(tron.isAddress(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('-----------')
from tronapi import Tron from tronapi import HttpProvider import time as tt import requests full_node = HttpProvider('https://api.trongrid.io') solidity_node = HttpProvider('https://api.trongrid.io') event_server = HttpProvider('https://api.trongrid.io') tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server) print("\n\n\t\t\t/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n" "\t\t\t\t we suggest to use a seperated wallet to do the airdrop from, not your main/personal one\n keep some TRX in your wallet which will be consumed by the network for bandwidth" "\n\n\t\t\t/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n") base58 = input("Your TRX address (which starts with ' T '): ") pk = input("Your wallet's private key: ") tron.private_key = pk tron.default_address = base58 token_id = (input('input the TRC10 token ID that you want to airdrop its holders (e.g: BTT = 1002000 ): ')) decimals = int(input("Decimals of the token to be dropped: ")) trc10_drop = int(input("The ID of token to be dropped: ")) add_to_show = input('input how many addresses you want to airdrop (min 1 / max 2000): ') token_amount = float(input("token to be dropped for each address: ")) token_amount = int(token_amount * (10**decimals))
try: time.sleep(0.3) url = "https://apilist.tronscan.org/api/token_trc20?sort=issue_time&limit={}&start={}".format( toread, start) req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) return urlopen(req).read() except Exception as e: print(e) continue ItemsFields = 'trc20_tokens' toread = 20 start = 0 f = open("signedList_TRC20.txt", "w+") tron = Tron() totalToken = 0 while (toread > 0): url = urlopen_with_retry(toread, start) data = json.loads(url.decode()) for T in data[ItemsFields]: address = tron.address.to_hex(T['contract_address']) f.write('{}{}{}{}, \"${} \", {}{},'.format("{", "{", conv(address), "}", T['symbol'], T['decimals'], "}")) f.write('\n') totalToken += len(data[ItemsFields]) if len(data[ItemsFields]) < toread: toread = 0
from tronapi import Tron from tronapi import HttpProvider full_node = HttpProvider('https://api.trongrid.io') solidity_node = HttpProvider('https://api.trongrid.io') event_server = HttpProvider('https://api.trongrid.io') tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server) tron.private_key = 'private_key' tron.default_address = 'default address' # added message send = tron.trx.send_transaction('to', 1, { 'message': 'hello' }) print(send)
from secp256k1 import PrivateKey, PublicKey # GET Sign PK from Env key = os.environ['TRONLEDGER_SIGN'] privkey = PrivateKey(bytes(bytearray.fromhex(key)), raw=True) print("Public key: {}".format( str(privkey.pubkey.serialize(compressed=False).hex()))) 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) def int_to_bytes(x): return x.to_bytes((x.bit_length() + 7) // 8, 'big') def getVariant(value): out = bytes() while True: byte = value & 0x7F value = value >> 7 if value == 0: out += bytes([byte]) break
def instantiate_tronapi(pk): tron = Tron(private_key=pk) tron.private_key = pk return tron
from tronapi import Tron from tronapi import HttpProvider full_node = HttpProvider('https://api.trongrid.io') solidity_node = HttpProvider('https://api.trongrid.io') event_server = HttpProvider('https://api.trongrid.io') # option 1 tron = Tron(full_node=full_node, solidity_node=solidity_node, event_server=event_server) # option 2 tron_v2 = Tron() # option 3 tron_v3 = Tron(default_address='TRWBqiqoFZysoAeyR1J35ibuyc8EvhUAoY', private_key='...')