├── .nvmrc ├── .gitignore ├── src ├── bot.ts ├── ton-connect │ ├── wallets.ts │ ├── storage.ts │ └── connector.ts ├── main.ts ├── utils.ts ├── connect-wallet-menu.ts └── commands-handlers.ts ├── .prettierrc.json ├── tonconnect-manifest.json ├── .env.example ├── README.md ├── tsconfig.json ├── package.json ├── .eslintrc.js └── LICENSE /.nvmrc: -------------------------------------------------------------------------------- 1 | v18.1.0 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .idea 4 | .env 5 | -------------------------------------------------------------------------------- /src/bot.ts: -------------------------------------------------------------------------------- 1 | import TelegramBot from 'node-telegram-bot-api'; 2 | import * as process from 'process'; 3 | 4 | const token = process.env.TELEGRAM_BOT_TOKEN!; 5 | 6 | export const bot = new TelegramBot(token, { polling: true }); 7 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "http://json.schemastore.org/prettierrc", 3 | "arrowParens": "avoid", 4 | "bracketSpacing": true, 5 | "printWidth": 100, 6 | "proseWrap": "always", 7 | "quoteProps": "as-needed", 8 | "semi": true, 9 | "singleQuote": true, 10 | "tabWidth": 4, 11 | "trailingComma": "none", 12 | "useTabs": false 13 | } 14 | -------------------------------------------------------------------------------- /tonconnect-manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "url": "https://github.com/ton-connect/demo-telegram-bot", 3 | "name": "Demo telegram bot dApp", 4 | "iconUrl": "https://ton-connect.github.io/demo-dapp-with-react-ui/apple-touch-icon.png", 5 | "termsOfUseUrl": "https://ton-connect.github.io/demo-dapp-with-react-ui/terms-of-use.txt", 6 | "privacyPolicyUrl": "https://ton-connect.github.io/demo-dapp-with-react-ui/privacy-policy.txt" 7 | } 8 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | TELEGRAM_BOT_TOKEN= 2 | TELEGRAM_BOT_LINK= 3 | MANIFEST_URL=https://ton-connect.github.io/demo-dapp-with-react-ui/tonconnect-manifest.json 4 | 5 | # 24h 6 | WALLETS_LIST_CACHE_TTL_MS=86400000 7 | REDIS_URL=redis://127.0.0.1:6379 8 | 9 | # 10m 10 | DELETE_SEND_TX_MESSAGE_TIMEOUT_MS=600000 11 | 12 | # 10m 13 | CONNECTOR_TTL_MS=600000 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TonConnect demo telegram bot 2 | 3 | ## Get started 4 | 1. Copy `.env.example` as `.env` and add your bot token there 5 | 2. `npm i` 6 | 3. `docker run -p 127.0.0.1:6379:6379 -it redis/redis-stack-server:latest` 7 | 4. `npm run compile` 8 | 5. `npm run start` 9 | 10 | [See the tutorial](https://docs.ton.org/develop/dapps/ton-connect/tg-bot-integration) 11 | 12 | ## Run process manager 13 | `npm run start:daemon` 14 | 15 | ## Stop process manager 16 | `npm run stop:daemon` 17 | 18 | 19 | ## Try it 20 | [ton_connect_example_bot](https://t.me/ton_connect_example_bot) 21 | -------------------------------------------------------------------------------- /src/ton-connect/wallets.ts: -------------------------------------------------------------------------------- 1 | import { isWalletInfoRemote, WalletInfoRemote, WalletsListManager } from '@tonconnect/sdk'; 2 | 3 | const walletsListManager = new WalletsListManager({ 4 | cacheTTLMs: Number(process.env.WALLETS_LIST_CACHE_TTL_MS) 5 | }); 6 | 7 | export async function getWallets(): Promise { 8 | const wallets = await walletsListManager.getWallets(); 9 | return wallets.filter(isWalletInfoRemote); 10 | } 11 | 12 | export async function getWalletInfo(walletAppName: string): Promise { 13 | const wallets = await getWallets(); 14 | return wallets.find(wallet => wallet.appName.toLowerCase() === walletAppName.toLowerCase()); 15 | } 16 | -------------------------------------------------------------------------------- /src/ton-connect/storage.ts: -------------------------------------------------------------------------------- 1 | import { IStorage } from '@tonconnect/sdk'; 2 | import { createClient } from 'redis'; 3 | 4 | const client = createClient({ url: process.env.REDIS_URL }); 5 | 6 | client.on('error', err => console.log('Redis Client Error', err)); 7 | 8 | export async function initRedisClient(): Promise { 9 | await client.connect(); 10 | } 11 | export class TonConnectStorage implements IStorage { 12 | constructor(private readonly chatId: number) {} 13 | 14 | private getKey(key: string): string { 15 | return this.chatId.toString() + key; 16 | } 17 | 18 | async removeItem(key: string): Promise { 19 | await client.del(this.getKey(key)); 20 | } 21 | 22 | async setItem(key: string, value: string): Promise { 23 | await client.set(this.getKey(key), value); 24 | } 25 | 26 | async getItem(key: string): Promise { 27 | return (await client.get(this.getKey(key))) || null; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "declaration": true, 4 | "lib": [ 5 | "ESNext", 6 | "dom" 7 | ], 8 | "resolveJsonModule": true, 9 | "experimentalDecorators": false, 10 | "esModuleInterop": true, 11 | "allowSyntheticDefaultImports": true, 12 | "target": "es6", 13 | "strict": true, 14 | "noImplicitAny": true, 15 | "strictNullChecks": true, 16 | "strictFunctionTypes": true, 17 | "strictPropertyInitialization": true, 18 | "noImplicitThis": true, 19 | "alwaysStrict": true, 20 | "noUnusedLocals": false, 21 | "noUnusedParameters": true, 22 | "noImplicitReturns": true, 23 | "noFallthroughCasesInSwitch": true, 24 | "module": "commonjs", 25 | "moduleResolution": "node", 26 | "sourceMap": true, 27 | "useUnknownInCatchVariables": false, 28 | "noUncheckedIndexedAccess": true, 29 | "emitDecoratorMetadata": false, 30 | "importHelpers": false, 31 | "skipLibCheck": true, 32 | "skipDefaultLibCheck": true, 33 | "allowJs": true, 34 | "outDir": "./dist" 35 | }, 36 | "include": ["src"], 37 | "exclude": [ 38 | "./tests","node_modules", "lib", "types"] 39 | } 40 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ton-connect-demo-bot", 3 | "version": "1.0.0", 4 | "scripts": { 5 | "compile": "npx rimraf dist && tsc", 6 | "run": "node ./dist/main.js", 7 | "start:redis": "docker run -d -p 127.0.0.1:6379:6379 redis/redis-stack-server:latest", 8 | "start:daemon": "pm2 start --name tgbot ./dist/main.js", 9 | "stop:daemon": "pm2 stop tgbot && pm2 delete tgbot" 10 | }, 11 | "dependencies": { 12 | "@tonconnect/sdk": "^3.0.0-beta.1", 13 | "dotenv": "^16.0.3", 14 | "node-telegram-bot-api": "^0.61.0", 15 | "qrcode": "^1.5.1", 16 | "redis": "^4.6.5" 17 | }, 18 | "devDependencies": { 19 | "@types/node-telegram-bot-api": "^0.61.4", 20 | "@types/qrcode": "^1.5.0", 21 | "@typescript-eslint/eslint-plugin": "^5.38.1", 22 | "@typescript-eslint/parser": "^5.38.1", 23 | "eslint": "8.22.0", 24 | "eslint-config-airbnb-typescript": "^17.0.0", 25 | "eslint-config-prettier": "^8.5.0", 26 | "eslint-plugin-import": "^2.26.0", 27 | "eslint-plugin-prettier": "^4.2.1", 28 | "eslint-plugin-unused-imports": "^2.0.0", 29 | "pm2": "^5.2.2", 30 | "prettier": "^2.7.1", 31 | "rimraf": "^3.0.2", 32 | "typescript": "^4.9.5" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/ton-connect/connector.ts: -------------------------------------------------------------------------------- 1 | import TonConnect from '@tonconnect/sdk'; 2 | import { TonConnectStorage } from './storage'; 3 | import * as process from 'process'; 4 | 5 | type StoredConnectorData = { 6 | connector: TonConnect; 7 | timeout: ReturnType; 8 | onConnectorExpired: ((connector: TonConnect) => void)[]; 9 | }; 10 | 11 | const connectors = new Map(); 12 | 13 | export function getConnector( 14 | chatId: number, 15 | onConnectorExpired?: (connector: TonConnect) => void 16 | ): TonConnect { 17 | let storedItem: StoredConnectorData; 18 | if (connectors.has(chatId)) { 19 | storedItem = connectors.get(chatId)!; 20 | clearTimeout(storedItem.timeout); 21 | } else { 22 | storedItem = { 23 | connector: new TonConnect({ 24 | manifestUrl: process.env.MANIFEST_URL, 25 | storage: new TonConnectStorage(chatId) 26 | }), 27 | onConnectorExpired: [] 28 | } as unknown as StoredConnectorData; 29 | } 30 | 31 | if (onConnectorExpired) { 32 | storedItem.onConnectorExpired.push(onConnectorExpired); 33 | } 34 | 35 | storedItem.timeout = setTimeout(() => { 36 | if (connectors.has(chatId)) { 37 | const storedItem = connectors.get(chatId)!; 38 | storedItem.connector.pauseConnection(); 39 | storedItem.onConnectorExpired.forEach(callback => callback(storedItem.connector)); 40 | connectors.delete(chatId); 41 | } 42 | }, Number(process.env.CONNECTOR_TTL_MS)); 43 | 44 | connectors.set(chatId, storedItem); 45 | return storedItem.connector; 46 | } 47 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import dotenv from 'dotenv'; 2 | dotenv.config(); 3 | 4 | import { bot } from './bot'; 5 | import { walletMenuCallbacks } from './connect-wallet-menu'; 6 | import { 7 | handleConnectCommand, 8 | handleDisconnectCommand, 9 | handleSendTXCommand, 10 | handleShowMyWalletCommand 11 | } from './commands-handlers'; 12 | import { initRedisClient } from './ton-connect/storage'; 13 | import TelegramBot from 'node-telegram-bot-api'; 14 | 15 | async function main(): Promise { 16 | await initRedisClient(); 17 | 18 | const callbacks = { 19 | ...walletMenuCallbacks 20 | }; 21 | 22 | bot.on('callback_query', query => { 23 | if (!query.data) { 24 | return; 25 | } 26 | 27 | let request: { method: string; data: string }; 28 | 29 | try { 30 | request = JSON.parse(query.data); 31 | } catch { 32 | return; 33 | } 34 | 35 | if (!callbacks[request.method as keyof typeof callbacks]) { 36 | return; 37 | } 38 | 39 | callbacks[request.method as keyof typeof callbacks](query, request.data); 40 | }); 41 | 42 | bot.onText(/\/connect/, handleConnectCommand); 43 | 44 | bot.onText(/\/send_tx/, handleSendTXCommand); 45 | 46 | bot.onText(/\/disconnect/, handleDisconnectCommand); 47 | 48 | bot.onText(/\/my_wallet/, handleShowMyWalletCommand); 49 | 50 | bot.onText(/\/start/, (msg: TelegramBot.Message) => { 51 | bot.sendMessage( 52 | msg.chat.id, 53 | ` 54 | This is an example of a telegram bot for connecting to TON wallets and sending transactions with TonConnect. 55 | 56 | Commands list: 57 | /connect - Connect to a wallet 58 | /my_wallet - Show connected wallet 59 | /send_tx - Send transaction 60 | /disconnect - Disconnect from the wallet 61 | 62 | GitHub: https://github.com/ton-connect/demo-telegram-bot 63 | ` 64 | ); 65 | }); 66 | } 67 | 68 | main(); 69 | -------------------------------------------------------------------------------- /src/utils.ts: -------------------------------------------------------------------------------- 1 | import { encodeTelegramUrlParameters, isTelegramUrl, WalletInfoRemote } from '@tonconnect/sdk'; 2 | import { InlineKeyboardButton } from 'node-telegram-bot-api'; 3 | 4 | export const AT_WALLET_APP_NAME = 'telegram-wallet'; 5 | 6 | export const pTimeoutException = Symbol(); 7 | 8 | export function pTimeout( 9 | promise: Promise, 10 | time: number, 11 | exception: unknown = pTimeoutException 12 | ): Promise { 13 | let timer: ReturnType; 14 | return Promise.race([ 15 | promise, 16 | new Promise((_r, rej) => (timer = setTimeout(rej, time, exception))) 17 | ]).finally(() => clearTimeout(timer)) as Promise; 18 | } 19 | 20 | export function addTGReturnStrategy(link: string, strategy: string): string { 21 | const parsed = new URL(link); 22 | parsed.searchParams.append('ret', strategy); 23 | link = parsed.toString(); 24 | 25 | const lastParam = link.slice(link.lastIndexOf('&') + 1); 26 | return link.slice(0, link.lastIndexOf('&')) + '-' + encodeTelegramUrlParameters(lastParam); 27 | } 28 | 29 | export function convertDeeplinkToUniversalLink(link: string, walletUniversalLink: string): string { 30 | const search = new URL(link).search; 31 | const url = new URL(walletUniversalLink); 32 | 33 | if (isTelegramUrl(walletUniversalLink)) { 34 | const startattach = 'tonconnect-' + encodeTelegramUrlParameters(search.slice(1)); 35 | url.searchParams.append('startattach', startattach); 36 | } else { 37 | url.search = search; 38 | } 39 | 40 | return url.toString(); 41 | } 42 | 43 | export async function buildUniversalKeyboard( 44 | link: string, 45 | wallets: WalletInfoRemote[] 46 | ): Promise { 47 | const atWallet = wallets.find(wallet => wallet.appName.toLowerCase() === AT_WALLET_APP_NAME); 48 | const atWalletLink = atWallet 49 | ? addTGReturnStrategy( 50 | convertDeeplinkToUniversalLink(link, atWallet?.universalLink), 51 | process.env.TELEGRAM_BOT_LINK! 52 | ) 53 | : undefined; 54 | 55 | const keyboard = [ 56 | { 57 | text: 'Choose a Wallet', 58 | callback_data: JSON.stringify({ method: 'chose_wallet' }) 59 | }, 60 | { 61 | text: 'Open Link', 62 | url: `https://ton-connect.github.io/open-tc?connect=${encodeURIComponent(link)}` 63 | } 64 | ]; 65 | 66 | if (atWalletLink) { 67 | keyboard.unshift({ 68 | text: '@wallet', 69 | url: atWalletLink 70 | }); 71 | } 72 | 73 | return keyboard; 74 | } 75 | -------------------------------------------------------------------------------- /src/connect-wallet-menu.ts: -------------------------------------------------------------------------------- 1 | import TelegramBot, { CallbackQuery } from 'node-telegram-bot-api'; 2 | import { getWalletInfo, getWallets } from './ton-connect/wallets'; 3 | import { bot } from './bot'; 4 | import { getConnector } from './ton-connect/connector'; 5 | import QRCode from 'qrcode'; 6 | import * as fs from 'fs'; 7 | import { isTelegramUrl, isWalletInfoRemote } from '@tonconnect/sdk'; 8 | import { addTGReturnStrategy, buildUniversalKeyboard } from './utils'; 9 | 10 | export const walletMenuCallbacks = { 11 | chose_wallet: onChooseWalletClick, 12 | select_wallet: onWalletClick, 13 | universal_qr: onOpenUniversalQRClick 14 | }; 15 | async function onChooseWalletClick(query: CallbackQuery, _: string): Promise { 16 | const wallets = await getWallets(); 17 | 18 | await bot.editMessageReplyMarkup( 19 | { 20 | inline_keyboard: [ 21 | wallets.map(wallet => ({ 22 | text: wallet.name, 23 | callback_data: JSON.stringify({ method: 'select_wallet', data: wallet.appName }) 24 | })), 25 | [ 26 | { 27 | text: '« Back', 28 | callback_data: JSON.stringify({ 29 | method: 'universal_qr' 30 | }) 31 | } 32 | ] 33 | ] 34 | }, 35 | { 36 | message_id: query.message?.message_id, 37 | chat_id: query.message?.chat.id 38 | } 39 | ); 40 | } 41 | 42 | async function onOpenUniversalQRClick(query: CallbackQuery, _: string): Promise { 43 | const chatId = query.message!.chat.id; 44 | const wallets = await getWallets(); 45 | 46 | const connector = getConnector(chatId); 47 | 48 | const link = connector.connect(wallets); 49 | 50 | await editQR(query.message!, link); 51 | 52 | const keyboard = await buildUniversalKeyboard(link, wallets); 53 | 54 | await bot.editMessageReplyMarkup( 55 | { 56 | inline_keyboard: [keyboard] 57 | }, 58 | { 59 | message_id: query.message?.message_id, 60 | chat_id: query.message?.chat.id 61 | } 62 | ); 63 | } 64 | 65 | async function onWalletClick(query: CallbackQuery, data: string): Promise { 66 | const chatId = query.message!.chat.id; 67 | const connector = getConnector(chatId); 68 | 69 | const selectedWallet = await getWalletInfo(data); 70 | if (!selectedWallet) { 71 | return; 72 | } 73 | 74 | let buttonLink = connector.connect({ 75 | bridgeUrl: selectedWallet.bridgeUrl, 76 | universalLink: selectedWallet.universalLink 77 | }); 78 | 79 | let qrLink = buttonLink; 80 | 81 | if (isTelegramUrl(selectedWallet.universalLink)) { 82 | buttonLink = addTGReturnStrategy(buttonLink, process.env.TELEGRAM_BOT_LINK!); 83 | qrLink = addTGReturnStrategy(qrLink, 'none'); 84 | } 85 | 86 | await editQR(query.message!, qrLink); 87 | 88 | await bot.editMessageReplyMarkup( 89 | { 90 | inline_keyboard: [ 91 | [ 92 | { 93 | text: '« Back', 94 | callback_data: JSON.stringify({ method: 'chose_wallet' }) 95 | }, 96 | { 97 | text: `Open ${selectedWallet.name}`, 98 | url: buttonLink 99 | } 100 | ] 101 | ] 102 | }, 103 | { 104 | message_id: query.message?.message_id, 105 | chat_id: chatId 106 | } 107 | ); 108 | } 109 | 110 | async function editQR(message: TelegramBot.Message, link: string): Promise { 111 | const fileName = 'QR-code-' + Math.round(Math.random() * 10000000000); 112 | 113 | await QRCode.toFile(`./${fileName}`, link); 114 | 115 | await bot.editMessageMedia( 116 | { 117 | type: 'photo', 118 | media: `attach://${fileName}` 119 | }, 120 | { 121 | message_id: message?.message_id, 122 | chat_id: message?.chat.id 123 | } 124 | ); 125 | 126 | await new Promise(r => fs.rm(`./${fileName}`, r)); 127 | } 128 | -------------------------------------------------------------------------------- /src/commands-handlers.ts: -------------------------------------------------------------------------------- 1 | import { CHAIN, isTelegramUrl, toUserFriendlyAddress, UserRejectsError } from '@tonconnect/sdk'; 2 | import { bot } from './bot'; 3 | import { getWallets, getWalletInfo } from './ton-connect/wallets'; 4 | import QRCode from 'qrcode'; 5 | import TelegramBot from 'node-telegram-bot-api'; 6 | import { getConnector } from './ton-connect/connector'; 7 | import { addTGReturnStrategy, buildUniversalKeyboard, pTimeout, pTimeoutException } from './utils'; 8 | 9 | let newConnectRequestListenersMap = new Map void>(); 10 | 11 | export async function handleConnectCommand(msg: TelegramBot.Message): Promise { 12 | const chatId = msg.chat.id; 13 | let messageWasDeleted = false; 14 | 15 | newConnectRequestListenersMap.get(chatId)?.(); 16 | 17 | const connector = getConnector(chatId, () => { 18 | unsubscribe(); 19 | newConnectRequestListenersMap.delete(chatId); 20 | deleteMessage(); 21 | }); 22 | 23 | await connector.restoreConnection(); 24 | if (connector.connected) { 25 | const connectedName = 26 | (await getWalletInfo(connector.wallet!.device.appName))?.name || 27 | connector.wallet!.device.appName; 28 | await bot.sendMessage( 29 | chatId, 30 | `You have already connect ${connectedName} wallet\nYour address: ${toUserFriendlyAddress( 31 | connector.wallet!.account.address, 32 | connector.wallet!.account.chain === CHAIN.TESTNET 33 | )}\n\n Disconnect wallet firstly to connect a new one` 34 | ); 35 | 36 | return; 37 | } 38 | 39 | const unsubscribe = connector.onStatusChange(async wallet => { 40 | if (wallet) { 41 | await deleteMessage(); 42 | 43 | const walletName = 44 | (await getWalletInfo(wallet.device.appName))?.name || wallet.device.appName; 45 | await bot.sendMessage(chatId, `${walletName} wallet connected successfully`); 46 | unsubscribe(); 47 | newConnectRequestListenersMap.delete(chatId); 48 | } 49 | }); 50 | 51 | const wallets = await getWallets(); 52 | 53 | const link = connector.connect(wallets); 54 | const image = await QRCode.toBuffer(link); 55 | 56 | const keyboard = await buildUniversalKeyboard(link, wallets); 57 | 58 | const botMessage = await bot.sendPhoto(chatId, image, { 59 | reply_markup: { 60 | inline_keyboard: [keyboard] 61 | } 62 | }); 63 | 64 | const deleteMessage = async (): Promise => { 65 | if (!messageWasDeleted) { 66 | messageWasDeleted = true; 67 | await bot.deleteMessage(chatId, botMessage.message_id); 68 | } 69 | }; 70 | 71 | newConnectRequestListenersMap.set(chatId, async () => { 72 | unsubscribe(); 73 | 74 | await deleteMessage(); 75 | 76 | newConnectRequestListenersMap.delete(chatId); 77 | }); 78 | } 79 | 80 | export async function handleSendTXCommand(msg: TelegramBot.Message): Promise { 81 | const chatId = msg.chat.id; 82 | 83 | const connector = getConnector(chatId); 84 | 85 | await connector.restoreConnection(); 86 | if (!connector.connected) { 87 | await bot.sendMessage(chatId, 'Connect wallet to send transaction'); 88 | return; 89 | } 90 | 91 | pTimeout( 92 | connector.sendTransaction({ 93 | validUntil: Math.round( 94 | (Date.now() + Number(process.env.DELETE_SEND_TX_MESSAGE_TIMEOUT_MS)) / 1000 95 | ), 96 | messages: [ 97 | { 98 | amount: '1000000', 99 | address: '0:0000000000000000000000000000000000000000000000000000000000000000' 100 | } 101 | ] 102 | }), 103 | Number(process.env.DELETE_SEND_TX_MESSAGE_TIMEOUT_MS) 104 | ) 105 | .then(() => { 106 | bot.sendMessage(chatId, `Transaction sent successfully`); 107 | }) 108 | .catch(e => { 109 | if (e === pTimeoutException) { 110 | bot.sendMessage(chatId, `Transaction was not confirmed`); 111 | return; 112 | } 113 | 114 | if (e instanceof UserRejectsError) { 115 | bot.sendMessage(chatId, `You rejected the transaction`); 116 | return; 117 | } 118 | 119 | bot.sendMessage(chatId, `Unknown error happened`); 120 | }) 121 | .finally(() => connector.pauseConnection()); 122 | 123 | let deeplink = ''; 124 | const walletInfo = await getWalletInfo(connector.wallet!.device.appName); 125 | if (walletInfo) { 126 | deeplink = walletInfo.universalLink; 127 | } 128 | 129 | if (isTelegramUrl(deeplink)) { 130 | const url = new URL(deeplink); 131 | url.searchParams.append('startattach', 'tonconnect'); 132 | deeplink = addTGReturnStrategy(url.toString(), process.env.TELEGRAM_BOT_LINK!); 133 | } 134 | 135 | await bot.sendMessage( 136 | chatId, 137 | `Open ${walletInfo?.name || connector.wallet!.device.appName} and confirm transaction`, 138 | { 139 | reply_markup: { 140 | inline_keyboard: [ 141 | [ 142 | { 143 | text: `Open ${walletInfo?.name || connector.wallet!.device.appName}`, 144 | url: deeplink 145 | } 146 | ] 147 | ] 148 | } 149 | } 150 | ); 151 | } 152 | 153 | export async function handleDisconnectCommand(msg: TelegramBot.Message): Promise { 154 | const chatId = msg.chat.id; 155 | 156 | const connector = getConnector(chatId); 157 | 158 | await connector.restoreConnection(); 159 | if (!connector.connected) { 160 | await bot.sendMessage(chatId, "You didn't connect a wallet"); 161 | return; 162 | } 163 | 164 | await connector.disconnect(); 165 | 166 | await bot.sendMessage(chatId, 'Wallet has been disconnected'); 167 | } 168 | 169 | export async function handleShowMyWalletCommand(msg: TelegramBot.Message): Promise { 170 | const chatId = msg.chat.id; 171 | 172 | const connector = getConnector(chatId); 173 | 174 | await connector.restoreConnection(); 175 | if (!connector.connected) { 176 | await bot.sendMessage(chatId, "You didn't connect a wallet"); 177 | return; 178 | } 179 | 180 | const walletName = 181 | (await getWalletInfo(connector.wallet!.device.appName))?.name || 182 | connector.wallet!.device.appName; 183 | 184 | await bot.sendMessage( 185 | chatId, 186 | `Connected wallet: ${walletName}\nYour address: ${toUserFriendlyAddress( 187 | connector.wallet!.account.address, 188 | connector.wallet!.account.chain === CHAIN.TESTNET 189 | )}` 190 | ); 191 | } 192 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | ignorePatterns: ['**/*.js'], 4 | overrides: [ 5 | { 6 | files: ['src/**/*.ts', 'src/**/*.tsx'], 7 | parser: '@typescript-eslint/parser', 8 | parserOptions: { 9 | project: './tsconfig.json', 10 | tsconfigRootDir: __dirname, 11 | createDefaultProgram: true 12 | }, 13 | plugins: [ 14 | '@typescript-eslint', 15 | 'import', 16 | 'unused-imports' 17 | ], 18 | extends: [ 19 | 'airbnb-typescript/base', 20 | 'plugin:prettier/recommended', 21 | 'prettier' 22 | ], 23 | rules: { 24 | 'import/extensions': [ 25 | 'error', 26 | 'ignorePackages', 27 | { 28 | js: "never", 29 | jsx: "never", 30 | ts: "never", 31 | tsx: "never" 32 | } 33 | ], 34 | '@typescript-eslint/no-use-before-define': 'off', 35 | 'import/prefer-default-export': 'off', 36 | '@typescript-eslint/no-useless-constructor': 'off', 37 | "@typescript-eslint/explicit-function-return-type": 'error', 38 | 'no-plusplus': 'off', 39 | 'class-method-use-this': 'off', 40 | 'no-underscore-dangle': 'off', 41 | 'no-inferrable-types': 'off', 42 | '@typescript-eslint/no-explicit-any': 2, 43 | '@typescript-eslint/no-unused-vars': 'off', 44 | 'unused-imports/no-unused-imports': 'error', 45 | 'unused-imports/no-unused-vars': [ 46 | 'error', 47 | { 48 | vars: 'all', 49 | args: 'all', 50 | ignoreRestSiblings: false, 51 | argsIgnorePattern: '^_', 52 | varsIgnorePattern: '^_' 53 | } 54 | ], 55 | '@typescript-eslint/no-inferrable-types': 'off', 56 | 'class-methods-use-this': 'off', 57 | complexity: ['error', 21], 58 | eqeqeq: ['error', 'smart'], 59 | '@typescript-eslint/naming-convention': [ 60 | 'error', 61 | { 62 | selector: 'enumMember', 63 | format: ['UPPER_CASE'] 64 | } 65 | ], 66 | 'no-empty': ['error', { 'allowEmptyCatch': true }], 67 | // Styling. 68 | 'array-bracket-spacing': ['error', 'never'], 69 | 'object-curly-spacing': ['error', 'always'], 70 | indent: 'off', 71 | 'comma-dangle': 'off', 72 | '@typescript-eslint/comma-dangle': ['error', 'never'], 73 | 'import/no-extraneous-dependencies': 'off', 74 | '@typescript-eslint/dot-notation': 'off', 75 | 'no-restricted-globals': 'off', 76 | '@typescript-eslint/no-empty-function': 'off', 77 | 'no-param-reassign': 'off', 78 | 'max-classes-per-file': 'off', 79 | radix: ['warn', 'as-needed'], 80 | 'no-prototype-builtins': 'off', 81 | 'no-return-assign': 'off', 82 | 'no-restricted-syntax': [ 83 | 'error', 84 | 'LabeledStatement', 85 | 'WithStatement' 86 | ], 87 | 'no-console': [ 88 | 'warn', 89 | { 90 | allow: ['debug', 'error', 'info'] 91 | } 92 | ], 93 | 'import/export': 0, 94 | '@typescript-eslint/no-shadow': 'off', 95 | '@typescript-eslint/return-await': 'off' 96 | } 97 | }, 98 | { 99 | files: ['tests/**/*.ts'], 100 | parser: '@typescript-eslint/parser', 101 | parserOptions: { 102 | project: './tsconfig.test.json', 103 | tsconfigRootDir: __dirname, 104 | createDefaultProgram: true 105 | }, 106 | plugins: [ 107 | '@typescript-eslint', 108 | 'unused-imports' 109 | ], 110 | extends: [ 111 | 'airbnb-typescript/base', 112 | 'plugin:prettier/recommended', 113 | 'prettier' 114 | ], 115 | rules: { 116 | 'import/prefer-default-export': 'off', 117 | '@typescript-eslint/no-useless-constructor': 'off', 118 | 'no-plusplus': 'off', 119 | 'class-method-use-this': 'off', 120 | 'no-underscore-dangle': 'off', 121 | 'no-inferrable-types': 'off', 122 | '@typescript-eslint/no-explicit-any': 0, 123 | '@typescript-eslint/no-unused-vars': 'off', 124 | 'unused-imports/no-unused-imports': 'error', 125 | 'unused-imports/no-unused-vars': [ 126 | 'error', 127 | { 128 | vars: 'all', 129 | args: 'all', 130 | ignoreRestSiblings: false, 131 | argsIgnorePattern: '^_' 132 | } 133 | ], 134 | '@typescript-eslint/no-inferrable-types': 'off', 135 | 'class-methods-use-this': 'off', 136 | complexity: ['error', 20], 137 | eqeqeq: ['error', 'smart'], 138 | '@typescript-eslint/naming-convention': [ 139 | 'error', 140 | { 141 | selector: 'enumMember', 142 | format: ['UPPER_CASE'] 143 | } 144 | ], 145 | 'no-empty': ['error', { 'allowEmptyCatch': true }], 146 | // Styling. 147 | 'array-bracket-spacing': ['error', 'never'], 148 | 'object-curly-spacing': ['error', 'always'], 149 | indent: 'off', 150 | 'comma-dangle': 'off', 151 | '@typescript-eslint/comma-dangle': ['error', 'never'], 152 | 'import/no-extraneous-dependencies': 'off', 153 | '@typescript-eslint/dot-notation': 'off', 154 | 'no-restricted-globals': 'off', 155 | '@typescript-eslint/no-empty-function': 'off', 156 | 'no-param-reassign': 'off', 157 | 'max-classes-per-file': 'off', 158 | radix: ['warn', 'as-needed'], 159 | 'no-prototype-builtins': 'off', 160 | 'no-return-assign': 'off', 161 | 'no-restricted-syntax': [ 162 | 'error', 163 | 'LabeledStatement', 164 | 'WithStatement' 165 | ], 166 | 'no-console': 'off', 167 | 'import/export': 0, 168 | '@typescript-eslint/no-shadow': 'off', 169 | '@typescript-eslint/return-await': 'off' 170 | } 171 | } 172 | ] 173 | } 174 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 Ton Apps 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------