Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 29 additions & 4 deletions bot/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,14 @@ const waitPayment = async (ctx: MainContext, bot: HasTelegram, buyer: UserDocume
fiatAmount: order.fiat_amount,
});
const amount = Math.floor(order.amount + order.fee);
const { hash, secret } = await createHoldInvoice({
const createHoldInvoiceResult = await createHoldInvoice({
amount,
description,
});
if (createHoldInvoiceResult === undefined) {
throw new Error("createHoldInvoice() returned undefined");
}
const { hash, secret } = createHoldInvoiceResult;
order.hash = hash;
order.secret = secret;
order.taken_at = new Date();
Expand Down Expand Up @@ -245,6 +249,8 @@ const cancelAddInvoice = async (ctx: CommunityContext, order: IOrder | null = nu
ctx.deleteMessage();
ctx.scene.leave();
userAction = true;
if (ctx.from === undefined)
throw new Error("ctx.from is undefined");
userTgId = String(ctx.from.id);
if (order === null) {
const orderId = !!ctx && (ctx.update as any).callback_query.message.text;
Expand All @@ -255,6 +261,9 @@ const cancelAddInvoice = async (ctx: CommunityContext, order: IOrder | null = nu
if (order === null) return;

// We make sure the seller can't send us sats now
if (order.hash === null){
throw new Error("order.hash is null");
}
await cancelHoldInvoice({ hash: order.hash });
Comment thread
webwarrior-ws marked this conversation as resolved.

const user = await User.findOne({ _id: order.buyer_id });
Expand All @@ -270,6 +279,8 @@ const cancelAddInvoice = async (ctx: CommunityContext, order: IOrder | null = nu
if(sellerUser === null)
throw new Error("sellerUser was not found");
const buyerUser = await User.findOne({ _id: order.buyer_id });
if(buyerUser === null)
throw new Error("buyerUser was not found");
const sellerTgId = sellerUser.tg_id;
// If order creator cancels it, it will not be republished
if (order.creator_id === order.buyer_id) {
Expand Down Expand Up @@ -362,7 +373,7 @@ const showHoldInvoice = async (ctx: CommunityContext, bot: HasTelegram, order?:
const orderId = (ctx.update as any).callback_query?.message?.text;
if (!orderId) return;
order = await Order.findOne({ _id: orderId });
if (order === null) return;
if (order === null || order === undefined) return;
}

const user = await User.findOne({ _id: order.seller_id });
Expand Down Expand Up @@ -408,10 +419,14 @@ const showHoldInvoice = async (ctx: CommunityContext, bot: HasTelegram, order?:
Math.floor(order.amount) :
Math.floor(order.amount + order.fee);

const { request, hash, secret } = await createHoldInvoice({
const holdInvoice = await createHoldInvoice({
description,
amount,
});
if (holdInvoice === undefined) {
throw new Error("createHoldInvoice returned undefined");
}
const { request, hash, secret } = holdInvoice;
order.hash = hash;
order.secret = secret;
await order.save();
Expand Down Expand Up @@ -441,6 +456,8 @@ const cancelShowHoldInvoice = async (ctx: CommunityContext, order: IOrder | null
ctx.deleteMessage();
ctx.scene.leave();
userAction = true;
if (ctx.from === undefined)
throw new Error("ctx.from is undefined");
userTgId = String(ctx.from.id);
if (order === null) {
const orderId = !!ctx && (ctx.update as any).callback_query.message.text;
Expand All @@ -450,6 +467,9 @@ const cancelShowHoldInvoice = async (ctx: CommunityContext, order: IOrder | null
}
if (order === null) return;

if (order.hash === null) {
throw new Error("order.hash is null");
}
// We make sure the seller can't send us sats now
await cancelHoldInvoice({ hash: order.hash });

Expand All @@ -464,6 +484,8 @@ const cancelShowHoldInvoice = async (ctx: CommunityContext, order: IOrder | null
if(buyerUser === null)
throw new Error("buyerUser was not found");
const sellerUser = await User.findOne({ _id: order.seller_id });
if(sellerUser === null)
throw new Error("sellerUser was not found");
const buyerTgId = buyerUser.tg_id;
// If order creator cancels it, it will not be republished
if (order.creator_id === order.seller_id) {
Expand Down Expand Up @@ -624,7 +646,7 @@ const cancelOrder = async (ctx: CommunityContext, orderId: string, user: UserDoc
if (order.type === 'sell') {
const seller = await User.findById(order.seller_id);
if (!seller) throw new Error('sellerUser was not found');
if (String(ctx.from.id) === seller.tg_id) {
if (String(ctx.from?.id) === seller.tg_id) {
return cancelShowHoldInvoice(ctx, order);
}
}
Expand Down Expand Up @@ -773,6 +795,9 @@ const release = async (ctx: MainContext, orderId: string, user: UserDocument | n
await dispute.save();
}

if (order.secret === null) {
throw new Error("order.secret is null");
}
Comment thread
webwarrior-ws marked this conversation as resolved.
await settleHoldInvoice({ secret: order.secret });
} catch (error) {
logger.error(error);
Expand Down
2 changes: 1 addition & 1 deletion bot/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@
await bot.telegram.sendMediaGroup(seller.tg_id, [{
type: 'photo',
media: { source: Buffer.from(order.random_image, 'base64') },
caption: caption,

Check warning on line 369 in bot/messages.ts

View workflow job for this annotation

GitHub Actions / Lint

Expected property shorthand
}]
);

Expand Down Expand Up @@ -412,7 +412,7 @@
await ctx.reply(
ctx.i18n.t('pay_invoice', {
amount: numberFormat(fiatCode, amount),
fiatAmount: numberFormat(fiatCode, fiatAmount),
fiatAmount: numberFormat(fiatCode, fiatAmount!),
currency: currencySymbol,
})
);
Expand Down
17 changes: 8 additions & 9 deletions bot/modules/block/commands.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { CustomContext } from './customContext';
import { User, Block, Order } from '../../../models';
import * as messages from './messages';
import * as globalMessages from '../../messages';
import { MainContext } from '../../start';

const { User, Block, Order } = require('../../../models');
const messages = require('./messages');
const globalMessages = require('../../messages');

const block = async (ctx: CustomContext, username: string): Promise<void> => {
const block = async (ctx: MainContext, username: string): Promise<void> => {
const userToBlock = await User.findOne({ username: username.substring(1) });
const user = ctx.user;

Expand Down Expand Up @@ -54,7 +53,7 @@ const block = async (ctx: CustomContext, username: string): Promise<void> => {
await messages.userBlocked(ctx);
};

const unblock = async (ctx: CustomContext, username: string): Promise<void> => {
const unblock = async (ctx: MainContext, username: string): Promise<void> => {
const userToUnblock = await User.findOne({ username: username.substring(1) });
if (!userToUnblock) {
await globalMessages.notFoundUserMessage(ctx);
Expand All @@ -74,9 +73,9 @@ const unblock = async (ctx: CustomContext, username: string): Promise<void> => {
}
};

const blocklist = async (ctx: CustomContext): Promise<void> => {
const blocklist = async (ctx: MainContext): Promise<void> => {
const blocks = await Block.find({ blocker_tg_id: ctx.user.tg_id });
const tgIdBlocks = blocks.map(blocked => blocked.blocked_tg_id);
const tgIdBlocks = blocks.map((blocked: { blocked_tg_id: any; }) => blocked.blocked_tg_id);

if (!tgIdBlocks.length) {
await messages.blocklistEmptyMessage(ctx);
Expand Down
11 changes: 0 additions & 11 deletions bot/modules/block/customContext.ts

This file was deleted.

15 changes: 8 additions & 7 deletions bot/modules/block/messages.ts
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
import { CustomContext } from './customContext';
import { UserDocument } from '../../../models/user';
import { MainContext } from '../../start';

const { logger } = require('../../../logger');

const ordersInProcess = async (ctx: CustomContext) => {
const ordersInProcess = async (ctx: MainContext) => {
try {
ctx.reply(ctx.i18n.t('orders_in_process'));
} catch (error) {
logger.error(error);
}
};

const userAlreadyBlocked = async (ctx: CustomContext) => {
const userAlreadyBlocked = async (ctx: MainContext) => {
try {
ctx.reply(ctx.i18n.t('user_already_blocked'));
} catch (error) {
logger.error(error);
}
};

const userBlocked = async (ctx: CustomContext) => {
const userBlocked = async (ctx: MainContext) => {
try {
ctx.reply(ctx.i18n.t('user_blocked'));
} catch (error) {
logger.error(error);
}
};

const userUnblocked = async (ctx: CustomContext) => {
const userUnblocked = async (ctx: MainContext) => {
try {
ctx.reply(ctx.i18n.t('user_unblocked'));
} catch (error) {
logger.error(error);
}
};

const blocklistMessage = async (ctx: CustomContext, usersBlocked) => {
const blocklistMessage = async (ctx: MainContext, usersBlocked: UserDocument[]) => {
try {
if (!usersBlocked?.length) {
return await blocklistEmptyMessage(ctx);
Expand All @@ -46,7 +47,7 @@ const blocklistMessage = async (ctx: CustomContext, usersBlocked) => {
}
};

const blocklistEmptyMessage = async (ctx: CustomContext) => {
const blocklistEmptyMessage = async (ctx: MainContext) => {
try {
ctx.reply(ctx.i18n.t('blocklist_empty'));
} catch (error) {
Expand Down
2 changes: 1 addition & 1 deletion bot/modules/nostr/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const orderToTags = async (order: IOrder) => {
const community = await Community.findById(order.community_id);
if(community === null)
throw new Error("community was not found");
let order_channel: string;
let order_channel: string = "";
if (community.order_channels.length === 1)
order_channel = removeAtSymbol(community.order_channels[0].name);
else if (community.order_channels.length === 2){
Expand Down
6 changes: 5 additions & 1 deletion bot/modules/orders/takeOrder.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { logger } from '../../../logger';
import { Block, Order, User } from '../../../models';
import { UserDocument } from '../../../models/user';
import { deleteOrderFromChannel, generateRandomImage } from '../../../util';
import * as messages from '../../messages';
import { HasTelegram, MainContext } from '../../start';
Expand Down Expand Up @@ -105,6 +106,9 @@ export const takesell = async (
const order = await Order.findOne({ _id: orderId });
if (!order) return;
const seller = await User.findOne({ _id: order.seller_id });
if(seller === null) {
throw new Error("seller is null");
}

const sellerIsBlocked = await Block.exists({
blocker_tg_id: user.tg_id,
Expand Down Expand Up @@ -140,7 +144,7 @@ export const takesell = async (
}
};

const checkBlockingStatus = async (ctx, user, otherUser) => {
const checkBlockingStatus = async (ctx: MainContext, user: UserDocument, otherUser: UserDocument) => {
const userIsBlocked = await Block.exists({
blocker_tg_id: user.tg_id,
blocked_tg_id: otherUser.tg_id,
Expand Down
1 change: 1 addition & 0 deletions bot/scenes.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Scenes } from 'telegraf';
// @ts-ignore
import { parsePaymentRequest } from 'invoices';
import { isValidInvoice, validateLightningAddress } from './validations';
import { Order, PendingPayment } from '../models';
Expand Down
11 changes: 7 additions & 4 deletions bot/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ export const ctxUpdateAssertMsg = "ctx.update.message.text is not available.";
const COMMIT_HASH = (() => {
try {
return execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();
} catch (e) {
} catch (e: any) {
logger.warning(`Could not retrieve Git commit hash: ${e.message}`);
return 'unknown';
}
Expand Down Expand Up @@ -218,7 +218,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<Communit
});

schedule.scheduleJob(`0 0 * * *`, async () => {
await checkSolvers(bot);
await checkSolvers(bot as any as Telegraf<MainContext>);
});

bot.start(async (ctx: MainContext) => {
Expand Down Expand Up @@ -573,12 +573,15 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<Communit
if (!order.hash) return;

const invoice = await getInvoice({ hash: order.hash });
if (invoice === undefined){
throw new Error("invoice is undefined");
}

await messages.checkInvoiceMessage(
ctx,
invoice.is_confirmed,
invoice.is_canceled,
invoice.is_held
invoice.is_canceled!,
invoice.is_held!
);
} catch (error) {
logger.error(error);
Expand Down
4 changes: 2 additions & 2 deletions bot/validations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { IUsernameId } from "../models/community";
import { FilterQuery } from "mongoose";
import { UserDocument } from "../models/user";
import { IOrder } from "../models/order";

// @ts-ignore
import { parsePaymentRequest } from 'invoices';
Comment thread
webwarrior-ws marked this conversation as resolved.
import * as messages from './messages';
import { Order, User, Community } from '../models';
Expand Down Expand Up @@ -434,7 +434,7 @@ const isValidInvoice = async (ctx: MainContext, lnInvoice: string) => {
};


const validateTakeSellOrder = async (ctx: MainContext, bot: HasTelegram, user: UserDocument, order: IOrder) => {
const validateTakeSellOrder = async (ctx: MainContext, bot: HasTelegram, user: UserDocument, order: IOrder | null) => {
try {
if (!order) {
await messages.invalidOrderMessage(ctx, bot, user);
Expand Down
3 changes: 1 addition & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
{
"compilerOptions": {
"strict": false,
"strict": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"downlevelIteration": true,
"lib":["ES2021", "DOM"],
"outDir": "./dist",
"rootDir": ".",
"allowJs": true,
"moduleResolution": "node"
},
"include": [
Expand Down
4 changes: 2 additions & 2 deletions util/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ const generateRandomImage = async (nonce: string) => {

if (!wasHoneybadgerSelected) {
const files = await fs.readdir('images');
const imageFiles = files.filter(file =>
const imageFiles = files.filter((file: string) =>
['.png'].includes(path.extname(file).toLowerCase()) &&
file !== honeybadgerFilename
);
Expand All @@ -609,7 +609,7 @@ const generateRandomImage = async (nonce: string) => {
return { randomImage, isGoldenHoneyBadger };
};

const generateQRWithImage = async (request, randomImage) => {
const generateQRWithImage = async (request: string, randomImage: string) => {
const canvas = createCanvas(400, 400);
await QRCode.toCanvas(canvas, request, {
margin: 2,
Expand Down
Loading