def unwraptx(duco_username, recipient, amount, private_key, public_key): txn = wduco.functions.initiateWithdraw( duco_username, recipient, int(float(amount) * 10**6)).with_owner( PublicKey(PrivateKey(bytes.fromhex( wrapper_public_key)))).fee_limit(5_000_000).build().sign( PrivateKey(bytes.fromhex(wrapper_private_key))) feedback = txn.broadcast().wait() return feedback
def balance_of(self, address): if self.network_type == 'mainnet': key = PrivateKey() elif self.network_type == 'testnet': key = PrivateKeyTestnet() else: raise Exception( f'network_type not in [mainnet, testnet], value={self.network_type}' ) key._address = address return self.to_human_format_amount(key.get_balance())
def transferToken(): # cttAddr = '' _from = request.form.get('from_address') _to = request.form.get('to_address') _privKey = request.form.get('private_key') _amount = request.form.get('amount') _fee_limit = request.form.get('fee_limit', 20) try: _amount = to_sun(_amount) _fee_limit = to_sun(_fee_limit) if _amount <= 0: raise Exception('转账金额需大于0') if not is_address(_from): raise Exception('from 地址格式不正确') if not is_address(_to): raise Exception('to 地址格式不正确') client = Tron() priv_key = PrivateKey(bytes.fromhex(_privKey)) contract = client.get_contract(cttAddr) # print('Balance', contract.functions.balanceOf(_from)) txn = ( contract.functions.transfer(_to, _amount).with_owner( _from).fee_limit(_fee_limit).build().sign(priv_key) # .inspect() .broadcast()) return jsonify({"data": txn, "code": 200, "msg": "TOKEN交易成功"}) except Exception as e: return jsonify({"data": None, "code": 500, "msg": str(e)})
async def test_async_contract_create(): # TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu priv_key = PrivateKey( bytes.fromhex( "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") ) async with AsyncTron(network='nile') as client: bytecode = "608060405234801561001057600080fd5b5060c78061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c806360fe47b11460375780636d4ce63c146062575b600080fd5b606060048036036020811015604b57600080fd5b8101908080359060200190929190505050607e565b005b60686088565b6040518082815260200191505060405180910390f35b8060008190555050565b6000805490509056fea2646970667358221220c8daade51f673e96205b4a991ab6b94af82edea0f4b57be087ab123f03fc40f264736f6c63430006000033" abi = [{ "inputs": [], "name": "get", "outputs": [{ "internalType": "uint256", "name": "retVal", "type": "uint256" }], "stateMutability": "view", "type": "function", }] cntr = AsyncContract(name="SimpleStore", bytecode=bytecode, abi=abi) txb = client.trx.deploy_contract('TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu', cntr).fee_limit(1_000_000) txn = await txb.build() txn = txn.sign(priv_key).inspect() txn_ret = await txn.broadcast() print(txn_ret) result = await txn_ret.wait() print(result) print('Created:', result['contract_address'])
def test_client_get_contract(): client = Tron() priv_key = PrivateKey( bytes.fromhex( "ebf7c9cad1ca710553c22669fd3c7c70832e7024c1a32da69bbc5ad19dcc8992") ) """ txn = ( client.trx.asset_issue( "TGxv9UXRNMh4E6b33iuH1pqJfBffz6hXnV", "BTCC", 1_0000_0000_000000, url="https://www.example.com" ) .memo("test issue BTCC coin") .fee_limit(0) .build() .inspect() .sign(priv_key) # .broadcast() ) print(txn) """ # print(client.get_account_permission("TGxv9UXRNMh4E6b33iuH1pqJfBffz6hXnV")) # very old address, of mainnet # print(client.get_account_resource("TTjacDH5PL8hpWirqU7HQQNZDyF723PuCg")) # "TGj1Ej1qRzL9feLTLhjwgxXF4Ct6GTWg2U")) cntr = client.get_contract("TMDRdYAcXbQDajbGFy4rgXcNLYswuYsfk1") print(cntr) print(cntr.abi) # print(client.get_contract("TTjacDH5PL8hpWirqU7HQQNZDyF723PuCg")) cntr.functions.name()
async def test_async_manual_client(): from httpx import AsyncClient, Timeout, Limits from tronpy.providers.async_http import AsyncHTTPProvider from tronpy.defaults import CONF_NILE _http_client = AsyncClient(limits=Limits(max_connections=100, max_keepalive_connections=20), timeout=Timeout(timeout=10, connect=5, read=5)) provider = AsyncHTTPProvider(CONF_NILE, client=_http_client) client = AsyncTron(provider=provider) priv_key = PrivateKey( bytes.fromhex( "8888888888888888888888888888888888888888888888888888888888888888") ) txb = (client.trx.transfer("TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000).memo("test memo").fee_limit(1_000_000)) txn = await txb.build() txn_ret = await txn.sign(priv_key).broadcast() print(txn_ret) print(await txn_ret.wait()) # must call .close at end to release connections await client.close()
async def test_async_trc20_transfer(): priv_key = PrivateKey( bytes.fromhex( "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee") ) async with AsyncTron(network='nile') as client: contract = await client.get_contract( 'THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia') print( 'Balance', await contract.functions.balanceOf('TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu')) txb = await contract.functions.transfer( 'TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA', 1_000) txb = txb.with_owner('TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu').fee_limit( 5_000_000) txn = await txb.build() txn = txn.sign(priv_key).inspect() txn_ret = await txn.broadcast() print(txn) # wait receipt = await txn_ret.wait() print(receipt) if 'contractResult' in receipt: print( 'result:', contract.functions.transfer.parse_output( receipt['contractResult'][0])) # result print(await txn_ret.result())
def transferTrx(): _from = request.form.get('from_address') _to = request.form.get('to_address') _privKey = request.form.get('private_key') _amount = request.form.get('amount') try: _amount = to_sun(_amount) if _amount <= 0: raise Exception('转账金额需大于0') if not is_address(_from): raise Exception('from 地址格式不正确') if not is_address(_to): raise Exception('to 地址格式不正确') client = Tron() priv_key = PrivateKey(bytes.fromhex(_privKey)) txn = ( client.trx.transfer(_from, _to, _amount).memo("psex").build() # .inspect() .sign(priv_key).broadcast()) return jsonify({"data": txn, "code": 200, "msg": "TRX交易成功"}) except Exception as e: return jsonify({"data": None, "code": 500, "msg": str(e)})
def confirmunwraptx(duco_username, recipient, amount): txn = wduco.functions.confirmWithdraw( duco_username, recipient, int(float(amount) * 10**6)).with_owner( wrapper_public_key).fee_limit(5_000_000).build().sign( PrivateKey(bytes.fromhex(wrapper_private_key))) txn = txn.broadcast() print("Sent confirm tx to tron network") return feedback
def wraptx(duco_username, address, amount): print("Tron wrapper called !") txn = wduco.functions.wrap( address, duco_username, int(float(amount) * 10**6)).with_owner( wrapper_public_key).fee_limit(5_000_000).build().sign( PrivateKey(bytes.fromhex(wrapper_private_key))) txn = txn.broadcast() print("Sent wrap tx to TRON network") feedback = txn.wait() return feedback
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(), }
def sendTo(self, address): client = Tron() priv_key = PrivateKey(bytes.fromhex("YOUR_PRIVATE_KEY")) txn = ( client.trx.transfer("TTfsJKVRDmFXRSYtp2QTGwEzjZvuWe7Fmj", address, 1) # 1 is 0.000001 tron .memo("sending using tronpy").build().inspect().sign( priv_key).broadcast()) print(txn) print(txn.wait())
def test_signature_sign(signature: Signature, raw_data: bytes, txid: bytes): priv_key = PrivateKey.fromhex( "0000000000000000000000000000000000000000000000000000000000000001" ) sig = priv_key.sign_msg(raw_data) pub_key = sig.recover_public_key_from_msg(raw_data) assert priv_key.public_key == pub_key sig = priv_key.sign_msg_hash(txid) pub_key = sig.recover_public_key_from_msg_hash(txid) assert priv_key.public_key == pub_key
def transfer(self, from_pri_key, to_address, human_format_amount, params): from_address = self.chain_client.pri_key_to_address(from_pri_key) priv_key = PrivateKey(bytes.fromhex(from_pri_key)) currency_format_amount = self.to_currency_format_amount( human_format_amount) currency_format_amount = int(float(currency_format_amount)) txn = (self.get_contract().functions.transfer( to_address, currency_format_amount).with_owner( from_address).build().sign(priv_key)) ret = txn.broadcast() return ret['txid']
def transfer(self, from_pri_key, to_address, human_format_amount, params): decimals = 6 from_address = self.chain_client.pri_key_to_address(from_pri_key) priv_key = PrivateKey(bytes.fromhex(from_pri_key)) tron = self.chain_client.get_lib_client() currency_format_amount = int(float(human_format_amount) * 10**decimals) txn = (tron.trx.transfer( from_address, to_address, currency_format_amount).build().inspect().sign( priv_key).broadcast()) ret = txn.wait() return ret['id']
def test_client(): client = Tron(network='nile') print(client) priv_key = PrivateKey( bytes.fromhex( "8888888888888888888888888888888888888888888888888888888888888888") ) txn = (client.trx.transfer( "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000).memo("test memo").fee_limit(100_000_000).build().inspect().sign( priv_key).broadcast()) print(txn)
def test_client_transfer_trc10(): client = Tron(network='nile') priv_key = PrivateKey( bytes.fromhex( "ebf7c9cad1ca710553c22669fd3c7c70832e7024c1a32da69bbc5ad19dcc8992") ) txn = (client.trx.asset_transfer( "TGxv9UXRNMh4E6b33iuH1pqJfBffz6hXnV", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000000, token_id=1000047).memo("test transfer coin").fee_limit( 0).build().inspect().sign(priv_key).broadcast()) print(txn)
def trans_trx(key,tplayer,to_add,to_num,memo): # trx转账 client = Tron() priv_key = PrivateKey(bytes.fromhex(key)) txn = ( client.trx.transfer(tplayer, to_add, int(to_num * 1000000)) .memo(memo) .build() .inspect() .sign(priv_key) .broadcast() ) print(txn) # > {'result': True, 'txid': '5182b96bc0d74f416d6ba8e22380e5920d8627f8fb5ef5a6a11d4df030459132'} ok=txn.wait() return ok
async def test_async_client(): async with AsyncTron(network='nile') as client: print(client) priv_key = PrivateKey( bytes.fromhex( "8888888888888888888888888888888888888888888888888888888888888888" )) txb = (client.trx.transfer( "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1_000).memo("test memo").fee_limit(100_000_000)) txn = await txb.build() txn.inspect() txn_ret = await txn.sign(priv_key).broadcast() print(txn_ret) print(await txn_ret.wait())
async def test_async_client_sign_offline(): async with AsyncTron(network='nile') as client: priv_key = PrivateKey( bytes.fromhex( "8888888888888888888888888888888888888888888888888888888888888888" )) tx = await client.trx.transfer( "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1).memo("test memo").fee_limit(100_000_000).build() tx_j = tx.to_json() # offline tx_offline = await AsyncTransaction.from_json( tx_j) # tx_offline._client is None so it's offline tx_offline.sign(priv_key) tx_j2 = tx_offline.to_json() # online tx_2 = await AsyncTransaction.from_json(tx_j2, client=client) await tx_2.broadcast()
def trc2_trans(to_con,key,tplayer,to_add,to_num,trc20_decimals): client = Tron() contract = client.get_contract(to_con) priv_key = PrivateKey(bytes.fromhex(key)) txn = ( contract.functions.transfer(to_add, int(to_num * (10 ** trc20_decimals))) .with_owner(tplayer) .fee_limit(1_000_000) .build() .sign(priv_key) .inspect() .broadcast() ) # wait ok = txn.wait() print("结果", ok) return ok
def sign(self, priv_key: PrivateKey) -> "Transaction": """Sign the transaction with a private key.""" assert self.txid, "txID not calculated" if self._permission is not None: addr_of_key = priv_key.public_key.to_hex_address() for key in self._permission["keys"]: if key["address"] == addr_of_key: break else: raise BadKey( "provided private key is not in the permission list", "provided {}".format(priv_key.public_key.to_base58check_address()), "required {}".format(self._permission), ) sig = priv_key.sign_msg_hash(bytes.fromhex(self.txid)) self._signature.append(sig.hex()) return self
def test_client_update_tx(): client = Tron(network='nile') priv_key = PrivateKey( bytes.fromhex( "8888888888888888888888888888888888888888888888888888888888888888") ) tx: Transaction = client.trx.transfer( "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3", "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA", 1).memo("test memo").fee_limit(100_000_000).build() tx.sign(priv_key) tx.broadcast() tx_id = tx.txid # update and transfer again time.sleep(0.01) tx.update() assert tx_id != tx.txid assert tx._signature == [] tx.sign(priv_key) tx.broadcast()
def trc10_trans(key,tplayer,to_add,to_num,token_ids,token_pre,memo): # trc10转账 client = Tron() priv_key = PrivateKey(bytes.fromhex(key)) txn = ( client.trx.asset_transfer( tplayer, to_add, int(to_num * (10 ** token_pre)), token_id=token_ids ) .memo(memo) .fee_limit(0) .build() .inspect() .sign(priv_key) .broadcast() ) print(txn) ok = txn.wait() return ok
def test_contract_create(): # TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu priv_key = PrivateKey(bytes.fromhex("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")) client = Tron(network='nile') bytecode = "608060405234801561001057600080fd5b5060c78061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c806360fe47b11460375780636d4ce63c146062575b600080fd5b606060048036036020811015604b57600080fd5b8101908080359060200190929190505050607e565b005b60686088565b6040518082815260200191505060405180910390f35b8060008190555050565b6000805490509056fea2646970667358221220c8daade51f673e96205b4a991ab6b94af82edea0f4b57be087ab123f03fc40f264736f6c63430006000033" abi = [ { "inputs": [], "name": "get", "outputs": [{"internalType": "uint256", "name": "retVal", "type": "uint256"}], "stateMutability": "view", "type": "function", } ] cntr = Contract(name="SimpleStore", bytecode=bytecode, abi=abi) # https://developers.tron.network/docs/setting-a-fee-limit-on-deployexecution # The maximum limit is 1000 TRX, or 1e9 SUN. Setting it to a value larger than 1e9 will produce an error. # When deploying large contracts or running complex functions, this limit may need to be increased up to 1000 TRX. However, check out timeouts, infinite loops, illegal operations, and non-existent account transfer sections are why setting a higher limit may sometimes be bad practice. # The maximum limit is 1000 TRX, or 1e9 SUN. Setting it to a value larger than 1e9 will produce an error. # feeLimit: 1e9, // Set fee limit txn = ( client.trx.deploy_contract('TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu', cntr) .fee_limit(1000000000) .build() .sign(priv_key) .inspect() .broadcast() ) print(txn) result = txn.wait() print(result) print('Created:', result['contract_address'])
def test_key_convert(): priv_key = PrivateKey.fromhex( "0000000000000000000000000000000000000000000000000000000000000001" )
def test_private_key(): with pytest.raises(BadKey): PrivateKey( bytes.fromhex("0000000000000000000000000000000000000000000000000000000000000000") )
def pri_key_to_address(self, pri_key): tron = self.get_lib_client() ret = tron.generate_address(PrivateKey.fromhex(pri_key)) return ret['base58check_address']
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)
wss_conn.send(bytes("CLOSE", encoding="utf8")) except: pass os._exit(0) elif command == "wrapperconf": # wrapper config config.read(RESOURCES_DIR + "/CLIWallet_config.cfg") if (not config["wrapper"]["use_wrapper"] == "true" and tronpy_installed): print(Style.RESET_ALL + Fore.WHITE + getString("select_option")) try: choice = int(input(getString("choice_input_wrapper"))) if choice <= 1: priv_key = str(PrivateKey.random()) pub_key = PrivateKey(bytes.fromhex( priv_key)).public_key.to_base58check_address() print(getString("how_encrypt_private_key")) incorrect_value = True while incorrect_value: try: encryption_choice = int( input(getString("encryption_choice"))) incorrect_value = False except ValueError: print(getString("value_not_numeric")) incorrect_value = True if encryption_choice <= 1: