Skip to content

Commit a46260d

Browse files
Convert JS to TS (commits 7-13 of PR435) - attempt#2 (lnp2pBot#585)
* util/index: convert js to ts The languageModel & fiatModel interface created to type-check the data and ensure that it conforms to the expected structure and format. This can help you avoid errors and bugs when working with the data in your code. This commit enables resolveJsonModule to import module with '.json' extension. Co-authored-by: webwarrior <[email protected]> * jobs: convert js to ts The --downlevelIteration flag is a TypeScript compiler option that enables support for iterating over new concepts like Map, Set, or Generator in older JavaScript runtimes. By default, TypeScript targets ES3, which does not support these features. If you use a for...of loop or a spread operator on an iterable object, you may get an error. Use Date instead of Date.toISOString cause paid_at has type Date and during the conversion from js to ts, we got compilation errors. Co-authored-by: webwarrior <[email protected]> * bot/start: fixing types & import/exports Co-authored-by: webwarrior <[email protected]> * bot/validation: convert js to ts Using null instead of a boolean/undefined type is better. * lnurl/lnurl-pay: convert js to ts I had to change the '|', otherwise typescript would complain this error msg: ``` The '|' operator is not allowed for boolean types. Consider using '||' instead. ``` Co-authored-by: webwarrior <[email protected]> * refactor: correcting a bad practice * refactor: there's no need for isInt() * bot: fix bugs in validations.ts Fix bugs in validations.ts introduced in d36a6b7 when porting to TypeScript. * bot,util: fix bug in validateAdmin Fixed bug in validateAdmin that would throw an error when community is null even though null value is valid in this case. * bot: fix date comparison in isValidInvoice Don't convert dates to strings in isValidInvoice. * WIP: added some debug logging Added debug logging for case when `Invoice expiry is too short` error is encountered. * WIP: more debug logging Added debug logging of message that caused error when taking dispute in community. * bot,util,locales,tests: don't use objects in locales Don't use object properties inside locales, as it doesn't work and leads to parse errors. --------- Co-authored-by: Mehrshad <[email protected]>
1 parent 2ee0fce commit a46260d

29 files changed

+427
-311
lines changed

bot/modules/dispute/messages.js

+24-20
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
const { getDisputeChannel, getDetailedOrder, sanitizeMD } = require('../../../util');
1+
const {
2+
getDisputeChannel,
3+
getDetailedOrder,
4+
sanitizeMD,
5+
} = require('../../../util');
26
const { logger } = require('../../../logger');
37

48
exports.beginDispute = async (ctx, initiator, order, buyer, seller) => {
@@ -91,25 +95,25 @@ exports.disputeData = async (
9195
// Fix Issue 543: Escape underscores in usernames
9296
const escapedInitiatorUsername = sanitizeMD(initiatorUser.username);
9397
const escapedCounterPartyUsername = sanitizeMD(counterPartyUser.username);
94-
95-
await ctx.telegram.sendMessage(
96-
solver.tg_id,
97-
ctx.i18n.t('dispute_started_channel', {
98-
initiatorUser: { ...initiatorUser, username: escapedInitiatorUsername },
99-
initiatorTgId: initiatorUser.tg_id,
100-
counterPartyUser: { ...counterPartyUser, username: escapedCounterPartyUsername },
101-
counterPartyUserTgId: counterPartyUser.tg_id,
102-
buyer,
103-
seller,
104-
buyerDisputes,
105-
sellerDisputes,
106-
detailedOrder,
107-
type,
108-
sellerToken: order.seller_dispute_token,
109-
buyerToken: order.buyer_dispute_token,
110-
}),
111-
{ parse_mode: 'MarkdownV2' }
112-
);
98+
99+
const message = ctx.i18n.t('dispute_started_channel', {
100+
initiatorUser: escapedInitiatorUsername,
101+
initiatorTgId: initiatorUser.tg_id,
102+
counterPartyUser: escapedCounterPartyUsername,
103+
counterPartyUserTgId: counterPartyUser.tg_id,
104+
buyer,
105+
seller,
106+
buyerDisputes,
107+
sellerDisputes,
108+
detailedOrder,
109+
type,
110+
sellerToken: order.seller_dispute_token,
111+
buyerToken: order.buyer_dispute_token,
112+
});
113+
console.log(`Contens of message:\n${message}`);
114+
await ctx.telegram.sendMessage(solver.tg_id, message, {
115+
parse_mode: 'MarkdownV2',
116+
});
113117
// message to both parties letting them know the dispute
114118
// has been taken by a solver
115119
await ctx.telegram.sendMessage(

bot/start.ts

+41-34
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,17 @@ import { Message } from 'typegram'
44
import { UserDocument } from '../models/user'
55
import { FilterQuery } from 'mongoose';
66
const OrderEvents = require('./modules/events/orders');
7-
8-
const { limit } = require('@grammyjs/ratelimiter');
7+
import { limit } from "@grammyjs/ratelimiter"
98
const schedule = require('node-schedule');
10-
const {
9+
import {
1110
Order,
1211
User,
1312
PendingPayment,
1413
Community,
1514
Dispute,
1615
Config,
17-
} = require('../models');
18-
const { getCurrenciesWithPrice, deleteOrderFromChannel, removeAtSymbol } = require('../util');
16+
} from '../models';
17+
import { getCurrenciesWithPrice, deleteOrderFromChannel, removeAtSymbol } from '../util';
1918
const {
2019
commandArgsMiddleware,
2120
stageMiddleware,
@@ -55,32 +54,34 @@ const {
5554
validateLightningAddress,
5655
} = require('./validations');
5756
import * as messages from './messages';
58-
const {
57+
import {
5958
attemptPendingPayments,
6059
cancelOrders,
6160
deleteOrders,
6261
calculateEarnings,
6362
attemptCommunitiesPendingPayments,
6463
deleteCommunity,
6564
nodeInfo,
66-
} = require('../jobs');
67-
const { logger } = require('../logger');
65+
} from '../jobs';
66+
import { logger } from "../logger";
67+
import { ICommunity, IUsernameId } from '../models/community';
68+
6869
export interface MainContext extends Context {
6970
match: Array<string> | null;
7071
i18n: I18nContext;
7172
user: UserDocument;
7273
admin: UserDocument;
7374
}
7475

75-
interface OrderQuery {
76+
export interface OrderQuery {
7677
status?: string;
7778
buyer_id?: string;
7879
seller_id?: string;
7980
}
8081

8182
const askForConfirmation = async (user: UserDocument, command: string) => {
8283
try {
83-
let orders = [];
84+
let orders: any[] = [];
8485
if (command === '/cancel') {
8586
const where: FilterQuery<OrderQuery> = {
8687
$and: [
@@ -133,6 +134,7 @@ const askForConfirmation = async (user: UserDocument, command: string) => {
133134
return orders;
134135
} catch (error) {
135136
logger.error(error);
137+
return null;
136138
}
137139
};
138140

@@ -145,7 +147,7 @@ has the same condition.
145147
The problem mentioned above is similar to this issue:
146148
https://github.com/telegraf/telegraf/issues/1319#issuecomment-766360594
147149
*/
148-
const ctxUpdateAssertMsg = "ctx.update.message.text is not available.";
150+
export const ctxUpdateAssertMsg = "ctx.update.message.text is not available.";
149151

150152
const initialize = (botToken: string, options: Partial<Telegraf.Options<MainContext>>): Telegraf<MainContext> => {
151153
const i18n = new I18n({
@@ -215,7 +217,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
215217
const [val] = await validateParams(ctx, 2, '\\<_on/off_\\>');
216218
if (!val) return;
217219
let config = await Config.findOne();
218-
if (!config) {
220+
if (config === null) {
219221
config = new Config();
220222
}
221223
config.maintenance = false;
@@ -262,11 +264,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
262264
throw new Error(ctxUpdateAssertMsg);
263265
}
264266
const params = ctx.update.message.text.split(' ');
265-
const [command, orderId] = params.filter((el) => el);
267+
const [command, orderId] = params.filter((el: string) => el);
266268

267269
if (!orderId) {
268270
const orders = await askForConfirmation(ctx.user, command);
269-
if (!orders.length) return await ctx.reply(`${command} <order Id>`);
271+
if (orders === null || orders.length === 0) return await ctx.reply(`${command} <order Id>`);
270272

271273
return await messages.showConfirmationButtons(ctx, orders, command);
272274
} else if (!(await validateObjectId(ctx, orderId))) {
@@ -325,7 +327,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
325327
if (!(await validateObjectId(ctx, orderId))) return;
326328
const order = await Order.findOne({ _id: orderId });
327329

328-
if (!order) return;
330+
if (order === null) return;
329331

330332
// We look for a dispute for this order
331333
const dispute = await Dispute.findOne({ order_id: order._id });
@@ -367,10 +369,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
367369

368370
order.status = 'CANCELED_BY_ADMIN';
369371
order.canceled_by = ctx.admin._id;
370-
const buyer = await User.findOne({ _id: order.buyer_id });
371-
const seller = await User.findOne({ _id: order.seller_id });
372372
await order.save();
373373
OrderEvents.orderUpdated(order);
374+
const buyer = await User.findOne({ _id: order.buyer_id });
375+
const seller = await User.findOne({ _id: order.seller_id });
376+
if (buyer === null || seller === null) throw Error("buyer and/or seller were not found in DB");
374377
// we sent a private message to the admin
375378
await messages.successCancelOrderMessage(ctx, ctx.admin, order, ctx.i18n);
376379
// we sent a private message to the seller
@@ -390,11 +393,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
390393
throw new Error(ctxUpdateAssertMsg);
391394
}
392395
const params = ctx.update.message.text.split(' ');
393-
const [command, orderId] = params.filter((el) => el);
396+
const [command, orderId] = params.filter((el: string) => el);
394397

395398
if (!orderId) {
396399
const orders = await askForConfirmation(ctx.user, command);
397-
if (!orders.length) return await ctx.reply(`${command} <order Id>`);
400+
if (orders === null || orders.length === 0) return await ctx.reply(`${command} <order Id>`);
398401

399402
return await messages.showConfirmationButtons(ctx, orders, command);
400403
} else if (!(await validateObjectId(ctx, orderId))) {
@@ -445,7 +448,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
445448
await order.save();
446449
OrderEvents.orderUpdated(order);
447450
// We delete the messages related to that order from the channel
448-
await deleteOrderFromChannel(order, bot.telegram);
451+
await deleteOrderFromChannel(order, bot.telegram as any);
449452
}
450453
// we sent a private message to the user
451454
await messages.successCancelAllOrdersMessage(ctx);
@@ -462,7 +465,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
462465
if (!(await validateObjectId(ctx, orderId))) return;
463466

464467
const order = await Order.findOne({ _id: orderId });
465-
if (!order) return;
468+
if (order === null) return;
466469

467470
// Check if the order status is already PAID_HOLD_INVOICE
468471
if (order.status === 'PAID_HOLD_INVOICE') {
@@ -498,10 +501,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
498501
}
499502

500503
order.status = 'COMPLETED_BY_ADMIN';
501-
const buyer = await User.findOne({ _id: order.buyer_id });
502-
const seller = await User.findOne({ _id: order.seller_id });
503504
await order.save();
504505
OrderEvents.orderUpdated(order);
506+
const buyer = await User.findOne({ _id: order.buyer_id });
507+
const seller = await User.findOne({ _id: order.seller_id });
508+
if (buyer === null || seller === null) throw Error("buyer and/or seller were not found in DB");
505509
// we sent a private message to the admin
506510
await messages.successCompleteOrderMessage(ctx, order);
507511
// we sent a private message to the seller
@@ -525,11 +529,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
525529
if (!(await validateObjectId(ctx, orderId))) return;
526530
const order = await Order.findOne({ _id: orderId });
527531

528-
if (!order) return;
532+
if (order === null) return;
529533

530534
const buyer = await User.findOne({ _id: order.buyer_id });
531535
const seller = await User.findOne({ _id: order.seller_id });
532-
536+
if (buyer === null || seller === null) throw Error("buyer and/or seller were not found in DB");
533537
await messages.checkOrderMessage(ctx, order, buyer, seller);
534538
} catch (error) {
535539
logger.error(error);
@@ -543,7 +547,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
543547
if (!(await validateObjectId(ctx, orderId))) return;
544548
const order = await Order.findOne({ _id: orderId });
545549

546-
if (!order) return;
550+
if (order === null) return;
547551
if (!order.hash) return;
548552

549553
const invoice = await getInvoice({ hash: order.hash });
@@ -567,7 +571,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
567571

568572
const order = await Order.findOne({ hash });
569573

570-
if (!order) return;
574+
if (order === null) return;
571575
await subscribeInvoice(bot, hash, true);
572576
ctx.reply(`hash resubscribed`);
573577
} catch (error: any) {
@@ -606,11 +610,11 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
606610
throw new Error(ctxUpdateAssertMsg);
607611
}
608612
const params = ctx.update.message.text.split(' ');
609-
const [command, orderId] = params.filter((el) => el);
613+
const [command, orderId] = params.filter((el: string) => el);
610614

611615
if (!orderId) {
612616
const orders = await askForConfirmation(ctx.user, command);
613-
if (!orders.length) return await ctx.reply(`${command} <order Id>`);
617+
if (orders === null || orders.length === 0) return await ctx.reply(`${command} <order Id>`);
614618

615619
return await messages.showConfirmationButtons(ctx, orders, command);
616620
} else if (!(await validateObjectId(ctx, orderId))) {
@@ -637,7 +641,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
637641
const user = await User.findOne({
638642
$or: [{ username }, { tg_id: username }],
639643
});
640-
if (!user) {
644+
if (user === null) {
641645
await messages.notFoundUserMessage(ctx);
642646
return;
643647
}
@@ -648,6 +652,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
648652
const community = await Community.findById(
649653
ctx.admin.default_community_id
650654
);
655+
if (community === null) throw Error("Community was not found in DB");
651656
community.banned_users.push({
652657
id: user._id,
653658
username: user.username,
@@ -680,7 +685,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
680685
const user = await User.findOne({
681686
$or: [{ username }, { tg_id: username }],
682687
});
683-
if (!user) {
688+
if (user === null) {
684689
await messages.notFoundUserMessage(ctx);
685690
return;
686691
}
@@ -691,8 +696,9 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
691696
const community = await Community.findById(
692697
ctx.admin.default_community_id
693698
);
694-
community.banned_users = community.banned_users.filter(
695-
(el: any) => el.id !== user.id
699+
if (community === null) throw Error("Community was not found in DB");
700+
community.banned_users = community.banned_users.toObject().filter(
701+
(el: IUsernameId) => el.id !== user.id
696702
);
697703
await community.save();
698704
} else {
@@ -739,7 +745,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
739745
try {
740746
const command = '/setinvoice';
741747
const orders = await askForConfirmation(ctx.user, command);
742-
if (!orders.length) return await ctx.reply(ctx.i18n.t('setinvoice_no_response'));
748+
if (orders === null || !orders.length) return await ctx.reply(ctx.i18n.t('setinvoice_no_response'));
743749

744750
return await messages.showConfirmationButtons(ctx, orders, command);
745751
} catch (error) {
@@ -859,6 +865,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
859865
bot.command('info', userMiddleware, async (ctx: MainContext) => {
860866
try {
861867
const config = await Config.findOne({});
868+
if (config === null) throw Error("Config was not found in DB");
862869
await messages.showInfoMessage(ctx, ctx.user, config);
863870
} catch (error) {
864871
logger.error(error);

0 commit comments

Comments
 (0)