Skip to content
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
26 changes: 9 additions & 17 deletions components/ZapsnagButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,19 @@ import {
SignerContext,
} from "@/components/utility-components/nostr-context-provider";
import {
getLocalStorageData,
constructGiftWrappedEvent,
constructMessageSeal,
constructMessageGiftWrap,
getStoredRelays,
sendGiftWrappedMessageEvent,
} from "@/utils/nostr/nostr-helper-functions";
import { generateSecretKey, getPublicKey } from "nostr-tools";
import { SHOPSTRBUTTONCLASSNAMES } from "@/utils/STATIC-VARIABLES";
import { ProductData } from "@/utils/parsers/product-parser-functions";
import { validateZapReceipt } from "@/utils/nostr/zap-validator";

import { storage, STORAGE_KEYS } from "@/utils/storage";

export default function ZapsnagButton({ product }: { product: ProductData }) {
const { isOpen, onOpen, onClose } = useDisclosure();
const [loading, setLoading] = useState(false);
Expand All @@ -48,16 +50,9 @@ export default function ZapsnagButton({ product }: { product: ProductData }) {
const { signer, isLoggedIn, pubkey: userPubkey } = useContext(SignerContext);

useEffect(() => {
if (typeof window !== "undefined") {
const savedInfo = localStorage.getItem("shopstr_shipping_info");
if (savedInfo) {
try {
const parsed = JSON.parse(savedInfo);
setShippingInfo((prev) => ({ ...prev, ...parsed }));
} catch (e) {
console.error("Failed to load saved shipping info", e);
}
}
const savedInfo = storage.getJson(STORAGE_KEYS.SHIPPING_INFO, null);
if (savedInfo) {
setShippingInfo((prev) => ({ ...prev, ...savedInfo }));
}
}, []);

Expand Down Expand Up @@ -121,7 +116,7 @@ export default function ZapsnagButton({ product }: { product: ProductData }) {
}

originalWebLN = (window as any).webln;
const { nwcString } = getLocalStorageData();
const nwcString = storage.getItem(STORAGE_KEYS.NWC_STRING);
if (nwcString) {
const nwcProvider = new NostrWebLNProvider({
nostrWalletConnectUrl: nwcString,
Expand Down Expand Up @@ -179,7 +174,7 @@ export default function ZapsnagButton({ product }: { product: ProductData }) {
const ln = new LightningAddress(lud16);
await ln.fetch();

const { relays: userRelays } = getLocalStorageData();
const userRelays = getStoredRelays();
const targetRelays =
userRelays.length > 0
? userRelays
Expand All @@ -196,10 +191,7 @@ export default function ZapsnagButton({ product }: { product: ProductData }) {
const response = await ln.zap(zapArgs);

if (response.preimage) {
localStorage.setItem(
"shopstr_shipping_info",
JSON.stringify(shippingInfo)
);
storage.setJson(STORAGE_KEYS.SHIPPING_INFO, shippingInfo);

setStatus("Verifying receipt...");
const receiptFound = await validateZapReceipt(
Expand Down
68 changes: 32 additions & 36 deletions components/cart-invoice-card.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,10 @@ import {
constructMessageGiftWrap,
sendGiftWrappedMessageEvent,
generateKeys,
getLocalStorageData,
getStoredMints,
publishProofEvent,
} from "@/utils/nostr/nostr-helper-functions";
import { storage, STORAGE_KEYS } from "@/utils/storage";
import { LightningAddress } from "@getalby/lightning-tools";
import QRCode from "qrcode";
import { v4 as uuidv4 } from "uuid";
Expand Down Expand Up @@ -114,7 +115,8 @@ export default function CartInvoiceCard({
setCashuPaymentSent?: (cashuPaymentSent: boolean) => void;
setCashuPaymentFailed?: (cashuPaymentFailed: boolean) => void;
}) {
const { mints, tokens, history } = getLocalStorageData();
const mints = getStoredMints();
const tokens = storage.getJson<any[]>(STORAGE_KEYS.TOKENS, []);
const {
isLoggedIn,
pubkey: userPubkey,
Expand Down Expand Up @@ -220,26 +222,23 @@ export default function CartInvoiceCard({
}
});
}
sessionStorage.setItem(
"orderSummary",
JSON.stringify({
productTitle: pendingOrderRef.current.productTitle,
productImage: products[0]?.images?.[0] || "",
amount: String(totalCost),
subtotal: String(subtotalCost),
currency: pendingOrderRef.current.currency,
paymentMethod: pendingOrderRef.current.paymentMethod,
orderId: pendingOrderRef.current.orderId,
shippingAddress: pendingOrderRef.current.shippingAddress,
sellerPubkey: pendingOrderRef.current.sellerPubkey,
isCart: true,
cartItems,
freeShippingApplied: anyFreeShipping,
originalShippingCost: anyFreeShipping
? String(originalShipping)
: undefined,
})
);
storage.setSessionJson(STORAGE_KEYS.ORDER_SUMMARY, {
productTitle: pendingOrderRef.current.productTitle,
productImage: products[0]?.images?.[0] || "",
amount: String(totalCost),
subtotal: String(subtotalCost),
currency: pendingOrderRef.current.currency,
paymentMethod: pendingOrderRef.current.paymentMethod,
orderId: pendingOrderRef.current.orderId,
shippingAddress: pendingOrderRef.current.shippingAddress,
sellerPubkey: pendingOrderRef.current.sellerPubkey,
isCart: true,
cartItems,
freeShippingApplied: anyFreeShipping,
originalShippingCost: anyFreeShipping
? String(originalShipping)
: undefined,
});
} catch {}

pendingOrderRef.current = null;
Expand Down Expand Up @@ -482,7 +481,7 @@ export default function CartInvoiceCard({
// Load NWC info and check cart for NWC compatibility
useEffect(() => {
const loadNwcInfo = () => {
const { nwcInfo: infoString } = getLocalStorageData();
const infoString = storage.getItem(STORAGE_KEYS.NWC_INFO);
if (infoString) {
try {
const info = JSON.parse(infoString);
Expand Down Expand Up @@ -1061,7 +1060,7 @@ export default function CartInvoiceCard({
});
invoicePollRef.current = { cancelled: false, activeQuoteId: hash };

const { nwcString } = getLocalStorageData();
const nwcString = storage.getItem(STORAGE_KEYS.NWC_STRING);
if (!nwcString) throw new Error("NWC connection not found.");

nwc = new NostrWebLNProvider({ nostrWalletConnectUrl: nwcString });
Expand Down Expand Up @@ -1239,7 +1238,7 @@ export default function CartInvoiceCard({
"seller payment hand-off"
);
markMintQuoteClaimed(hash);
localStorage.setItem("cart", JSON.stringify([]));
storage.setJson(STORAGE_KEYS.CART, []);
setPaymentConfirmed(true);
if (setInvoiceIsPaid) {
setInvoiceIsPaid(true);
Expand Down Expand Up @@ -1285,7 +1284,7 @@ export default function CartInvoiceCard({
lastErrorMessage:
"Mint reports quote ISSUED before local claim recorded proofs",
});
localStorage.setItem("cart", JSON.stringify([]));
storage.setJson(STORAGE_KEYS.CART, []);
setPaymentConfirmed(true);
setQrCodeUrl(null);
setFailureText(
Expand All @@ -1308,7 +1307,7 @@ export default function CartInvoiceCard({
status: "failed_terminal",
lastErrorMessage: "Quote ISSUED before local claim recorded proofs",
});
localStorage.setItem("cart", JSON.stringify([]));
storage.setJson(STORAGE_KEYS.CART, []);
setPaymentConfirmed(true);
setQrCodeUrl(null);
setFailureText(
Expand Down Expand Up @@ -2410,14 +2409,11 @@ export default function CartInvoiceCard({
} else {
proofArray = [...remainingProofs];
}
localStorage.setItem("tokens", JSON.stringify(proofArray));
localStorage.setItem(
"history",
JSON.stringify([
{ type: 5, amount: price, date: Math.floor(Date.now() / 1000) },
...history,
])
);
storage.setJson(STORAGE_KEYS.TOKENS, proofArray);
storage.setJson(STORAGE_KEYS.HISTORY, [
{ type: 5, amount: price, date: Math.floor(Date.now() / 1000) },
...history,
]);
await publishProofEvent(
nostr!,
signer!,
Expand All @@ -2427,7 +2423,7 @@ export default function CartInvoiceCard({
price.toString(),
deletedEventIds
);
localStorage.setItem("cart", JSON.stringify([]));
storage.setJson(STORAGE_KEYS.CART, []);
setOrderConfirmed(true);
setPaymentConfirmed(true);
if (setCashuPaymentSent) {
Expand Down
12 changes: 6 additions & 6 deletions components/display-products.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ import {
NostrContext,
SignerContext,
} from "@/components/utility-components/nostr-context-provider";
import { getListingSlug } from "@/utils/url-slugs";
import { productSatisfiesAllFilters } from "@/utils/parsers/product-filter-helpers";
import { storage } from "@/utils/storage";

const DisplayProducts = ({
focusedPubkey,
Expand Down Expand Up @@ -64,7 +64,7 @@ const DisplayProducts = ({
const storageKey = focusedPubkey
? `marketplace-page-${focusedPubkey}`
: "marketplace-page-general";
const savedPage = sessionStorage.getItem(storageKey);
const savedPage = storage.getSessionItem(storageKey);
if (savedPage) {
const pageNum = parseInt(savedPage, 10);
if (!isNaN(pageNum) && pageNum > 0) {
Expand Down Expand Up @@ -174,7 +174,7 @@ const DisplayProducts = ({
const prevFiltersRef = `${selectedSearch}-${selectedLocation}-${Array.from(
selectedCategories
).join(",")}`;
const currentFiltersRef = sessionStorage.getItem("last-filters-ref");
const currentFiltersRef = storage.getSessionItem("last-filters-ref");

if (currentFiltersRef && currentFiltersRef !== prevFiltersRef) {
// Filters changed, reset to page 1
Expand All @@ -183,14 +183,14 @@ const DisplayProducts = ({
const storageKey = focusedPubkey
? `marketplace-page-${focusedPubkey}`
: "marketplace-page-general";
sessionStorage.setItem(storageKey, "1");
storage.setSessionItem(storageKey, "1");
}
} else if (currentPage > newTotalPages) {
// Current page exceeds total pages, go to last page
setCurrentPage(newTotalPages);
}

sessionStorage.setItem("last-filters-ref", prevFiltersRef);
storage.setSessionItem("last-filters-ref", prevFiltersRef);

onFilteredProductsChange?.(filtered);
}, [
Expand Down Expand Up @@ -287,7 +287,7 @@ const DisplayProducts = ({
const storageKey = focusedPubkey
? `marketplace-page-${focusedPubkey}`
: "marketplace-page-general";
sessionStorage.setItem(storageKey, page.toString());
storage.setSessionItem(storageKey, page.toString());
}
};

Expand Down
7 changes: 2 additions & 5 deletions components/nav-top.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { useRouter } from "next/router";
import SignInModal from "./sign-in/SignInModal";
import { ProfileWithDropdown } from "./utility-components/profile/profile-dropdown";
import { ShopProfile } from "../utils/types/types";
import { getLocalStorageJson } from "@/utils/safe-json";
import { storage, STORAGE_KEYS } from "@/utils/storage";

const TopNav = ({
setFocusedPubkey,
Expand Down Expand Up @@ -45,10 +45,7 @@ const TopNav = ({

useEffect(() => {
const fetchAndUpdateCartQuantity = async () => {
const cartList = getLocalStorageJson<unknown[]>("cart", [], {
removeOnError: true,
validate: Array.isArray,
});
const cartList = storage.getJson<unknown[]>(STORAGE_KEYS.CART, []);
if (cartList.length > 0) {
setCartQuantity(cartList.length);
} else {
Expand Down
4 changes: 2 additions & 2 deletions components/product-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ import {
SHIPPING_OPTIONS,
} from "@/utils/STATIC-VARIABLES";
import {
getStoredRelays,
PostListing,
getLocalStorageData,
finalizeAndSendNostrEvent,
} from "@/utils/nostr/nostr-helper-functions";
import LocationDropdown from "./utility-components/dropdowns/location-dropdown";
Expand Down Expand Up @@ -140,7 +140,7 @@ export default function ProductForm({

useEffect(() => {
if (typeof window !== "undefined") {
const { relays } = getLocalStorageData();
const relays = getStoredRelays();
setPubkey(signerPubKey as string);
setRelayHint(relays[0] as string);
}
Expand Down
Loading