set mint with npubxcash

This commit is contained in:
lemonknowsall committed 2025-10-13 12:33:02 -07:00
1 parent 5dc19e857f
commit 346ba70710
4 files changed
+173 -614

No files matched your search

+27 -2
View File
@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { useCashu, type HistoryEntry } from '@/hooks/useCashu';
import { useCashuMints } from '@/hooks/cashu/useCashuMints';
import { useLightningAddress } from '@/hooks/useLightningAddress';
import { useNpubCash } from '@/hooks/useNpubCash';
import { useToast } from '@/hooks/useToast';
import { useQRCode } from '@/hooks/useQRCode';
import { useCopyToClipboard } from '@/hooks/useCopyToClipboard';
@@ -13,6 +14,7 @@ import { SendCard } from '@/components/wallet/SendCard';
import { TransactionHistory } from '@/components/wallet/TransactionHistory';
import { ProofBreakdownModal } from '@/components/wallet/ProofBreakdownModal';
import { RemoveMintModal } from '@/components/wallet/RemoveMintModal';
import { LoginArea } from '@/components/auth/LoginArea';
export function CashuWallet() {
// ============================================================================
@@ -44,7 +46,7 @@ export function CashuWallet() {
const { getCleanMintLabel } = useCashuMints(null);
const { setMint: setNpubCashMint, isLoggedIn: isNpubCashLoggedIn } = useNpubCash();
const { getInvoice: getLightningInvoice, isLoading: isResolvingAddress } = useLightningAddress();
@@ -146,7 +148,24 @@ export function CashuWallet() {
const handleSetActiveMint = useCallback(async (mintUrl: string | null) => {
// Set the active mint locally
setActiveMintUrl(mintUrl);
}, []);
// If user is logged in to npub.cash and a mint is selected, sync it
if (isNpubCashLoggedIn && mintUrl) {
console.log('🔄 Syncing active mint with npub.cash:', mintUrl);
const success = await setNpubCashMint(mintUrl);
if (success) {
toast({
title: "Mint Synced",
description: "Your preferred mint has been updated on npub.cash",
});
} else {
// Don't show error toast - the hook already logs errors
// Just log that sync failed but local mint is still set
console.warn('⚠️ Failed to sync mint with npub.cash, but local mint is still set');
}
}
}, [isNpubCashLoggedIn, setNpubCashMint, toast]);
// ============================================================================
// HELPER FUNCTIONS - History
@@ -619,6 +638,12 @@ export function CashuWallet() {
<LoadingModal isLoading={isLoading || !isInitialized} />
<div className="max-w-4xl mx-auto py-1 px-3 sm:px-4 relative">
{/* ========================================================================
SECTION: Login Area
======================================================================== */}
<div className="absolute top-1 right-3 sm:right-4 z-10">
<LoginArea />
</div>
{/* ========================================================================
SECTION: Balance Display
+73
View File
@@ -0,0 +1,73 @@
import { useCallback } from 'react';
import { useCurrentUser } from './useCurrentUser';
import type { NostrEvent } from '@nostrify/nostrify';
export interface NIP98Options {
url: string;
method: string;
body?: unknown;
}
/**
* Hook for creating NIP-98 HTTP Authentication headers
* Based on https://github.com/nostr-protocol/nips/blob/master/98.md
*/
export function useNIP98() {
const { user } = useCurrentUser();
/**
* Create a NIP-98 authorization header for HTTP requests
* @param options - The request details (url, method, optional body)
* @returns Promise<string> - The "Nostr base64..." authorization header value
*/
const createAuthHeader = useCallback(async (options: NIP98Options): Promise<string> => {
if (!user) {
throw new Error('User must be logged in to create NIP-98 auth header');
}
const { url, method, body } = options;
// Parse URL to remove query parameters (per NIP-98 spec)
const urlObj = new URL(url);
const urlWithoutQuery = `${urlObj.protocol}//${urlObj.host}${urlObj.pathname}`;
const tags: string[][] = [
['u', urlWithoutQuery],
['method', method.toUpperCase()],
];
// If there's a request body (POST, PUT, PATCH), add payload hash
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
const bodyString = JSON.stringify(body);
const encoder = new TextEncoder();
const data = encoder.encode(bodyString);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const payloadHash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
tags.push(['payload', payloadHash]);
}
// Create and sign the NIP-98 event (kind 27235)
const event = await user.signer.signEvent({
kind: 27235,
content: '',
tags,
created_at: Math.floor(Date.now() / 1000),
}) as NostrEvent;
// Encode the event as base64
const eventJson = JSON.stringify(event);
const base64Event = btoa(eventJson);
return `Nostr ${base64Event}`;
}, [user]);
return {
createAuthHeader,
isLoggedIn: !!user,
pubkey: user?.pubkey,
};
}
+73
View File
@@ -0,0 +1,73 @@
import { useCallback, useState } from 'react';
import { useNIP98 } from './useNIP98';
const NPUBCASH_API_BASE = 'https://npub.cash/api/v2';
export interface NpubCashApiError {
error: true;
message: string;
}
/**
* Hook for interacting with npub.cash API
* Currently supports setting the user's preferred mint
*/
export function useNpubCash() {
const { createAuthHeader, isLoggedIn, pubkey } = useNIP98();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
/**
* Set the user's preferred mint on npub.cash
*/
const setMint = useCallback(async (mintUrl: string): Promise<boolean> => {
if (!isLoggedIn) {
console.error('❌ User must be logged in to set mint');
return false;
}
try {
setIsLoading(true);
setError(null);
const url = `${NPUBCASH_API_BASE}/user/mint`;
const body = { mint_url: mintUrl };
const authHeader = await createAuthHeader({ url, method: 'PATCH', body });
console.log(`🔄 Setting preferred mint on npub.cash to: ${mintUrl}`);
const response = await fetch(url, {
method: 'PATCH',
headers: {
'Authorization': authHeader,
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
if (!response.ok) {
const errorData = await response.json() as NpubCashApiError;
throw new Error(errorData.message || 'Failed to set mint');
}
console.log(`✅ Successfully set preferred mint on npub.cash to: ${mintUrl}`);
return true;
} catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
console.error('❌ Failed to set npub.cash mint:', errorMessage);
setError(errorMessage);
return false;
} finally {
setIsLoading(false);
}
}, [isLoggedIn, createAuthHeader]);
return {
setMint,
isLoading,
error,
isLoggedIn,
pubkey,
};
}