-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
550 lines (485 loc) · 17.1 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
/// <reference no-default-lib="true" />
/// <reference lib="dom" />
/// <reference lib="es2015" />
/// <reference lib="webworker" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
import TelegramBot, { Update } from "telegram-types";
import { Err, None, Ok, Option, Result, Some } from "monads";
import {
AccountResponse,
ChartData,
CommandMap,
Entries,
EventMap,
EventMapFunctions,
InfoResponse,
KucoinData,
MaybePromise,
NFTResponse,
RouteMap,
TokenResponse,
WranglerEnv,
} from "~/types.ts";
import { createChart, getBlockData } from "~/utils.ts";
const WEBHOOK = "/endpoint";
export const buildURL = <T extends keyof TelegramBot>(
name: T,
params: Option<Record<string, unknown>> = None,
env: WranglerEnv,
) => {
const result = params.match({
some: (obj) =>
`?` +
new URLSearchParams(
Object.fromEntries(
Object.entries(obj).map((
[k, v],
) => [k, typeof v === "object" ? JSON.stringify(v) : `${v}`]),
),
).toString(),
none: () => "",
});
return `https://api.telegram.org/bot${env.ENV_BOT_TOKEN}/${name}${result}`;
};
const safeFetch = async (
...[input, init]: Parameters<typeof fetch>
): Promise<Result<Response, number>> => {
const response = await fetch(input, init);
return response.ok ? Ok(response) : Err(response.status);
};
const send = async (url: string) => {
const result = await safeFetch(url);
result.match({
ok: () => console.log(`Fetched ${url} successfully`),
err: (status) => console.log(`Error fetching ${url}: ${status}`),
});
};
const dispatch = async (
key: keyof TelegramBot,
params: Record<string, unknown>,
env: WranglerEnv,
) => await send(buildURL(key, Some(params), env));
const commands: CommandMap = {
start: async (msg, _args, env) => {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: `Hello, *${
msg.from!.first_name
}*! I am *hawk*, a bot that can help you with XinFin Network. Start typing \`/\` to check all my commands!\n\nBuilt with *Deno* and *Cloudflare Workers*. Open source at [github](https://github.com/Jabolol/hawk)\n`,
parse_mode: "markdown",
}, env);
},
help: async (msg, _args, env) => {
const descriptions: { [k: string]: string } = {
start: "*::* show the welcome message",
help: " *::* show the full list of commands",
nft: "`address` `id` *::* get NFT info",
dump: "`from` `to` *::* save block data to pastebin",
token: "`address` *::* get token info",
balance: " *::* get XDC balance of an address",
info: " *::* get XinFin Network info",
graph: " *::* get XDC historical price data",
};
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text:
`*Commands:*\nHere's a list with all of my commands and a short explanation.\n\n` +
Object.keys(commands).map((cmd) => `- \`/${cmd}\` ${descriptions[cmd]}`)
.join("\n"),
parse_mode: "markdown",
}, env);
},
nft: async (msg, args, env) => {
if (args.length !== 2) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: "⚠️ Invalid arguments!",
parse_mode: "markdown",
}, env);
}
const conditions:
((args: string[]) => MaybePromise<Result<boolean, string>>)[] = [
([add]) =>
add.length === 43 ? Ok(true) : Err("Address must be 43 chars!"),
([add]) =>
add.startsWith("xdc")
? Ok(true)
: Err("Address must start with `xdc`"),
([, id]) => +id > 0 ? Ok(true) : Err("ID must be a positive number!"),
async ([add, id]) =>
(await safeFetch(
`https://xdc.blocksscan.io/api/tokens/${add}/tokenID/${id}`,
)).match<Result<boolean, string>>({
ok: () => Ok(true),
err: () => Err("Token does not exist!"),
}),
];
const errors = (await Promise.all(conditions.map((fn) => fn(args))))
.filter((
result,
) => result.isErr()).map((r) => `⚠️ ${r.err().unwrap()}`);
if (errors.length) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: errors[0],
parse_mode: "markdown",
}, env);
}
const [address, id] = args;
const nft = await (await safeFetch(
`https://xdc.blocksscan.io/api/tokens/${address}/tokenID/${id}`,
)).unwrap().json() as NFTResponse;
return await dispatch("sendPhoto", {
chat_id: msg.chat.id,
parse_mode: "markdown",
photo: nft.tokenImage,
caption:
`*[${nft.tokenName}](${nft.tokenImage})*\n\`\`\`\n${nft.tokenDescription}\n\`\`\``,
reply_markup: {
inline_keyboard: [
[
{
text: "View on Blockscan",
url:
`https://xdc.blocksscan.io/api/tokens/${address}/tokenID/${id}`,
},
],
],
},
}, env);
},
dump: async (msg, args, env) => {
if (args.length !== 2) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: "⚠️ Invalid arguments!",
parse_mode: "markdown",
}, env);
}
const conditions:
((args: string[]) => MaybePromise<Result<boolean, string>>)[] = [
([, id]) => +id > 0 ? Ok(true) : Err("ID must be a positive number!"),
([from, to]) =>
!isNaN(+from) && !isNaN(+to)
? Ok(true)
: Err("Invalid block number!"),
([from, to]) =>
+from <= +to ? Ok(true) : Err("From must be less than to!"),
([from, to]) =>
+to - +from <= 1000 ? Ok(true) : Err("Difference must be <= 1000!"),
([from, to]) =>
!(from === "latest" && to === "earliest")
? Ok(true)
: Err("You do not want to query the whole blockchain, do you?"),
];
const errors = (await Promise.all(conditions.map((fn) => fn(args))))
.filter((
result,
) => result.isErr()).map((r) => `⚠️ ${r.err().unwrap()}`);
if (errors.length) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: errors[0],
parse_mode: "markdown",
}, env);
}
const [from, to] = args;
const str = await getBlockData({
from: from === "latest" ? "latest" : BigInt(+from),
to: to === "earliest" ? "earliest" : BigInt(+to),
});
const result = await safeFetch("https://pastebin.com/api/api_post.php", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
api_option: "paste",
api_paste_code: str,
api_dev_key: env.PASTEBIN_API_KEY,
}),
});
const fn = result.match<Promise<string>>({
ok: async (res) => await res.text(),
err: (status) => new Promise((r) => r(`⚠️ Error fetching: ${status}`)),
});
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: await fn,
parse_mode: "markdown",
}, env);
},
token: async (msg, args, env) => {
if (args.length !== 1) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: "⚠️ Invalid arguments!",
parse_mode: "markdown",
}, env);
}
const conditions:
((args: string[]) => MaybePromise<Result<boolean, string>>)[] = [
([add]) =>
add.length === 43 ? Ok(true) : Err("Address must be 43 chars!"),
([add]) =>
add.startsWith("xdc")
? Ok(true)
: Err("Address must start with `xdc`"),
async ([add]) =>
(await safeFetch(
`https://xdc.blocksscan.io/api/tokens/${add}`,
)).match<Result<boolean, string>>({
ok: () => Ok(true),
err: () => Err("Token does not exist!"),
}),
];
const errors = (await Promise.all(conditions.map((fn) => fn(args))))
.filter((
result,
) => result.isErr()).map((r) => `⚠️ ${r.err().unwrap()}`);
if (errors.length) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: errors[0],
parse_mode: "markdown",
}, env);
}
const [address] = args;
const token = await (await safeFetch(
`https://xdc.blocksscan.io/api/tokens/${address}`,
)).unwrap().json() as TokenResponse;
return await dispatch("sendPhoto", {
chat_id: msg.chat.id,
parse_mode: "markdown",
photo:
`https://cdn.xinfinscan.com/tokens/${token.moreInfo.symbol.toLowerCase()}.png`,
caption:
`\`\`\`\n${`Token ${token.name} :: ${token.symbol}`}\n\`\`\`\n\`\`\`\n${`${
token.moreInfo.description.length
? token.moreInfo.description.trim()
: "No provided description"
}`}\n\`\`\`\n\`\`\`md\n# Hash\n${token.hash}\n\`\`\`\n\`\`\`md\n# Website\n${token.moreInfo.website}\n\`\`\`\n\`\`\`md\n${
[
"# Socials",
...(Object.keys(token.moreInfo.communities) as Array<
keyof typeof token.moreInfo.communities
>).filter((h) => token.moreInfo.communities[h].includes("http"))
.map((c) =>
`- ${c}: ${token.moreInfo.communities[c].replaceAll("_", ":")}`
),
"\n^ note: replace : with _ to get the correct link",
].join("\n")
}\n\`\`\`\n\`\`\`md\n# Data:\n- ${token.priceUSD} USD\n- ${token.holderCount} holders\n- ${token.totalSupplyNumber} ${token.name}\n- ${token.transferCount} transfers\n- ${token.volume24h} ${token.moreInfo.symbol} vol 24h\n- created: ${token.createdAt}\n- updated: ${token.updatedAt}\n- type: ${token.type}\`\`\`\n\`\`\`md\n# Fluctuation\n- ${token.changePercent}% ${
token.changePercent >= 0 ? "▲" : "▼"
}\n\`\`\``,
reply_markup: {
inline_keyboard: [
[
{
text: "View on Blockscan",
url: `https://xdc.blocksscan.io/api/tokens/${address}`,
},
],
],
},
}, env);
},
balance: async (msg, args, env) => {
if (args.length !== 1) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: "⚠️ Invalid arguments!",
parse_mode: "markdown",
}, env);
}
const conditions:
((args: string[]) => MaybePromise<Result<boolean, string>>)[] = [
([add]) =>
add.length === 43 ? Ok(true) : Err("Address must be 43 chars!"),
([add]) =>
add.startsWith("xdc")
? Ok(true)
: Err("Address must start with `xdc`"),
async ([add]) =>
(await safeFetch(
`https://xdc.blocksscan.io/api/tokens/${add}`,
)).match<Result<boolean, string>>({
ok: () => Ok(true),
err: () => Err("Token does not exist!"),
}),
];
const errors = (await Promise.all(conditions.map((fn) => fn(args))))
.filter((
result,
) => result.isErr()).map((r) => `⚠️ ${r.err().unwrap()}`);
if (errors.length) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: errors[0],
parse_mode: "markdown",
}, env);
}
const [address] = args;
const result = await (await safeFetch(
`https://xdc.blocksscan.io/api/accounts/${address}`,
)).unwrap().json() as AccountResponse;
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: `\`\`\`\n${result._id} :: ${
(+result.balance).toFixed(6)
} XDC\n\`\`\`\n\`\`\`md\n# Info\n- ${result.minedBlock} mined blocks\n- ${result.rewardCount} rewards\n- ${result.transactionCount} transactions\n- ${result.transactionToCount} trxs to\n- ${result.transactionFromCount} from\n\`\`\``,
parse_mode: "markdown",
}, env);
},
info: async (msg, _args, env) => {
const result = await (await safeFetch(
`https://xdc.blocksscan.io/api/setting/usd`,
)).unwrap().json() as InfoResponse;
return await dispatch("sendPhoto", {
chat_id: msg.chat.id,
caption:
`\`\`\`\n${result.price} ${result.symbol} ≈ 1 USD\n\`\`\`\n\`\`\`md\n# Info\n- total supply: ${result.total_supply} ${result.symbol}\n- circulating supply: ${result.circulating_supply} ${result.symbol}\n- market cap: ${result.market_cap} USD\n- 24hr volume: ${result.volume_24h} ${result.symbol}\n\`\`\`\n\`\`\`md\n# Fluctuation\n- ${result.percent_change_24h}% ${
+result.percent_change_24h >= 0 ? "▲" : "▼"
}\n\`\`\``,
photo:
`https://www.cryptopolitan.com/wp-content/uploads/2022/09/XDC_FeatureImage_1661944505NiAvsuEsaX.jpg`,
parse_mode: "markdown",
reply_markup: {
inline_keyboard: [
[
{
text: "View on Blockscan",
url: `https://xdc.blocksscan.io/`,
},
],
],
},
}, env);
},
graph: async (msg, _args, env) => {
const result = await (await safeFetch(
`https://scanner.tradingview.com/symbol?symbol=KUCOIN:XDCUSDT&fields=price_52_week_high,price_52_week_low,sector,country,market,Low.1M,High.1M,Perf.W,Perf.1M,Perf.3M,Perf.6M,Perf.Y,Perf.YTD,Recommend.All,average_volume_10d_calc,average_volume_30d_calc,nav_discount_premium&no_404=true`,
)).unwrap().json() as ChartData;
const extra = await (await safeFetch(
`https://api.kucoin.com/api/v1/market/histories?symbol=XDC-USDT`,
)).unwrap().json() as KucoinData;
return await dispatch("sendPhoto", {
chat_id: msg.chat.id,
caption: `\`\`\`md\n# Statistics\n- High 1M: ${
result["High.1M"]
}\n- Low 1M: ${result["Low.1M"]}\n- 1Y: ${result["Perf.Y"]} USD\n- 6M: ${
result["Perf.6M"]
} USD\n- 3M: ${result["Perf.3M"]}\n- 1M: ${result["Perf.1M"]}\n- 1W: ${
result["Perf.W"]
}\n\`\`\`\n\`\`\`md\n^ Real-time data provided by TradingView & KuCoin\n\`\`\``,
photo: createChart(extra),
parse_mode: "markdown",
}, env);
},
};
const events: EventMap = {
message: async (msg, env) => {
if (!msg.text) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: "How did you even do this?",
}, env);
}
if (!msg.text.startsWith("/")) return;
const split = msg.text.split(" ");
const conditions: ((args: string[]) => Result<boolean, string>)[] = [
(
[cmd],
) => (cmd.slice(1) in commands
? Ok(true)
: Err("The specified command does not exist")),
([cmd]) =>
cmd.startsWith("/") ? Ok(true) : Err("The command must start with /"),
(args) =>
args.length > 0
? Ok(true)
: Err("The command must have at least one argument"),
];
const errors = conditions.map((fn) => fn(split)).filter((result) =>
result.isErr()
).map(
(r) => `⚠️ ${r.err().unwrap()}`,
);
if (errors.length) {
return await dispatch("sendMessage", {
chat_id: msg.chat.id,
text: errors[0],
}, env);
}
const name = split[0].slice(1);
await (commands[name])(msg, split.slice(1), env);
},
};
const entries = <T extends object>(obj: T) => Object.entries(obj) as Entries<T>;
const routes: RouteMap = {
[WEBHOOK]: (r, e) => handleWebhook(r, e),
};
const getAuth = (headers: Headers): Option<string> => {
const auth = headers.get("X-Telegram-Bot-Api-Secret-Token");
return auth ? Some(auth) : None;
};
const getEvent = (
event: keyof EventMap,
): Option<NonNullable<EventMapFunctions>> => {
const fn = events[event];
return fn ? Some(fn) : None;
};
const execute = async <T extends keyof EventMap>(
{ event, payload }: {
event: T;
payload: Parameters<NonNullable<EventMapFunctions>>[0];
},
env: WranglerEnv,
) => {
const result = getEvent(event);
const fn = result.match({
some: (fn) => fn,
none: () => () => console.log(`Handler for ${event} not found!`),
});
// @ts-ignore Trust me, it's fine
await fn(payload, env);
};
const handleWebhook = async (
request: Request,
env: WranglerEnv,
): Promise<Response> => {
const auth = getAuth(request.headers).unwrapOr("[NONE]");
if (auth !== env.ENV_BOT_SECRET) {
return new Response("Unauthorized", { status: 403 });
}
const update: Update = await request.json();
const processable = entries(update).flatMap(([event, payload]) =>
events[event]
? Ok({ event, payload })
: Err(`Handler for ${event} not found!`)
).filter((entity) => entity.isOk()).flatMap((entity) => entity.unwrap());
const result = await Promise.allSettled(
processable.flatMap((data) => execute(data, env)),
);
const errors = result.filter(({ status }) => status === "rejected");
if (errors.length) {
return new Response(JSON.stringify(errors), { status: 500 });
}
return new Response("OK", { status: 200 });
};
const getHandler = (path: string): Option<typeof routes[number]> => {
const route = routes[path];
return route ? Some(route) : None;
};
export default {
async fetch(request: Request, env: WranglerEnv) {
const url = new URL(request.url);
const result = getHandler(url.pathname);
const fn = result.match({
some: (func) => func,
none: () => () => new Response("Not found", { status: 404 }),
});
return await fn(request, env);
},
};