Skip to content

Commit

Permalink
WIP1-3
Browse files Browse the repository at this point in the history
  • Loading branch information
Mersho committed Sep 6, 2023
1 parent d99430e commit 5a36da9
Show file tree
Hide file tree
Showing 21 changed files with 131 additions and 103 deletions.
18 changes: 10 additions & 8 deletions app.js → app.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
require('dotenv').config();
const { SocksProxyAgent } = require('socks-proxy-agent');
const { start } = require('./bot');
const mongoConnect = require('./db_connect');
import * as dotenv from "dotenv";
dotenv.config()
import { SocksProxyAgent } from "socks-proxy-agent";
import { start } from "./bot/start";
import mongoConnect from './db_connect'
const { resubscribeInvoices } = require('./ln');
const logger = require('./logger');
import logger from "./logger";
const { delay } = require('./util');

(async () => {
Expand All @@ -30,12 +31,13 @@ const { delay } = require('./util');
telegram: {
agent,
},
};
} as any;
}
const bot = start(process.env.BOT_TOKEN, options);
const bot = start(String(process.env.BOT_TOKEN), options);
// Wait 1 seconds before try to resubscribe hold invoices
await delay(1000);
await resubscribeInvoices(bot);
})
.on('error', error => logger.error(`Error connecting to Mongo: ${error}`));
.on('error', (error: Error) => logger.error(`Error connecting to Mongo: ${error}`));
})();

4 changes: 2 additions & 2 deletions bot/messages.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const { TelegramError } = require('telegraf');
import { TelegramError } from 'telegraf'
const QR = require('qrcode');
const {
getCurrency,
Expand All @@ -12,7 +12,7 @@ const {
decimalRound,
getUserAge
} = require('../util');
const logger = require('../logger');
import logger from "../logger";
import { MainContext } from './start';
import { UserDocument } from '../models/user'
import { IOrder } from '../models/order'
Expand Down
8 changes: 4 additions & 4 deletions bot/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ const {
deleteCommunity,
nodeInfo,
} = require('../jobs');
const logger = require('../logger');
import logger from "../logger";

export interface MainContext extends Context {
match: Array<string> | null;
Expand Down Expand Up @@ -266,7 +266,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
throw new Error(ctxUpdateAssertMsg);
}
const params = ctx.update.message.text.split(' ');
const [command, orderId] = params.filter((el) => el);
const [command, orderId] = params.filter((el: string) => el);

if (!orderId) {
const orders = await askForConfirmation(ctx.user, command);
Expand Down Expand Up @@ -357,7 +357,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
throw new Error(ctxUpdateAssertMsg);
}
const params = ctx.update.message.text.split(' ');
const [command, orderId] = params.filter((el) => el);
const [command, orderId] = params.filter((el: string) => el);

if (!orderId) {
const orders = await askForConfirmation(ctx.user, command);
Expand Down Expand Up @@ -525,7 +525,7 @@ const initialize = (botToken: string, options: Partial<Telegraf.Options<MainCont
throw new Error(ctxUpdateAssertMsg);
}
const params = ctx.update.message.text.split(' ');
const [command, orderId] = params.filter((el) => el);
const [command, orderId] = params.filter((el: string) => el);

if (!orderId) {
const orders = await askForConfirmation(ctx.user, command);
Expand Down
9 changes: 5 additions & 4 deletions db_connect.js → db_connect.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const mongoose = require('mongoose');
const logger = require('./logger');
import mongoose from "mongoose";
import logger from "./logger";

// connect to database
const credentials = process.env.DB_USER
Expand All @@ -12,12 +12,13 @@ if (!MONGO_URI) {
throw new Error('You must provide a MongoDB URI');
}
logger.info(`Connecting to: ${MONGO_URI}`);
// TODO: Update mongoose to latest version
const connect = () => {
mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
} as any); // older version of mongoose that does not have the ConnectOptions type defined.
return mongoose;
};

module.exports = connect;
export default connect;
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { Order, Community } = require('../models');
const logger = require('../logger');
import logger from "../logger";

const calculateEarnings = async () => {
try {
Expand All @@ -12,9 +12,9 @@ const calculateEarnings = async () => {
for (const order of orders) {
const amount = order.amount;
const fee = order.fee;
const botFee = order.bot_fee || parseFloat(process.env.MAX_FEE);
const botFee = order.bot_fee || Number(process.env.MAX_FEE);
const communityFeePercent =
order.community_fee || parseFloat(process.env.FEE_PERCENT);
order.community_fee || Number(process.env.FEE_PERCENT);
const maxFee = amount * botFee;
const communityFee = fee - maxFee * communityFeePercent;
const earnings = earningsMap.get(order.community_id) || [0, 0];
Expand All @@ -36,7 +36,7 @@ const calculateEarnings = async () => {
);
}
} catch (error) {
const message = error.toString();
const message = String(error);
logger.error(`calculateEarnings catch error: ${message}`);
}
};
Expand Down
11 changes: 7 additions & 4 deletions jobs/cancel_orders.js → jobs/cancel_orders.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
import { Telegraf } from "telegraf";
import { MainContext } from "../bot/start";

const { User, Order } = require('../models');
const { cancelShowHoldInvoice, cancelAddInvoice } = require('../bot/commands');
const messages = require('../bot/messages');
const { getUserI18nContext, holdInvoiceExpirationInSecs } = require('../util');
const logger = require('../logger');
import logger from "../logger";

const cancelOrders = async bot => {
const cancelOrders = async (bot: Telegraf<MainContext>) => {
try {
const holdInvoiceTime = new Date();
holdInvoiceTime.setSeconds(
holdInvoiceTime.getSeconds() -
parseInt(process.env.HOLD_INVOICE_EXPIRATION_WINDOW)
Number(process.env.HOLD_INVOICE_EXPIRATION_WINDOW)
);
// We get the orders where the seller didn't pay the hold invoice before expired
// or where the buyer didn't add the invoice
Expand Down Expand Up @@ -70,7 +73,7 @@ const cancelOrders = async bot => {
// Now we cancel orders expired
// ==============================
orderTime = new Date();
let orderExpirationTime = parseInt(
let orderExpirationTime = Number(
process.env.ORDER_PUBLISHED_EXPIRATION_WINDOW
);
orderExpirationTime = orderExpirationTime + orderExpirationTime * 0.2;
Expand Down
11 changes: 7 additions & 4 deletions jobs/communities.js → jobs/communities.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { Telegraf } from "telegraf";
import { MainContext } from "../bot/start";

const { Order, Community } = require('../models');
const logger = require('../logger');
import logger from "../logger";

const deleteCommunity = async bot => {
const deleteCommunity = async (bot: Telegraf<MainContext>) => {
try {
const communities = await Community.find();
for (const community of communities) {
// Delete communities with COMMUNITY_TTL days without a successful order
const days = 86400 * parseInt(process.env.COMMUNITY_TTL);
const days = 86400 * Number(process.env.COMMUNITY_TTL);
const time = new Date();
time.setSeconds(time.getSeconds() - days);
// If is a new community we don't do anything
Expand All @@ -26,7 +29,7 @@ const deleteCommunity = async bot => {
}
}
} catch (error) {
const message = error.toString();
const message = String(error);
logger.error(`deleteCommunity catch error: ${message}`);
}
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { Telegraf } from "telegraf";
import { MainContext } from "../bot/start";

const { Order } = require('../models');
const { deleteOrderFromChannel } = require('../util');
const logger = require('../logger');
import logger from "../logger";

const deleteOrders = async bot => {
const deleteOrders = async (bot: Telegraf<MainContext>) => {
try {
const windowTime = new Date();
windowTime.setSeconds(
windowTime.getSeconds() -
parseInt(process.env.ORDER_PUBLISHED_EXPIRATION_WINDOW)
Number(process.env.ORDER_PUBLISHED_EXPIRATION_WINDOW)
);
// We get the pending orders where time is expired
const pendingOrders = await Order.find({
Expand All @@ -25,7 +28,7 @@ const deleteOrders = async bot => {
await deleteOrderFromChannel(orderCloned, bot.telegram);
}
} catch (error) {
const message = error.toString();
const message = String(error);
logger.error(`deleteOrders catch error: ${message}`);
}
};
Expand Down
9 changes: 6 additions & 3 deletions jobs/node_info.js → jobs/node_info.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { Telegraf } from "telegraf";
import { MainContext } from "../bot/start";

const { Config } = require('../models');
const { getInfo } = require('../ln');
const logger = require('../logger');
import logger from "../logger";

const info = async bot => {
const info = async (bot: Telegraf<MainContext>) => {
try {
const config = await Config.findOne({});
const info = await getInfo();
Expand All @@ -12,7 +15,7 @@ const info = async bot => {
config.node_uri = info.uris[0];
await config.save();
} catch (error) {
const message = error.toString();
const message = String(error);
logger.error(`node info catch error: ${message}`);
}
};
Expand Down
2 changes: 1 addition & 1 deletion jobs/pending_payments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const { payRequest, isPendingPayment } = require('../ln');
const { PendingPayment, Order, User, Community } = require('../models');
const messages = require('../bot/messages');
const { getUserI18nContext } = require('../util');
const logger = require('../logger');
import logger from "../logger";
import { Telegraf } from 'telegraf';
import { I18nContext } from '@grammyjs/i18n';
import { MainContext } from '../bot/start';
Expand Down
10 changes: 5 additions & 5 deletions ln/connect.js → ln/connect.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const fs = require('fs');
const path = require('path');
const lightning = require('lightning');
const logger = require('../logger');
import * as fs from 'fs';
import path = require('path');
import * as lightning from "lightning";
import logger from "../logger";

const { authenticatedLndGrpc } = lightning;

Expand Down Expand Up @@ -47,4 +47,4 @@ const { lnd } = authenticatedLndGrpc({
socket,
});

module.exports = lnd;
export { lnd };
22 changes: 11 additions & 11 deletions ln/hold_invoice.js → ln/hold_invoice.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
const { createHash, randomBytes } = require('crypto');
const lightning = require('lightning');
const lnd = require('./connect');
const logger = require('../logger');
import { randomBytes, createHash } from 'crypto';
import * as lightning from "lightning";
import { lnd } from './connect'
import logger from "../logger";

const createHoldInvoice = async ({ description, amount }) => {
const createHoldInvoice = async (description: string, amount: number ) => {
try {
const randomSecret = () => randomBytes(32);
const sha256 = buffer => createHash('sha256').update(buffer).digest('hex');
const sha256 = (buffer: Buffer): string => createHash('sha256').update(buffer).digest('hex');
// We create a random secret
const secret = randomSecret();
const expiresAt = new Date();
expiresAt.setSeconds(expiresAt.getSeconds() + 3600);

const hash = sha256(secret);
const cltv_delta = parseInt(process.env.HOLD_INVOICE_CLTV_DELTA);
const cltv_delta = Number(process.env.HOLD_INVOICE_CLTV_DELTA);
const { request, id } = await lightning.createHodlInvoice({
cltv_delta,
lnd,
description,
id: hash,
tokens: amount,
expires_at: expiresAt,
expires_at: expiresAt.toISOString(),
});

// We sent back the response hash (id) to be used on testing
Expand All @@ -30,23 +30,23 @@ const createHoldInvoice = async ({ description, amount }) => {
}
};

const settleHoldInvoice = async ({ secret }) => {
const settleHoldInvoice = async ( secret: string ) => {
try {
await lightning.settleHodlInvoice({ lnd, secret });
} catch (error) {
logger.error(error);
}
};

const cancelHoldInvoice = async ({ hash }) => {
const cancelHoldInvoice = async ( hash: string ) => {
try {
await lightning.cancelHodlInvoice({ lnd, id: hash });
} catch (error) {
logger.error(error);
}
};

const getInvoice = async ({ hash }) => {
const getInvoice = async ( hash: string ) => {
try {
return await lightning.getInvoice({ lnd, id: hash });
} catch (error) {
Expand Down
13 changes: 0 additions & 13 deletions ln/info.js

This file was deleted.

11 changes: 11 additions & 0 deletions ln/info.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as lightning from "lightning";
import { lnd } from './connect'
import logger from "../logger";

export const getInfo = async () => {
try {
return await lightning.getWalletInfo({ lnd });
} catch (error) {
logger.error(error);
}
};
Loading

0 comments on commit 5a36da9

Please sign in to comment.