Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bot/modules/nostr: convert to TS #627

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
const Nostr = require('nostr-tools');
const { logger } = require('../../../logger');
const Config = require('./config');
import Nostr from 'nostr-tools';
import { logger } from '../../../logger';
import * as Config from './config';
import { MainContext } from '../../start';

exports.info = async ctx => {
export const info = async (ctx: MainContext) => {
try {
const publicKey = Config.getPublicKey();
if (!publicKey) return;
Expand Down
20 changes: 0 additions & 20 deletions bot/modules/nostr/config.js

This file was deleted.

20 changes: 20 additions & 0 deletions bot/modules/nostr/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const notsrPure = require('nostr-tools/pure');
const { SimplePool } = require('nostr-tools/pool');

const sk = process.env.NOSTR_SK || notsrPure.generateSecretKey();
const pk = notsrPure.getPublicKey(sk);

export const getPrivateKey = () => sk;
export const getPublicKey = () => pk;

export const pool = new SimplePool();
const relays = (env => {
if (!env.RELAYS) return [];
return env.RELAYS.split(',');
})(process.env);

export const addRelay = (relay: string) => {
relays.push(relay);
relays.map(relay => pool.ensureRelay(relay));
};
export const getRelays = () => relays;
23 changes: 16 additions & 7 deletions bot/modules/nostr/events.js → bot/modules/nostr/events.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
const { finalizeEvent, verifyEvent } = require('nostr-tools/pure');
const Config = require('./config');
import * as Config from './config';

const { Community } = require('../../../models');
const { toKebabCase, removeAtSymbol } = require('../../../util');
import { Community } from '../../../models';
import { toKebabCase, removeAtSymbol } from '../../../util';
import { IOrder } from '../../../models/order';

/// All events broadcasted are Parameterized Replaceable Events,
/// the event kind must be between 30000 and 39999
const kind = 38383;

const orderToTags = async order => {
const orderToTags = async (order: IOrder) => {
const orderPublishedExpirationWindow = process.env.ORDER_PUBLISHED_EXPIRATION_WINDOW;
if(orderPublishedExpirationWindow === undefined)
throw new Error("Environment variable ORDER_PUBLISHED_EXPIRATION_WINDOW is not defined");
const expiration =
Math.floor(Date.now() / 1000) +
parseInt(process.env.ORDER_PUBLISHED_EXPIRATION_WINDOW);
parseInt(orderPublishedExpirationWindow);
const fiat_amount = ['fa'];
if (order.fiat_amount === undefined) {
fiat_amount.push(order.min_amount.toString(), order.max_amount.toString());
} else {
fiat_amount.push(order.fiat_amount.toString());
}
const channel = removeAtSymbol(process.env.CHANNEL);
const channelEnvVar = process.env.CHANNEL;
if(channelEnvVar === undefined)
throw new Error("Environment variable CHANNEL is not defined")
const channel = removeAtSymbol(channelEnvVar);
let source = `https://t.me/${channel}/${order.tg_channel_message1}`;
const tags = [];
tags.push(['d', order.id]);
Expand All @@ -31,6 +38,8 @@ const orderToTags = async order => {
tags.push(['premium', order.price_margin.toString()]);
if (order.community_id) {
const community = await Community.findById(order.community_id);
if(community === null)
throw new Error("community was not found");
const group = removeAtSymbol(community.group);
source = `https://t.me/${group}/${order.tg_channel_message1}`;
tags.push(['community_id', order.community_id]);
Expand All @@ -45,7 +54,7 @@ const orderToTags = async order => {
return tags;
};

exports.createOrderEvent = async order => {
export const createOrderEvent = async (order: IOrder) => {
const myPrivKey = Config.getPrivateKey();
if (order.is_public === false) {
return;
Expand Down
35 changes: 0 additions & 35 deletions bot/modules/nostr/index.js

This file was deleted.

40 changes: 40 additions & 0 deletions bot/modules/nostr/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
require('websocket-polyfill'); // is it needed?
import { logger } from '../../../logger';
import * as Config from './config';
import { createOrderEvent } from './events';
import * as Commands from './commands';
import { Telegraf } from 'telegraf';
import { MainContext } from '../../start';
import { IOrder } from '../../../models/order';

export const configure = (bot: Telegraf<MainContext>) => {
bot.command('/nostr', Commands.info);

if (!Config.getRelays().length) {
['wss://nostr-pub.wellorder.net', 'wss://relay.damus.io'].map(
Config.addRelay
);
}

// I don't know why these requires are here and not at the top of the file,
// so I leave them as they are instead of converting to imports.
const CommunityEvents = require('../events/community');
CommunityEvents.onCommunityUpdated(async (community: any) => {
// todo: notify users
});

const OrderEvents = require('../events/orders');

OrderEvents.onOrderUpdated(async (order: IOrder) => {
try {
const event = await createOrderEvent(order);
if (event) {
await Promise.any(Config.pool.publish(Config.getRelays(), event));
}

return event;
} catch (err) {
logger.error(err);
}
});
};
6 changes: 3 additions & 3 deletions bot/modules/nostr/lib.js → bot/modules/nostr/lib.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const Nostr = require('nostr-tools');
import Nostr from 'nostr-tools';

exports.decodeNpub = npub => {
export const decodeNpub = (npub: string) => {
try {
const { type, data } = Nostr.nip19.decode(npub);
if (type === 'npub') return data;
} catch (err) {}
};
exports.encodeNpub = hex => {
export const encodeNpub = (hex: string) => {
return Nostr.nip19.npubEncode(hex);
};
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"esModuleInterop": true,
"resolveJsonModule": true,
"downlevelIteration": true,
"lib":["ES2021", "DOM"],
"outDir": "./dist",
"rootDir": ".",
"allowJs": true,
Expand Down
Loading