Инна
Инна

Reputation: 11

python payment in Web3 TON Token

I want to make a bot with payment in Web3 TON Token, but I can't do it. For some reason, after connecting the wallet, payment is made in ton and not in Web3 TON Token

import asyncio
from datetime import datetime
from tonsdk.utils import Address
from nacl.utils import random
from pytonconnect import TonConnect
from pytonconnect.parsers import WalletInfo
from telegram import Update, Bot, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackContext
import time
import json
import tracemalloc
tracemalloc.start()

def generate_payload(ttl: int) -> str:
    payload = bytearray(random(8))
    ts = int(datetime.now().timestamp()) + ttl
    payload.extend(ts.to_bytes(8, 'big'))
    return payload.hex()

# Перевірка payload
def check_payload(payload: str, wallet_info: WalletInfo):
    if len(payload) < 32:
        return False
    if not wallet_info.check_proof(payload):
        return False
    ts = int(payload[16:32], 16)
    if datetime.now().timestamp() > ts:
        return False
    return True

# Функція для створення платіжного запиту
async def create_payment_request(connector: TonConnect):
    proof_payload = generate_payload(600)
    wallets_list = connector.get_wallets()
    for i in wallets_list:
        print(i['name'])
    if wallets_list:
        generated_url = await connector.connect(wallets_list[0], {'ton_proof': proof_payload})
        return generated_url, proof_payload
    return None, None

# Функція для відправлення транзакцій
async def send_transaction(connector: TonConnect, transaction):
    try:
        # Використовуємо await для асинхронної операції
        result = await connector.send_transaction(transaction)
        if "boc" in result:
            return "Дякую за оплату! Транзакція пройшла успішно."
        else:
            return f"Помилка при відправленні транзакції: {result}"
    except Exception as e:
        return f"Неізвестна помилка: {str(e)}"

# Команда /start для бота
async def start(update: Update, context: CallbackContext):
    chat_id = update.message.chat_id
    bot = context.bot
    connector = TonConnect(manifest_url='https://raw.githubusercontent.com/XaBbl4/pytonconnect/main/pytonconnect-manifest.json')

    try:
        generated_url, proof_payload = await create_payment_request(connector)
        if generated_url:
            keyboard = [[InlineKeyboardButton("Connect Wallet", url=generated_url)]]
            reply_markup = InlineKeyboardMarkup(keyboard)
            await bot.send_message(chat_id=chat_id, text="Click the button below to connect your wallet:", reply_markup=reply_markup)

            def status_changed(wallet_info):
                async def process_status_change():
                    try:
                        print(wallet_info)
                        if wallet_info is not None and check_payload(proof_payload, wallet_info):
                            transaction = {
                                'valid_until': int(time.time()) + 3600,  # Дійсно протягом 1 години
                                'messages': [
                                    {
                                        'address': WALLET_ADDRESS,
                                        'amount': str(PAYMENT_AMOUNT),  # Сума в найменшій одиниці
                                        'token': WEB3_TON_TOKEN_ADDRESS  # Адреса токена
                                    }
                                ]
                            }
                            # Асинхронний виклик транзакції
                            result = await send_transaction(connector, transaction)
                            await bot.send_message(chat_id, result)
                        else:
                            await bot.send_message(chat_id, "Failed to verify the wallet info.")
                    except Exception as e:
                        error_message = f"Error in status change: {str(e)}"
                        print(error_message)
                        await bot.send_message(chat_id, error_message)

                asyncio.create_task(process_status_change())

            def status_error(e):
                async def process_error():
                    try:
                        error_message = f"Connection error: {str(e)}"
                        await bot.send_message(chat_id, error_message)
                    except Exception as e:
                        print(f"Error sending message: {e}")

                asyncio.create_task(process_error())

            connector.on_status_change(status_changed, status_error)
    except Exception as e:
        await bot.send_message(chat_id, f"An error occurred: {str(e)}")

# Основна функція для запуску бота
def main():
    loop = asyncio.get_event_loop()
    application = Application.builder().token(TOKEN).build()
    application.add_handler(CommandHandler("start", start))
    loop.run_until_complete(application.run_polling())

if __name__ == '__main__':
    main()

how to implement payment in Web3 TON Token with wallet connection? Maybe you need to use another library, or am I somehow not forming the request correctly?

Upvotes: 0

Views: 131

Answers (0)

Related Questions