Esempio n. 1
0
def getTransaction(txn_id):
    try:
        client = Tron()
        txn = client.get_transaction(txn_id)
        return jsonify({"data": txn, "code": 200, "msg": "交易查询成功"})
    except Exception as e:
        return jsonify({"data": None, "code": 500, "msg": str(e)})
Esempio n. 2
0
def balanceOf(address):
    try:
        if not is_address(address):
            raise Exception('地址格式不正确')

        client = Tron()
        contract = client.get_contract(cttAddr)
        # symbol = contract.functions.symbol()

        balance_raw = contract.functions.balanceOf(address)

        balance_sun = str(from_sun(balance_raw))

    except Exception as e:
        return jsonify({"data": None, "code": 500, "msg": str(e)})

    return jsonify({
        "data": {
            'cttAddr': cttAddr,
            # 'token': symbol,
            'balance': {
                'to_sun': balance_sun,
                'raw': balance_raw
            }
        },
        "code": 200,
        "msg": "查询成功"
    })
Esempio n. 3
0
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)})
Esempio n. 4
0
def test_trc20_transfer():
    # TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu
    priv_key = PrivateKey(
        bytes.fromhex(
            "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
    )

    client = Tron(network='nile')

    contract = client.get_contract('THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia')
    print('Balance',
          contract.functions.balanceOf('TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu'))
    txn = (contract.functions.transfer(
        'TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA',
        1_000).with_owner('TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu').fee_limit(
            5_000_000).build().sign(priv_key).inspect().broadcast())

    print(txn)
    # wait
    receipt = txn.wait()
    print(receipt)
    if 'contractResult' in receipt:
        print(
            'result:',
            contract.functions.transfer.parse_output(
                receipt['contractResult'][0]))

    # result
    print(txn.result())
Esempio n. 5
0
def balance(address):
    try:
        if not is_address(address):
            raise Exception('地址格式不正确')

        client = Tron()
        response = client.get_account(address)
        _balance = 0
        if 'balance' in response:
            _balance = response['balance']

        # if is_float:
        #     return self.tron.fromSun(response['balance'])
        #
        balance_raw = _balance

        balance_sun = str(from_sun(_balance))

    except Exception as e:
        return jsonify({"data": None, "code": 500, "msg": str(e)})

    return jsonify({
        "data": {
            'cttAddr': cttAddr,
            # 'token': symbol,
            'balance': {
                'to_sun': balance_sun,
                'raw': balance_raw
            }
        },
        "code": 200,
        "msg": "查询TRX余额成功"
    })
Esempio n. 6
0
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()
Esempio n. 7
0
def test_client_timeout():
    import requests.exceptions

    # must be a timeout
    client = Tron(network='nile', conf={'timeout': 0.0001})

    with pytest.raises(requests.exceptions.Timeout):
        client.get_block()
Esempio n. 8
0
def test_query_event_logs():
    client = Tron()
    txi = client.get_transaction_info('eb47b9779a759203899d46f2bda75c0335405f7bcba838aad8781697f216b177')
    time.sleep(1)   # due to tron official node's freq limit
    cnr = client.get_contract('TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8')
    events = list(cnr.events.Transfer.process_receipt(txi))
    assert events
    assert events[0]['event'] == 'Transfer'
    assert events[0]['address'] == 'TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8'
    assert events[0]['args'] == {
        'from': 'TMuY43m8TQ2hZ1naSiDyGujosVSMZoWLrq',
        'to': 'TXX1i3BWKBuTxUmTERCztGyxSSpRagEcjX',
        'value': 459155742
    }
Esempio n. 9
0
def test_query_account():
    client = Tron()

    # There are many TRC10 token named `BTT`
    with pytest.raises(Exception):
        btt = client.get_asset_from_name("BTT")
        print(btt)

    bals = client.get_account_asset_balances("TCrahg7N9cB1SwN21WzVMqxCptbRdvQata")
    print(bals)
    assert len(bals) > 0

    bal = client.get_account_asset_balance("TCrahg7N9cB1SwN21WzVMqxCptbRdvQata", 1002928)
    print(bal)
    assert bal > 0
Esempio n. 10
0
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)

    txn = (client.trx.deploy_contract('TGQgfK497YXmjdgvun9Bg5Zu3xE15v17cu',
                                      cntr).fee_limit(5_000_000).build().sign(
                                          priv_key).inspect().broadcast())
    print(txn)
    result = txn.wait()
    print(result)
    print('Created:', result['contract_address'])
Esempio n. 11
0
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)})
Esempio n. 12
0
def test_const_functions():
    client = Tron(network='nile')

    contract = client.get_contract(CNR_ADDR)
    assert contract

    assert 'name' in dir(contract.functions)

    print(dir(contract.functions))
    print(repr(contract.functions.name()))
    print(repr(contract.functions.decimals()))

    assert contract.functions.totalSupply() > 0

    for f in contract.functions:
        print(f)
Esempio n. 13
0
def test_const_functions():
    client = Tron(network='nile')

    contract = client.get_contract('THi2qJf6XmvTJSpZHc17HgQsmJop6kb3ia')
    assert contract

    assert 'name' in dir(contract.functions)

    print(dir(contract.functions))
    print(repr(contract.functions.name()))
    print(repr(contract.functions.decimals()))

    assert contract.functions.totalSupply() > 0

    for f in contract.functions:
        print(f)
Esempio n. 14
0
    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
Esempio n. 15
0
    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())
Esempio n. 16
0
def test_trc20_transfer():
    client = Tron(network='nile')

    contract = client.get_contract(CNR_ADDR)
    print('Balance', contract.functions.balanceOf(FROM_ADDR))
    txn = (contract.functions.transfer(
        TO_ADDR, 1_000).with_owner(FROM_ADDR).fee_limit(
            5_000_000).build().sign(FROM_PRIV_KEY).inspect().broadcast())

    print(txn)
    # wait
    receipt = txn.wait()
    print(receipt)
    if 'contractResult' in receipt:
        print(
            'result:',
            contract.functions.transfer.parse_output(
                receipt['contractResult'][0]))

    # result
    print(txn.result())
Esempio n. 17
0
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)
Esempio n. 18
0
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)
Esempio n. 19
0
    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
Esempio n. 20
0
def test_client_sign_offline():
    client = Tron(network='nile')
    priv_key = PrivateKey(
        bytes.fromhex(
            "8888888888888888888888888888888888888888888888888888888888888888")
    )
    tx = client.trx.transfer(
        "TJzXt1sZautjqXnpjQT4xSCBHNSYgBkDr3",
        "TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA",
        1).memo("test memo").fee_limit(100_000_000).build()
    tx_j = tx.to_json()
    # offline
    tx_offline = Transaction.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 = Transaction.from_json(tx_j2, client=client)
    tx_2.broadcast()
Esempio n. 21
0
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()
Esempio n. 22
0
    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
Esempio n. 23
0
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'])
Esempio n. 24
0
def test_client_keygen():
    client = Tron()
    print(client.generate_address())
    print(client.get_address_from_passphrase('A'))
Esempio n. 25
0
__dir__ = os.path.dirname(__file__)

dzi_trade = 'TSMssi9ojNkzj5fT5bAjzuGjrLmsKau8Xj'
from_addr = 'TVrSWkL6a9xvtxRKq5RHg2HjUpGdPN3wBa'
priv_key = keys.PrivateKey.fromhex("975a98.....(omitted)..........86b98d97b")


def timestamp():
    return int(time.time())


swap_abi = []
with open(os.path.join(__dir__, "JustSwapExchange.abi")) as fp:
    swap_abi = json.load(fp)

client = Tron(network='nile')

cntr = client.get_contract(dzi_trade)
cntr.abi = swap_abi

for f in cntr.functions:
    print(f)

# call contract functions with TRX transfer
txn = (cntr.functions.trxToTokenSwapInput.with_transfer(1_000_000_000)(
    1_000_000_000, timestamp() +
    120).with_owner(from_addr).fee_limit(1_000_000_000).build().sign(priv_key))
print("txn =>", txn)
# print("broadcast and result =>", txn.broadcast().wait())

# NOTE: before calling tokenToTrxSwapInput, you MUST add TRC20 allowance to the swap contract.
Esempio n. 26
0
File: bot.py Progetto: NVDMkPr/T_M
print("Importing Bot")
import time, json, sys, os, re
from telegram import (InlineKeyboardMarkup as IKM, InlineKeyboardButton as IKB)
from telegram.ext import (Updater, CommandHandler, CallbackQueryHandler)
print("Imported Bot")
print("Importing Blockchain")
from tronpy import Tron
from tronpy.keys import PrivateKey
from tronpy.exceptions import AddressNotFound

__all__ = ["GenAddr", "GetBalance"]

client = Tron()


def GenAddr():
    info = client.generate_address()
    result = [info["base58check_address"], info["private_key"]]
    return result


def GetBalance(addr):
    try:
        result = client.get_account_balance(addr)
    except AddressNotFound:
        result = False
    return result


print("Importing Database")
import sqlite3
Esempio n. 27
0
def generateAddress():
    client = Tron(network=network)
    account = client.generate_address()

    return jsonify({"data": account, "code": 200, "msg": "地址生成成功"})
Esempio n. 28
0
 def get_lib_client(self):
     return Tron(network=TRON_NETWORK)
Esempio n. 29
0
from tronpy import Tron
from pprint import pprint


client = Tron()
pprint(client.generate_address())