Skip to content

Commit

Permalink
jobs: convert js to ts
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
Mersho committed Oct 9, 2023
1 parent cf8be67 commit 9f3c44b
Show file tree
Hide file tree
Showing 9 changed files with 83 additions and 61 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const { Order, Community } = require('../models');
const logger = require('../logger');
import { Order, Community } from '../models';
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 @@ -27,6 +27,7 @@ const calculateEarnings = async () => {
}
for (const [communityId, earnings] of earningsMap) {
const community = await Community.findById(communityId);
if (community === null) throw Error("Community was not found in DB");
const amount = Math.round(earnings[0]);
community.earnings = community.earnings + amount;
community.orders_to_redeem = community.orders_to_redeem + earnings[1];
Expand All @@ -36,9 +37,9 @@ const calculateEarnings = async () => {
);
}
} catch (error) {
const message = error.toString();
const message = String(error);
logger.error(`calculateEarnings catch error: ${message}`);
}
};

module.exports = calculateEarnings;
export default calculateEarnings;
19 changes: 11 additions & 8 deletions jobs/cancel_orders.js → jobs/cancel_orders.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
const { User, Order } = require('../models');
import { Telegraf } from "telegraf";
import { MainContext } from "../bot/start";
import { User, Order } from "../models";
const { cancelShowHoldInvoice, cancelAddInvoice } = require('../bot/commands');
const messages = require('../bot/messages');
const { getUserI18nContext, holdInvoiceExpirationInSecs } = require('../util');
const logger = require('../logger');
import * as messages from "../bot/messages";
import { getUserI18nContext, holdInvoiceExpirationInSecs } from '../util';
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 @@ -45,6 +47,7 @@ const cancelOrders = async bot => {
for (const order of activeOrders) {
const buyerUser = await User.findOne({ _id: order.buyer_id });
const sellerUser = await User.findOne({ _id: order.seller_id });
if (buyerUser === null || sellerUser === null) return;
const i18nCtxBuyer = await getUserI18nContext(buyerUser);
const i18nCtxSeller = await getUserI18nContext(sellerUser);
// Instead of cancel this order we should send this to the admins
Expand All @@ -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 All @@ -96,4 +99,4 @@ const cancelOrders = async bot => {
}
};

module.exports = cancelOrders;
export default cancelOrders;
15 changes: 9 additions & 6 deletions jobs/communities.js → jobs/communities.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
const { Order, Community } = require('../models');
const logger = require('../logger');
import { Telegraf } from "telegraf";
import { MainContext } from "../bot/start";

const deleteCommunity = async bot => {
import { Order, Community } from '../models';
import logger from "../logger";

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,9 +29,9 @@ const deleteCommunity = async bot => {
}
}
} catch (error) {
const message = error.toString();
const message = String(error);
logger.error(`deleteCommunity catch error: ${message}`);
}
};

module.exports = deleteCommunity;
export default deleteCommunity;
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
const { Order } = require('../models');
import { Telegraf } from "telegraf";
import { MainContext } from "../bot/start";

import { Order } from '../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,9 +28,9 @@ 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}`);
}
};

module.exports = deleteOrders;
export default deleteOrders;
19 changes: 0 additions & 19 deletions jobs/index.js

This file was deleted.

19 changes: 19 additions & 0 deletions jobs/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import {
attemptPendingPayments,
attemptCommunitiesPendingPayments,
} from "./pending_payments";
import cancelOrders from "./cancel_orders";
import deleteOrders from "./delete_published_orders";
import calculateEarnings from './calculate_community_earnings'
import deleteCommunity from './communities'
import nodeInfo from './node_info'

export {
attemptPendingPayments,
cancelOrders,
deleteOrders,
calculateEarnings,
attemptCommunitiesPendingPayments,
deleteCommunity,
nodeInfo,
};
14 changes: 9 additions & 5 deletions jobs/node_info.js → jobs/node_info.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
const { Config } = require('../models');
import { Telegraf } from "telegraf";
import { MainContext } from "../bot/start";

import { Config } from '../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({});
if (config === null) throw Error("Config not found in DB");
const info = await getInfo();
if (info.is_synced_to_chain) {
config.node_status = 'up';
}
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}`);
}
};

module.exports = info;
export default info;
27 changes: 17 additions & 10 deletions jobs/pending_payments.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
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 { PendingPayment, Order, User, Community } from '../models';
import * as messages from '../bot/messages';
import logger from "../logger";
import { Telegraf } from 'telegraf';
import { I18nContext } from '@grammyjs/i18n';
import { MainContext } from '../bot/start';
const { payRequest, isPendingPayment } = require('../ln');
const { getUserI18nContext } = require('../util');

exports.attemptPendingPayments = async (bot: Telegraf<MainContext>): Promise<void> => {
export const attemptPendingPayments = async (bot: Telegraf<MainContext>): Promise<void> => {
const pendingPayments = await PendingPayment.find({
paid: false,
attempts: { $lt: process.env.PAYMENT_ATTEMPTS },
Expand All @@ -17,6 +17,7 @@ exports.attemptPendingPayments = async (bot: Telegraf<MainContext>): Promise<voi
for (const pending of pendingPayments) {
const order = await Order.findOne({ _id: pending.order_id });
try {
if (order === null) throw Error("Order was not found in DB");
pending.attempts++;
if (order.status === 'SUCCESS') {
pending.paid = true;
Expand All @@ -38,6 +39,7 @@ exports.attemptPendingPayments = async (bot: Telegraf<MainContext>): Promise<voi
request: pending.payment_request,
});
const buyerUser = await User.findOne({ _id: order.buyer_id });
if (buyerUser === null) throw Error("buyerUser was not found in DB");
const i18nCtx: I18nContext = await getUserI18nContext(buyerUser);
// If the buyer's invoice is expired we let it know and don't try to pay again
if (!!payment && payment.is_expired) {
Expand All @@ -55,12 +57,13 @@ exports.attemptPendingPayments = async (bot: Telegraf<MainContext>): Promise<voi
order.status = 'SUCCESS';
order.routing_fee = payment.fee;
pending.paid = true;
pending.paid_at = new Date().toISOString();
pending.paid_at = new Date();
// We add a new completed trade for the buyer
buyerUser.trades_completed++;
await buyerUser.save();
// We add a new completed trade for the seller
const sellerUser = await User.findOne({ _id: order.seller_id });
if (sellerUser === null) throw Error("sellerUser was not found in DB");
sellerUser.trades_completed++;
sellerUser.save();
logger.info(`Invoice with hash: ${pending.hash} paid`);
Expand Down Expand Up @@ -105,13 +108,15 @@ exports.attemptPendingPayments = async (bot: Telegraf<MainContext>): Promise<voi
const message: string = error.toString();
logger.error(`attemptPendingPayments catch error: ${message}`);
} finally {
await order.save();
if (order !== null) {
await order.save();
}
await pending.save();
}
}
};

exports.attemptCommunitiesPendingPayments = async (bot: Telegraf<MainContext>): Promise<void> => {
export const attemptCommunitiesPendingPayments = async (bot: Telegraf<MainContext>): Promise<void> => {
const pendingPayments = await PendingPayment.find({
paid: false,
attempts: { $lt: process.env.PAYMENT_ATTEMPTS },
Expand All @@ -134,6 +139,7 @@ exports.attemptCommunitiesPendingPayments = async (bot: Telegraf<MainContext>):
request: pending.payment_request,
});
const user = await User.findById(pending.user_id);
if (user === null) throw Error("User was not found in DB");
const i18nCtx: I18nContext = await getUserI18nContext(user);
// If the buyer's invoice is expired we let it know and don't try to pay again
if (!!payment && payment.is_expired) {
Expand All @@ -145,9 +151,10 @@ exports.attemptCommunitiesPendingPayments = async (bot: Telegraf<MainContext>):
}

const community = await Community.findById(pending.community_id);
if (community === null) throw Error("Community was not found in DB");
if (!!payment && !!payment.confirmed_at) {
pending.paid = true;
pending.paid_at = new Date().toISOString();
pending.paid_at = new Date();

// Reset the community's values
community.earnings = 0;
Expand Down
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
"resolveJsonModule": true
"resolveJsonModule": true,
"downlevelIteration": true
}
}

0 comments on commit 9f3c44b

Please sign in to comment.