UNPKG

applesauce-wallet-connect

Version:

NIP-47 Nostr Wallet Connect implementation for both clients and services.

57 lines (56 loc) 2.46 kB
import { isNIP04Encrypted } from "applesauce-core/helpers/encryption"; import { getTagValue, notifyEventUpdate } from "applesauce-core/helpers/event"; import { getHiddenContent, isHiddenContentUnlocked, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers/hidden-content"; export const WALLET_RESPONSE_KIND = 23195; // Set the encryption method to use for response kind setHiddenContentEncryptionMethod(WALLET_RESPONSE_KIND, "nip04"); /** A symbol used to cache the wallet response on the event */ export const WalletResponseSymbol = Symbol("wallet-response"); /** Checks if a kind 23195 event is locked */ export function isWalletResponseUnlocked(response) { // Wrap in try catch to avoid throwing validation errors try { return (WalletResponseSymbol in response || (isHiddenContentUnlocked(response) && getWalletResponse(response) !== undefined)); } catch { } return false; } /** Unlocks a kind 23195 event */ export async function unlockWalletResponse(response, signer, override) { if (WalletResponseSymbol in response) return response[WalletResponseSymbol]; // Unlock the hidden content const encryption = override ?? (!isNIP04Encrypted(response.content) ? "nip44" : "nip04"); await unlockHiddenContent(response, signer, encryption); // Get the wallet response const parsed = getWalletResponse(response); if (!parsed) throw new Error("Failed to unlock wallet response"); return parsed; } /** Gets the wallet response from a kind 23195 event */ export function getWalletResponse(response) { if (WalletResponseSymbol in response) return response[WalletResponseSymbol]; const content = getHiddenContent(response); if (!content) return undefined; const parsed = JSON.parse(content); // Save the parsed content Reflect.set(response, WalletResponseSymbol, parsed); notifyEventUpdate(response); return parsed; } export function getWalletResponseClientPubkey(response) { return getTagValue(response, "p"); } export function getWalletResponseRequestId(response) { return getTagValue(response, "e"); } /** Checks if event is a valid wallet response event */ export function isValidWalletResponse(response) { return (response.kind === WALLET_RESPONSE_KIND && getWalletResponseRequestId(response) !== undefined && getWalletResponseClientPubkey(response) !== undefined); }