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

Outbox #71

Merged
merged 15 commits into from
Jun 27, 2024
60 changes: 50 additions & 10 deletions components/sign-in/SignInModal.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useState, useContext } from "react";
import {
Modal,
ModalContent,
Expand All @@ -13,6 +13,7 @@ import {
setLocalStorageDataOnSignIn,
validateNSecKey,
} from "@/components/utility/nostr-helper-functions";
import { RelaysContext } from "../../utils/context/context";
import { getPublicKey, nip19 } from "nostr-tools";
import CryptoJS from "crypto-js";
import { useRouter } from "next/router";
Expand All @@ -31,16 +32,36 @@ export default function SignInModal({

const [showNsecSignIn, setShowNsecSignIn] = useState(false);

const relaysContext = useContext(RelaysContext);

const router = useRouter();

const startExtensionLogin = async () => {
try {
// @ts-ignore
var pk = await window.nostr.getPublicKey();
setLocalStorageDataOnSignIn({
signInMethod: "extension",
pubkey: pk,
});
if (
!relaysContext.isLoading &&
relaysContext.relayList.length >= 0 &&
relaysContext.readRelayList &&
relaysContext.writeRelayList
) {
const allRelays = [
...relaysContext.relayList,
...relaysContext.readRelayList,
...relaysContext.writeRelayList,
];
setLocalStorageDataOnSignIn({
signInMethod: "extension",
pubkey: pk,
relays: allRelays,
});
} else {
setLocalStorageDataOnSignIn({
signInMethod: "extension",
pubkey: pk,
});
}
onClose();
} catch (error) {
alert("Extension sign in failed!");
Expand All @@ -67,11 +88,30 @@ export default function SignInModal({
onClose(); // avoids tree walker issue by closing modal
}, 500);

setLocalStorageDataOnSignIn({
signInMethod: "nsec",
pubkey: pk,
encryptedPrivateKey: encryptedPrivateKey,
});
if (
!relaysContext.isLoading &&
relaysContext.relayList.length >= 0 &&
relaysContext.readRelayList &&
relaysContext.writeRelayList
) {
const allRelays = [
...relaysContext.relayList,
...relaysContext.readRelayList,
...relaysContext.writeRelayList,
];
setLocalStorageDataOnSignIn({
signInMethod: "nsec",
pubkey: pk,
encryptedPrivateKey: encryptedPrivateKey,
relays: allRelays,
});
} else {
setLocalStorageDataOnSignIn({
signInMethod: "nsec",
pubkey: pk,
encryptedPrivateKey: encryptedPrivateKey,
});
}
}
} else {
alert(
Expand Down
107 changes: 85 additions & 22 deletions components/utility/nostr-helper-functions.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import * as CryptoJS from "crypto-js";
import {
finalizeEvent,
getPublicKey,
nip04,
nip19,
nip98,
SimplePool,
} from "nostr-tools";
import { finalizeEvent, nip04, nip19, nip98, SimplePool } from "nostr-tools";
import axios from "axios";
import { NostrEvent } from "@/utils/types/types";
import { ProductFormValues } from "@/pages/api/nostr/post-event";

function containsRelay(relays: string[], relay: string): boolean {
return relays.some((r) => r.includes(relay));
}

export async function PostListing(
values: ProductFormValues,
passphrase: string,
) {
const { signInMethod, userPubkey, relays } = getLocalStorageData();
const { signInMethod, userPubkey, relays, writeRelays } =
getLocalStorageData();
const summary = values.find(([key]) => key === "summary")?.[1] || "";

const dValue = values.find(([key]) => key === "d")?.[1] || undefined;
Expand Down Expand Up @@ -65,11 +63,22 @@ export async function PostListing(

const pool = new SimplePool();

await Promise.any(pool.publish(relays, signedEvent));
await Promise.any(pool.publish(relays, signedRecEvent));
await Promise.any(pool.publish(relays, signedHandlerEvent));
const allWriteRelays = [...writeRelays, ...relays];
const blastrRelay = "wss://nostr.mutinywallet.com";
if (!containsRelay(allWriteRelays, blastrRelay)) {
allWriteRelays.push(blastrRelay);
}

await Promise.any(pool.publish(allWriteRelays, signedEvent));
await Promise.any(pool.publish(allWriteRelays, signedRecEvent));
await Promise.any(pool.publish(allWriteRelays, signedHandlerEvent));
return signedEvent;
} else {
const allWriteRelays = [...writeRelays, ...relays];
const blastrRelay = "wss://nostr.mutinywallet.com";
if (!containsRelay(allWriteRelays, blastrRelay)) {
allWriteRelays.push(blastrRelay);
}
const res = await axios({
method: "POST",
url: "/api/nostr/post-event",
Expand All @@ -84,7 +93,7 @@ export async function PostListing(
// kind: 30018,
tags: updatedValues,
content: summary,
relays: relays,
relays: allWriteRelays,
},
});
return {
Expand Down Expand Up @@ -144,7 +153,7 @@ export async function sendEncryptedMessage(
encryptedMessageEvent: EncryptedMessageEvent,
passphrase?: string,
) {
const { signInMethod, relays } = getLocalStorageData();
const { signInMethod, relays, writeRelays } = getLocalStorageData();
let signedEvent;
if (signInMethod === "extension") {
signedEvent = await window.nostr.signEvent(encryptedMessageEvent);
Expand All @@ -154,15 +163,20 @@ export async function sendEncryptedMessage(
signedEvent = finalizeEvent(encryptedMessageEvent, senderPrivkey);
}
const pool = new SimplePool();
await Promise.any(pool.publish(relays, signedEvent));
const allWriteRelays = [...writeRelays, ...relays];
const blastrRelay = "wss://nostr.mutinywallet.com";
if (!containsRelay(allWriteRelays, blastrRelay)) {
allWriteRelays.push(blastrRelay);
}
await Promise.any(pool.publish(allWriteRelays, signedEvent));
}

export async function finalizeAndSendNostrEvent(
nostrEvent: NostrEvent,
passphrase?: string,
) {
try {
const { signInMethod, relays } = getLocalStorageData();
const { signInMethod, relays, writeRelays } = getLocalStorageData();
let signedEvent;
if (signInMethod === "extension") {
signedEvent = await window.nostr.signEvent(nostrEvent);
Expand All @@ -172,7 +186,12 @@ export async function finalizeAndSendNostrEvent(
signedEvent = finalizeEvent(nostrEvent, senderPrivkey);
}
const pool = new SimplePool();
await Promise.any(pool.publish(relays, signedEvent));
const allWriteRelays = [...writeRelays, ...relays];
const blastrRelay = "wss://nostr.mutinywallet.com";
if (!containsRelay(allWriteRelays, blastrRelay)) {
allWriteRelays.push(blastrRelay);
}
await Promise.any(pool.publish(allWriteRelays, signedEvent));
} catch (e: any) {
console.log("Error: ", e);
alert("Failed to send event: " + e.message);
Expand Down Expand Up @@ -296,6 +315,8 @@ const LOCALSTORAGECONSTANTS = {
userPubkey: "userPubkey",
encryptedPrivateKey: "encryptedPrivateKey",
relays: "relays",
readRelays: "readRelays",
writeRelays: "writeRelays",
mints: "mints",
tokens: "tokens",
history: "history",
Expand All @@ -307,13 +328,17 @@ export const setLocalStorageDataOnSignIn = ({
pubkey,
encryptedPrivateKey,
relays,
readRelays,
writeRelays,
mints,
wot,
}: {
signInMethod: string;
pubkey: string;
encryptedPrivateKey?: string;
relays?: string[];
readRelays?: string[];
writeRelays?: string[];
mints?: string[];
wot?: number;
}) => {
Expand All @@ -333,16 +358,27 @@ export const setLocalStorageDataOnSignIn = ({
localStorage.setItem(
LOCALSTORAGECONSTANTS.relays,
JSON.stringify(
relays
relays && relays.length != 0
? relays
: [
"wss://relay.damus.io",
"wss://nos.lol",
"wss://nostr.mutinywallet.com",
"wss://purplepag.es",
],
),
);

localStorage.setItem(
LOCALSTORAGECONSTANTS.readRelays,
JSON.stringify(readRelays && readRelays.length != 0 ? readRelays : []),
);

localStorage.setItem(
LOCALSTORAGECONSTANTS.writeRelays,
JSON.stringify(writeRelays && writeRelays.length != 0 ? writeRelays : []),
);

localStorage.setItem(
LOCALSTORAGECONSTANTS.mints,
JSON.stringify(mints ? mints : ["https://mint.minibits.cash/Bitcoin"]),
Expand All @@ -364,6 +400,8 @@ export interface LocalStorageInterface {
userNPub: string;
userPubkey: string;
relays: string[];
readRelays: string[];
writeRelays: string[];
mints: string[];
tokens: [];
history: [];
Expand All @@ -377,6 +415,8 @@ export const getLocalStorageData = (): LocalStorageInterface => {
let userNPub;
let userPubkey;
let relays;
let readRelays;
let writeRelays;
let mints;
let tokens;
let history;
Expand All @@ -403,24 +443,45 @@ export const getLocalStorageData = (): LocalStorageInterface => {
localStorage.removeItem("chats");
}

relays = localStorage.getItem(LOCALSTORAGECONSTANTS.relays);
const relaysString = localStorage.getItem(LOCALSTORAGECONSTANTS.relays);
relays = relaysString ? (JSON.parse(relaysString) as string[]) : [];

const defaultRelays = [
"wss://relay.damus.io",
"wss://nos.lol",
"wss://nostr.mutinywallet.com",
"wss://purplepag.es",
];

if (!relays) {
if (relays && relays.length === 0) {
relays = defaultRelays;
localStorage.setItem("relays", JSON.stringify(relays));
} else {
try {
relays = (JSON.parse(relays) as string[]).filter((r) => r);
if (relays) {
relays = relays.filter((r) => r);
}
} catch {
relays = defaultRelays;
localStorage.setItem("relays", JSON.stringify(relays));
}
}
localStorage.setItem("relays", JSON.stringify(relays));

readRelays = localStorage.getItem(LOCALSTORAGECONSTANTS.readRelays)
? (
JSON.parse(
localStorage.getItem(LOCALSTORAGECONSTANTS.readRelays) as string,
) as string[]
).filter((r) => r)
: [];

writeRelays = localStorage.getItem(LOCALSTORAGECONSTANTS.writeRelays)
? (
JSON.parse(
localStorage.getItem(LOCALSTORAGECONSTANTS.writeRelays) as string,
) as string[]
).filter((r) => r)
: [];

mints = localStorage.getItem(LOCALSTORAGECONSTANTS.mints)
? JSON.parse(localStorage.getItem("mints") as string)
Expand Down Expand Up @@ -455,6 +516,8 @@ export const getLocalStorageData = (): LocalStorageInterface => {
userNPub: userNPub as string,
userPubkey: userPubkey as string,
relays: relays || [],
readRelays: readRelays || [],
writeRelays: writeRelays || [],
mints,
tokens: tokens || [],
history: history || [],
Expand Down
14 changes: 7 additions & 7 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"next-pwa": "^5.6.0",
"next-themes": "^0.2.1",
"node-geocoder": "^4.2.0",
"nostr-tools": "^2.3.1",
"nostr-tools": "^2.7.0",
"pg": "^8.11.3",
"postcss": "8.4.31",
"qrcode": "^1.5.3",
Expand Down
Loading
Loading