applesauce-wallet-connect 6.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import { EventFactory, blankEventTemplate } from "applesauce-core/factories";
2
+ import { eventPipe } from "applesauce-core/helpers/pipeline";
2
3
  import { includeSingletonTag } from "applesauce-core/operations/tags";
3
4
  import { setEncryptedContent } from "applesauce-core/operations/encrypted-content";
4
5
  import { WALLET_REQUEST_KIND } from "../helpers/request.js";
@@ -13,10 +14,11 @@ export class WalletRequestFactory extends EventFactory {
13
14
  }
14
15
  request(request, encryption = "nip44_v2") {
15
16
  let result;
16
- result = this.chain(async (draft) => {
17
- const encrypted = await setEncryptedContent(draft.tags.find((t) => t[0] === "p")?.[1] || "", JSON.stringify(request), result.signer, encryption === "nip44_v2" ? "nip44" : "nip04")(draft);
18
- return includeSingletonTag(["encryption", encryption])(encrypted);
19
- });
17
+ // Compose via eventPipe so the "encryption" tag's `{ ...draft }` spread cannot silently drop
18
+ // the non-enumerable EncryptedContentSymbol that setEncryptedContent writes — the pipe's
19
+ // same-kind carry-forward restores it. Sequencing these two operations by hand (encrypt then
20
+ // spread) dropped the plaintext cache once the write became non-enumerable.
21
+ result = this.chain((draft) => eventPipe(setEncryptedContent(draft.tags.find((t) => t[0] === "p")?.[1] || "", JSON.stringify(request), result.signer, encryption === "nip44_v2" ? "nip44" : "nip04"), includeSingletonTag(["encryption", encryption]))(draft));
20
22
  return result;
21
23
  }
22
24
  }
@@ -1,4 +1,4 @@
1
- import { getHiddenContent, isHiddenContentUnlocked, notifyEventUpdate, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers";
1
+ import { getHiddenContent, isHiddenContentUnlocked, notifyEventUpdate, safeParse, setCachedValue, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers";
2
2
  export const WALLET_NOTIFICATION_KIND = 23197;
3
3
  export const WALLET_LEGACY_NOTIFICATION_KIND = 23196;
4
4
  /** A symbol used to cache the wallet notification on the event */
@@ -8,7 +8,9 @@ setHiddenContentEncryptionMethod(WALLET_NOTIFICATION_KIND, "nip44");
8
8
  setHiddenContentEncryptionMethod(WALLET_LEGACY_NOTIFICATION_KIND, "nip04");
9
9
  /** Checks if a kind 23196 or 23197 event is locked */
10
10
  export function isWalletNotificationUnlocked(notification) {
11
- // Wrap in try catch to avoid throwing validation errors
11
+ // The catch guards the `any` parameter only: `X in notification` throws a TypeError when
12
+ // handed a primitive. It is no longer masking a parse failure — getWalletNotification returns
13
+ // undefined for malformed content rather than throwing.
12
14
  try {
13
15
  return (WalletNotificationSymbol in notification ||
14
16
  (isHiddenContentUnlocked(notification) && getWalletNotification(notification) !== undefined));
@@ -34,10 +36,16 @@ export function getWalletNotification(notification) {
34
36
  const content = getHiddenContent(notification);
35
37
  if (!content)
36
38
  return undefined;
37
- // Parse the content as a wallet notification
38
- const parsed = JSON.parse(content);
39
- // Save the parsed content
40
- Reflect.set(notification, WalletNotificationSymbol, parsed);
39
+ // Parse the content as a wallet notification. safeParse (not JSON.parse) because this content
40
+ // arrives from the remote wallet service — malformed JSON is a routine network condition, not
41
+ // a programmer error, and this getter's return type already carries undefined for it.
42
+ const parsed = safeParse(content);
43
+ // Not cached on failure: the rejection describes the content available right now, and caching
44
+ // it would leave the notification permanently unreadable.
45
+ if (!parsed)
46
+ return undefined;
47
+ // Save the parsed content (identity memo, non-enumerable so a spread drops it)
48
+ setCachedValue(notification, WalletNotificationSymbol, parsed);
41
49
  notifyEventUpdate(notification);
42
50
  return parsed;
43
51
  }
@@ -1,6 +1,7 @@
1
1
  import { isNIP04Encrypted } from "applesauce-core/helpers/encryption";
2
2
  import { getTagValue, notifyEventUpdate } from "applesauce-core/helpers/event";
3
3
  import { getHiddenContent, isHiddenContentUnlocked, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers/hidden-content";
4
+ import { setCachedValue } from "applesauce-core/helpers/cache";
4
5
  import { unixNow } from "applesauce-core/helpers/time";
5
6
  import { nip47EncryptionMethodToNip07EncryptionMethod } from "./encryption.js";
6
7
  export const WALLET_REQUEST_KIND = 23194;
@@ -37,8 +38,8 @@ export function getWalletRequest(request) {
37
38
  if (!content)
38
39
  return undefined;
39
40
  const parsed = JSON.parse(content);
40
- // Save the parsed content
41
- Reflect.set(request, WalletRequestSymbol, parsed);
41
+ // Save the parsed content (identity memo, non-enumerable so a spread drops it)
42
+ setCachedValue(request, WalletRequestSymbol, parsed);
42
43
  notifyEventUpdate(request);
43
44
  return parsed;
44
45
  }
@@ -1,6 +1,7 @@
1
1
  import { isNIP04Encrypted } from "applesauce-core/helpers/encryption";
2
2
  import { getTagValue, notifyEventUpdate } from "applesauce-core/helpers/event";
3
3
  import { getHiddenContent, isHiddenContentUnlocked, setHiddenContentEncryptionMethod, unlockHiddenContent, } from "applesauce-core/helpers/hidden-content";
4
+ import { setCachedValue } from "applesauce-core/helpers/cache";
4
5
  export const WALLET_RESPONSE_KIND = 23195;
5
6
  // Set the encryption method to use for response kind
6
7
  setHiddenContentEncryptionMethod(WALLET_RESPONSE_KIND, "nip04");
@@ -37,8 +38,8 @@ export function getWalletResponse(response) {
37
38
  if (!content)
38
39
  return undefined;
39
40
  const parsed = JSON.parse(content);
40
- // Save the parsed content
41
- Reflect.set(response, WalletResponseSymbol, parsed);
41
+ // Save the parsed content (identity memo, non-enumerable so a spread drops it)
42
+ setCachedValue(response, WalletResponseSymbol, parsed);
42
43
  notifyEventUpdate(response);
43
44
  return parsed;
44
45
  }
@@ -3,7 +3,7 @@ import { EventSigner } from "applesauce-core";
3
3
  import { NostrEvent } from "applesauce-core/helpers";
4
4
  import { BehaviorSubject, Observable, Subscription } from "rxjs";
5
5
  import { NotificationType, WalletAuthURI, WalletConnectEncryptionMethod, WalletConnectURI, WalletNotification, WalletNotificationEvent, WalletResponseEvent, WalletSupport } from "./helpers/index.js";
6
- import { CommonWalletMethods, GetBalanceMethod, GetInfoMethod, ListTransactionsMethod, LookupInvoiceMethod, MakeInvoiceMethod, MultiPayInvoiceMethod, MultiPayKeysendMethod, PayInvoiceMethod, PayKeysendMethod, TWalletMethod } from "./helpers/methods.js";
6
+ import { CommonWalletMethods, GetBalanceMethod, GetInfoMethod, ListTransactionsMethod, LookupInvoiceMethod, MakeInvoiceMethod, MultiPayInvoiceMethod, MultiPayKeysendMethod, PayInvoiceMethod, PayKeysendMethod, Transaction, TWalletMethod } from "./helpers/methods.js";
7
7
  import { NostrConnectionMethodsOptions, NostrPool, NostrPublishMethod, NostrSubscriptionMethod } from "./interop.js";
8
8
  export type SerializedWalletConnect = WalletConnectURI;
9
9
  export type WalletConnectOptions = NostrConnectionMethodsOptions & {
@@ -18,6 +18,11 @@ export type WalletConnectOptions = NostrConnectionMethodsOptions & {
18
18
  /** Whether to accept the relay hint from the wallet service */
19
19
  acceptRelayHint?: boolean;
20
20
  };
21
+ export type WaitForPaidInvoice = MakeInvoiceMethod["response"]["result"] | LookupInvoiceMethod["request"]["params"];
22
+ export type WaitForPaidOptions = {
23
+ /** Polling interval in milliseconds when payment_received notifications are not supported */
24
+ pollInterval?: number;
25
+ };
21
26
  export declare class WalletConnect<Methods extends TWalletMethod = CommonWalletMethods> {
22
27
  /** A fallback method to use for subscriptionMethod if none is passed in when creating the client */
23
28
  static subscriptionMethod: NostrSubscriptionMethod | undefined;
@@ -128,6 +133,8 @@ export declare class WalletConnect<Methods extends TWalletMethod = CommonWalletM
128
133
  }>): Promise<MultiPayKeysendMethod["response"]["result"][]>;
129
134
  /** Create a new invoice */
130
135
  makeInvoice(amount: number, options?: Omit<MakeInvoiceMethod["request"]["params"], "amount">): Promise<MakeInvoiceMethod["response"]["result"]>;
136
+ /** Wait for an invoice to be paid, or reject when it expires */
137
+ waitForPaid(invoice: WaitForPaidInvoice, options?: WaitForPaidOptions): Promise<Transaction>;
131
138
  /** Look up an invoice by payment hash or invoice string */
132
139
  lookupInvoice(payment_hash?: string, invoice?: string): Promise<LookupInvoiceMethod["response"]["result"]>;
133
140
  /** List transactions */
@@ -1,12 +1,14 @@
1
- import { bytesToHex, hexToBytes } from "@noble/hashes/utils";
1
+ import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
2
2
  import { simpleTimeout } from "applesauce-core";
3
3
  import { finalizeEvent, getPublicKey, verifyEvent } from "applesauce-core/helpers";
4
- import { nip04, nip44 } from "applesauce-core/helpers/encryption";
5
- import { BehaviorSubject, combineLatest, defer, filter, firstValueFrom, from, fromEvent, identity, ignoreElements, lastValueFrom, map, merge, mergeMap, of, repeat, ReplaySubject, retry, share, switchMap, take, takeUntil, tap, timer, toArray, } from "rxjs";
4
+ import { getCachedConversationKey, nip04, nip44 } from "applesauce-core/helpers/encryption";
5
+ import { BehaviorSubject, combineLatest, defer, filter, firstValueFrom, from, fromEvent, identity, ignoreElements, interval, lastValueFrom, map, merge, mergeMap, of, repeat, ReplaySubject, retry, share, switchMap, take, takeUntil, tap, timer, toArray, } from "rxjs";
6
6
  import { WalletRequestFactory } from "./factories/index.js";
7
7
  import { createWalletError } from "./helpers/error.js";
8
8
  import { createWalletAuthURI, createWalletConnectURI, getPreferredEncryption, getWalletRequestEncryption, getWalletResponseRequestId, getWalletSupport, isValidWalletNotification, isValidWalletResponse, parseWalletConnectURI, supportsMethod, supportsNotifications, supportsNotificationType, unlockWalletNotification, unlockWalletResponse, WALLET_INFO_KIND, WALLET_LEGACY_NOTIFICATION_KIND, WALLET_NOTIFICATION_KIND, WALLET_RESPONSE_KIND, } from "./helpers/index.js";
9
9
  import { getConnectionMethods, } from "./interop.js";
10
+ /** Node's 32-bit signed timer limit (~24.8 days); setTimeout delays beyond this overflow and clamp to ~1ms. */
11
+ const MAX_TIMER_DELAY = 2_147_483_647;
10
12
  export class WalletConnect {
11
13
  /** A fallback method to use for subscriptionMethod if none is passed in when creating the client */
12
14
  static subscriptionMethod = undefined;
@@ -66,8 +68,8 @@ export class WalletConnect {
66
68
  decrypt: async (pubkey, ciphertext) => nip04.decrypt(this.secret, pubkey, ciphertext),
67
69
  },
68
70
  nip44: {
69
- encrypt: async (pubkey, plaintext) => nip44.encrypt(plaintext, nip44.getConversationKey(this.secret, pubkey)),
70
- decrypt: async (pubkey, ciphertext) => nip44.decrypt(ciphertext, nip44.getConversationKey(this.secret, pubkey)),
71
+ encrypt: async (pubkey, plaintext) => nip44.encrypt(plaintext, getCachedConversationKey(this.secret, pubkey)),
72
+ decrypt: async (pubkey, ciphertext) => nip44.decrypt(ciphertext, getCachedConversationKey(this.secret, pubkey)),
71
73
  },
72
74
  };
73
75
  // Get the subscription and publish methods
@@ -167,24 +169,24 @@ export class WalletConnect {
167
169
  genericCall(method, params, options = {}) {
168
170
  if (!this.service)
169
171
  throw new Error("WalletConnect is not connected to a service");
170
- // Create the request event
171
- return defer(async () => {
172
- // Get the preferred encryption method for the wallet
173
- const encryption = await firstValueFrom(this.encryption$);
174
- // Create and sign the request event
175
- return await WalletRequestFactory.create(this.service, { method, params }, encryption).as(this.signer).sign();
176
- }).pipe(
172
+ const timeout = options.timeout || this.defaultTimeout;
173
+ // Keep negotiation in the stream so timing out also releases its subscription.
174
+ return this.encryption$.pipe(
175
+ // Use the first negotiation result, then release the negotiation subscription
176
+ take(1),
177
+ // Create and sign the request event once the encryption method is known
178
+ switchMap((encryption) => defer(() => WalletRequestFactory.create(this.service, { method, params }, encryption).as(this.signer).sign())),
177
179
  // Then switch to the request observable
178
180
  switchMap((requestEvent) => {
179
181
  const encryption = getWalletRequestEncryption(requestEvent) === "nip44_v2" ? "nip44" : "nip04";
180
182
  // Create an observable that publishes the request event when subscribed to
181
183
  const request$ = defer(() => from(this.publishMethod(this.relays, requestEvent))).pipe(ignoreElements());
182
184
  // Create an observable that listens for response events
183
- const responses$ = this.events$.pipe(filter(isValidWalletResponse), filter((response) => getWalletResponseRequestId(response) === requestEvent.id), mergeMap((response) => this.handleResponseEvent(response, encryption)),
184
- // Set timeout for response events
185
- simpleTimeout(options.timeout || this.defaultTimeout));
185
+ const responses$ = this.events$.pipe(filter(isValidWalletResponse), filter((response) => getWalletResponseRequestId(response) === requestEvent.id), mergeMap((response) => this.handleResponseEvent(response, encryption)));
186
186
  return merge(request$, responses$);
187
- }));
187
+ }),
188
+ // Bound negotiation and request creation until the first response; promises already running cannot be cancelled.
189
+ simpleTimeout(timeout, "WalletConnect request timed out"));
188
190
  }
189
191
  /** Request method with generic type */
190
192
  async genericRequest(method, params, options = {}) {
@@ -221,6 +223,9 @@ export class WalletConnect {
221
223
  async waitForService(abortSignal) {
222
224
  if (this.service)
223
225
  return this.service;
226
+ // fromEvent only observes future aborts.
227
+ if (abortSignal?.aborted)
228
+ throw abortSignal.reason ?? new Error("Aborted");
224
229
  return await firstValueFrom(this.waitForService$.pipe(
225
230
  // Listen for abort signal
226
231
  abortSignal ? takeUntil(fromEvent(abortSignal, "abort")) : identity));
@@ -280,6 +285,53 @@ export class WalletConnect {
280
285
  async makeInvoice(amount, options) {
281
286
  return await this.genericRequest("make_invoice", { amount, ...options });
282
287
  }
288
+ /** Wait for an invoice to be paid, or reject when it expires */
289
+ async waitForPaid(invoice, options = {}) {
290
+ const transaction = "state" in invoice ? invoice : await this.lookupInvoice(invoice.payment_hash, invoice.invoice);
291
+ if (transaction.state === "settled")
292
+ return Promise.resolve(transaction);
293
+ if (!transaction.payment_hash)
294
+ return Promise.reject(new Error("Invoice is missing payment hash"));
295
+ const expiresAt = transaction.expires_at ? transaction.expires_at * 1000 : undefined;
296
+ const now = Date.now();
297
+ if (expiresAt && expiresAt <= now)
298
+ return Promise.reject(new Error("Invoice expired"));
299
+ const supportsNotifications = await this.supportsNotificationType("payment_received");
300
+ if (!supportsNotifications) {
301
+ return await firstValueFrom(interval(options.pollInterval ?? 5000).pipe(switchMap(() => this.lookupInvoice(transaction.payment_hash, transaction.invoice)), mergeMap((result) => {
302
+ if (result.state === "settled")
303
+ return of(result);
304
+ if (result.state === "expired")
305
+ throw new Error("Invoice expired");
306
+ return [];
307
+ }),
308
+ // Skip the timeout operator entirely when there's no expiry — an Infinity delay
309
+ // would clamp to ~1ms, causing an immediate spurious TimeoutError.
310
+ expiresAt ? simpleTimeout(expiresAt - now) : identity));
311
+ }
312
+ return new Promise((resolve, reject) => {
313
+ const subscription = this.notification("payment_received", (payment) => {
314
+ if (payment.payment_hash !== transaction.payment_hash)
315
+ return;
316
+ cleanup();
317
+ resolve(payment);
318
+ });
319
+ // Clamp the delay to the 32-bit timer limit; invoices expiring further out than
320
+ // ~24.8 days will reject at the cap instead of at the true expiry (accepted tradeoff,
321
+ // since this callback rejects rather than re-arming and so cannot hot-loop).
322
+ const timeout = expiresAt
323
+ ? setTimeout(() => {
324
+ cleanup();
325
+ reject(new Error("Invoice expired"));
326
+ }, Math.min(expiresAt - now, MAX_TIMER_DELAY))
327
+ : undefined;
328
+ function cleanup() {
329
+ subscription.unsubscribe();
330
+ if (timeout)
331
+ clearTimeout(timeout);
332
+ }
333
+ });
334
+ }
283
335
  /** Look up an invoice by payment hash or invoice string */
284
336
  async lookupInvoice(payment_hash, invoice) {
285
337
  return await this.genericRequest("lookup_invoice", { payment_hash, invoice });
@@ -1,4 +1,4 @@
1
- import { EventSigner } from "applesauce-core";
1
+ import { EventSigner, type Debugger } from "applesauce-core";
2
2
  import { Observable, Subscription } from "rxjs";
3
3
  import { WalletAuthURI } from "./helpers/auth-uri.js";
4
4
  import { WalletErrorCode } from "./helpers/error.js";
@@ -53,7 +53,7 @@ export declare class WalletService<Methods extends TWalletMethod = CommonWalletM
53
53
  protected readonly subscriptionMethod: NostrSubscriptionMethod;
54
54
  /** A method for publishing events */
55
55
  protected readonly publishMethod: NostrPublishMethod;
56
- protected log: import("debug").Debugger;
56
+ protected log: Debugger;
57
57
  /** A special method for getting the generic wallet information */
58
58
  getInfo?: () => Promise<WalletServiceInfo>;
59
59
  /** The relays to use for the service */
@@ -2,7 +2,7 @@ import { logger } from "applesauce-core";
2
2
  import { verifyEvent } from "applesauce-core/helpers/event";
3
3
  import { generateSecretKey, getPublicKey } from "applesauce-core/helpers/keys";
4
4
  import { filter, from, mergeMap, repeat, retry, share, tap } from "rxjs";
5
- import { bytesToHex } from "@noble/hashes/utils";
5
+ import { bytesToHex } from "@noble/hashes/utils.js";
6
6
  import { WalletLegacyNotificationFactory, WalletNotificationFactory } from "./factories/notification.js";
7
7
  import { WalletResponseFactory } from "./factories/response.js";
8
8
  import { WalletInfoFactory } from "./factories/support.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "applesauce-wallet-connect",
3
- "version": "6.0.0",
3
+ "version": "7.0.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -58,18 +58,17 @@
58
58
  }
59
59
  },
60
60
  "dependencies": {
61
- "@noble/hashes": "^1.7.1",
62
- "applesauce-common": "^6.0.0",
63
- "applesauce-core": "^6.0.0",
61
+ "@noble/hashes": "^2.2.0",
62
+ "applesauce-common": "^7.0.0",
63
+ "applesauce-core": "^7.0.0",
64
64
  "rxjs": "^7.8.1"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@hirez_io/observer-spy": "^2.2.0",
68
- "applesauce-signers": "^6.0.0",
69
- "@types/debug": "^4.1.12",
70
- "rimraf": "^6.0.1",
71
- "typescript": "^5.8.3",
72
- "vitest": "^4.0.15"
68
+ "applesauce-signers": "^7.0.0",
69
+ "rimraf": "^6.1.3",
70
+ "typescript": "^7.0.2",
71
+ "vitest": "^4.1.11"
73
72
  },
74
73
  "funding": {
75
74
  "type": "lightning",