-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathNWCClient.ts
1051 lines (954 loc) · 29.1 KB
/
NWCClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
nip04,
relayInit,
getEventHash,
nip19,
generatePrivateKey,
getPublicKey,
Relay,
Event,
UnsignedEvent,
finishEvent,
Sub,
} from "nostr-tools";
import { NWCAuthorizationUrlOptions } from "./types";
type WithDTag = {
dTag: string;
};
type WithOptionalId = {
id?: string;
};
type Nip47SingleMethod =
| "get_info"
| "get_balance"
| "get_budget"
| "make_invoice"
| "pay_invoice"
| "pay_keysend"
| "lookup_invoice"
| "list_transactions"
| "sign_message";
type Nip47MultiMethod = "multi_pay_invoice" | "multi_pay_keysend";
export type Nip47Method = Nip47SingleMethod | Nip47MultiMethod;
export type Nip47Capability = Nip47Method | "notifications";
export type Nip47GetInfoResponse = {
alias: string;
color: string;
pubkey: string;
network: string;
block_height: number;
block_hash: string;
methods: Nip47Method[];
notifications?: Nip47NotificationType[];
};
export type Nip47GetBudgetResponse =
| {
used_budget: number; // msats
total_budget: number; // msats
renews_at?: number; // timestamp
renewal_period: "daily" | "weekly" | "monthly" | "yearly" | "never";
}
// eslint-disable-next-line @typescript-eslint/ban-types
| {};
export type Nip47GetBalanceResponse = {
balance: number; // msats
};
export type Nip47PayResponse = {
preimage: string;
};
export type Nip47MultiPayInvoiceRequest = {
invoices: (Nip47PayInvoiceRequest & WithOptionalId)[];
};
export type Nip47MultiPayKeysendRequest = {
keysends: (Nip47PayKeysendRequest & WithOptionalId)[];
};
export type Nip47MultiPayInvoiceResponse = {
invoices: ({ invoice: Nip47PayInvoiceRequest } & Nip47PayResponse &
WithDTag)[];
errors: []; // TODO: add error handling
};
export type Nip47MultiPayKeysendResponse = {
keysends: ({ keysend: Nip47PayKeysendRequest } & Nip47PayResponse &
WithDTag)[];
errors: []; // TODO: add error handling
};
export interface Nip47ListTransactionsRequest {
from?: number;
until?: number;
limit?: number;
offset?: number;
unpaid?: boolean;
type?: "incoming" | "outgoing";
}
export type Nip47ListTransactionsResponse = {
transactions: Nip47Transaction[];
};
export type Nip47Transaction = {
type: string;
invoice: string;
description: string;
description_hash: string;
preimage: string;
payment_hash: string;
amount: number;
fees_paid: number;
settled_at: number;
created_at: number;
expires_at: number;
metadata?: Record<string, unknown>;
};
export type Nip47NotificationType = Nip47Notification["notification_type"];
export type Nip47Notification =
| {
notification_type: "payment_received";
notification: Nip47Transaction;
}
| {
notification_type: "payment_sent";
notification: Nip47Transaction;
};
export type Nip47PayInvoiceRequest = {
invoice: string;
metadata?: unknown;
amount?: number; // msats
};
export type Nip47PayKeysendRequest = {
amount: number; //msat
pubkey: string;
preimage?: string;
tlv_records?: { type: number; value: string }[];
};
export type Nip47MakeInvoiceRequest = {
amount: number; //msat
description?: string;
description_hash?: string;
expiry?: number; // in seconds
metadata?: unknown; // TODO: update to also include known keys (payerData, nostr, comment)
};
export type Nip47LookupInvoiceRequest = {
payment_hash?: string;
invoice?: string;
};
export type Nip47SignMessageRequest = {
message: string;
};
export type Nip47SignMessageResponse = {
message: string;
signature: string;
};
export interface NWCOptions {
authorizationUrl?: string; // the URL to the NWC interface for the user to confirm the session
relayUrl: string;
walletPubkey: string;
secret?: string;
lud16?: string;
}
export class Nip47Error extends Error {
/**
* @deprecated please use message. Deprecated since v3.3.2. Will be removed in v4.0.0.
*/
error: string;
code: string;
constructor(message: string, code: string) {
super(message);
this.error = message;
this.code = code;
}
}
/**
* A NIP-47 response was received, but with an error code (see https://github.com/nostr-protocol/nips/blob/master/47.md#error-codes)
*/
export class Nip47WalletError extends Nip47Error {}
export class Nip47TimeoutError extends Nip47Error {}
export class Nip47PublishTimeoutError extends Nip47TimeoutError {}
export class Nip47ReplyTimeoutError extends Nip47TimeoutError {}
export class Nip47PublishError extends Nip47Error {}
export class Nip47ResponseDecodingError extends Nip47Error {}
export class Nip47ResponseValidationError extends Nip47Error {}
export class Nip47UnexpectedResponseError extends Nip47Error {}
export class Nip47NetworkError extends Nip47Error {}
export const NWCs: Record<string, NWCOptions> = {
alby: {
authorizationUrl: "https://nwc.getalby.com/apps/new",
relayUrl: "wss://relay.getalby.com/v1",
walletPubkey:
"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9",
},
};
export type NewNWCClientOptions = {
providerName?: string;
authorizationUrl?: string;
relayUrl?: string;
secret?: string;
walletPubkey?: string;
nostrWalletConnectUrl?: string;
};
export class NWCClient {
relay: Relay;
relayUrl: string;
secret: string | undefined;
lud16: string | undefined;
walletPubkey: string;
options: NWCOptions;
static parseWalletConnectUrl(walletConnectUrl: string): NWCOptions {
// makes it possible to parse with URL in the different environments (browser/node/...)
// parses both new and legacy protocols, with or without "//"
walletConnectUrl = walletConnectUrl
.replace("nostrwalletconnect://", "http://")
.replace("nostr+walletconnect://", "http://")
.replace("nostrwalletconnect:", "http://")
.replace("nostr+walletconnect:", "http://");
const url = new URL(walletConnectUrl);
const relayUrl = url.searchParams.get("relay");
if (!relayUrl) {
throw new Error("No relay URL found in connection string");
}
const options: NWCOptions = {
walletPubkey: url.host,
relayUrl,
};
const secret = url.searchParams.get("secret");
if (secret) {
options.secret = secret;
}
const lud16 = url.searchParams.get("lud16");
if (lud16) {
options.lud16 = lud16;
}
return options;
}
static withNewSecret(options?: ConstructorParameters<typeof NWCClient>[0]) {
options = options || {};
options.secret = generatePrivateKey();
return new NWCClient(options);
}
constructor(options?: NewNWCClientOptions) {
if (options && options.nostrWalletConnectUrl) {
options = {
...NWCClient.parseWalletConnectUrl(options.nostrWalletConnectUrl),
...options,
};
}
const providerOptions = NWCs[options?.providerName || "alby"] as NWCOptions;
this.options = {
...providerOptions,
...(options || {}),
} as NWCOptions;
this.relayUrl = this.options.relayUrl;
this.relay = relayInit(this.relayUrl);
if (this.options.secret) {
this.secret = (
this.options.secret.toLowerCase().startsWith("nsec")
? nip19.decode(this.options.secret).data
: this.options.secret
) as string;
}
this.lud16 = this.options.lud16;
this.walletPubkey = (
this.options.walletPubkey.toLowerCase().startsWith("npub")
? nip19.decode(this.options.walletPubkey).data
: this.options.walletPubkey
) as string;
// this.subscribers = {};
if (globalThis.WebSocket === undefined) {
console.error(
"WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments",
);
}
}
get nostrWalletConnectUrl() {
return this.getNostrWalletConnectUrl();
}
getNostrWalletConnectUrl(includeSecret = true) {
let url = `nostr+walletconnect://${this.walletPubkey}?relay=${this.relayUrl}&pubkey=${this.publicKey}`;
if (includeSecret) {
url = `${url}&secret=${this.secret}`;
}
return url;
}
get connected() {
return this.relay.status === 1;
}
get publicKey() {
if (!this.secret) {
throw new Error("Missing secret key");
}
return getPublicKey(this.secret);
}
getPublicKey(): Promise<string> {
return Promise.resolve(this.publicKey);
}
signEvent(event: UnsignedEvent): Promise<Event> {
if (!this.secret) {
throw new Error("Missing secret key");
}
return Promise.resolve(finishEvent(event, this.secret));
}
getEventHash(event: Event) {
return getEventHash(event);
}
close() {
return this.relay.close();
}
async encrypt(pubkey: string, content: string) {
if (!this.secret) {
throw new Error("Missing secret");
}
const encrypted = await nip04.encrypt(this.secret, pubkey, content);
return encrypted;
}
async decrypt(pubkey: string, content: string) {
if (!this.secret) {
throw new Error("Missing secret");
}
const decrypted = await nip04.decrypt(this.secret, pubkey, content);
return decrypted;
}
getAuthorizationUrl(options?: NWCAuthorizationUrlOptions): URL {
if (!this.options.authorizationUrl) {
throw new Error("Missing authorizationUrl option");
}
const url = new URL(this.options.authorizationUrl);
if (options?.name) {
url.searchParams.set("name", options?.name);
}
url.searchParams.set("pubkey", this.publicKey);
if (options?.returnTo) {
url.searchParams.set("return_to", options.returnTo);
}
if (options?.budgetRenewal) {
url.searchParams.set("budget_renewal", options.budgetRenewal);
}
if (options?.expiresAt) {
url.searchParams.set(
"expires_at",
Math.floor(options.expiresAt.getTime() / 1000).toString(),
);
}
if (options?.maxAmount) {
url.searchParams.set("max_amount", options.maxAmount.toString());
}
if (options?.editable !== undefined) {
url.searchParams.set("editable", options.editable.toString());
}
if (options?.requestMethods) {
url.searchParams.set("request_methods", options.requestMethods.join(" "));
}
return url;
}
initNWC(options: NWCAuthorizationUrlOptions = {}) {
// here we assume an browser context and window/document is available
// we set the location.host as a default name if none is given
if (!options.name) {
options.name = document.location.host;
}
const url = this.getAuthorizationUrl(options);
const height = 600;
const width = 400;
const top = window.outerHeight / 2 + window.screenY - height / 2;
const left = window.outerWidth / 2 + window.screenX - width / 2;
return new Promise((resolve, reject) => {
const popup = window.open(
url.toString(),
`${document.title} - Wallet Connect`,
`height=${height},width=${width},top=${top},left=${left}`,
);
if (!popup) {
reject(new Error("failed to execute window.open"));
return;
}
const checkForPopup = () => {
if (popup && popup.closed) {
clearInterval(popupChecker);
window.removeEventListener("message", onMessage);
reject(new Error("Popup closed"));
}
};
const onMessage = (message: {
data?: { type: "nwc:success" | unknown };
origin: string;
}) => {
const data = message.data;
if (
data &&
data.type === "nwc:success" &&
message.origin === `${url.protocol}//${url.host}`
) {
resolve(data);
clearInterval(popupChecker);
window.removeEventListener("message", onMessage);
if (popup) {
popup.close(); // close the popup
}
}
};
const popupChecker = setInterval(checkForPopup, 500);
window.addEventListener("message", onMessage);
});
}
/**
* @deprecated please use getWalletServiceInfo. Deprecated since v3.5.0. Will be removed in v4.0.0.
*/
async getWalletServiceSupportedMethods(): Promise<Nip47Capability[]> {
console.warn(
"getWalletServiceSupportedMethods is deprecated. Please use getWalletServiceInfo instead.",
);
const info = await this.getWalletServiceInfo();
return info.capabilities;
}
async getWalletServiceInfo(): Promise<{
capabilities: Nip47Capability[];
notifications: Nip47NotificationType[];
}> {
await this._checkConnected();
const events = await this.relay.list(
[
{
kinds: [13194],
limit: 1,
authors: [this.walletPubkey],
},
],
{
eoseSubTimeout: 10000,
},
);
if (!events.length) {
throw new Error("no info event (kind 13194) returned from relay");
}
const content = events[0].content;
const notificationsTag = events[0].tags.find(
(t) => t[0] === "notifications",
);
return {
// delimiter is " " per spec, but Alby NWC originally returned ","
capabilities: content.split(/[ |,]/g) as Nip47Method[],
notifications: (notificationsTag?.[1]?.split(" ") ||
[]) as Nip47NotificationType[],
};
}
async getInfo(): Promise<Nip47GetInfoResponse> {
try {
const result = await this.executeNip47Request<Nip47GetInfoResponse>(
"get_info",
{},
(result) => !!result.methods,
);
return result;
} catch (error) {
console.error("Failed to request get_info", error);
throw error;
}
}
async getBudget(): Promise<Nip47GetBudgetResponse> {
try {
const result = await this.executeNip47Request<Nip47GetBudgetResponse>(
"get_budget",
{},
(result) => result !== undefined,
);
return result;
} catch (error) {
console.error("Failed to request get_budget", error);
throw error;
}
}
async getBalance(): Promise<Nip47GetBalanceResponse> {
try {
const result = await this.executeNip47Request<Nip47GetBalanceResponse>(
"get_balance",
{},
(result) => result.balance !== undefined,
);
return result;
} catch (error) {
console.error("Failed to request get_balance", error);
throw error;
}
}
async payInvoice(request: Nip47PayInvoiceRequest): Promise<Nip47PayResponse> {
try {
const result = await this.executeNip47Request<Nip47PayResponse>(
"pay_invoice",
request,
(result) => !!result.preimage,
);
return result;
} catch (error) {
console.error("Failed to request pay_invoice", error);
throw error;
}
}
async payKeysend(request: Nip47PayKeysendRequest): Promise<Nip47PayResponse> {
try {
const result = await this.executeNip47Request<Nip47PayResponse>(
"pay_keysend",
request,
(result) => !!result.preimage,
);
return result;
} catch (error) {
console.error("Failed to request pay_keysend", error);
throw error;
}
}
async signMessage(
request: Nip47SignMessageRequest,
): Promise<Nip47SignMessageResponse> {
try {
const result = await this.executeNip47Request<Nip47SignMessageResponse>(
"sign_message",
request,
(result) => result.message === request.message && !!result.signature,
);
return result;
} catch (error) {
console.error("Failed to request sign_message", error);
throw error;
}
}
async multiPayInvoice(
request: Nip47MultiPayInvoiceRequest,
): Promise<Nip47MultiPayInvoiceResponse> {
try {
const results = await this.executeMultiNip47Request<
{ invoice: Nip47PayInvoiceRequest } & Nip47PayResponse
>(
"multi_pay_invoice",
request,
request.invoices.length,
(result) => !!result.preimage,
);
return {
invoices: results,
// TODO: error handling
errors: [],
};
} catch (error) {
console.error("Failed to request multi_pay_invoice", error);
throw error;
}
}
async multiPayKeysend(
request: Nip47MultiPayKeysendRequest,
): Promise<Nip47MultiPayKeysendResponse> {
try {
const results = await this.executeMultiNip47Request<
{ keysend: Nip47PayKeysendRequest } & Nip47PayResponse
>(
"multi_pay_keysend",
request,
request.keysends.length,
(result) => !!result.preimage,
);
return {
keysends: results,
// TODO: error handling
errors: [],
};
} catch (error) {
console.error("Failed to request multi_pay_keysend", error);
throw error;
}
}
async makeInvoice(
request: Nip47MakeInvoiceRequest,
): Promise<Nip47Transaction> {
try {
if (!request.amount) {
throw new Error("No amount specified");
}
const result = await this.executeNip47Request<Nip47Transaction>(
"make_invoice",
request,
(result) => !!result.invoice,
);
return result;
} catch (error) {
console.error("Failed to request make_invoice", error);
throw error;
}
}
async lookupInvoice(
request: Nip47LookupInvoiceRequest,
): Promise<Nip47Transaction> {
try {
const result = await this.executeNip47Request<Nip47Transaction>(
"lookup_invoice",
request,
(result) => !!result.invoice,
);
return result;
} catch (error) {
console.error("Failed to request lookup_invoice", error);
throw error;
}
}
async listTransactions(
request: Nip47ListTransactionsRequest,
): Promise<Nip47ListTransactionsResponse> {
try {
// maybe we can tailor the response to our needs
const result =
await this.executeNip47Request<Nip47ListTransactionsResponse>(
"list_transactions",
request,
(response) => !!response.transactions,
);
return result;
} catch (error) {
console.error("Failed to request list_transactions", error);
throw error;
}
}
async subscribeNotifications(
onNotification: (notification: Nip47Notification) => void,
notificationTypes?: Nip47NotificationType[],
): Promise<() => void> {
let subscribed = true;
let endPromise: (() => void) | undefined;
let onRelayDisconnect: (() => void) | undefined;
let sub: Sub<23196> | undefined;
(async () => {
while (subscribed) {
try {
await this._checkConnected();
sub = this.relay.sub([
{
kinds: [23196],
authors: [this.walletPubkey],
"#p": [this.publicKey],
},
]);
console.info("subscribed to relay");
sub.on("event", async (event) => {
const decryptedContent = await this.decrypt(
this.walletPubkey,
event.content,
);
let notification;
try {
notification = JSON.parse(decryptedContent) as Nip47Notification;
} catch (e) {
console.error("Failed to parse decrypted event content", e);
return;
}
if (notification.notification) {
if (
!notificationTypes ||
notificationTypes.indexOf(notification.notification_type) > -1
) {
onNotification(notification);
}
} else {
console.error("No notification in response", notification);
}
});
await new Promise<void>((resolve) => {
endPromise = () => {
resolve();
};
onRelayDisconnect = () => {
console.info("relay disconnected");
endPromise?.();
};
this.relay.on("disconnect", onRelayDisconnect);
});
if (onRelayDisconnect !== undefined) {
this.relay.off("disconnect", onRelayDisconnect);
}
} catch (error) {
console.error(
"error subscribing to notifications",
error || "unknown relay error",
);
}
if (subscribed) {
// wait a second and try re-connecting
// any notifications during this period will be lost
await new Promise((resolve) => setTimeout(resolve, 1000));
}
}
})();
return () => {
subscribed = false;
endPromise?.();
sub?.unsub();
};
}
private async executeNip47Request<T>(
nip47Method: Nip47SingleMethod,
params: unknown,
resultValidator: (result: T) => boolean,
): Promise<T> {
await this._checkConnected();
return new Promise<T>((resolve, reject) => {
(async () => {
const command = {
method: nip47Method,
params,
};
const encryptedCommand = await this.encrypt(
this.walletPubkey,
JSON.stringify(command),
);
const unsignedEvent: UnsignedEvent = {
kind: 23194,
created_at: Math.floor(Date.now() / 1000),
tags: [["p", this.walletPubkey]],
content: encryptedCommand,
pubkey: this.publicKey,
};
const event = await this.signEvent(unsignedEvent);
// subscribe to NIP_47_SUCCESS_RESPONSE_KIND and NIP_47_ERROR_RESPONSE_KIND
// that reference the request event (NIP_47_REQUEST_KIND)
const sub = this.relay.sub([
{
kinds: [23195],
authors: [this.walletPubkey],
"#e": [event.id],
},
]);
function replyTimeout() {
sub.unsub();
//console.error(`Reply timeout: event ${event.id} `);
reject(
new Nip47ReplyTimeoutError(
`reply timeout: event ${event.id}`,
"INTERNAL",
),
);
}
const replyTimeoutCheck = setTimeout(replyTimeout, 60000);
sub.on("event", async (event) => {
// console.log(`Received reply event: `, event);
clearTimeout(replyTimeoutCheck);
sub.unsub();
const decryptedContent = await this.decrypt(
this.walletPubkey,
event.content,
);
// console.log(`Decrypted content: `, decryptedContent);
let response;
try {
response = JSON.parse(decryptedContent);
} catch (e) {
clearTimeout(replyTimeoutCheck);
sub.unsub();
reject(
new Nip47ResponseDecodingError(
"failed to deserialize response",
"INTERNAL",
),
);
return;
}
if (response.result) {
// console.info("NIP-47 result", response.result);
if (resultValidator(response.result)) {
resolve(response.result);
} else {
clearTimeout(replyTimeoutCheck);
sub.unsub();
reject(
new Nip47ResponseValidationError(
"response from NWC failed validation: " +
JSON.stringify(response.result),
"INTERNAL",
),
);
}
} else {
clearTimeout(replyTimeoutCheck);
sub.unsub();
// console.error("Wallet error", response.error);
reject(
new Nip47WalletError(
response.error?.message || "unknown Error",
response.error?.code || "INTERNAL",
),
);
}
});
function publishTimeout() {
sub.unsub();
//console.error(`Publish timeout: event ${event.id}`);
reject(
new Nip47PublishTimeoutError(
`publish timeout: ${event.id}`,
"INTERNAL",
),
);
}
const publishTimeoutCheck = setTimeout(publishTimeout, 5000);
try {
await this.relay.publish(event);
clearTimeout(publishTimeoutCheck);
//console.debug(`Event ${event.id} for ${invoice} published`);
} catch (error) {
//console.error(`Failed to publish to ${this.relay.url}`, error);
clearTimeout(publishTimeoutCheck);
reject(
new Nip47PublishError(`failed to publish: ${error}`, "INTERNAL"),
);
}
})();
});
}
// TODO: this method currently fails if any payment fails.
// this could be improved in the future.
// TODO: reduce duplication between executeNip47Request and executeMultiNip47Request
private async executeMultiNip47Request<T>(
nip47Method: Nip47MultiMethod,
params: unknown,
numPayments: number,
resultValidator: (result: T) => boolean,
): Promise<(T & { dTag: string })[]> {
await this._checkConnected();
const results: (T & { dTag: string })[] = [];
return new Promise<(T & { dTag: string })[]>((resolve, reject) => {
(async () => {
const command = {
method: nip47Method,
params,
};
const encryptedCommand = await this.encrypt(
this.walletPubkey,
JSON.stringify(command),
);
const unsignedEvent: UnsignedEvent = {
kind: 23194,
created_at: Math.floor(Date.now() / 1000),
tags: [["p", this.walletPubkey]],
content: encryptedCommand,
pubkey: this.publicKey,
};
const event = await this.signEvent(unsignedEvent);
// subscribe to NIP_47_SUCCESS_RESPONSE_KIND and NIP_47_ERROR_RESPONSE_KIND
// that reference the request event (NIP_47_REQUEST_KIND)
const sub = this.relay.sub([
{
kinds: [23195],
authors: [this.walletPubkey],
"#e": [event.id],
},
]);
function replyTimeout() {
sub.unsub();
//console.error(`Reply timeout: event ${event.id} `);
reject(
new Nip47ReplyTimeoutError(
`reply timeout: event ${event.id}`,
"INTERNAL",
),
);
}
const replyTimeoutCheck = setTimeout(replyTimeout, 60000);
sub.on("event", async (event) => {
// console.log(`Received reply event: `, event);
const decryptedContent = await this.decrypt(
this.walletPubkey,
event.content,
);
// console.log(`Decrypted content: `, decryptedContent);
let response;
try {
response = JSON.parse(decryptedContent);
} catch (e) {
// console.error(e);
clearTimeout(replyTimeoutCheck);
sub.unsub();
reject(
new Nip47ResponseDecodingError(
"failed to deserialize response",
"INTERNAL",
),
);
}
if (response.result) {
// console.info("NIP-47 result", response.result);
if (!resultValidator(response.result)) {
clearTimeout(replyTimeoutCheck);
sub.unsub();
reject(
new Nip47ResponseValidationError(
"Response from NWC failed validation: " +
JSON.stringify(response.result),
"INTERNAL",
),
);
return;
}
const dTag = event.tags.find((tag) => tag[0] === "d")?.[1];
if (dTag === undefined) {
clearTimeout(replyTimeoutCheck);
sub.unsub();
reject(
new Nip47ResponseValidationError(
"No d tag found in response event",
"INTERNAL",
),
);
return;
}
results.push({
...response.result,
dTag,
});
if (results.length === numPayments) {
clearTimeout(replyTimeoutCheck);
sub.unsub();
//console.log("Received results", results);
resolve(results);
}
} else {
clearTimeout(replyTimeoutCheck);