This commit is contained in:
pablof7z
2025-04-09 11:45:30 +01:00
parent 630ed0cbd0
commit b258f49201
8 changed files with 134 additions and 48 deletions

85
lib/cache/wallets.ts vendored
View File

@@ -1,5 +1,9 @@
import {
NDKCashuMintList,
NDKPrivateKeySigner,
type NDKSigner,
} from "@nostr-dev-kit/ndk";
import { NDKCashuWallet, NDKNutzapMonitor } from "@nostr-dev-kit/ndk-wallet";
import { NDKCashuMintList, NDKPrivateKeySigner, type NDKSigner } from "@nostr-dev-kit/ndk";
import { ndk } from "../../ndk.js";
import { log } from "../utils/log.js";
@@ -15,7 +19,12 @@ export const walletsCache: Record<string, NDKCashuWallet> = {};
* @param pubkey The public key to get the wallet for
* @returns The wallet (from cache or newly loaded)
*/
export async function getWallet(pubkey: string, signer: NDKSigner): Promise<NDKCashuWallet | undefined> {
export async function getWallet(
pubkey: string,
signer: NDKSigner
): Promise<NDKCashuWallet | undefined> {
let newWallet = false;
// Return from cache if available
if (walletsCache[pubkey]) {
console.log(`Returning cached wallet for ${pubkey}`);
@@ -23,45 +32,53 @@ export async function getWallet(pubkey: string, signer: NDKSigner): Promise<NDKC
}
ndk.signer = signer;
// Not in cache, fetch from Nostr
try {
let wallet: NDKCashuWallet | undefined;
const user = ndk.getUser({pubkey});
const event = await ndk.fetchEvent({ kinds: [17375], authors: [pubkey] });
const user = ndk.getUser({ pubkey });
const event = await ndk.fetchEvent({
kinds: [17375],
authors: [pubkey],
});
// Use the existing wallet
if (event) {
console.log(`Found wallet event for ${pubkey}: ${event.id}`, event.inspect);
console.log(
`Found wallet event for ${pubkey}: ${event.id}`,
event.inspect
);
wallet = await NDKCashuWallet.from(event);
} else {
console.log('No wallet event found for', pubkey);
console.log("No wallet event found for", pubkey);
}
if (!wallet) {
newWallet = true;
wallet = new NDKCashuWallet(ndk);
wallet.mints = ["https://mint.coinos.io"];
// Generate a P2PK address for receiving nutzaps
await wallet.getP2pk();
log(`Generated P2PK address for ${pubkey}: ${wallet.p2pk}`);
// Publish the wallet info event (kind 17375)
await wallet.publish();
log(`Published wallet info event for ${pubkey}`);
// Set up the mint list for nutzap reception (kind 10019)
const mintList = new NDKCashuMintList(ndk);
mintList.mints = wallet.mints;
mintList.relays = ['wss://relay.pri']
mintList.relays = ["wss://relay.primal.net"];
mintList.p2pk = wallet.p2pk;
// Publish the mint list
await mintList.publish();
log(`Published mint list for ${pubkey} with mints: ${mintList.mints.join(', ')}`);
log(
`Published mint list for ${pubkey} with mints: ${mintList.mints.join(", ")}`
);
}
// Start wallet for monitoring balance and nutzaps
console.log(`Starting wallet for ${pubkey}`);
await wallet.start();
@@ -72,25 +89,45 @@ export async function getWallet(pubkey: string, signer: NDKSigner): Promise<NDKC
const nutzapMonitor = new NDKNutzapMonitor(ndk, user, {});
nutzapMonitor.wallet = wallet;
nutzapMonitor.on("seen", () => {
log('seen nutzap');
log("seen nutzap");
});
nutzapMonitor.on("redeemed", (events) => {
log(`Nutzap redeemed for ${pubkey}: ${events.reduce((acc, event) => acc + event.amount, 0)} sats`);
log(
`Nutzap redeemed for ${pubkey}: ${events.reduce((acc, event) => acc + event.amount, 0)} sats`
);
});
nutzapMonitor.start({});
log(`Started nutzap monitor for ${pubkey}`);
// Set up balance update listener
wallet.on('balance_updated', (newBalance) => {
log(`Balance updated for ${pubkey}: ${newBalance?.amount || 0} sats`);
wallet.on("balance_updated", (newBalance) => {
log(
`Balance updated for ${pubkey}: ${newBalance?.amount || 0} sats`
);
});
} catch (error) {
console.error(`Error starting nutzap monitor for ${pubkey}:`, error);
console.error(
`Error starting nutzap monitor for ${pubkey}:`,
error
);
}
walletsCache[pubkey] = wallet;
// No wallet found
if (!newWallet) {
// Total hack, but we have a race condition getting the balance of the wallet,
// if we're starting the wallet with a get_balance command we'll always return zero
// in the first call, so let's give it some time to catch up. wallet.start() should
// have returned once it knows it has all the proofs
return new Promise((resolve) => {
setTimeout(() => {
resolve(wallet);
}, 1000);
wallet.on("balance_updated", () => resolve(wallet));
});
}
// NKo wallet found
return wallet;
} catch (error) {
console.error(`Error fetching wallet for ${pubkey}:`, error);
@@ -105,4 +142,4 @@ export function clearWalletsCache(): void {
for (const key of Object.keys(walletsCache)) {
delete walletsCache[key];
}
}
}

View File

@@ -1,10 +1,14 @@
import type { NDKEvent, NDKFilter } from "@nostr-dev-kit/ndk";
import { db } from "../../db.js";
import { ndk } from "../../ndk.js";
import {
formatPartialMatches,
formatSnippets,
toSnippet,
} from "../converters/index.js";
import type { CodeSnippet, FindSnippetsParams } from "../types/index.js";
import { log } from "../utils/log.js";
import { SNIPPET_KIND, identifierToPubkeys } from "./utils.js";
import { formatPartialMatches, formatSnippets, toSnippet } from "../converters/index.js";
/**
* Get code snippets from Nostr events of kind 1337
@@ -54,6 +58,19 @@ export async function getSnippets(params: FindSnippetsParams = {}): Promise<{
log(`Fetching snippets with filter: ${JSON.stringify(filter, null, 2)}`);
// ndk.subscribe(
// [filter],
// { closeOnEose: true },
// {
// onEvent: (event) => {
// log(`Received event: ${event.id}`);
// },
// onEose: () => {
// log("EOSE received.");
// },
// }
// );
// Fetch events
const events = await ndk.fetchEvents(filter);
@@ -73,8 +90,11 @@ export async function getSnippets(params: FindSnippetsParams = {}): Promise<{
.filter((t): t is string => t !== undefined); // Ensure tag value exists and narrow type
// Count how many of the searched tags are present in the event's tags
return params.tags.filter((searchTag) =>
aTags.some((eventTag) => eventTag.match(new RegExp(searchTag, "i"))) // Case-insensitive tag matching
return params.tags.filter(
(searchTag) =>
aTags.some((eventTag) =>
eventTag.match(new RegExp(searchTag, "i"))
) // Case-insensitive tag matching
).length;
}
@@ -98,7 +118,6 @@ export async function getSnippets(params: FindSnippetsParams = {}): Promise<{
const snippets = selectedEvents.map(toSnippet);
const otherSnippets = notSelectedEvents.map(toSnippet);
// --- BEGIN DATABASE INSERTION ---
const allSnippets = [...snippets, ...otherSnippets];
if (allSnippets.length > 0) {

View File

@@ -1,8 +1,8 @@
import * as fs from "node:fs";
import { promises as fsPromises } from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
const id = Math.floor(Math.random() * 1000000);
const timeZero = Date.now();
/**
@@ -21,7 +21,7 @@ export function log(
const now = new Date();
const timestamp = new Date().toISOString();
const relativeTime = now.getTime() - timeZero;
const logMessage = `[${relativeTime}ms] ${timestamp} - ${message}\n`;
const logMessage = `[${id}] [${relativeTime}ms] ${timestamp} - ${message}\n`;
fs.appendFile(logFilePath, logMessage, (err) => {
if (err) {
console.error("Error writing to log file:", err);