diff --git a/app.js b/app.ts similarity index 71% rename from app.js rename to app.ts index 2fbc6604..99e5609a 100644 --- a/app.js +++ b/app.ts @@ -1,7 +1,8 @@ -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() +const SocksProxyAgent = require('socks-proxy-agent') +import { start } from "./bot/start"; +import mongoConnect from './db_connect' const { resubscribeInvoices } = require('./ln'); const logger = require('./logger'); const { delay } = require('./util'); @@ -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}`)); })(); + diff --git a/db_connect.js b/db_connect.ts similarity index 76% rename from db_connect.js rename to db_connect.ts index e38fbd10..30e43ef7 100644 --- a/db_connect.js +++ b/db_connect.ts @@ -1,4 +1,4 @@ -const mongoose = require('mongoose'); +import mongoose from "mongoose"; const logger = require('./logger'); // connect to database @@ -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; diff --git a/jobs/calculate_community_earnings.js b/jobs/calculate_community_earnings.ts similarity index 88% rename from jobs/calculate_community_earnings.js rename to jobs/calculate_community_earnings.ts index 56151d48..acdf030a 100644 --- a/jobs/calculate_community_earnings.js +++ b/jobs/calculate_community_earnings.ts @@ -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]; @@ -36,7 +36,7 @@ const calculateEarnings = async () => { ); } } catch (error) { - const message = error.toString(); + const message = String(error); logger.error(`calculateEarnings catch error: ${message}`); } }; diff --git a/jobs/cancel_orders.js b/jobs/cancel_orders.ts similarity index 93% rename from jobs/cancel_orders.js rename to jobs/cancel_orders.ts index 00cef019..e9d2b43b 100644 --- a/jobs/cancel_orders.js +++ b/jobs/cancel_orders.ts @@ -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'); -const cancelOrders = async bot => { +const cancelOrders = async (bot: Telegraf) => { 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 @@ -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; diff --git a/jobs/communities.js b/jobs/communities.ts similarity index 80% rename from jobs/communities.js rename to jobs/communities.ts index e9ddb503..bce48988 100644 --- a/jobs/communities.js +++ b/jobs/communities.ts @@ -1,12 +1,15 @@ +import { Telegraf } from "telegraf"; +import { MainContext } from "../bot/start"; + const { Order, Community } = require('../models'); const logger = require('../logger'); -const deleteCommunity = async bot => { +const deleteCommunity = async (bot: Telegraf) => { 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 @@ -26,7 +29,7 @@ const deleteCommunity = async bot => { } } } catch (error) { - const message = error.toString(); + const message = String(error); logger.error(`deleteCommunity catch error: ${message}`); } }; diff --git a/jobs/delete_published_orders.js b/jobs/delete_published_orders.ts similarity index 81% rename from jobs/delete_published_orders.js rename to jobs/delete_published_orders.ts index b4e284ae..ed117b83 100644 --- a/jobs/delete_published_orders.js +++ b/jobs/delete_published_orders.ts @@ -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'); -const deleteOrders = async bot => { +const deleteOrders = async (bot: Telegraf) => { 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({ @@ -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}`); } }; diff --git a/jobs/node_info.js b/jobs/node_info.ts similarity index 72% rename from jobs/node_info.js rename to jobs/node_info.ts index bad5d904..aea34294 100644 --- a/jobs/node_info.js +++ b/jobs/node_info.ts @@ -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'); -const info = async bot => { +const info = async (bot: Telegraf) => { try { const config = await Config.findOne({}); const info = await getInfo(); @@ -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}`); } }; diff --git a/ln/connect.js b/ln/connect.ts similarity index 92% rename from ln/connect.js rename to ln/connect.ts index 167d5445..2a09bd88 100644 --- a/ln/connect.js +++ b/ln/connect.ts @@ -1,6 +1,6 @@ -const fs = require('fs'); -const path = require('path'); -const lightning = require('lightning'); +import * as fs from 'fs'; +import path = require('path'); +import * as lightning from "lightning"; const logger = require('../logger'); const { authenticatedLndGrpc } = lightning; @@ -47,4 +47,4 @@ const { lnd } = authenticatedLndGrpc({ socket, }); -module.exports = lnd; +export default lnd; diff --git a/ln/hold_invoice.js b/ln/hold_invoice.ts similarity index 65% rename from ln/hold_invoice.js rename to ln/hold_invoice.ts index 1a36c39c..ea3a4cc5 100644 --- a/ln/hold_invoice.js +++ b/ln/hold_invoice.ts @@ -1,26 +1,26 @@ -const { createHash, randomBytes } = require('crypto'); -const lightning = require('lightning'); -const lnd = require('./connect'); +import { randomBytes, createHash } from 'crypto'; +import * as lightning from "lightning"; +import lnd from './connect' const logger = require('../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 @@ -30,7 +30,7 @@ const createHoldInvoice = async ({ description, amount }) => { } }; -const settleHoldInvoice = async ({ secret }) => { +const settleHoldInvoice = async ( secret: string ) => { try { await lightning.settleHodlInvoice({ lnd, secret }); } catch (error) { @@ -38,7 +38,7 @@ const settleHoldInvoice = async ({ secret }) => { } }; -const cancelHoldInvoice = async ({ hash }) => { +const cancelHoldInvoice = async ( hash: string ) => { try { await lightning.cancelHodlInvoice({ lnd, id: hash }); } catch (error) { @@ -46,7 +46,7 @@ const cancelHoldInvoice = async ({ hash }) => { } }; -const getInvoice = async ({ hash }) => { +const getInvoice = async ( hash: string ) => { try { return await lightning.getInvoice({ lnd, id: hash }); } catch (error) { diff --git a/ln/info.js b/ln/info.ts similarity index 52% rename from ln/info.js rename to ln/info.ts index da731135..fca1b322 100644 --- a/ln/info.js +++ b/ln/info.ts @@ -1,13 +1,11 @@ -const lightning = require('lightning'); -const lnd = require('./connect'); +import * as lightning from "lightning"; +import lnd from './connect' const logger = require('../logger'); -const getInfo = async () => { +export const getInfo = async () => { try { return await lightning.getWalletInfo({ lnd }); } catch (error) { logger.error(error); } }; - -module.exports = { getInfo }; diff --git a/ln/resubscribe_invoices.js b/ln/resubscribe_invoices.ts similarity index 73% rename from ln/resubscribe_invoices.js rename to ln/resubscribe_invoices.ts index 644dbbba..410813f0 100644 --- a/ln/resubscribe_invoices.js +++ b/ln/resubscribe_invoices.ts @@ -1,13 +1,15 @@ -const { getInvoices } = require('lightning'); -const lnd = require('./connect'); +import { Telegraf } from 'telegraf'; +import { MainContext } from "../bot/start"; +import { getInvoices, GetInvoicesResult } from 'lightning'; +import lnd from './connect'; const subscribeInvoice = require('./subscribe_invoice'); const { Order } = require('../models'); const logger = require('../logger'); -const resubscribeInvoices = async bot => { +const resubscribeInvoices = async (bot: Telegraf) => { try { let invoicesReSubscribed = 0; - const isHeld = invoice => !!invoice.is_held; + const isHeld = (invoice: any) => !!invoice.is_held; const unconfirmedInvoices = ( await getInvoices({ lnd, @@ -29,7 +31,7 @@ const resubscribeInvoices = async bot => { } logger.info(`Invoices resubscribed: ${invoicesReSubscribed}`); } catch (error) { - logger.error(`ResuscribeInvoice catch: ${error.toString()}`); + logger.error(`ResuscribeInvoice catch: ${String(error)}`); return false; } }; diff --git a/ln/subscribe_invoice.js b/ln/subscribe_invoice.ts similarity index 94% rename from ln/subscribe_invoice.js rename to ln/subscribe_invoice.ts index 2f96e36a..f65a3588 100644 --- a/ln/subscribe_invoice.js +++ b/ln/subscribe_invoice.ts @@ -1,13 +1,15 @@ -const { subscribeToInvoice } = require('lightning'); +import { Telegraf } from "telegraf"; +import { MainContext } from "../bot/start"; +import {subscribeToInvoice} from 'lightning' const { Order, User } = require('../models'); const { payToBuyer } = require('./pay_request'); -const lnd = require('./connect'); +import lnd from "./connect"; const messages = require('../bot/messages'); const ordersActions = require('../bot/ordersActions'); const { getUserI18nContext, getEmojiRate, decimalRound } = require('../util'); const logger = require('../logger'); -const subscribeInvoice = async (bot, id, resub) => { +const subscribeInvoice = async (bot: Telegraf, id: string, resub: boolean) => { try { const sub = subscribeToInvoice({ id, lnd }); sub.on('invoice_updated', async invoice => { diff --git a/lnurl/lnurl-pay.js b/lnurl/lnurl-pay.ts similarity index 80% rename from lnurl/lnurl-pay.js rename to lnurl/lnurl-pay.ts index 45235898..e49d593b 100644 --- a/lnurl/lnurl-pay.js +++ b/lnurl/lnurl-pay.ts @@ -1,11 +1,11 @@ -const axios = require('axios').default; +import axios from 'axios'; const logger = require('../logger'); // { // pr: String, // bech32-serialized lightning invoice // routes: [], // an empty array // } -const resolvLightningAddress = async (address, amountMsat) => { +const resolvLightningAddress = async (address: string, amountMsat: number) => { const [user, domain] = address.split('@'); const lnAddressQuery = `https://${domain}/.well-known/lnurlp/${user}`; @@ -17,7 +17,7 @@ const resolvLightningAddress = async (address, amountMsat) => { } if ( - (lnAddressRes.minSendable > amountMsat) | + (lnAddressRes.minSendable > amountMsat) || (lnAddressRes.maxSendable < amountMsat) ) { logger.info('lnAddress invalid amount'); @@ -31,7 +31,7 @@ const resolvLightningAddress = async (address, amountMsat) => { return res; }; -const existLightningAddress = async address => { +const existLightningAddress = async (address: string) => { const [user, domain] = address.split('@'); const lnAddressQuery = `https://${domain}/.well-known/lnurlp/${user}`; @@ -49,7 +49,4 @@ const existLightningAddress = async address => { } }; -module.exports = { - resolvLightningAddress, - existLightningAddress, -}; +export { resolvLightningAddress, existLightningAddress } diff --git a/logger.js b/logger.ts similarity index 82% rename from logger.js rename to logger.ts index ada7ed8e..d5fe6e2a 100644 --- a/logger.js +++ b/logger.ts @@ -1,4 +1,4 @@ -const winston = require('winston'); +import * as winston from 'winston'; const level = process.env.LOG_LEVEL || 'notice'; @@ -9,9 +9,8 @@ const logger = winston.createLogger({ }), winston.format.colorize(), winston.format.printf(info => { - return `[${info.timestamp}] ${info.level}: ${info.message} ${ - info.stack ? info.stack : '' - }`; + return `[${info.timestamp}] ${info.level}: ${info.message} ${info.stack ? info.stack : '' + }`; }) ), levels: winston.config.syslog.levels, @@ -24,4 +23,5 @@ const logger = winston.createLogger({ exitOnError: false, }); -module.exports = logger; + +export default logger; diff --git a/tsconfig.json b/tsconfig.json index 8039f57e..7328ef96 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,6 @@ { "compilerOptions": { "strict": true, + "downlevelIteration": true, } }