Skip to content

Commit

Permalink
WIP4
Browse files Browse the repository at this point in the history
  • Loading branch information
Mersho committed Sep 6, 2023
1 parent b0bfe74 commit a429201
Show file tree
Hide file tree
Showing 6 changed files with 228 additions and 44 deletions.
2 changes: 1 addition & 1 deletion bot/messages.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TelegramError } from 'telegraf'
const QR = require('qrcode');
import QR from 'qrcode';
const {
getCurrency,
numberFormat,
Expand Down
9 changes: 4 additions & 5 deletions bot/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import { I18n, I18nContext } from '@grammyjs/i18n';
import { Message } from 'typegram'
import { UserDocument } from '../models/user'
import { FilterQuery } from 'mongoose';

const { limit } = require('@grammyjs/ratelimiter');
const schedule = require('node-schedule');
import { limit } from "@grammyjs/ratelimiter"
import schedule from 'node-schedule';
const {
Order,
User,
Expand Down Expand Up @@ -75,7 +74,7 @@ export interface MainContext extends Context {
admin: UserDocument;
}

interface OrderQuery {
export interface OrderQuery {
status?: string;
buyer_id?: string;
seller_id?: string;
Expand Down Expand Up @@ -137,7 +136,7 @@ has the same condition.
The problem mentioned above is similar to this issue:
https://github.com/telegraf/telegraf/issues/1319#issuecomment-766360594
*/
const ctxUpdateAssertMsg = "ctx.update.message.text is not available.";
export const ctxUpdateAssertMsg = "ctx.update.message.text is not available.";

const initialize = (botToken: string, options: Partial<Telegraf.Options<MainContext>>): Telegraf<MainContext> => {
const i18n = new I18n({
Expand Down
97 changes: 60 additions & 37 deletions bot/validations.js → bot/validations.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import { MainContext, OrderQuery, ctxUpdateAssertMsg } from "./start";
import { ICommunity } from "../models/community";
import { FilterQuery } from "mongoose";
import { UserDocument } from "../models/user";
import { IOrder } from "../models/order";
import { Telegraf } from "telegraf";

const { parsePaymentRequest } = require('invoices');
const { ObjectId } = require('mongoose').Types;
const messages = require('./messages');
Expand All @@ -8,11 +15,18 @@ const logger = require('../logger');

// We look in database if the telegram user exists,
// if not, it creates a new user
const validateUser = async (ctx, start) => {
const validateUser = async (ctx: MainContext, start: boolean) => {
try {
const tgUser = ctx.update.callback_query
? ctx.update.callback_query.from
: ctx.update.message.from;
let tgUser = null
if (("callback_query" in ctx.update) && ctx.update.callback_query) {
tgUser = ctx.update.callback_query.from
}
else if (("message" in ctx.update) && ctx.update.message) {
tgUser = ctx.update.message.from
}
else {
throw new Error(ctxUpdateAssertMsg);
}
// We need to make sure the user has a username
if (!tgUser.username) {
return await messages.nonHandleErrorMessage(ctx);
Expand Down Expand Up @@ -45,8 +59,11 @@ const validateUser = async (ctx, start) => {
}
};

const validateSuperAdmin = async (ctx, id) => {
const validateSuperAdmin = async (ctx: MainContext, id?: string) => { // id is UNKNOWN & not used
try {
if (!('message' in ctx.update) || !('text' in ctx.update.message)) {
throw new Error(ctxUpdateAssertMsg);
}
const tgUserId = id || ctx.update.message.from.id;
const user = await User.findOne({ tg_id: tgUserId });
// If the user never started the bot we can't send messages
Expand All @@ -62,8 +79,11 @@ const validateSuperAdmin = async (ctx, id) => {
}
};

const validateAdmin = async (ctx, id) => {
const validateAdmin = async (ctx: MainContext, id?: string) => { // id is UNKNOWN & not used
try {
if (!('message' in ctx.update) || !('text' in ctx.update.message)) {
throw new Error(ctxUpdateAssertMsg);
}
const tgUserId = id || ctx.update.message.from.id;
const user = await User.findOne({ tg_id: tgUserId });
// If the user never started the bot we can't send messages
Expand All @@ -86,7 +106,7 @@ const validateAdmin = async (ctx, id) => {
}
};

const validateSellOrder = async ctx => {
const validateSellOrder = async (ctx: MainContext) => {
try {
const args = ctx.state.command.args;
if (args.length < 4) {
Expand Down Expand Up @@ -130,7 +150,7 @@ const validateSellOrder = async ctx => {
return false;
}

if (amount !== 0 && amount < process.env.MIN_PAYMENT_AMT) {
if (amount !== 0 && amount < Number(process.env.MIN_PAYMENT_AMT)) {
await messages.mustBeGreatherEqThan(
ctx,
'monto_en_sats',
Expand All @@ -149,7 +169,7 @@ const validateSellOrder = async ctx => {
return false;
}

if (fiatAmount.some(x => x < 1)) {
if (fiatAmount.some((x: number) => x < 1)) {
await messages.mustBeGreatherEqThan(ctx, 'monto_en_fiat', 1);
return false;
}
Expand All @@ -174,7 +194,7 @@ const validateSellOrder = async ctx => {
}
};

const validateBuyOrder = async ctx => {
const validateBuyOrder = async (ctx: MainContext) => {
try {
const args = ctx.state.command.args;
if (args.length < 4) {
Expand Down Expand Up @@ -216,7 +236,7 @@ const validateBuyOrder = async ctx => {
return false;
}

if (amount !== 0 && amount < process.env.MIN_PAYMENT_AMT) {
if (amount !== 0 && amount < Number(process.env.MIN_PAYMENT_AMT)) {
await messages.mustBeGreatherEqThan(
ctx,
'monto_en_sats',
Expand All @@ -235,7 +255,7 @@ const validateBuyOrder = async ctx => {
return false;
}

if (fiatAmount.some(x => x < 1)) {
if (fiatAmount.some((x: number) => x < 1)) {
await messages.mustBeGreatherEqThan(ctx, 'monto_en_fiat', 1);
return false;
}
Expand All @@ -259,26 +279,26 @@ const validateBuyOrder = async ctx => {
return false;
}
};
const validateLightningAddress = async lightningAddress => {
const validateLightningAddress = async (lightningAddress: string) => {
const pattern = /^[\w-.]+@([\w-]+.)+[\w-]{2,4}$/g;

return (
pattern.test(lightningAddress) && existLightningAddress(lightningAddress)
);
};

const validateInvoice = async (ctx, lnInvoice) => {
const validateInvoice = async (ctx: MainContext, lnInvoice: string) => {
try {
const invoice = parsePaymentRequest({ request: lnInvoice });
const latestDate = new Date(
Date.now() + parseInt(process.env.INVOICE_EXPIRATION_WINDOW)
Date.now() + Number(process.env.INVOICE_EXPIRATION_WINDOW)
).toISOString();
if (!!invoice.tokens && invoice.tokens < process.env.MIN_PAYMENT_AMT) {
if (!!invoice.tokens && invoice.tokens < Number(process.env.MIN_PAYMENT_AMT)) {
await messages.minimunAmountInvoiceMessage(ctx);
return false;
}

if (new Date(invoice.expires_at) < latestDate) {
if (new Date(invoice.expires_at).toISOString() < latestDate) {
await messages.minimunExpirationTimeInvoiceMessage(ctx);
return false;
}
Expand Down Expand Up @@ -306,20 +326,20 @@ const validateInvoice = async (ctx, lnInvoice) => {
}
};

const isValidInvoice = async (ctx, lnInvoice) => {
const isValidInvoice = async (ctx: MainContext, lnInvoice: string) => {
try {
const invoice = parsePaymentRequest({ request: lnInvoice });
const latestDate = new Date(
Date.now() + parseInt(process.env.INVOICE_EXPIRATION_WINDOW)
Date.now() + Number(process.env.INVOICE_EXPIRATION_WINDOW)
).toISOString();
if (!!invoice.tokens && invoice.tokens < process.env.MIN_PAYMENT_AMT) {
if (!!invoice.tokens && invoice.tokens < Number(process.env.MIN_PAYMENT_AMT)) {
await messages.invoiceMustBeLargerMessage(ctx);
return {
success: false,
};
}

if (new Date(invoice.expires_at) < latestDate) {
if (new Date(invoice.expires_at).toISOString() < latestDate) {
await messages.invoiceExpiryTooShortMessage(ctx);
return {
success: false,
Expand Down Expand Up @@ -359,7 +379,7 @@ const isValidInvoice = async (ctx, lnInvoice) => {
}
};

const isOrderCreator = (user, order) => {
const isOrderCreator = (user: UserDocument, order: IOrder) => {
try {
return user._id == order.creator_id;
} catch (error) {
Expand All @@ -368,7 +388,7 @@ const isOrderCreator = (user, order) => {
}
};

const validateTakeSellOrder = async (ctx, bot, user, order) => {
const validateTakeSellOrder = async (ctx: MainContext, bot: Telegraf<MainContext>, user: UserDocument, order: IOrder) => {
try {
if (!order) {
await messages.invalidOrderMessage(ctx, bot, user);
Expand Down Expand Up @@ -397,7 +417,7 @@ const validateTakeSellOrder = async (ctx, bot, user, order) => {
}
};

const validateTakeBuyOrder = async (ctx, bot, user, order) => {
const validateTakeBuyOrder = async (ctx: MainContext, bot: Telegraf<MainContext>, user: UserDocument, order: IOrder) => {
try {
if (!order) {
await messages.invalidOrderMessage(bot, user);
Expand All @@ -422,9 +442,9 @@ const validateTakeBuyOrder = async (ctx, bot, user, order) => {
}
};

const validateReleaseOrder = async (ctx, user, orderId) => {
const validateReleaseOrder = async (ctx: MainContext, user: UserDocument, orderId: string) => {
try {
let where = {
let where: FilterQuery<OrderQuery> = {
seller_id: user._id,
status: 'WAITING_BUYER_INVOICE',
_id: orderId,
Expand Down Expand Up @@ -465,7 +485,7 @@ const validateReleaseOrder = async (ctx, user, orderId) => {
}
};

const validateDisputeOrder = async (ctx, user, orderId) => {
const validateDisputeOrder = async (ctx: MainContext, user: UserDocument, orderId: string) => {
try {
const where = {
$and: [
Expand All @@ -489,9 +509,9 @@ const validateDisputeOrder = async (ctx, user, orderId) => {
}
};

const validateFiatSentOrder = async (ctx, user, orderId) => {
const validateFiatSentOrder = async (ctx: MainContext, user: UserDocument, orderId: string) => {
try {
const where = {
const where: FilterQuery<OrderQuery> = {
$and: [
{ buyer_id: user._id },
{ $or: [{ status: 'ACTIVE' }, { status: 'PAID_HOLD_INVOICE' }] },
Expand Down Expand Up @@ -525,7 +545,7 @@ const validateFiatSentOrder = async (ctx, user, orderId) => {
};

// If a seller have an order with status FIAT_SENT, return false
const validateSeller = async (ctx, user) => {
const validateSeller = async (ctx: MainContext, user: UserDocument) => {
try {
const where = {
seller_id: user._id,
Expand All @@ -546,10 +566,13 @@ const validateSeller = async (ctx, user) => {
}
};

const validateParams = async (ctx, paramNumber, errOutputString) => {
const validateParams = async (ctx: MainContext, paramNumber: number, errOutputString: string) => {
try {
if (!('message' in ctx.update) || !('text' in ctx.update.message)) {
throw new Error(ctxUpdateAssertMsg);
}
const paramsArray = ctx.update.message.text.split(' ');
const params = paramsArray.filter(el => el !== '');
const params = paramsArray.filter((el: string) => el !== '');
if (params.length !== paramNumber) {
await messages.customMessage(
ctx,
Expand All @@ -566,7 +589,7 @@ const validateParams = async (ctx, paramNumber, errOutputString) => {
}
};

const validateObjectId = async (ctx, id) => {
const validateObjectId = async (ctx: MainContext, id: string) => {
try {
if (!ObjectId.isValid(id)) {
await messages.notValidIdMessage(ctx);
Expand All @@ -580,10 +603,10 @@ const validateObjectId = async (ctx, id) => {
}
};

const validateUserWaitingOrder = async (ctx, bot, user) => {
const validateUserWaitingOrder = async (ctx: MainContext, bot: Telegraf<MainContext>, user: UserDocument) => {
try {
// If is a seller
let where = {
let where: FilterQuery<OrderQuery> = {
seller_id: user._id,
status: 'WAITING_PAYMENT',
};
Expand All @@ -610,12 +633,12 @@ const validateUserWaitingOrder = async (ctx, bot, user) => {
};

// We check if the user is banned from the community in the order
const isBannedFromCommunity = async (user, communityId) => {
const isBannedFromCommunity = async (user: UserDocument, communityId: string) => {
try {
if (!communityId) return false;
const community = await Community.findOne({ _id: communityId });
if (!community) return false;
return community.banned_users.some(buser => buser.id == user._id);
return community.banned_users.some((buser: ICommunity) => buser.id == user._id);
} catch (error) {
logger.error(error);
return false;
Expand Down
2 changes: 1 addition & 1 deletion ln/connect.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as fs from 'fs';
import path = require('path');
import * as path from 'path';
import * as lightning from "lightning";
import logger from "../logger";

Expand Down
Loading

0 comments on commit a429201

Please sign in to comment.