Skip to content

Commit

Permalink
ln: convert js to ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Mersho committed Jul 6, 2024
1 parent 98709de commit 877ad0f
Show file tree
Hide file tree
Showing 8 changed files with 62 additions and 55 deletions.
2 changes: 1 addition & 1 deletion app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import "dotenv/config";
import { SocksProxyAgent } from "socks-proxy-agent";
import { MainContext, start } from "./bot/start";
import { connect as mongoConnect } from './db_connect'
const { resubscribeInvoices } = require('./ln');
import { resubscribeInvoices } from './ln';
import { logger } from "./logger";
import { Telegraf } from "telegraf";
const { delay } = require('./util');
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 * as path from '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 };
24 changes: 12 additions & 12 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, amount } : { 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,31 +30,31 @@ const createHoldInvoice = async ({ description, amount }) => {
}
};

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

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

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

module.exports = {
export {
createHoldInvoice,
settleHoldInvoice,
cancelHoldInvoice,
Expand Down
12 changes: 6 additions & 6 deletions ln/index.js → ln/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
const {
import {
createHoldInvoice,
settleHoldInvoice,
cancelHoldInvoice,
getInvoice,
} = require('./hold_invoice');
const { subscribeInvoice, payHoldInvoice } = require('./subscribe_invoice');
} from './hold_invoice';
import { subscribeInvoice, payHoldInvoice } from './subscribe_invoice';
const subscribeProbe = require('./subscribe_probe');
const resubscribeInvoices = require('./resubscribe_invoices');
import { resubscribeInvoices } from './resubscribe_invoices';
const { payRequest, payToBuyer, isPendingPayment } = require('./pay_request');
const { getInfo } = require('./info');
import { getInfo } from './info';

module.exports = {
export {
createHoldInvoice,
subscribeInvoice,
resubscribeInvoices,
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);
}
};
20 changes: 11 additions & 9 deletions ln/resubscribe_invoices.js → ln/resubscribe_invoices.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
const { getInvoices } = require('lightning');
const lnd = require('./connect');
const { subscribeInvoice } = require('./subscribe_invoice');
const { Order } = require('../models');
const { logger } = require('../logger');
import { Telegraf } from 'telegraf';
import { MainContext } from "../bot/start";
import { getInvoices, GetInvoicesResult } from 'lightning';
import { lnd } from './connect';
import { subscribeInvoice } from './subscribe_invoice';
import { Order } from '../models';
import { logger } from "../logger";

const resubscribeInvoices = async bot => {
const resubscribeInvoices = async (bot: Telegraf<MainContext>) => {
try {
let invoicesReSubscribed = 0;
const isHeld = invoice => !!invoice.is_held;
const isHeld = (invoice: any) => !!invoice.is_held;
const unconfirmedInvoices = (
await getInvoices({
lnd,
Expand All @@ -29,9 +31,9 @@ const resubscribeInvoices = async bot => {
}
logger.info(`Invoices resubscribed: ${invoicesReSubscribed}`);
} catch (error) {
logger.error(`ResubcribeInvoice catch: ${error.toString()}`);
logger.error(`ResuscribeInvoice catch: ${String(error)}`);
return false;
}
};

module.exports = resubscribeInvoices;
export { resubscribeInvoices };
25 changes: 16 additions & 9 deletions ln/subscribe_invoice.js → ln/subscribe_invoice.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
const { subscribeToInvoice } = require('lightning');
const { Order, User } = require('../models');
import { Telegraf } from "telegraf";
import { MainContext } from "../bot/start";
import { subscribeToInvoice } from 'lightning'
import { Order, User } from '../models';
const { payToBuyer } = require('./pay_request');
const lnd = require('./connect');
const messages = require('../bot/messages');
import { lnd } from "./connect";
import * as messages from '../bot/messages';
const ordersActions = require('../bot/ordersActions');
const { getUserI18nContext, getEmojiRate, decimalRound } = require('../util');
const { logger } = require('../logger');
import { logger } from "../logger";
import { IOrder } from "../models/order";
const OrderEvents = require('../bot/modules/events/orders');

const subscribeInvoice = async (bot, id, resub) => {
const subscribeInvoice = async (bot: Telegraf<MainContext>, id: string, resub: boolean) => {
try {
const sub = subscribeToInvoice({ id, lnd });
sub.on('invoice_updated', async invoice => {
if (invoice.is_held && !resub) {
const order = await Order.findOne({ hash: invoice.id });
if (order === null) throw Error("Order was not found in DB");
logger.info(
`Order ${order._id} Invoice with hash: ${id} is being held!`
);
const buyerUser = await User.findOne({ _id: order.buyer_id });
const sellerUser = await User.findOne({ _id: order.seller_id });
if (buyerUser === null || sellerUser === null) throw Error("buyer or seller was not found in DB");
order.status = 'ACTIVE';
// This is the i18n context we need to pass to the message
const i18nCtxBuyer = await getUserI18nContext(buyerUser);
Expand Down Expand Up @@ -48,12 +53,13 @@ const subscribeInvoice = async (bot, id, resub) => {
rate
);
}
order.invoice_held_at = Date.now();
order.invoice_held_at = new Date();
order.save();
OrderEvents.orderUpdated(order);
}
if (invoice.is_confirmed) {
const order = await Order.findOne({ hash: id });
if (order === null) throw Error("Order was not found in DB");
logger.info(
`Order ${order._id} - Invoice with hash: ${id} was settled!`
);
Expand All @@ -72,13 +78,14 @@ const subscribeInvoice = async (bot, id, resub) => {
}
};

const payHoldInvoice = async (bot, order) => {
const payHoldInvoice = async (bot: Telegraf<MainContext>, order: IOrder) => {
try {
order.status = 'PAID_HOLD_INVOICE';
await order.save();
OrderEvents.orderUpdated(order);
const buyerUser = await User.findOne({ _id: order.buyer_id });
const sellerUser = await User.findOne({ _id: order.seller_id });
if (buyerUser === null || sellerUser === null) throw Error("buyer or seller was not found in DB");
// We need two i18n contexts to send messages to each user
const i18nCtxBuyer = await getUserI18nContext(buyerUser);
const i18nCtxSeller = await getUserI18nContext(sellerUser);
Expand Down Expand Up @@ -138,4 +145,4 @@ const payHoldInvoice = async (bot, order) => {
}
};

module.exports = { subscribeInvoice, payHoldInvoice };
export { subscribeInvoice, payHoldInvoice };

0 comments on commit 877ad0f

Please sign in to comment.