Ejemplo n.º 1
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)})
Ejemplo n.º 2
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)})
Ejemplo n.º 3
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": "查询成功"
    })
Ejemplo n.º 4
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余额成功"
    })
Ejemplo n.º 5
0
    def execute(self, bot, update, args):
        if len(args) != 2:
            update.message.reply_text(text=f"Usage:\n{self.get_usage()}",
                                      parse_mode=ParseMode.MARKDOWN)
            return

        amount = args[0]

        # Check if amount is valid
        try:
            amount = float(amount)
        except:
            msg = f"{emo.ERROR} Provided amount is not valid"
            logging.info(f"{msg} - {update}")
            update.message.reply_text(msg)
            return

        to_address = args[1]

        # Check if provided address is valid
        if not bool(is_address(to_address)):
            msg = f"{emo.ERROR} Provided wallet is not valid"
            logging.info(f"{msg} - {update}")
            update.message.reply_text(msg)
            return

        user_id = update.effective_user.id

        sql = self.get_global_resource("select_address.sql")
        res = self.execute_global_sql(sql, user_id)

        if not res["success"] or not res["data"]:
            msg = f"{emo.ERROR} Something went wrong. Please contact Support"

            logging.error(f"{msg}: {res} - {update}")
            update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN)
            return

        from_address = res["data"][0][1]

        trx_kwargs = dict()
        trx_kwargs["private_key"] = res["data"][0][2]
        trx_kwargs["default_address"] = from_address

        tron = TRXAPI(**trx_kwargs)

        balance = tron.re(tron.trx.get_balance)
        available_amount = tron.fromSun(balance)

        # Check if address has enough balance
        if amount > (float(available_amount) - con.TRX_FEE):
            msg = f"{emo.ERROR} Not enough funds. You balance is {available_amount} TRX"
            logging.info(f"{msg} - {from_address} - {update}")
            update.message.reply_text(msg)
            return

        message = None

        try:
            send = tron.re(tron.trx.send, to_address, amount)

            logging.info(
                f"Sent {amount} TRX from {from_address} to {to_address}: {send}"
            )

            if "transaction" not in send:
                logging.error(f"Key 'transaction' not in result")
                raise Exception(send["message"])

            # Insert details into database
            sql = self.get_resource("insert_sent.sql")
            self.execute_global_sql(sql, from_address, to_address,
                                    tron.toSun(amount))

            txid = send["transaction"]["txID"]
            explorer_link = f"https://tronscan.org/#/transaction/{txid}"
            msg = f"{emo.DONE} Successfully sent `{amount}` TRX. [View " \
                  f"on Block Explorer]({explorer_link}) (wait ~1 minute)"

            message = update.message.reply_text(msg,
                                                parse_mode=ParseMode.MARKDOWN,
                                                disable_web_page_preview=True)
        except Exception as e:
            msg = f"{emo.ERROR} Couldn't send {amount} TRX from {from_address} to {to_address}: {e}"

            logging.error(msg)
            update.message.reply_text(msg)

        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}")
Ejemplo n.º 6
0
    def execute(self, bot, update, args):
        if len(args) != 1:
            update.message.reply_text(text=f"Usage:\n{self.get_usage()}",
                                      parse_mode=ParseMode.MARKDOWN)
            return

        to_address = args[0]

        # Check if provided address is valid
        if not bool(is_address(to_address)):
            msg = f"{emo.ERROR} Provided WIN wallet is not valid"
            update.message.reply_text(msg)
            return

        user_id = update.effective_user.id

        sql = self.get_global_resource("select_address.sql")
        res = self.execute_global_sql(sql, user_id)

        if not res["success"] or not res["data"]:
            msg = f"{emo.ERROR} Something went wrong. Please contact Support"

            logging.error(f"{msg}: {res} - {update}")
            update.message.reply_text(msg, parse_mode=ParseMode.MARKDOWN)
            return

        from_address = res["data"][0][1]

        tron_kwargs = dict()
        tron_kwargs["private_key"] = res["data"][0][2]
        tron_kwargs["default_address"] = from_address

        tron = TRXAPI(**tron_kwargs)

        # Get TRX balance
        trx_balance = tron.re(tron.trx.get_balance)
        trx_amount = tron.fromSun(trx_balance)

        # Check if enough TRX to pay transaction fee
        if float(trx_amount) < con.TRX_FEE:
            msg = f"{emo.ERROR} Not enough funds. You can't pay the transaction fee of {con.TRX_FEE} TRX"
            logging.info(f"{msg} - Current balance: {trx_amount} - {update}")
            update.message.reply_text(msg)
            return

        account = Trongrid().get_account(from_address)

        win_balance = 0
        win_amount = 0

        # Get WIN balance
        if account and account["data"]:
            for trc20 in account["data"][0]["trc20"]:
                for trc20_addr, trc20_bal in trc20.items():
                    if trc20_addr == TRC20().SC["WIN"]:
                        win_balance = int(trc20_bal)
                        win_amount = tron.fromSun(win_balance)

        message = None

        try:
            sent_win = TRC20().send("WIN", tron, to_address, win_amount)
            logging.info(
                f"Withdrawn {win_amount} WIN from {from_address} to {to_address}: {sent_win}"
            )

            if "transaction" not in sent_win:
                logging.error(f"Key 'transaction' not in result")
                raise Exception(sent_win["message"])

            sql = self.get_resource("insert_withdrawal.sql")
            self.execute_global_sql(sql, from_address, to_address, win_balance)

            txid = sent_win["transaction"]["txID"]
            explorer_link = f"https://tronscan.org/#/transaction/{txid}"
            msg = f"{emo.DONE} Successfully withdrawn `{win_amount}` WIN. [View " \
                  f"on Block Explorer]({explorer_link}) (wait ~1 minute)"

            message = update.message.reply_text(msg,
                                                parse_mode=ParseMode.MARKDOWN,
                                                disable_web_page_preview=True)
        except Exception as e:
            msg = f"{emo.ERROR} Couldn't withdraw {win_amount} WIN from {from_address} to {to_address}: {e}"

            logging.error(msg)
            update.message.reply_text(msg)

        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}")
Ejemplo n.º 7
0
 def is_address(self, addr):
     try:
         return is_address(addr)
     except:
         return False