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

+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,
};
}