working locally

This commit is contained in:
zmeyer44 2023-10-18 21:55:45 -04:00
parent 4a35a785a7
commit e3364bb86c
9 changed files with 59 additions and 50 deletions

View File

@ -64,7 +64,7 @@ export default function FeaturedLists() {
</SectionHeader> </SectionHeader>
<SectionContent className="sm:md-feed-cols relative flex flex-col gap-3"> <SectionContent className="sm:md-feed-cols relative flex flex-col gap-3">
{processedEvents.map((e) => ( {processedEvents.map((e) => (
<Link href={`/list/${e.encode()}`}> <Link key={e.id} href={`/list/${e.encode()}`}>
<ListCard key={e.id} event={e} /> <ListCard key={e.id} event={e} />
</Link> </Link>
))} ))}

View File

@ -15,6 +15,7 @@ import {
type NDKList, type NDKList,
} from "@nostr-dev-kit/ndk"; } from "@nostr-dev-kit/ndk";
import { useNDK } from "../ndk"; import { useNDK } from "../ndk";
import { log } from "@/lib/utils";
export type SignerStoreItem = { export type SignerStoreItem = {
signer: NDKPrivateKeySigner; signer: NDKPrivateKeySigner;
@ -67,15 +68,19 @@ export default function SignerProvider({
} }
async function getSigner(list: NDKList): Promise<SignerStoreItem> { async function getSigner(list: NDKList): Promise<SignerStoreItem> {
log("func", "getSigner");
const id = list.encode(); const id = list.encode();
log("info", "list ID", id.toString());
let item = signers.get(id); let item = signers.get(id);
if (item) return item; if (item) return item;
log("info", "NO local signer");
let signer = await findEphemeralSigner(ndk!, ndk!.signer!, { let signer = await findEphemeralSigner(ndk!, ndk!.signer!, {
associatedEventNip19: list.encode(), associatedEventNip19: list.encode(),
}); });
if (signer) { if (signer) {
console.log(`found a signer for list ${list.title}`); log("info", `found a signer for list ${list.title}`, signer.toString());
item = { item = {
signer: signer!, signer: signer!,
user: await signer.user(), user: await signer.user(),
@ -83,9 +88,9 @@ export default function SignerProvider({
id, id,
}; };
} else { } else {
console.log(`no signer found for list ${list.title}`); log("info", `no signer found for list ${list.title}`);
signer = NDKPrivateKeySigner.generate(); signer = NDKPrivateKeySigner.generate();
console.log(`Signer generated ${JSON.stringify(signer)}`); log("info", "generated signer", signer.toString());
item = { item = {
signer, signer,
user: await signer.user(), user: await signer.user(),

View File

@ -13,6 +13,7 @@ import { getTagValues } from "@/lib/nostr/utils";
import { NDKList } from "@nostr-dev-kit/ndk"; import { NDKList } from "@nostr-dev-kit/ndk";
import { saveEphemeralSigner } from "@/lib/actions/ephemeral"; import { saveEphemeralSigner } from "@/lib/actions/ephemeral";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { log } from "@/lib/utils";
const CreateListSchema = z.object({ const CreateListSchema = z.object({
title: z.string(), title: z.string(),
@ -32,6 +33,7 @@ export default function CreateList() {
const { currentUser, updateUser } = useCurrentUser(); const { currentUser, updateUser } = useCurrentUser();
const { ndk } = useNDK(); const { ndk } = useNDK();
const { getSigner } = useSigner()!; const { getSigner } = useSigner()!;
async function handleSubmit(data: CreateListType) { async function handleSubmit(data: CreateListType) {
setIsLoading(true); setIsLoading(true);
const random = randomId(); const random = randomId();
@ -60,7 +62,6 @@ export default function CreateList() {
kind: 30001, kind: 30001,
tags: tags, tags: tags,
}); });
console.log("EVENT Created", event);
if (event && getTagValues("subscriptions", event.tags)) { if (event && getTagValues("subscriptions", event.tags)) {
await getSigner(new NDKList(ndk, event.rawEvent())) await getSigner(new NDKList(ndk, event.rawEvent()))
.then((delegateSigner) => .then((delegateSigner) =>
@ -75,7 +76,9 @@ export default function CreateList() {
}), }),
) )
.then( .then(
(savedSigner) => savedSigner, (savedSigner) => {
log("info", "savedSigner", savedSigner.toString());
},
// updateList(ndk!, event.rawEvent(), [ // updateList(ndk!, event.rawEvent(), [
// ["delegate", savedSigner.hexpubkey], // ["delegate", savedSigner.hexpubkey],
// ]), // ]),

View File

@ -126,7 +126,6 @@ export default function ShortTextNoteModal() {
slug: "list", slug: "list",
options: lists options: lists
.map((l) => { .map((l) => {
console.log("MApping", l);
const title = const title =
getTagValues("title", l.tags) ?? getTagValues("title", l.tags) ??
getTagValues("name", l.tags) ?? getTagValues("name", l.tags) ??

View File

@ -10,6 +10,7 @@ import NDK, {
import { generateRandomString, encryptMessage, randomId } from "@/lib/nostr"; import { generateRandomString, encryptMessage, randomId } from "@/lib/nostr";
import { unixTimeNowInSeconds } from "@/lib/nostr/dates"; import { unixTimeNowInSeconds } from "@/lib/nostr/dates";
import { getTagsValues } from "@/lib/nostr/utils"; import { getTagsValues } from "@/lib/nostr/utils";
import { log } from "@/lib/utils";
export async function createEvent( export async function createEvent(
ndk: NDK, ndk: NDK,
@ -19,6 +20,7 @@ export async function createEvent(
tags: string[][]; tags: string[][];
}, },
) { ) {
log("func", "createEvent");
try { try {
const pubkey = await window.nostr?.getPublicKey(); const pubkey = await window.nostr?.getPublicKey();
if (!pubkey || !window.nostr) { if (!pubkey || !window.nostr) {
@ -29,14 +31,11 @@ export async function createEvent(
pubkey, pubkey,
created_at: unixTimeNowInSeconds(), created_at: unixTimeNowInSeconds(),
} as NostrEvent); } as NostrEvent);
console.log("eventToPublish ", eventToPublish); await eventToPublish.sign();
const signed = await eventToPublish.sign();
console.log("signed", signed);
await eventToPublish.publish(); await eventToPublish.publish();
return eventToPublish; return eventToPublish;
} catch (err) { } catch (err) {
console.log(err); log("error", err);
alert("An error has occured"); alert("An error has occured");
return false; return false;
} }
@ -52,6 +51,7 @@ export async function createEventHandler(
list?: NDKList, list?: NDKList,
delegateSigner?: NDKPrivateKeySigner, delegateSigner?: NDKPrivateKeySigner,
) { ) {
log("func", "createEventHandler");
const pubkey = await window.nostr?.getPublicKey(); const pubkey = await window.nostr?.getPublicKey();
if (!pubkey || !window.nostr) { if (!pubkey || !window.nostr) {
throw new Error("No public key provided!"); throw new Error("No public key provided!");
@ -68,6 +68,7 @@ export async function createEventHandler(
let publishedEvent: NDKEvent | null = null; let publishedEvent: NDKEvent | null = null;
// Check if is private event // Check if is private event
if (isPrivate) { if (isPrivate) {
log("info", "isPrivate");
const rawEventString = JSON.stringify(eventToPublish.rawEvent()); const rawEventString = JSON.stringify(eventToPublish.rawEvent());
const passphrase = generateRandomString(); const passphrase = generateRandomString();
const encryptedRawEventString = await encryptMessage( const encryptedRawEventString = await encryptMessage(
@ -76,7 +77,7 @@ export async function createEventHandler(
); );
const signer = delegateSigner ?? ndk.signer!; const signer = delegateSigner ?? ndk.signer!;
const user = await signer.user(); const user = await signer.user();
log("info", "Signer", user.toString());
const newEvent = new NDKEvent(ndk, { const newEvent = new NDKEvent(ndk, {
content: encryptedRawEventString, content: encryptedRawEventString,
kind: 3745, kind: 3745,
@ -144,21 +145,6 @@ export async function createReaction(
], ],
}); });
} }
export async function createList(
ndk: NDK,
title: string,
description?: string,
) {
return createEvent(ndk, {
content: "",
kind: 30001,
tags: [
["name", title],
["description", description ?? ""],
["d", randomId()],
],
});
}
export async function deleteEvent( export async function deleteEvent(
ndk: NDK, ndk: NDK,
events: [["e", string] | ["a", `${number}:${string}:${string}`]], events: [["e", string] | ["a", `${number}:${string}:${string}`]],

View File

@ -9,6 +9,8 @@ import NDK, {
} from "@nostr-dev-kit/ndk"; } from "@nostr-dev-kit/ndk";
import { getHashedKeyName } from "@/lib/nostr"; import { getHashedKeyName } from "@/lib/nostr";
import { z } from "zod"; import { z } from "zod";
import { log } from "@/lib/utils";
const SignerSchema = z.object({ const SignerSchema = z.object({
key: z.string(), key: z.string(),
}); });
@ -26,6 +28,7 @@ export async function findEphemeralSigner(
mainSigner: NDKSigner, mainSigner: NDKSigner,
opts: IFindEphemeralSignerLookups, opts: IFindEphemeralSignerLookups,
): Promise<NDKPrivateKeySigner | undefined> { ): Promise<NDKPrivateKeySigner | undefined> {
log("func", "findEphemeralSigner");
const filter: NDKFilter = { kinds: [2600 as number] }; const filter: NDKFilter = { kinds: [2600 as number] };
if (opts.name) { if (opts.name) {
@ -37,13 +40,11 @@ export async function findEphemeralSigner(
); );
filter["#e"] = [hashedEventReference]; filter["#e"] = [hashedEventReference];
} }
console.log("filter", filter); log("info", "filter", filter.toString());
const event = await ndk.fetchEvent(filter); const event = await ndk.fetchEvent(filter);
if (event) { if (event) {
const decryptEventFunction = async (event: NDKEvent) => { const decryptEventFunction = async (event: NDKEvent) => {
await event.decrypt(await mainSigner.user()); await event.decrypt(await mainSigner.user());
const content = SignerSchema.parse(JSON.parse(event.content)); const content = SignerSchema.parse(JSON.parse(event.content));
return new NDKPrivateKeySigner(content.key as string); return new NDKPrivateKeySigner(content.key as string);
}; };
@ -99,18 +100,18 @@ function generateContent(
return JSON.stringify(content); return JSON.stringify(content);
} }
async function generateTags(mainSigner: NDKSigner, opts: ISaveOpts = {}) { async function generateTags(mainSigner: NDKSigner, opts: ISaveOpts = {}) {
log("func", "generateTags", opts.toString());
const mainUser = await mainSigner.user(); const mainUser = await mainSigner.user();
const tags = [ const tags = [
["p", mainUser.pubkey], ["p", mainUser.pubkey],
["client", "flockstr"], ["client", "flockstr"],
]; ];
if (opts.associatedEvent) { if (opts.associatedEvent) {
const encodedEvent = opts.associatedEvent.encode(); const encodedEvent = opts.associatedEvent.encode();
console.log("encodedEvent", encodedEvent); log("info", "encodedEvent", encodedEvent.toString());
// TODO: This is trivially reversable; better to encrypt it or hash it with the pubkey // TODO: This is trivially reversable; better to encrypt it or hash it with the pubkey
const hashedEventReference = await getHashedKeyName(encodedEvent); const hashedEventReference = await getHashedKeyName(encodedEvent);
console.log("hashedEventReference", hashedEventReference); log("info", "hashedEventReference", hashedEventReference.toString());
tags.push(["e", hashedEventReference]); tags.push(["e", hashedEventReference]);
} }
@ -127,6 +128,7 @@ export async function saveEphemeralSigner(
targetSigner: NDKPrivateKeySigner, targetSigner: NDKPrivateKeySigner,
opts: ISaveOpts = {}, opts: ISaveOpts = {},
) { ) {
log("func", "saveEphemeralSigner");
// Determine current user signer // Determine current user signer
const mainSigner = opts.mainSigner || ndk.signer; const mainSigner = opts.mainSigner || ndk.signer;
@ -145,7 +147,7 @@ export async function saveEphemeralSigner(
await event.publish(); await event.publish();
// Update Ephemeral signers metadata // Update Ephemeral signers metadata
console.log("Checking keyProfile", opts.keyProfile); log("info", "Checking keyProfile", opts.keyProfile?.toString());
const user = await targetSigner.user(); const user = await targetSigner.user();
if (opts.keyProfile) { if (opts.keyProfile) {
const event = new NDKEvent(ndk, { const event = new NDKEvent(ndk, {

View File

@ -13,6 +13,8 @@ import { getTagValues, getTagsAllValues } from "../nostr/utils";
import { unixTimeNowInSeconds } from "../nostr/dates"; import { unixTimeNowInSeconds } from "../nostr/dates";
import { createEvent } from "./create"; import { createEvent } from "./create";
import { findEphemeralSigner } from "@/lib/actions/ephemeral"; import { findEphemeralSigner } from "@/lib/actions/ephemeral";
import { log } from "@/lib/utils";
const fetchWithZod = createZodFetcher(); const fetchWithZod = createZodFetcher();
const ZapEndpointResponseSchema = z.object({ const ZapEndpointResponseSchema = z.object({
nostrPubkey: z.string(), nostrPubkey: z.string(),
@ -24,15 +26,14 @@ export async function sendZap(
_event: NostrEvent, _event: NostrEvent,
comment?: string, comment?: string,
) { ) {
console.log("sendzap called", amount); log("func", "sendZap");
const event = await new NDKEvent(ndk, _event); const event = await new NDKEvent(ndk, _event);
console.log("Event", event); log("info", event.toString());
const pr = await event.zap(amount * 1000, comment); const pr = await event.zap(amount * 1000, comment);
if (!pr) { if (!pr) {
console.log("No PR"); log("info", "No PR");
return; return;
} }
console.log("PR", pr);
const webln = await requestProvider(); const webln = await requestProvider();
return await webln.sendPayment(pr); return await webln.sendPayment(pr);
} }
@ -105,6 +106,7 @@ export async function updateListUsersFromZaps(
tagId: string, tagId: string,
event: NostrEvent, event: NostrEvent,
) { ) {
log("func", "updateListUsersFromZaps");
const SECONDS_IN_MONTH = 2_628_000; const SECONDS_IN_MONTH = 2_628_000;
const SECONDS_IN_YEAR = SECONDS_IN_MONTH * 365; const SECONDS_IN_YEAR = SECONDS_IN_MONTH * 365;
const paymentEvents = await ndk.fetchEvents({ const paymentEvents = await ndk.fetchEvents({
@ -136,7 +138,6 @@ export async function updateListUsersFromZaps(
paymentInvoice.zappee, paymentInvoice.zappee,
event, event,
); );
console.log("Is valid?", isValid);
if (isValid) { if (isValid) {
validUsers.push([ validUsers.push([
paymentInvoice.zappee, paymentInvoice.zappee,
@ -148,15 +149,15 @@ export async function updateListUsersFromZaps(
// Send old codes to user // Send old codes to user
} }
} }
log("info", "New users", newUsers.toString());
await sendCodesToNewUsers(ndk, newUsers, tagId, event); await sendCodesToNewUsers(ndk, newUsers, tagId, event);
// Add self // Add self;
console.log("Adding self");
const selfIndex = validUsers.findIndex(([vu]) => vu === event.pubkey); const selfIndex = validUsers.findIndex(([vu]) => vu === event.pubkey);
if (selfIndex === -1) { if (selfIndex === -1) {
validUsers.push([event.pubkey, "", "self", "4000000000"]); validUsers.push([event.pubkey, "", "self", "4000000000"]);
} }
console.log("Valid users", validUsers);
return createEvent(ndk, { return createEvent(ndk, {
...event, ...event,
kind: event.kind as number, kind: event.kind as number,
@ -176,7 +177,9 @@ async function sendCodesToNewUsers(
const signer = await findEphemeralSigner(ndk, ndk.signer!, { const signer = await findEphemeralSigner(ndk, ndk.signer!, {
associatedEventNip19: new NDKEvent(ndk, event).encode(), associatedEventNip19: new NDKEvent(ndk, event).encode(),
}); });
console.log("Signer", signer); log("func", "sendCodesToNewUsers");
log("info", "Signer", signer?.toString());
if (!signer) return; if (!signer) return;
const delegate = await signer.user(); const delegate = await signer.user();
const messages = await ndk.fetchEvents({ const messages = await ndk.fetchEvents({
@ -189,7 +192,7 @@ async function sendCodesToNewUsers(
await message.decrypt(); await message.decrypt();
codes.push([getTagValues("e", message.tags) ?? "", message.content]); codes.push([getTagValues("e", message.tags) ?? "", message.content]);
} }
console.log("codes", codes); log("info", "codes", codes.toString());
for (const user of users) { for (const user of users) {
for (const [event, code] of codes) { for (const [event, code] of codes) {
@ -203,7 +206,7 @@ async function sendCodesToNewUsers(
], ],
pubkey: delegate.pubkey, pubkey: delegate.pubkey,
} as NostrEvent); } as NostrEvent);
console.log("Sending message"); log("info", "sending message");
await messageEvent.encrypt(new NDKUser({ hexpubkey: user }), signer); await messageEvent.encrypt(new NDKUser({ hexpubkey: user }), signer);
await messageEvent.sign(signer); await messageEvent.sign(signer);
await messageEvent.publish(); await messageEvent.publish();

View File

@ -69,7 +69,7 @@ export default function useEvents({
} }
}); });
} catch (err) { } catch (err) {
log(debug, "error", `❌ nostr (${err})`); log("error", `❌ nostr (${err})`);
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }

View File

@ -85,12 +85,23 @@ export function formatNumber(number: number) {
} else return "not a number"; } else return "not a number";
} }
export function log( export function log(
isOn: boolean | undefined, type: "info" | "error" | "warn" | "func",
type: "info" | "error" | "warn",
...args: unknown[] ...args: unknown[]
) { ) {
const isOn = true;
if (!isOn) return; if (!isOn) return;
console[type](...args); const consoleType = type === "func" ? "info" : type;
const items = [...args].map((a) => `%c${a}`);
console[consoleType](
...items,
type === "info"
? "color: aqua;"
: type === "warn"
? "color: yellow;"
: type === "func"
? "color: green;"
: "color: red;",
);
} }
export function validateUrl(value: string) { export function validateUrl(value: string) {