-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
3148 lines (2778 loc) · 105 KB
/
index.js
File metadata and controls
3148 lines (2778 loc) · 105 KB
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require("dotenv/config");
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const { Telegraf, Markup } = require("telegraf");
const Queue = require("queue-promise");
const connectDb = require("./db/connectDb");
const User = require("./models/User");
require("dotenv").config();
const fs = require("fs");
const { TelegramClient, Api } = require("telegram");
const { StringSession } = require("telegram/sessions");
const input = require("input"); // for prompting in terminal
const { message } = require("telegraf/filters");
const checkParticipantEligibity = require("./helpers/checkParticipantEligibity");
const Group = require("./models/Group");
const createInviteLink = require("./helpers/createInviteLink");
const sendInviteMessage = require("./helpers/sendInviteMessage");
const createGroup = require("./services/createGroup");
const allParticipantsHaveJoined = require("./helpers/allParticipantsHaveJoined");
const startEscrow = require("./services/startEscrow");
const requestDeposit = require("./helpers/requestDeposit");
const findUserEscrow = require("./helpers/findUserEscrow");
const checkDeposit = require("./services/checkDeposit");
const System = require("./models/System");
const MultiChainWallet = require("./wallet/wallet_create");
const { checkSolBalance, checkEvmBalance } = require("./helpers/checkBalance");
const getLiveFee = require("./wallet/fees_calc");
const getFeeInNative = require("./helpers/getFeeInNative");
const nativeFeeToUSD = require("./helpers/nativeFeeToUSD");
const transferFunds = require("./services/transferFunds");
const clearGroupMessages = require("./helpers/clearGroupMessages");
const revokeLink = require("./helpers/revokeLink");
const isFormMessage = require("./helpers/isFormMessage");
const isGroupMember = require("./helpers/isGroupMember");
const updateCache = require("./helpers/updateCache");
const pinMessageInGroup = require("./helpers/pinMessage");
const isGroupAdmin = require("./helpers/isGroupAdmin");
const bot = new Telegraf(process.env.BOT_TOKEN);
global.bot = bot;
global.activeEscrows = [];
const app = express();
// throttle queue: up to 25 messages/sec → interval ≈ 40 ms, concurrency 1
const msgQueue = new Queue({ concurrent: 1, interval: 40 });
//system schema
// utility to enqueue send/edit
function sendWrapped(fn) {
msgQueue.enqueue(() => fn().catch(console.error));
}
// middleware: ensure channel membership
async function requireJoin(ctx, next) {
try {
const member = await ctx.telegram.getChatMember(
global.channel,
ctx.from.id
);
const okStatuses = ["member", "creator", "administrator"];
if (!okStatuses.includes(member.status)) {
await ctx.reply(
`Please join the channel to use this bot.\n\nلطفاً برای استفاده از ربات، به کانال بپیوندید:\n${global.channel}`
);
return;
}
} catch (err) {
console.error(err);
await ctx.reply(
"Error verifying membership. Try again later.\n\nخطا در بررسی عضویت. لطفاً بعداً دوباره امتحان کنید."
);
return;
}
return next();
}
bot.start(async (ctx) => {
const { id: chatId, username } = ctx.from;
let user = await User.findOne({ chatId });
if (!user) {
await User.create({ chatId, username });
}
ctx.reply("Welcome");
});
const apiId = parseInt(process.env.API_ID);
const apiHash = process.env.API_HASH;
const sessionString = process.env.SESSION_STRING || ""; // For user accounts
const session = new StringSession(sessionString);
const client = new TelegramClient(session, apiId, apiHash, {
connectionRetries: 5,
});
global.client = client;
// Admin and allowed users configuration
const ADMINS = ["@endurenow", "@jsornothing", "@escrowfatherthe"]; // Replace with actual admin usernames
const BOT_USERNAME = "@escrow_tg_official_bot"; // Replace with your bot's username
const ALLOWED_USERS = ["@xdfrozennn"]; // Users allowed to join via link
// (async () => {
// await client.connect();
// })();
// async function handleUpdate(update) {
// if (update instanceof Api.UpdateChatParticipants) {
// const participants = update.participants;
// // Only process our target group
// if (groupId && participants.chatId.toString() !== groupId) return;
// for (const participant of participants.newParticipants || []) {
// try {
// const user = await client.getEntity(participant.userId);
// const username = user.username
// ? `@${user.username}`
// : user.id.toString();
// // Check if user is allowed
// if (!ALLOWED_USERS.includes(username)) {
// console.log(`Removing unauthorized user: ${username}`);
// await removeUser(groupId, user);
// continue;
// }
// // Track allowed users
// if (!joinedUsers.has(username)) {
// joinedUsers.add(username);
// console.log(`Allowed user joined: ${username}`);
// // Check if all allowed users have joined
// if (joinedUsers.size === ALLOWED_USERS.length) {
// await revokeLinkAndScheduleCleanup();
// }
// }
// } catch (error) {
// console.error("Error processing participant:", error);
// }
// }
// }
// }
// Add this after client.connect()
async function revokeLinkAndScheduleCleanup() {
// try {
// const botChatId = `-100${groupId.toString()}`;
// console.log("All allowed users have joined - revoking link...");
// // 1️⃣ Revoke old link
// await bot.telegram.revokeChatInviteLink(botChatId, groupLink);
// // 2️⃣ Create new link
// const newLink = await bot.telegram.createChatInviteLink(botChatId, {
// expire_date: Math.floor(Date.now() / 1000) + 86400, // 1 day expiry
// member_limit: 8, // optional: limit members
// });
// console.log(`✅ Old link revoked!\n🔗 New link: ${newLink.invite_link}`);
// // Schedule cleanup after 10 minutes
// setTimeout(async () => {
// try {
// console.log("Executing scheduled cleanup...");
// await removeAllowedUsers();
// ALLOWED_USERS.length = 0; // Empty the array
// console.log(
// "Cleanup complete. Allowed users removed and array cleared."
// );
// } catch (error) {
// console.error("Cleanup error:", error);
// }
// }, 10 * 60 * 1000); // 10 minutes
// } catch (error) {
// console.error("Error revoking link:", error);
// }
try {
// 1️⃣ Get all active invite links for the group
const invites = await client.invoke(
new Api.messages.GetExportedChatInvites({
peer: groupId,
adminId: await client.getMe(),
limit: 50,
})
);
// 2️⃣ Revoke all existing active links
for (const invite of invites.invites) {
try {
await client.invoke(
new Api.messages.DeleteExportedChatInvite({
peer: groupId,
link: invite.link,
})
);
} catch (err) {
console.warn(`Failed to delete invite ${invite.link}: ${err.message}`);
}
}
// 3️⃣ Create a brand new invite link
const newInvite = await client.invoke(
new Api.messages.ExportChatInvite({
peer: groupId,
expireDate: 0, // 0 = never expire
usageLimit: 0, // 0 = unlimited uses
legacyRevokePermanent: true,
})
);
console.log("✅ New invite link created:", newInvite.link);
return newInvite.link;
} catch (error) {
console.error("❌ Failed to revoke/regenerate links:", error);
}
}
async function removeAllowedUsers() {
if (!client.connected) {
await client.connect();
console.log("Reconnected successfully");
}
try {
// Get current participants
const participants = await client.invoke(
new Api.channels.GetParticipants({
channel: groupId,
filter: new Api.ChannelParticipantsRecent(),
limit: 100,
})
);
// Remove each allowed user
for (const user of participants.users) {
const username = user.username ? `@${user.username}` : user.id.toString();
if (ALLOWED_USERS.includes(username)) {
await removeUser(groupId, user);
console.log(`Removed user: ${username}`);
}
}
await client.disconnect();
} catch (error) {
console.error("Error removing users:", error);
}
}
async function removeUser(groupId, user) {
if (!client.connected) {
await client.connect();
console.log("Reconnected successfully");
}
await client.invoke(
new Api.channels.EditBanned({
channel: groupId,
participant: user,
bannedRights: new Api.ChatBannedRights({
viewMessages: false, // Important: false means remove but don't ban
untilDate: 0,
}),
})
);
await client.disconnect();
}
bot.command("escrow", async (ctx) => {
const chat = ctx.chat;
// 1️⃣ Ensure command is run in a group
if (chat.type !== "group" && chat.type !== "supergroup") {
return ctx.reply("❌ This command can only be used in a group chat.", {
reply_to_message_id: ctx.message.message_id,
});
}
const chatId = ctx.chat.id;
const messageId = ctx.message.message_id;
//Store this message for deletion later
const escrowInitiatorMsg = {
chatId,
messageId,
};
let sellerUsername = ctx.from.username;
if (!sellerUsername) {
return ctx.reply("❌ Please set a username to use escrow", {
reply_to_message_id: ctx.message.message_id,
});
}
// 2️⃣ Get username argument
const args = ctx.message.text.trim().split(" ").slice(1);
let buyerUsername = args[0]?.replace(/^@/, ""); // remove @ if present
if (!buyerUsername) {
return ctx.reply(
"⚠️ Please provide a username. Example: /escrow @username",
{
reply_to_message_id: ctx.message.message_id,
}
);
}
try {
// 3️⃣ Try to find user in group
const admins = await ctx.telegram.getChatAdministrators(chat.id);
let found = false;
// Check admins first
found = admins.some(
(admin) =>
admin.user.username?.toLowerCase() === buyerUsername.toLowerCase()
);
const buyerUser = await client.getEntity(buyerUsername);
// If not found in admins, try getChatMember for regular members
if (!found) {
console.log("Checking members");
try {
const member = await ctx.telegram.getChatMember(chat.id, buyerUser.id);
found = member.status !== "left" && member.status !== "kicked";
} catch (err) {
console.log("Err checking members", err);
// Will throw if user not found
found = false;
}
}
// 4️⃣ Reply appropriately
if (found) {
sellerUsername = `@` + sellerUsername.toLowerCase();
buyerUsername = `@` + buyerUsername.toLowerCase();
const groupsExist = await Group.find();
//If at least a group exists, check for free groups
if (groupsExist.length > 0) {
//Check if they have pending escrows
const usernames = [sellerUsername, buyerUsername];
const checkResult = await checkParticipantEligibity(usernames, client);
//Reply and reject escrow request
if (checkResult.inAGroup) {
return await ctx.reply(checkResult.message, {
reply_to_message_id: ctx.message.message_id,
parse_mode: "Markdown",
});
}
//Look for an empty group
const emptyGroups = await Group.find({
inUse: false,
"currentDeal.participants": { $size: 0 },
});
if (emptyGroups.length == 0) {
//No empty groups, proceed with new group creation
createGroup(
[sellerUsername, buyerUsername],
client,
ctx,
escrowInitiatorMsg
);
} else {
//Empty groups exist, invite users to the first one
const groupToUse = emptyGroups[0];
//Setup group
await groupToUse.updateOne({
escrowInitiatorMsg,
inUse: true,
currentDeal: {
participants: [
{ role: "Seller", username: sellerUsername },
{ role: "Buyer", username: buyerUsername },
],
},
});
//Create invite link
const link = await createInviteLink(client, groupToUse.groupId);
sendInviteMessage(
ctx,
sellerUsername,
buyerUsername,
groupToUse.name,
link,
client,
groupToUse.id,
chatId,
true // Indicate that groupId was included, so that it saves the invite msg to db instantly
);
}
} else {
//Since no groups have been created, just create one
createGroup(
[sellerUsername, buyerUsername],
client,
ctx,
escrowInitiatorMsg
);
}
} else {
ctx.reply(
`❌ @${buyerUsername} is NOT a member of this group. They must be in this group to use escrow.`,
{
reply_to_message_id: ctx.message.message_id,
}
);
}
} catch (err) {
console.error("Error checking member:", err);
// await ctx.reply("⚠️ Could not verify member status.", {
// reply_to_message_id: ctx.message.message_id,
// });
}
});
bot.action("confirm-deposit", async (ctx) => {
await ctx.answerCbQuery();
try {
const username = ctx.from.username;
if (!username) {
return ctx.reply("❌ You must set a username to use that command.");
}
//check if they have an active escrow session
const userEscrowGroup = findUserEscrow("@" + username);
if (!userEscrowGroup) {
return ctx.reply("❌ Network error. Please try again.");
}
//check if the right party sent that command (seller only)
const seller = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Seller"
);
const buyer = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Buyer"
);
const invokerUsername = "@" + ctx.from.username;
if (seller.username.toLowerCase() !== invokerUsername.toLowerCase()) {
return ctx.reply(
`❌ You can't use that command.\nOnly [${seller.username}](tg://user?id=${seller.userId}) can confirm deposits.`,
{
parse_mode: "Markdown",
}
);
}
const { network, token, cryptoAmount } = userEscrowGroup.currentDeal;
const { totalAmount, waitingForDeposit } = userEscrowGroup;
if (!waitingForDeposit) {
return await ctx.reply("Already confirmed deposit.\nPlease proceed.");
}
await ctx.reply("🔍 I will confirm in the next 5 secs...");
const { wallets } = userEscrowGroup;
const deposit = {
native: null,
usdt: null,
usdc: null,
};
setTimeout(() => {
const confirmBalances = async () => {
if (network == "POL") {
const polBalances = await checkEvmBalance(
"pol",
wallets["POL"].address
);
deposit["native"] = polBalances.native;
deposit["usdc"] = polBalances.usdc;
deposit["usdt"] = polBalances.usdt;
} else if (network == "SOL") {
const solBalances = await checkSolBalance(wallets["SOL"].address);
deposit["native"] = solBalances.native;
deposit["usdc"] = solBalances.usdc;
deposit["usdt"] = solBalances.usdt;
} else {
const bscBalances = await checkEvmBalance(
"bsc",
wallets["BEP20"].address
);
console.log(bscBalances);
deposit["native"] = bscBalances.native;
deposit["usdc"] = bscBalances.usdc;
deposit["usdt"] = bscBalances.usdt;
}
console.log("fetched deposits", deposit);
//Reject native deposits
if (!deposit[token.toLowerCase()])
return await ctx.reply(
`No deposit of ${token} found🔍`,
{ parse_mode: "Markdown" }
);
//Confirm deposit
let msg = `Deposit of $${deposit.usdc} ${token.toUpperCase()} on ${
network.toLowerCase() == "bep20" ? "BSC" : network.toUpperCase()
} confirmed✅`;
//Check deposit equality
const expectedAmount = userEscrowGroup.totalAmount;
const amountDeposited = deposit[token.toLowerCase()];
//If they sent greater amounts
if (amountDeposited > expectedAmount) {
//check if the excess is over $1
const excess = amountDeposited - expectedAmount > 1;
//Delete invoker msg
await ctx.deleteMessage();
const refundAmount = amountDeposited - expectedAmount;
//Calculate tx fee for refund
let feeInNative = await getFeeInNative(network.toUpperCase(), token);
const feeInUsd = await nativeFeeToUSD(
network.toUpperCase(),
feeInNative
); //1x of fees to cover buyer refund
const buyerNetworkFeeInUSD = excess ? feeInUsd : 0; //Charge buyer network fees if seller needs a refund
const escrowFee = Number(((0.5 / 100) * cryptoAmount).toFixed(3));
const buyerPayment = Number(
(cryptoAmount - (escrowFee + buyerNetworkFeeInUSD)).toFixed(3)
); //Deduct refund fee from buyer's payment
const buyerUsername = buyer.username.replace("@", "");
const buyerMention = `<a href="tg://user?id=${buyer.userId}">${buyerUsername}</a>`;
msg += `
${excess ? `Expected amount: <b>${expectedAmount} USD</b>` : ""}
Amount Deposited: <b>${amountDeposited} USD</b>
Escrow Fee(0.5%): <b>${escrowFee} USD</b>
${excess ? `Refund Amount: <b>${refundAmount} USD</b>` : ""}
${excess ? `Refund fee: <b>${feeInUsd} USD</b>` : ""}
Hey ${buyerMention}, you will receive: <b>${buyerPayment} USD</b>
Please send the fiat equivalent of $${cryptoAmount} to ${seller.username} 👇
<b>Payment Method:</b> ${userEscrowGroup.currentDeal.paymentMethod}
<b>Payment Details:</b> ${userEscrowGroup.currentDeal.fiatPaymentDetails}
After sending fiat, please confirm payment`;
await ctx.reply(msg, {
parse_mode: "HTML",
reply_markup: {
inline_keyboard: [
[
{
text: "Fiat Paid✅",
callback_data: "confirm-fiat",
},
],
],
},
});
//Update group record with changed parameters
const updatedGroupInfo = await Group.findOneAndUpdate(
{ groupId: userEscrowGroup.groupId },
{
$set: {
refundAmount: excess ? refundAmount : 0,
waitingForDeposit: false,
feeCount: excess ? 3 : 2,
withdrawalAmount: buyerPayment,
typeOfPaymentReceived: deposit.native ? "native" : "token",
},
},
{ new: true }
);
//Update in cache
return updateCache(userEscrowGroup, updatedGroupInfo);
}
//If they send lesser amounts
if (
amountDeposited < expectedAmount &&
expectedAmount - amountDeposited > 0.5
) {
return await ctx.reply(
`[${seller.username}](tg://user?id=${
seller.userId
}) you sent *$${amountDeposited}* out of *$${expectedAmount}*.
Send $${(expectedAmount - amountDeposited).toFixed(2)} more to continue.
After topup, click *Confirm*✅ above so i can check`,
{
parse_mode: "Markdown",
}
);
}
//If they paid the exact amount
if (amountDeposited == expectedAmount) {
//Delete invoker msg
await ctx.deleteMessage();
const escrowFee = Number(((0.5 / 100) * cryptoAmount).toFixed(3));
const buyerPayment = Number((cryptoAmount - escrowFee).toFixed(3));
msg += `
Amount Deposited: <b>${amountDeposited} USD</b>
Escrow Fee(0.5%): <b>${escrowFee} USD</b>
Hey <a href="tg://user?id=${buyer.userId}">${buyer.username}</a>, you will receive: <b>$${buyerPayment} USD</b>
Please send the fiat equivalent of $${cryptoAmount} to ${seller.username} 👇
<b>Payment Method:</b> ${userEscrowGroup.currentDeal.paymentMethod}
<b>Payment Details:</b> ${userEscrowGroup.currentDeal.fiatPaymentDetails}
After sending fiat, please confirm payment`;
await ctx.reply(msg, {
parse_mode: "HTML",
reply_markup: {
inline_keyboard: [
[
{
text: "Fiat Paid✅",
callback_data: "confirm-fiat",
},
],
],
},
});
//Update group record with changed parameters
const updatedGroupInfo = await Group.findOneAndUpdate(
{ groupId: userEscrowGroup.groupId },
{
$set: {
waitingForDeposit: false,
feeCount: 2,
withdrawalAmount: buyerPayment,
typeOfPaymentReceived: deposit.native ? "native" : "token",
},
},
{ new: true }
);
//Update in cache
updateCache(userEscrowGroup, updatedGroupInfo);
return;
}
};
confirmBalances();
}, 1000 * 5);
// console.log("Deposit check result", deposit);
} catch (error) {
console.log("Error in >confirm-deposit handler:\n", error);
}
});
bot.action("admin-confirm-deposit", async (ctx) => {
// await ctx.answerCbQuery();
try {
const isAdmin = await isGroupAdmin(ctx);
const groupId = Number(ctx.chat.id.toString().split("-100")[1]);
// if(!isAdmin) {
// return await ctx.reply("A non-admin tried to confirm deposit manually⚠️\nFraud attempt😂\n\nONLY admins can do that!")
// }
const userEscrowGroup = global.activeEscrows.find(
(e) => e.groupId == groupId
);
const amountExpected = userEscrowGroup.totalAmount;
const { cryptoAmount, token, paymentMethod, fiatPaymentDetails } =
userEscrowGroup.currentDeal;
const seller = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Seller"
);
const buyer = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Buyer"
);
await ctx.deleteMessage();
await ctx.reply(
`Deposit of ${amountExpected.toFixed(
2
)} ${token} has been manually confirmed by the admin.`
);
const escrowFee = Number(((0.5 / 100) * cryptoAmount).toFixed(3));
const buyerPayment = Number((cryptoAmount - escrowFee).toFixed(3));
console.log(escrowFee, cryptoAmount, buyerPayment);
const msg = `
Escrow Fee(0.5%): <b>${escrowFee} USD</b>
Hey <a href="tg://user?id=${buyer.userId}">${buyer.username}</a>, you will receive: <b>$${buyerPayment} USD</b>
Please send the fiat equivalent of $${cryptoAmount} to ${seller.username} 👇
<b>Payment Method:</b> ${paymentMethod}
<b>Payment Details:</b> ${fiatPaymentDetails}
After sending fiat, please confirm payment`;
await ctx.reply(msg, {
parse_mode: "HTML",
reply_markup: {
inline_keyboard: [
[
{
text: "Fiat Paid✅",
callback_data: "confirm-fiat",
},
],
],
},
});
//Update group record with changed parameters
const updatedGroupInfo = await Group.findOneAndUpdate(
{ groupId: userEscrowGroup.groupId },
{
$set: {
waitingForDeposit: false,
feeCount: 2,
withdrawalAmount: buyerPayment,
},
},
{ new: true }
);
//Update in cache
updateCache(userEscrowGroup, updatedGroupInfo);
} catch (error) {
console.log("Error in admin deposit confirmation:\n", error);
}
});
bot.action("confirm-fiat", async (ctx) => {
try {
const username = ctx.from.username;
if (!username) {
return ctx.reply("❌ You must set a username to use that command.");
}
//check if they have an active escrow session
const userEscrowGroup = findUserEscrow("@" + username);
if (!userEscrowGroup) {
return ctx.reply("❌ Network error. Please try again.");
}
//check if the right party sent that command (buyer only)
const seller = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Seller"
);
const buyer = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Buyer"
);
const invokerUsername = "@" + ctx.from.username;
if (buyer.username.toLowerCase() !== invokerUsername.toLowerCase()) {
return ctx.reply(
`❌ You can't use that command.\nOnly [${buyer.username}](tg://user?id=${buyer.userId}) can confirm fiat payment.`,
{
parse_mode: "Markdown",
}
);
}
await ctx.deleteMessage();
const sellerMention = `<a href="tg://user?id=${seller.userId}">${seller.username}</a>`;
const confirm1Msg = await ctx.reply(
`Hey ${sellerMention}, the [Buyer] has confirmed fiat payment.
Please check your account to confirm fiat is received before releasing the crypto.
Please note that this process is irreversible.
<b>Release Crypto ONLY</b> if you are <b>SURE</b>`,
{
parse_mode: "HTML",
reply_markup: {
inline_keyboard: [
[
{
text: "Release Payment",
callback_data: "fiat-received",
},
],
[
{
text: "Partial Release Payment",
callback_data: "partial",
},
],
[
{
text: "Dispute",
callback_data: "dispute",
},
{
text: "CANCEL",
callback_data: "try-cancel-release",
},
],
],
},
}
);
//Update group record with changed parameters
const updatedGroupInfo = await Group.findOneAndUpdate(
{ groupId: userEscrowGroup.groupId },
{
$set: {
confirm1Msg: confirm1Msg.message_id,
},
},
{ new: true }
);
//Update in cache
updateCache(userEscrowGroup, updatedGroupInfo);
} catch (error) {
console.log("Error in >fiat-paid handler:\n", error);
}
});
bot.action("fiat-received", async (ctx) => {
try {
const username = ctx.from.username;
if (!username) {
return ctx.reply("❌ You must set a username to use that command.");
}
//check if they have an active escrow session
const userEscrowGroup = findUserEscrow("@" + username);
if (!userEscrowGroup) {
console.log(userEscrowGroup);
return ctx.reply("❌ Network error. Please try again.");
}
//check if the right party sent that command (buyer only)
const seller = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Seller"
);
const buyer = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Buyer"
);
const invokerUsername = "@" + ctx.from.username;
if (seller.username.toLowerCase() !== invokerUsername.toLowerCase()) {
return ctx.reply(
`❌ You can't use that command.\nOnly [${seller.username}](tg://user?id=${seller.userId}) can release payment.`,
{
parse_mode: "Markdown",
}
);
}
//Remove the buttons from confirm1Msg
await ctx.telegram.editMessageReplyMarkup(
ctx.chat.id,
userEscrowGroup.confirm1Msg,
undefined,
{
inline_keyboard: [],
}
);
const confirm2Msg = await ctx.reply(
`[${seller.username}](tg://user?id=${seller.userId}) are you really Really REALLY Sure???
*Your ${userEscrowGroup.currentDeal.token}* will be sent to ${buyer.username} and if you have not received your *INR*, then you are responsible for your LOSS!`,
{
parse_mode: "Markdown",
reply_markup: {
inline_keyboard: [
[
{
text: "Yes, I am Responsible!",
callback_data: "i-am-responsible",
},
],
],
},
}
);
//Update group record with changed parameters
const updatedGroupInfo = await Group.findOneAndUpdate(
{ groupId: userEscrowGroup.groupId },
{
$set: {
confirm2Msg: confirm2Msg.message_id,
},
},
{ new: true }
);
//Update in cache
updateCache(userEscrowGroup, updatedGroupInfo);
} catch (error) {
console.log("Error in >fiat--received handler:\n", error);
}
});
bot.action("partial", async (ctx) => {
try {
const username = ctx.from.username;
if (!username) {
return ctx.reply("❌ You must set a username to use that command.");
}
//check if they have an active escrow session
const userEscrowGroup = findUserEscrow("@" + username);
if (!userEscrowGroup) {
return ctx.reply("❌ Network error. Please try again.");
}
//check if the right party sent that command (buyer only)
const seller = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Seller"
);
const buyer = userEscrowGroup.currentDeal.participants.find(
(e) => e.role == "Buyer"
);
const sellerMention = `<a href="tg://user?id=${seller.userId}">${seller.username}</a>`;
const buyerMention = `<a href="tg://user?id=${buyer.userId}">${buyer.username}</a>`;
const { groupId } = userEscrowGroup;
const { token, network } = userEscrowGroup.currentDeal;
const invokerUsername = "@" + ctx.from.username;
if (seller.username.toLowerCase() !== invokerUsername.toLowerCase()) {
return ctx.reply(
`❌ You can't click that button.\nOnly [${seller.username}](tg://user?id=${seller.userId}) can confirm release crypto partially.`,
{
parse_mode: "Markdown",
}
);
}
let feeInNative = await getFeeInNative(network.toUpperCase(), token);
const feeInUSD = await nativeFeeToUSD(network, feeInNative);
const message = `
${sellerMention} [Seller] please <b>QUOTE</b> this message and reply with the Amount of <b>${token}</b> to Release to ${buyerMention} [Buyer].
Please be mindful that the amount needs to be equivalent to the <b>INR</b> you received.
⚠️ <b>Important:</b> Please discuss with the buyer before replying with the amount to avoid disputes.
Once the seller replies with the amount, ${buyerMention} [Buyer] needs to confirm it before the release is finalized.
The remaining ${token} will be refunded to the seller accordingly
Escrow fees will be deducted before releasing ${token} to the Buyer.
And Refund Network fee of $${feeInUSD.toFixed(
2
)} will be deducted before releasing to the Seller.`;
await ctx.editMessageText(message, {parse_mode:"HTML"});
const updatedGroupInfo = await Group.findOneAndUpdate(
{ groupId },
{
$set: {
takingPartialAmount: true,
},
},
{ new: true }
);
updateCache(userEscrowGroup, updatedGroupInfo);
} catch (error) {
console.log("Error in >partial handler:\n", error);
}
});
bot.action("i-am-responsible", async (ctx) => {
try {
const username = ctx.from.username;
if (!username) {
return ctx.reply("❌ You must set a username to use that command.");
}
//check if they have an active escrow session
const userEscrowGroup = findUserEscrow("@" + username);
if (!userEscrowGroup) {
console.log(userEscrowGroup);
return ctx.reply("❌ Network error. Please try again.");
}