-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
967 lines (910 loc) Β· 38.2 KB
/
app.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
import http from "serverless-http";
import {Markup, Telegraf} from "telegraf";
import {isAddress} from "@ethersproject/address";
import i18n from "i18n";
import {Redis} from "@upstash/redis/with-fetch";
import {message} from "telegraf/filters";
const token = process.env.BOT_TOKEN!;
const bot = new Telegraf(token);
const chainId = process.env.CHAIN_ID;
const hostname = process.env.HOSTNAME;
const redis_url = process.env.UPSTASH_REDIS_REST_URL!;
const redis_token = process.env.UPSTASH_REDIS_REST_TOKEN!;
const connect_url = process.env.CONNECT_URL;
const nestfi_url = process.env.NESTFI_URL!;
const redis = new Redis({
url: redis_url,
token: redis_token,
})
i18n.configure({
locales: ['en', 'es', 'ja', 'ko', 'pt', 'ru', 'tr', 'vi'],
defaultLocale: 'en',
directory: "./locales",
register: global
})
const t = (p: any, l: any, ph?: any) => {
return i18n.__({phrase: p, locale: l}, ph)
}
bot.start(async (ctx) => {
const from = ctx.from;
const chatId = ctx.chat.id;
let lang = from.language_code;
if (from.is_bot || chatId < 0) {
return
}
try {
const klAddress = ctx.startPayload;
const jwt = await redis.get(`auth:${from.id}`) as string | undefined
if (jwt) {
const decode = jwt.split('.')[1]
const decodeJson = JSON.parse(Buffer.from(decode, 'base64').toString())
const address = decodeJson.walletAddress
if (klAddress && isAddress(klAddress)) {
const [isKol, isFollowed, data] = await Promise.all([
fetch(`${hostname}/nestfi/copy/kol/isKol?walletAddress=${klAddress}`, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
// @ts-ignore
.then(data => data?.value || false),
fetch(`${hostname}/nestfi/copy/follower/kolList?chainId=${chainId}`, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
// @ts-ignore
.then(data => data?.value?.filter((item: any) => item.walletAddress.toLowerCase() === klAddress.toLowerCase() && JSON.parse(item?.follow || false)).length > 0),
fetch(`${hostname}/nestfi/copy/kol/info?chainId=${chainId}&walletAddress=${klAddress}`, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
])
if (isKol) {
if (!isFollowed) {
const nickName = data?.value?.nickName || 'No name'
await fetch(`${hostname}/nestfi/copy/follower/setting`, {
method: 'POST',
headers: {
'Authorization': jwt,
'Content-Type': 'application/json',
'token': `${Math.ceil(Date.now() / 1000)}`
},
body: JSON.stringify({
chainId: chainId,
copyAccountBalance: 0,
copyKolAddress: klAddress,
follow: false,
followingMethod: "FIEXD",
followingValue: 0
})
})
ctx.reply(t(`Would you like to copy Trader π€ {{nickName}}'s positions immediately?`, lang, {
nickName: nickName
}), Markup.inlineKeyboard([
[Markup.button.callback(t(`Nope, I change my mind.`, lang), 'cb_menu')],
[Markup.button.callback(t(`Yes, copy now!`, lang), `cb_copy_setting_${klAddress}`)],
]))
} else {
ctx.reply(t(`You have already followed this trader. All positions from this trader will be automatically executed for you.`, lang), Markup.inlineKeyboard([
[Markup.button.callback(t(`Settings`, lang), `cb_copy_setting_${klAddress}`)],
[Markup.button.callback(t(`Β« Back`, lang), 'cb_menu')],
]))
}
} else {
ctx.reply(t(`π’ Invalid Trader\nββββββββββββββββββββ\nPeter Mason is not on the NESTFi traders list.\nPlease select other traders on NESTFi.`, lang), {
...Markup.inlineKeyboard([
[Markup.button.url(t(`PC β NESTFi Website`, lang), `https://${nestfi_url}`)],
[Markup.button.url(t(`Mobile β NESTFi Website`, lang), `https://metamask.app.link/dapp/${nestfi_url}`)]
])
})
}
} else {
const data = await fetch(`${hostname}/nestfi/copy/follower/position/info?chainId=${chainId}`, {
headers: {
'Authorization': jwt
}
}).then((res) => res.json())
// @ts-ignore
.then(res => res.value)
ctx.reply(t(`π My Trades\nββββββββββββββββββββ\nCopy Trading Total Amount: {{total}} NEST\nProfit: {{profit}} NEST\nUnrealized PnL: {{unrealizedPnl}} NEST\nAddress: \`{{address}}\``, lang, {
total: (data?.assets || 0).toFixed(2),
profit: (data?.profit || 0).toFixed(2),
unrealizedPnl: (data?.unRealizedPnl || 0).toFixed(2),
address: address,
}), {
parse_mode: "Markdown",
...Markup.inlineKeyboard([
[Markup.button.callback(t(`My Account`, lang), 'cb_account')],
[Markup.button.callback(t(`My Traders`, lang), 'cb_kls_p_1')],
[Markup.button.callback(t(`My Copy Trading`, lang), 'cb_ps_all_1')],
])
})
}
} else {
if (klAddress && isAddress(klAddress)) {
ctx.reply(t(`π©βπ» Once you've linked your wallet, click "Copy Now" to continue with the copy trading.`, lang), Markup.inlineKeyboard([
[Markup.button.url(t(`Copy Now`, lang), `https://t.me/NESTFiBot?start=${klAddress}`)],
]))
}
const nonce = Math.random().toString(36).substring(2, 18);
const message = await ctx.reply(t(`π Link Wallet\nββββββββββββββββββββ\nHi there, before copying trading, please link your wallet on NESTFi.\n\nπNote: The link is valid for 10 minutes.`, lang), {
...Markup.inlineKeyboard([
[Markup.button.url(t(`PC β My Wallet`, lang), `https://${connect_url}/${nonce}`)],
[Markup.button.url(t(`Mobile β My Wallet`, lang), `https://metamask.app.link/dapp/${connect_url}/${nonce}`)],
])
})
const message_id = message.message_id
await redis.set(`code:${nonce}`, JSON.stringify({
message_id: message_id,
user: from,
}), {
ex: 600
})
}
} catch (e) {
ctx.reply(t(`Something went wrong.`, lang))
console.log(e)
}
});
bot.help((ctx) => {
const from = ctx.from;
const chat = ctx.chat;
let lang = from.language_code;
if (chat.id < 0 || from.is_bot) {
return
}
ctx.reply(t(`π For further information, please access nestfi.org\n\nControl me by sending these commands:\n\n/account - View my account\n/cancel - Cancel link wallet\n/help - Commands`, lang))
});
bot.command('account', async (ctx) => {
const from = ctx.from;
const chat = ctx.chat;
let lang = from.language_code;
if (chat.id < 0 || from.is_bot) {
return
}
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null | null
if (jwt) {
const decode = jwt.split('.')[1]
const decodeJson = JSON.parse(Buffer.from(decode, 'base64').toString())
const address = decodeJson.walletAddress
const data = await fetch(`${hostname}/nestfi/copy/follower/position/info?chainId=${chainId}`, {
headers: {
'Authorization': jwt
}
}).then((res) => res.json())
// @ts-ignore
.then(res => res?.value)
ctx.reply(t(`π My Trades\nββββββββββββββββββββ\nCopy Trading Total Amount: {{total}} NEST\nProfit: {{profit}} NEST\nUnrealized PnL: {{unrealizedPnl}} NEST\nAddress: \`{{address}}\``, lang, {
total: (data?.assets || 0).toFixed(2),
profit: (data?.profit || 0).toFixed(2),
unrealizedPnl: (data?.unRealizedPnl || 0).toFixed(2),
address: address
}), {
parse_mode: "Markdown",
...Markup.inlineKeyboard([
[Markup.button.callback(t(`My Account`, lang), 'cb_account')],
[Markup.button.callback(t(`My Traders`, lang), 'cb_kls_p_1')],
[Markup.button.callback(t(`My Copy Trading`, lang), 'cb_ps_all_1')],
])
})
} else {
ctx.reply(t(`Hi here! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang))
}
} catch (e) {
ctx.reply(t(`Something went wrong.`, lang))
console.log(e)
}
})
// Stop command use to delete authorization request
bot.command('cancel', async (ctx) => {
const from = ctx.from;
const chat = ctx.chat;
let lang = from.language_code;
if (chat.id < 0 || from.is_bot) {
return
}
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const decode = jwt.split('.')[1]
const decodeJson = JSON.parse(Buffer.from(decode, 'base64').toString())
const address = decodeJson.walletAddress
ctx.reply(t(`You are about to cancel your NESTFi authorization in this bot. Is that correct?\n\nAddress: \`{{address}}\``, lang, {
address: address
}), {
parse_mode: "Markdown",
...Markup.inlineKeyboard([
[Markup.button.callback(t(`Yes, deauthorize now.`, lang), 'cb_unauthorize')],
[Markup.button.callback(t(`Nope, I change my mind.`, lang), 'cb_menu')],
])
})
} else {
ctx.reply(t(`π©βπ» You have not authorized any wallet yet.`, lang))
}
})
bot.command('token', async (ctx) => {
const from = ctx.from;
const chat = ctx.chat;
let lang = from.language_code;
if (chat.id < 0 || from.is_bot) {
return
}
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
ctx.reply(`This is your NESTFi Token, be careful!
\`${jwt}\``, {
parse_mode: 'Markdown'
})
} else {
ctx.reply(t(`π©βπ» You have not authorized any wallet yet.`, lang))
}
})
// cb_copy_setting_[KL]
bot.action(/cb_copy_setting_.*/, async (ctx) => {
// @ts-ignore
const {from, data: action} = ctx.update.callback_query;
const klAddress = action.split('_')[3];
const lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const decode = jwt.split('.')[1]
const decodeJson = JSON.parse(Buffer.from(decode, 'base64').toString())
const address = decodeJson.walletAddress
const [availableBalance, positionInfo, klInfo] = await Promise.all([
fetch(`${hostname}/nestfi/op/user/asset?chainId=${chainId}&walletAddress=${address}`, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
// @ts-ignore
.then(data => data?.value?.availableBalance || 0),
fetch(`${hostname}/nestfi/copy/follower/future/info?chainId=${chainId}©KolAddress=${klAddress}`, {
headers: {
'Authorization': jwt
}
}).then((res) => res.json())
// @ts-ignore
.then(data => data?.value),
fetch(`${hostname}/nestfi/copy/kol/info?chainId=${chainId}&walletAddress=${klAddress}`, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
// @ts-ignore
.then(data => data.value)
])
const position = positionInfo?.totalCopyAmount || 0
const nickName = klInfo?.nickName || '-'
const groupId = klInfo?.groupId || '-'
if (availableBalance + position < 200) {
ctx.reply(t(`π Insufficient Balance\nββββββββββββββββββββ\nYour account balance is insufficient. Please deposit first to initiate lightning trading on NESTFi.`, lang), {
...Markup.inlineKeyboard([
[Markup.button.url(t(`PC β Deposit`, lang), `https://${nestfi_url}`)],
[Markup.button.url(t(`Mobile β Deposit`, lang), `https://metamask.app.link/dapp/${nestfi_url}`)],
[Markup.button.callback(t(`Completed, go on!`, lang), `cb_copy_setting_${klAddress}`)],
])
})
return
} else {
await redis.set(`intent:${from.id}`, JSON.stringify({
category: 'cb_copy_setting',
value: {
kl: klAddress,
total: 0,
single: 0,
availableBalance: availableBalance,
position: position,
nickName: nickName,
groupId: groupId,
}
}), {
ex: 600
});
let choice = [0, 0, 0];
choice[0] = Math.floor(availableBalance * 0.5 / 50) * 50;
choice[1] = Math.floor(availableBalance * 0.75 / 50) * 50;
choice[2] = Math.floor(availableBalance / 50) * 50;
ctx.reply(t(`π΅ Add Copy Trading Amount\nββββββββββββββββββββ\nMy Account Balance: {{balance}} NEST\nCopy Trading Total Amount: {{total}} NEST\n\nYou are following: {{nickName}}\nPlease add the amount you invest to this trader below.`, lang, {
balance: (availableBalance || 0).toFixed(2),
total: (position || 0)?.toFixed(2),
nickName: nickName,
}), {
...Markup.keyboard([
choice.filter((i) => i >= 200).map((i: number) => String(i)),
['Skip', 'Β« Back'],
]).oneTime().resize()
})
}
} else {
ctx.reply(t(`Hi here! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
bot.action('cb_menu', async (ctx) => {
const {from} = ctx.update.callback_query;
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const decode = jwt.split('.')[1]
const decodeJson = JSON.parse(Buffer.from(decode, 'base64').toString())
const address = decodeJson.walletAddress
const data = await fetch(`${hostname}/nestfi/copy/follower/position/info?chainId=${chainId}`, {
headers: {
'Authorization': jwt
}
}).then((res) => res.json())
// @ts-ignore
.then(res => res?.value)
ctx.editMessageText(t(`π My Trades\nββββββββββββββββββββ\nCopy Trading Total Amount: {{total}} NEST\nProfit: {{profit}} NEST\nUnrealized PnL: {{unrealizedPnl}} NEST\nAddress: \`{{address}}\``, lang, {
total: (data?.assets || 0).toFixed(2),
profit: (data?.profit || 0).toFixed(2),
unrealizedPnl: (data?.unRealizedPnl || 0).toFixed(2),
address: address,
}), {
parse_mode: "Markdown",
...Markup.inlineKeyboard([
[Markup.button.callback(t(`My Account`, lang), 'cb_account')],
[Markup.button.callback(t(`My Traders`, lang), 'cb_kls_p_1')],
[Markup.button.callback(t(`My Copy Trading`, lang), 'cb_ps_all_1')],
])
})
} else {
ctx.reply(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
bot.action('cb_account', async (ctx) => {
const {from} = ctx.update.callback_query;
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const decode = jwt.split('.')[1]
const decodeJson = JSON.parse(Buffer.from(decode, 'base64').toString())
const address = decodeJson.walletAddress
const data = await fetch(`${hostname}/nestfi/op/user/asset?chainId=${chainId}&walletAddress=${address}`, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
// @ts-ignore
.then(res => res?.value)
ctx.editMessageText(t(`π³ My Account\nββββββββββββββββββββ\nAccount Balance: {{availableBalance}} NEST\nCopy Trading Total Amount: {{copyBalance}} NEST`, lang, {
availableBalance: (data?.availableBalance || 0).toFixed(2),
copyBalance: Number(data?.copyBalance || 0).toFixed(2),
}), {
...Markup.inlineKeyboard([
[Markup.button.url(t(`PC β Deposit/Withdraw`, lang), `https://${nestfi_url}`)],
[Markup.button.url(t(`Mobile β Deposit/Withdraw`, lang), `https://metamask.app.link/dapp/${nestfi_url}`)],
[Markup.button.callback(t(`Β« Back`, lang), 'cb_menu')],
])
})
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery('Something went wrong.')
}
})
// cb_kls_p_[PAGE]
bot.action(/cb_kls_p_.*/, async (ctx) => {
// @ts-ignore
const {from, data: action} = ctx.update.callback_query;
const page = Number(action.split('_')[3]);
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const data = await fetch(`${hostname}/nestfi/copy/follower/kolList?chainId=${chainId}`, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
.then(data => data.value
?.filter((item: any) => JSON.parse(item?.follow || false))
?.sort((a: any, b: any) => b.copyAccountBalance - a.copyAccountBalance))
// @ts-ignore
const length = data?.length || 0
let inlineKeyboard: any[] = []
// @ts-ignore
const showArray = data?.slice((page - 1) * 5, page * 5)
for (let i = 0; i < showArray.length; i++) {
// @ts-ignore
inlineKeyboard.push([Markup.button.callback(`${showArray[i]?.nickName || '-'}`, `cb_kl_${showArray[i]?.walletAddress}`)])
}
if (page * 5 < length) {
inlineKeyboard.push([Markup.button.callback(t(`Β» Next Page`, lang), `cb_kls_p_${page + 1}`)])
}
inlineKeyboard.push([Markup.button.callback(t(`Β« Back`, lang), 'cb_menu')])
ctx.editMessageText(t(`πͺ My Traders\nββββββββββββββββββββ\nThese are the traders you followed.`, lang), {
...Markup.inlineKeyboard(inlineKeyboard)
})
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
// cb_kl_[KL]
bot.action(/cb_kl_.*/, async (ctx) => {
// @ts-ignore
const {from, data: action} = ctx.update.callback_query;
const klAddress = action.split('_')[2];
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const data = await fetch(`${hostname}/nestfi/copy/kol/info?chainId=${chainId}&walletAddress=${klAddress}`, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
// @ts-ignore
.then(res => res?.value)
ctx.editMessageText(t(`π€ {{nickName}}\nββββββββββββββββββββ\nFollowers: {{currentFollowers}}\nAUM: {{followersAssets}} NEST\n7D ROI: {{kolProfitLossRate}}%\n7D Earnings: {{kolProfitLoss}} NEST`, lang, {
nickName: data?.nickName || '-',
currentFollowers: data?.currentFollowers || 0,
followersAssets: Number(data?.followersAssets || 0).toFixed(2),
kolProfitLossRate: Number(data.kolProfitLossRate || 0).toFixed(2),
kolProfitLoss: (data?.followerProfitLoss || 0).toFixed(2),
}), {
parse_mode: 'Markdown',
...Markup.inlineKeyboard([
[Markup.button.callback(t(`View Copy Trading`, lang), `cb_ps_${klAddress}_1`)],
[Markup.button.callback(t(`Stop Copying`, lang), `cb_r_stop_kl_${klAddress}`), Markup.button.callback('Settings', `cb_copy_setting_${klAddress}`)],
[Markup.button.callback(t(`Β« Back`, lang), 'cb_kls_p_1')]
])
})
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
// cb_ps_[KL]_[PAGE]
bot.action(/cb_ps_.*/, async (ctx) => {
// @ts-ignore
const {from, data: action} = ctx.update.callback_query;
const klAddress = action.split('_')[2]
const page = Number(action.split('_')[3])
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
let url;
if (klAddress === "all") {
url = `${hostname}/nestfi/copy/follower/future/list?chainId=${chainId}`
} else {
url = `${hostname}/nestfi/copy/follower/future/list?chainId=${chainId}©KolAddress=${klAddress}`
}
const data = await fetch(url, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
// @ts-ignore
const length = data?.value?.length || 0
// @ts-ignore
const showData = data?.value?.sort((a, b) => b?.timestamp - a?.timestamp).slice((page - 1) * 5, page * 5)
let inlineKeyboard: any [] = []
const buttons = showData.map((item: any, index: number) => (
Markup.button.callback(`${index + 1 + (page - 1) * 5}`, `cb_oi_${item.id}_${klAddress}`)
))
if (buttons.length > 0) {
inlineKeyboard.push(buttons)
}
if (page * 5 < length) {
inlineKeyboard.push([Markup.button.callback(t(`Β» Next Page`, lang), `cb_ps_${klAddress}_${page + 1}`)])
}
inlineKeyboard.push([Markup.button.callback(t(`History`, lang), `cb_klh_${klAddress}_1`), Markup.button.callback('Β« Back', klAddress === 'all' ? 'cb_menu' : `cb_kl_${klAddress}`)])
ctx.editMessageText(`π― ${(t(`Current Copy Trading Position`, lang))}
${showData.length > 0 ? `${showData.map((item: any, index: number) => (`
=============================
${index + 1 + (page - 1) * 5}. ${item?.product || '-'} ${item?.direction ? 'Long' : 'Short'} ${item?.leverage || '-'}x
${(t(`Actual Margin`, lang))}: ${(item?.margin || 0).toFixed(2)} NEST ${item?.profitLossRate > 0 ? `+${item?.profitLossRate?.toFixed(2)}` : item?.profitLossRate?.toFixed(2)}%
${(t(`Open Price`, lang))}: ${(item?.orderPrice || 0).toFixed(5)} USDT
${(t(`Open: UTC`, lang))} ${new Date(item?.timestamp * 1000 || 0).toISOString().replace('T', ' ').substring(5, 19)}`)).join('')}
π ${(t(`Click the number to manage the corresponding order.`, lang))}` : `\n${(t(`No copy trading position yet!`, lang))}`}`, {
...Markup.inlineKeyboard(inlineKeyboard)
})
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
// cb_klh_[KL]_[PAGE]
bot.action(/cb_klh_.*/, async (ctx) => {
// @ts-ignore
const {from, data: action} = ctx.update.callback_query;
const klAddress = action.split('_')[2];
const page = Number(action.split('_')[3]);
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
let url;
if (klAddress === "all") {
url = `${hostname}/nestfi/copy/follower/future/history?chainId=${chainId}`
} else {
url = `${hostname}/nestfi/copy/follower/future/history?chainId=${chainId}©KolAddress=${klAddress}`
}
const data = await fetch(url, {
headers: {
'Authorization': jwt
}
}).then(res => res.json())
// @ts-ignore
const length = data?.value?.length || 0
// @ts-ignore
const showData = data?.value?.sort((a, b) => b.closeTime - a.closeTime)?.slice((page - 1) * 5, page * 5)
let inlineKeyboard: any [] = []
if (page * 5 < length) {
inlineKeyboard.push([Markup.button.callback(t(`Β» Next Page`, lang), `cb_klh_${klAddress}_${page + 1}`)])
}
inlineKeyboard.push([Markup.button.callback(t(`Β« Back`, lang), `cb_ps_${klAddress}_1`)])
ctx.editMessageText(`π§© ${t(`History`, lang)}
${showData?.length > 0 ? `${showData?.map((item: any, index: number) => (`
=============================
${index + 1 + (page - 1) * 5}. ${item?.product || '-'} ${item?.direction ? 'Long' : 'Short'} ${item?.leverage || '-'}x
${t(`Actual Margin`, lang)}: ${(item?.margin || 0).toFixed(2)} NEST ${item?.profitLossRate > 0 ? `+${item?.profitLossRate?.toFixed(2)}` : item?.profitLossRate?.toFixed(2)}%
${t(`Open Price`, lang)}: ${(item?.openPrice || 0).toFixed(5)} USDT
${t(`Close price`, lang)}: ${(item?.closePrice || 0).toFixed(5)} USDT
${t(`Liq Price`, lang)}: ${item?.lipPrice ? item?.lipPrice?.toFixed(5) : '-'} USDT
${t(`Open: UTC`, lang)} ${new Date(item?.openTime * 1000 || 0).toISOString().replace('T', ' ').substring(5, 19)}
${t(`Close: UTC`, lang)} ${new Date(item?.closeTime * 1000 || 0).toISOString().replace('T', ' ').substring(5, 19)}`)).join('')}` : `\n${t(`No copy trading position yet!`, lang)}`}`, {
...Markup.inlineKeyboard(inlineKeyboard)
})
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
// cb_r_stop_kl_[KL]
bot.action(/cb_r_stop_kl_.*/, async (ctx) => {
// @ts-ignore
const {from, data: action} = ctx.update.callback_query;
const klAddress = action.split('_')[4];
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const request = await fetch(`${hostname}/nestfi/copy/follower/future/info?chainId=${chainId}©KolAddress=${klAddress}`, {
headers: {
'Authorization': jwt
}
}).then((res) => res.json())
// @ts-ignore
.then(data => data?.value)
ctx.editMessageText(t(`π
Stop Copying\nββββββββββββββββββββ\nTotal Copy Amount: {{total}} NEST\nOpen Interest: {{openInterest}} NEST\nTotal Profit: {{totalProfit}} NEST\nEstimated Realized Amount: {{aum}} NEST\n\n_End copy will liquidate your position with market orders, and automatically return the assets to your Account after deducting the profits sharing._\nβAre you sure to stop copying?`, lang, {
total: (request?.totalCopyAmount || 0).toFixed(2),
openInterest: Number(request?.openInterest || 0).toFixed(2),
totalProfit: Number(request?.totalProfit || 0).toFixed(2),
aum: Number(request?.aum || 0).toFixed(2),
}
), {
parse_mode: 'Markdown',
...Markup.inlineKeyboard([
[Markup.button.callback(t(`Nope, I change my mind.`, lang), `cb_kl_${klAddress}`)],
[Markup.button.callback(t(`Yes, stop copying trading.`, lang), `cb_stop_kl_${klAddress}`)],
])
})
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
// cb_stop_kl_[KL]
bot.action(/cb_stop_kl_.*/, async (ctx) => {
// @ts-ignore
const {from, data: action} = ctx.update.callback_query;
const klAddress = action.split('_')[3];
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const data = await fetch(`${hostname}/nestfi/copy/follower/cancle?chainId=${chainId}©KolAddress=${klAddress}`, {
method: 'POST',
headers: {
"Authorization": jwt,
"token": `${Math.ceil(Date.now() / 1000)}`,
}
}).then(res => res.json())
// @ts-ignore
const status = data?.value || false
if (status) {
ctx.editMessageText(t(`π₯³ Stop Copying Successfully!`, lang), {
...Markup.inlineKeyboard([
[Markup.button.callback(t(`Β« Back`, lang), 'cb_kls_p_1')],
])
})
} else {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
// cb_po_[ORDER_INDEX]_[KL]
bot.action(/cb_oi_.*/, async (ctx) => {
// @ts-ignore
const {from, data: action} = ctx.update.callback_query;
const oi = action.split('_')[2];
const klAddress = action.split('_')[3];
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const data = await fetch(`${hostname}/nestfi/op/future/getById/${oi}`, {
headers: {
'Authorization': jwt,
}
}).then(res => res.json())
// @ts-ignore
.then(res => res?.value)
ctx.editMessageText(t(`π― Position {{oi}}\nββββββββββββββββββββ\n{{product}} {{direction}} {{leverage}}x\nActual Margin: {{margin}} NEST {{profitLossRate}}%\nOpen Price: {{orderPrice}} USDT\nMarket Price: {{marketPrice}} USDT\nLiq Price: {{lipPrice}} USDT\nOpen: UTC {{open}}`, lang, {
oi: oi,
product: data?.product || '-',
direction: data?.direction ? 'Long' : 'Short',
leverage: data?.leverage || '-',
margin: (data?.margin || 0).toFixed(2),
profitLossRate: data?.profitLossRate > 0 ? `+${data?.profitLossRate.toFixed(2)}` : data?.profitLossRate.toFixed(2),
orderPrice: Number(data?.orderPrice || 0).toFixed(5),
marketPrice: Number(data?.marketPrice || 0).toFixed(5),
lipPrice: data?.lipPrice ? data?.lipPrice?.toFixed(5) : '-',
open: new Date(data?.timestamp * 1000 || 0).toISOString().replace('T', ' ').substring(5, 19)
}), {
parse_mode: 'HTML',
...Markup.inlineKeyboard([
[Markup.button.callback(t(`Close the Position`, lang), `cb_close_oi_${oi}_${klAddress}`)],
[Markup.button.callback(t(`Β« Back`, lang), `cb_ps_${klAddress}_1`)],
])
})
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
// cb_close_oi_[ORDER_INDEX]_[KL]
bot.action(/cb_close_oi_.*/, async (ctx) => {
// @ts-ignore
const {from, data: action} = ctx.update.callback_query;
const oi = action.split('_')[3];
const klAddress = action.split('_')[4];
let lang = from.language_code;
try {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const request = await fetch(`${hostname}/nestfi/op/future/close?id=${oi}`, {
method: 'POST',
headers: {
'Authorization': jwt,
'token': `${Math.ceil(Date.now() / 1000)}`,
}
}).then(res => res.json())
// @ts-ignore
.then(data => data?.value || false)
if (request) {
ctx.editMessageText(t(`π₯³ Close Position Successfully!`, lang), {
...Markup.inlineKeyboard([
[Markup.button.callback(t(`Β« Back`, lang), `cb_ps_${klAddress}_1`)]
])
})
} else {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
// Handle logout button click
bot.action('cb_unauthorize', async (ctx) => {
const {from} = ctx.update.callback_query;
let lang = from.language_code;
try {
await redis.del(`auth:${from.id}`)
ctx.editMessageText(t(`π©βπ» You have successfully deauthorized the NESTFi Copy Trading bot on NESTFi.`, lang), Markup.inlineKeyboard([]))
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
bot.action('confirm_copy_setting', async (ctx) => {
const {from} = ctx.update.callback_query;
let lang = from.language_code;
try {
const intent = await redis.get(`intent:${from.id}`) as any
if (intent) {
if (intent?.category === 'cb_copy_setting') {
const jwt = await redis.get(`auth:${from.id}`) as string | undefined | null
if (jwt) {
const {kl, total, single, nickName, groupId} = intent.value
const request = await fetch(`${hostname}/nestfi/copy/follower/setting`, {
method: 'POST',
headers: {
'Authorization': jwt,
'token': `${Math.ceil(Date.now() / 1000)}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
chainId: chainId,
copyAccountBalance: total,
copyKolAddress: kl,
follow: true,
followingMethod: "FIEXD",
followingValue: single,
})
}).then(res => res.json())
// @ts-ignore
.then(data => data?.value || false)
if (request) {
ctx.editMessageText(t(`π₯³ Successfully Copy Trading\nββββββββββββββββββββ\nMore latest orders from {{nickName}} will be posted in the group.\n\nTelegram Group: {{groupId}}`, lang, {
nickName: nickName,
groupId: groupId
}), {
...Markup.inlineKeyboard([
[Markup.button.callback(t('Β« Back', lang), 'cb_menu')],
])
})
} else {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
} else {
ctx.editMessageText(t(`Hi {{username}}! Please authorize me to set up a NESTFi integration.\n\nYou can use command: /start`, lang, {
username: from.username
}))
}
} else {
ctx.editMessageText(t(`Sorry, we have not found your copy trading request`, lang), {
...Markup.inlineKeyboard([]),
})
}
}
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
bot.action('cancel_copy_setting', async (ctx) => {
const {from} = ctx.update.callback_query;
let lang = from.language_code;
try {
await redis.del(`intent:${from.id}`)
ctx.editMessageText(t(`π
βοΈ Alright, your copy trading request has been cancelled successfully!`, lang), {
...Markup.inlineKeyboard([
[Markup.button.callback(t(`Β« Back`, lang), 'cb_menu')],
]),
})
} catch (e) {
ctx.answerCbQuery(t(`Something went wrong.`, lang))
}
})
bot.on(message("text"), async (ctx) => {
const {from, chat} = ctx.update.message;
let lang = from.language_code;
if (chat.id < 0 || from.is_bot) {
return
}
// @ts-ignore
const input = ctx.message.text;
const intent = await redis.get(`intent:${from.id}`) as any
if (intent) {
if (intent.category === 'cb_copy_setting') {
if (input === 'Β« Back') {
await redis.del(`intent:${from.id}`)
ctx.reply(t(`π
β Alright, your copy trading request has been cancelled successfully!`, lang))
return
}
let {total, single, availableBalance, position, nickName} = intent.value
if (total === 0) {
const add = Number(input) || 0
if ((add + position) < 200 || add > availableBalance) {
ctx.reply(t(`π’ Invalid Amount\nPlease enter a valid amount between 200 and {{availableBalance}}`, lang, {
availableBalance: availableBalance.toFixed(2)
}))
return
}
// update intent
await redis.set(`intent:${from.id}`, JSON.stringify({
category: 'cb_copy_setting',
value: {
...intent.value,
total: add + position,
}
}), {
ex: 600
})
let choice = [0, 0, 0]
choice[0] = Math.floor((add + position) * 0.1 / 50) * 50
choice[1] = Math.floor((add + position) * 0.2 / 50) * 50
choice[2] = Math.floor((add + position) * 0.4 / 50) * 50
ctx.reply(t(`π΅ Copy Trading Each Order\nββββββββββββββββββββ\nYou are following: {{nickName}}\nPlease type the amount you invest to this trader for each order below.`, lang, {
nickName: nickName
}), {
...Markup.keyboard([
choice.filter((i) => i >= 50).map(i => String(i)),
['Β« Back'],
]).oneTime().resize()
})
} else if (single === 0) {
const new_single = Number(input) || 0
if (new_single < 50 || new_single > total) {
let choice = [0, 0, 0]
choice[0] = Math.floor(total * 0.1 / 50) * 50
choice[1] = Math.floor(total * 0.2 / 50) * 50
choice[2] = Math.floor(total * 0.4 / 50) * 50
ctx.reply(t(`π’ Invalid Amount\nPlease enter a valid amount between 50 and your CopyTrading Total Amount, {{total}}`, lang, {
total: total.toFixed(2)
}), {
...Markup.keyboard([
choice.filter((i) => i >= 50).map(i => String(i)),
['Β« Back'],
])
})
} else {
await redis.set(`intent:${from.id}`, JSON.stringify({
category: 'cb_copy_setting',
value: {
...intent.value,
single: new_single,
}
}), {
ex: 600
})
ctx.reply(t(`π©βπ» Confirm\nββββββββββββββββββββ\nCopy Trading Total Amount: {{total}} NEST \nCopy Trading Each Order: {{input}} NEST \n\nYou are following: {{nickName}}\nAre you sure?`, lang, {
total: total.toFixed(2),
input: Number(input).toFixed(2),
nickName: nickName,
}), {
...Markup.inlineKeyboard([
[Markup.button.callback(t(`Yes, Iβm sure.`, lang), 'confirm_copy_setting')],
[Markup.button.callback(t(`Nope, I change my mind.`, lang), 'cancel_copy_setting')]
])
})
}
}
}
}
})
export const handler = http(bot.webhookCallback("/bot"));