applesauce-wallet-connect 0.0.0-next-20251009095925 → 0.0.0-next-20251012142625

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,9 +1,9 @@
1
1
  import { EventBlueprint } from "applesauce-factory";
2
- import { WalletRequest } from "../helpers/request.js";
3
2
  import { WalletConnectEncryptionMethod } from "../helpers/encryption.js";
3
+ import { TWalletMethod } from "../helpers/methods.js";
4
4
  /**
5
5
  * Creates a walelt request event
6
6
  * @param service - The service pubkey
7
7
  * @param request - The request to create an event for
8
8
  */
9
- export declare function WalletRequestBlueprint<TRequest extends WalletRequest>(service: string, request: TRequest, encryption?: WalletConnectEncryptionMethod): EventBlueprint;
9
+ export declare function WalletRequestBlueprint<Method extends TWalletMethod>(service: string, request: Method["request"], encryption?: WalletConnectEncryptionMethod): EventBlueprint;
@@ -1,5 +1,5 @@
1
1
  import { EventBlueprint } from "applesauce-factory";
2
2
  import { NostrEvent } from "nostr-tools";
3
- import { WalletResponse } from "../helpers/response.js";
3
+ import { TWalletMethod } from "../helpers/methods.js";
4
4
  /** Creates a wallet response event */
5
- export declare function WalletResponseBlueprint(request: NostrEvent, response: WalletResponse): EventBlueprint;
5
+ export declare function WalletResponseBlueprint<Method extends TWalletMethod>(request: NostrEvent, response: Method["response"] | Method["error"]): EventBlueprint;
@@ -1,9 +1,10 @@
1
1
  import { EventBlueprint } from "applesauce-factory";
2
2
  import { WalletSupport } from "../helpers/support.js";
3
+ import { TWalletMethod } from "../helpers/methods.js";
3
4
  /**
4
5
  * Creates a wallet info event
5
6
  * @param info - The wallet support information
6
7
  * @param client - The client pubkey
7
8
  * @param overrideRelay - An optional relay to tell the client which relay to use (for nostr+walletauth URI connections)
8
9
  */
9
- export declare function WalletSupportBlueprint(info: WalletSupport, client?: string, overrideRelay?: string): EventBlueprint;
10
+ export declare function WalletSupportBlueprint<Methods extends TWalletMethod>(info: WalletSupport<Methods>, client?: string, overrideRelay?: string): EventBlueprint;
@@ -1,6 +1,6 @@
1
1
  import { NotificationType } from "./notification.js";
2
- import { WalletMethod } from "./support.js";
3
- export interface WalletAuthURI {
2
+ import { CommonWalletMethods, TWalletMethod } from "./methods.js";
3
+ export interface WalletAuthURI<Methods extends TWalletMethod = CommonWalletMethods> {
4
4
  /** The public key of the client requesting authorization */
5
5
  client: string;
6
6
  /** Required. URL of the relay where the client intends to communicate with the wallet service */
@@ -18,7 +18,7 @@ export interface WalletAuthURI {
18
18
  /** The reset the budget at the end of the given budget renewal. Can be never (default), daily, weekly, monthly, yearly (optional) */
19
19
  budgetRenewal?: "never" | "daily" | "weekly" | "monthly" | "yearly";
20
20
  /** List of request types that you need permission for (optional) */
21
- methods?: WalletMethod[];
21
+ methods?: Methods["method"][];
22
22
  /** List of notification types that you need permission for (optional) */
23
23
  notifications?: NotificationType[];
24
24
  /** The makes an isolated app connection / sub-wallet with its own balance and only access to its own transaction list (optional) */
@@ -32,13 +32,11 @@ export interface WalletAuthURI {
32
32
  * Parses a nostr+walletauth URI
33
33
  * @throws {Error} if the authorization URI is invalid
34
34
  */
35
- export declare function parseWalletAuthURI(authURI: string): WalletAuthURI;
36
- /**
37
- * Creates a nostr+walletauth URI from a WalletAuthURI object
38
- */
39
- export declare function createWalletAuthURI(parts: WalletAuthURI): string;
35
+ export declare function parseWalletAuthURI<Methods extends TWalletMethod = CommonWalletMethods>(authURI: string): WalletAuthURI<Methods>;
36
+ /** Creates a nostr+walletauth URI from a WalletAuthURI object */
37
+ export declare function createWalletAuthURI<Methods extends TWalletMethod = CommonWalletMethods>(parts: WalletAuthURI<Methods>): string;
40
38
  /**
41
39
  * Validates a WalletAuthURI object
42
40
  * @returns true if valid, throws Error if invalid
43
41
  */
44
- export declare function validateWalletAuthURI(parts: WalletAuthURI): boolean;
42
+ export declare function validateWalletAuthURI(parts: WalletAuthURI<TWalletMethod>): boolean;
@@ -60,9 +60,7 @@ export function parseWalletAuthURI(authURI) {
60
60
  walletName,
61
61
  };
62
62
  }
63
- /**
64
- * Creates a nostr+walletauth URI from a WalletAuthURI object
65
- */
63
+ /** Creates a nostr+walletauth URI from a WalletAuthURI object */
66
64
  export function createWalletAuthURI(parts) {
67
65
  validateWalletAuthURI(parts);
68
66
  // Determine the protocol based on whether wallet name is specified
@@ -6,3 +6,4 @@ export * from "./support.js";
6
6
  export * from "./notification.js";
7
7
  export * from "./encryption.js";
8
8
  export * from "./auth-uri.js";
9
+ export * from "./methods.js";
@@ -6,3 +6,4 @@ export * from "./support.js";
6
6
  export * from "./notification.js";
7
7
  export * from "./encryption.js";
8
8
  export * from "./auth-uri.js";
9
+ export * from "./methods.js";
@@ -0,0 +1,234 @@
1
+ import { WalletErrorCode } from "./error.js";
2
+ import { WalletSupport } from "./support.js";
3
+ /** Base request structure for all NIP-47 requests */
4
+ export interface TWalletRequest<Method extends string, Params> {
5
+ /** The method to call */
6
+ method: Method;
7
+ /** Parameters for the method */
8
+ params: Params;
9
+ }
10
+ /** Error object for wallet responses */
11
+ export interface TWalletResponseError {
12
+ type: WalletErrorCode;
13
+ message: string;
14
+ }
15
+ /** Base response structure for all NIP-47 responses */
16
+ export type TWalletErrorResponse<Method extends string> = {
17
+ /** Indicates the structure of the result field */
18
+ result_type: Method;
19
+ /** Error object, non-null in case of error */
20
+ error: TWalletResponseError;
21
+ result: null;
22
+ };
23
+ export type TWalletSuccessResponse<Method extends string, Result> = {
24
+ /** Indicates the structure of the result field */
25
+ result_type: Method;
26
+ error: null;
27
+ /** Result object, null in case of error */
28
+ result: Result;
29
+ };
30
+ /** Merged wallet response and request types, this is designed to only be used with typescript */
31
+ export type TWalletMethod<Method extends string = string, Params extends any = any, Result extends any = any> = {
32
+ /** Method string */
33
+ method: Method;
34
+ /** Request type */
35
+ request: TWalletRequest<Method, Params>;
36
+ /** Response success type */
37
+ response: TWalletSuccessResponse<Method, Result>;
38
+ /** Response error type */
39
+ error: TWalletErrorResponse<Method>;
40
+ };
41
+ /** TLV record for keysend payments */
42
+ export interface TLVRecord {
43
+ /** TLV type */
44
+ type: number;
45
+ /** Hex encoded TLV value */
46
+ value: string;
47
+ }
48
+ /** Transaction object used in multiple response types */
49
+ export interface Transaction {
50
+ /** Type of transaction */
51
+ type: "incoming" | "outgoing";
52
+ /** State of the transaction */
53
+ state: "pending" | "settled" | "expired" | "failed";
54
+ /** Value in msats */
55
+ amount: number;
56
+ /** Value in msats */
57
+ fees_paid: number;
58
+ /** Invoice/payment creation unix timestamp */
59
+ created_at: number;
60
+ /** Encoded invoice, optional */
61
+ invoice?: string;
62
+ /** Invoice's description, optional */
63
+ description?: string;
64
+ /** Invoice's description hash, optional */
65
+ description_hash?: string;
66
+ /** Payment's preimage, optional if unpaid */
67
+ preimage?: string;
68
+ /** Payment hash for the payment, optional */
69
+ payment_hash?: string;
70
+ /** Invoice expiration unix timestamp, optional if not applicable */
71
+ expires_at?: number;
72
+ /** Invoice/payment settlement unix timestamp, optional if unpaid */
73
+ settled_at?: number;
74
+ /** Generic metadata that can be used to add things like zap/boostagram details */
75
+ metadata?: Record<string, any>;
76
+ }
77
+ export type PayInvoiceMethod = TWalletMethod<"pay_invoice", {
78
+ /** BOLT11 invoice */
79
+ invoice: string;
80
+ /** Invoice amount in msats, optional */
81
+ amount?: number;
82
+ }, {
83
+ /** Preimage of the payment */
84
+ preimage: string;
85
+ /** Value in msats, optional */
86
+ fees_paid?: number;
87
+ }>;
88
+ export type MultiPayInvoiceMethod = TWalletMethod<"multi_pay_invoice", {
89
+ /** Array of invoices to pay */
90
+ invoices: Array<{
91
+ /** ID to identify this invoice in the response */
92
+ id?: string;
93
+ /** BOLT11 invoice */
94
+ invoice: string;
95
+ /** Invoice amount in msats, optional */
96
+ amount?: number;
97
+ }>;
98
+ }, {
99
+ /** Preimage of the payment */
100
+ preimage: string;
101
+ /** Value in msats, optional */
102
+ fees_paid?: number;
103
+ }>;
104
+ export type PayKeysendMethod = TWalletMethod<"pay_keysend", {
105
+ /** Amount in msats, required */
106
+ amount: number;
107
+ /** Payee pubkey, required */
108
+ pubkey: string;
109
+ /** Preimage of the payment, optional */
110
+ preimage?: string;
111
+ /** TLV records, optional */
112
+ tlv_records?: TLVRecord[];
113
+ }, {
114
+ /** Preimage of the payment */
115
+ preimage: string;
116
+ /** Value in msats, optional */
117
+ fees_paid?: number;
118
+ }>;
119
+ export type MultiPayKeysendMethod = TWalletMethod<"multi_pay_keysend", {
120
+ /** Array of keysend payments */
121
+ keysends: Array<{
122
+ /** ID to identify this keysend in the response */
123
+ id?: string;
124
+ /** Payee pubkey, required */
125
+ pubkey: string;
126
+ /** Amount in msats, required */
127
+ amount: number;
128
+ /** Preimage of the payment, optional */
129
+ preimage?: string;
130
+ /** TLV records, optional */
131
+ tlv_records?: TLVRecord[];
132
+ }>;
133
+ }, {
134
+ /** Preimage of the payment */
135
+ preimage: string;
136
+ /** Value in msats, optional */
137
+ fees_paid?: number;
138
+ }>;
139
+ export type MakeInvoiceMethod = TWalletMethod<"make_invoice", {
140
+ /** Value in msats */
141
+ amount: number;
142
+ /** Invoice's description, optional */
143
+ description?: string;
144
+ /** Invoice's description hash, optional */
145
+ description_hash?: string;
146
+ /** Expiry in seconds from time invoice is created, optional */
147
+ expiry?: number;
148
+ }, Transaction>;
149
+ export type LookupInvoiceMethod = TWalletMethod<"lookup_invoice", {
150
+ /** Payment hash of the invoice, one of payment_hash or invoice is required */
151
+ payment_hash?: string;
152
+ /** Invoice to lookup */
153
+ invoice?: string;
154
+ }, Transaction>;
155
+ export type ListTransactionsMethod = TWalletMethod<"list_transactions", {
156
+ /** Starting timestamp in seconds since epoch (inclusive), optional */
157
+ from?: number;
158
+ /** Ending timestamp in seconds since epoch (inclusive), optional */
159
+ until?: number;
160
+ /** Maximum number of invoices to return, optional */
161
+ limit?: number;
162
+ /** Offset of the first invoice to return, optional */
163
+ offset?: number;
164
+ /** Include unpaid invoices, optional, default false */
165
+ unpaid?: boolean;
166
+ /** "incoming" for invoices, "outgoing" for payments, undefined for both */
167
+ type?: "incoming" | "outgoing";
168
+ }, {
169
+ /** Array of transactions */
170
+ transactions: Transaction[];
171
+ }>;
172
+ export type GetBalanceMethod = TWalletMethod<"get_balance", {}, {
173
+ /** User's balance in msats */
174
+ balance: number;
175
+ }>;
176
+ /** Type for wallet get_info */
177
+ export type WalletInfo = Omit<WalletSupport, "encryption"> & {
178
+ /** Node alias */
179
+ alias?: string;
180
+ /** Node color as hex string */
181
+ color?: string;
182
+ /** Node public key as hex string */
183
+ pubkey?: string;
184
+ /** Network type */
185
+ network?: "mainnet" | "testnet" | "signet" | "regtest";
186
+ /** Current block height */
187
+ block_height?: number;
188
+ /** Current block hash as hex string */
189
+ block_hash?: string;
190
+ };
191
+ export type GetInfoMethod = TWalletMethod<"get_info", {}, WalletInfo>;
192
+ /** Union type for all wallet method definitions */
193
+ export type CommonWalletMethods = PayInvoiceMethod | MultiPayInvoiceMethod | PayKeysendMethod | MultiPayKeysendMethod | MakeInvoiceMethod | LookupInvoiceMethod | ListTransactionsMethod | GetBalanceMethod | GetInfoMethod;
194
+ /** Withdraw a token from the wallet */
195
+ export type CashuWithdrawMethod = TWalletMethod<"cashu_withdraw", {
196
+ /** Token amount */
197
+ amount: number;
198
+ /** required token unit */
199
+ unit: string;
200
+ /** Optional array of mints, if provided token MUST be from one */
201
+ mints?: string[];
202
+ /** Size of proofs (optional) */
203
+ proofs?: number[];
204
+ /** Lock to pubkey (optional) */
205
+ p2pk?: string;
206
+ }, {
207
+ token: string;
208
+ }>;
209
+ /** Deposit a token into the wallet */
210
+ export type CashuDepositMethod = TWalletMethod<"cashu_deposit", {
211
+ /** Token to deposit */
212
+ token: string;
213
+ }, {
214
+ success: true;
215
+ }>;
216
+ export type CashuPayRequestMethod = TWalletMethod<"cashu_pay_request", {
217
+ /** Cashu payment request. if request originally does not contain an amount they client may add one and re-encode */
218
+ request: string;
219
+ }, {
220
+ success: true;
221
+ }>;
222
+ /** Info for a single mint used in the wallet service */
223
+ export type CashuMintInfo = {
224
+ /** Mint URL */
225
+ url: string;
226
+ /** Units and balances */
227
+ balances: Record<string, number>;
228
+ };
229
+ /** Get the list of mints that are used in the wallet and their balances */
230
+ export type CashuListMintsMethod = TWalletMethod<"cashu_list_mints", {}, {
231
+ mints: CashuMintInfo[];
232
+ }>;
233
+ /** Union of all cashu methods */
234
+ export type CashuWalletMethods = CashuWithdrawMethod | CashuDepositMethod | CashuPayRequestMethod | CashuListMintsMethod;
@@ -0,0 +1 @@
1
+ export {};
@@ -1,6 +1,6 @@
1
1
  import { HiddenContentSigner, KnownEvent, UnlockedHiddenContent } from "applesauce-core/helpers";
2
2
  import { NostrEvent } from "nostr-tools";
3
- import { Transaction } from "./response.js";
3
+ import { Transaction } from "./methods.js";
4
4
  export declare const WALLET_NOTIFICATION_KIND = 23197;
5
5
  export declare const WALLET_LEGACY_NOTIFICATION_KIND = 23196;
6
6
  /** A type for validated wallet notification events */
@@ -1,131 +1,21 @@
1
1
  import { HiddenContentSigner, KnownEvent, UnlockedHiddenContent } from "applesauce-core/helpers";
2
2
  import { NostrEvent } from "nostr-tools";
3
3
  import { WalletConnectEncryptionMethod } from "./encryption.js";
4
- import { WalletMethod } from "./support.js";
4
+ import { TWalletMethod } from "./methods.js";
5
5
  export declare const WALLET_REQUEST_KIND = 23194;
6
6
  export type WalletRequestEvent = KnownEvent<typeof WALLET_REQUEST_KIND>;
7
7
  /** A symbol used to cache the wallet request on the event */
8
8
  export declare const WalletRequestSymbol: unique symbol;
9
9
  /** Type for events with unlocked hidden content */
10
- export type UnlockedWalletRequest = UnlockedHiddenContent & {
11
- [WalletRequestSymbol]: WalletRequest;
10
+ export type UnlockedWalletRequest<Method extends TWalletMethod = TWalletMethod> = UnlockedHiddenContent & {
11
+ [WalletRequestSymbol]: Method["request"];
12
12
  };
13
- /** TLV record for keysend payments */
14
- export interface TLVRecord {
15
- /** TLV type */
16
- type: number;
17
- /** Hex encoded TLV value */
18
- value: string;
19
- }
20
- /** Base request structure for all NIP-47 requests */
21
- export interface BaseWalletRequest<TMethod extends WalletMethod, TParams> {
22
- /** The method to call */
23
- method: TMethod;
24
- /** Parameters for the method */
25
- params: TParams;
26
- }
27
- /** Parameters for pay_invoice method */
28
- export interface PayInvoiceParams {
29
- /** BOLT11 invoice */
30
- invoice: string;
31
- /** Invoice amount in msats, optional */
32
- amount?: number;
33
- }
34
- export type PayInvoiceRequest = BaseWalletRequest<"pay_invoice", PayInvoiceParams>;
35
- /** Parameters for multi_pay_invoice method */
36
- export interface MultiPayInvoiceParams {
37
- /** Array of invoices to pay */
38
- invoices: Array<{
39
- /** ID to identify this invoice in the response */
40
- id?: string;
41
- /** BOLT11 invoice */
42
- invoice: string;
43
- /** Invoice amount in msats, optional */
44
- amount?: number;
45
- }>;
46
- }
47
- export type MultiPayInvoiceRequest = BaseWalletRequest<"multi_pay_invoice", MultiPayInvoiceParams>;
48
- /** Parameters for pay_keysend method */
49
- export interface PayKeysendParams {
50
- /** Amount in msats, required */
51
- amount: number;
52
- /** Payee pubkey, required */
53
- pubkey: string;
54
- /** Preimage of the payment, optional */
55
- preimage?: string;
56
- /** TLV records, optional */
57
- tlv_records?: TLVRecord[];
58
- }
59
- export type PayKeysendRequest = BaseWalletRequest<"pay_keysend", PayKeysendParams>;
60
- /** Parameters for multi_pay_keysend method */
61
- export interface MultiPayKeysendParams {
62
- /** Array of keysend payments */
63
- keysends: Array<{
64
- /** ID to identify this keysend in the response */
65
- id?: string;
66
- /** Payee pubkey, required */
67
- pubkey: string;
68
- /** Amount in msats, required */
69
- amount: number;
70
- /** Preimage of the payment, optional */
71
- preimage?: string;
72
- /** TLV records, optional */
73
- tlv_records?: TLVRecord[];
74
- }>;
75
- }
76
- export type MultiPayKeysendRequest = BaseWalletRequest<"multi_pay_keysend", MultiPayKeysendParams>;
77
- /** Parameters for make_invoice method */
78
- export interface MakeInvoiceParams {
79
- /** Value in msats */
80
- amount: number;
81
- /** Invoice's description, optional */
82
- description?: string;
83
- /** Invoice's description hash, optional */
84
- description_hash?: string;
85
- /** Expiry in seconds from time invoice is created, optional */
86
- expiry?: number;
87
- }
88
- export type MakeInvoiceRequest = BaseWalletRequest<"make_invoice", MakeInvoiceParams>;
89
- /** Parameters for lookup_invoice method */
90
- export interface LookupInvoiceParams {
91
- /** Payment hash of the invoice, one of payment_hash or invoice is required */
92
- payment_hash?: string;
93
- /** Invoice to lookup */
94
- invoice?: string;
95
- }
96
- export type LookupInvoiceRequest = BaseWalletRequest<"lookup_invoice", LookupInvoiceParams>;
97
- /** Parameters for list_transactions method */
98
- export interface ListTransactionsParams {
99
- /** Starting timestamp in seconds since epoch (inclusive), optional */
100
- from?: number;
101
- /** Ending timestamp in seconds since epoch (inclusive), optional */
102
- until?: number;
103
- /** Maximum number of invoices to return, optional */
104
- limit?: number;
105
- /** Offset of the first invoice to return, optional */
106
- offset?: number;
107
- /** Include unpaid invoices, optional, default false */
108
- unpaid?: boolean;
109
- /** "incoming" for invoices, "outgoing" for payments, undefined for both */
110
- type?: "incoming" | "outgoing";
111
- }
112
- export type ListTransactionsRequest = BaseWalletRequest<"list_transactions", ListTransactionsParams>;
113
- /** Parameters for get_balance method */
114
- export interface GetBalanceParams {
115
- }
116
- export type GetBalanceRequest = BaseWalletRequest<"get_balance", GetBalanceParams>;
117
- /** Parameters for get_info method */
118
- export interface GetInfoParams {
119
- }
120
- export type GetInfoRequest = BaseWalletRequest<"get_info", GetInfoParams>;
121
- /** Union type for all NIP-47 request types */
122
- export type WalletRequest = PayInvoiceRequest | MultiPayInvoiceRequest | PayKeysendRequest | MultiPayKeysendRequest | MakeInvoiceRequest | LookupInvoiceRequest | ListTransactionsRequest | GetBalanceRequest | GetInfoRequest;
123
13
  /** Checks if a kind 23194 event is locked */
124
- export declare function isWalletRequestUnlocked(request: any): request is UnlockedWalletRequest;
14
+ export declare function isWalletRequestUnlocked<Method extends TWalletMethod = TWalletMethod>(request: any): request is UnlockedWalletRequest<Method>;
125
15
  /** Unlocks a kind 23194 event */
126
- export declare function unlockWalletRequest(request: NostrEvent, signer: HiddenContentSigner): Promise<WalletRequest | undefined>;
16
+ export declare function unlockWalletRequest<Method extends TWalletMethod = TWalletMethod>(request: NostrEvent, signer: HiddenContentSigner): Promise<Method["request"] | undefined>;
127
17
  /** Gets the wallet request from a kind 23194 event */
128
- export declare function getWalletRequest(request: NostrEvent): WalletRequest | undefined;
18
+ export declare function getWalletRequest<Method extends TWalletMethod = TWalletMethod>(request: NostrEvent): Method["request"] | undefined;
129
19
  /** Returns the wallet service pubkey from a request */
130
20
  export declare function getWalletRequestServicePubkey(request: WalletRequestEvent): string;
131
21
  export declare function getWalletRequestServicePubkey(request: NostrEvent): string | undefined;
@@ -1,143 +1,21 @@
1
1
  import { EncryptionMethod, HiddenContentSigner, KnownEvent, UnlockedHiddenContent } from "applesauce-core/helpers";
2
2
  import { NostrEvent } from "nostr-tools";
3
- import { WalletErrorCode } from "./error.js";
4
- import { NotificationType } from "./notification.js";
5
- import { WalletMethod } from "./support.js";
3
+ import { TWalletMethod } from "./methods.js";
6
4
  export declare const WALLET_RESPONSE_KIND = 23195;
7
5
  /** A symbol used to cache the wallet response on the event */
8
6
  export declare const WalletResponseSymbol: unique symbol;
9
7
  /** Type for events with unlocked hidden content */
10
- export type UnlockedWalletResponse = UnlockedHiddenContent & {
11
- [WalletResponseSymbol]: WalletResponse;
8
+ export type UnlockedWalletResponse<Method extends TWalletMethod = TWalletMethod> = UnlockedHiddenContent & {
9
+ [WalletResponseSymbol]: Method["response"];
12
10
  };
13
11
  /** Type for validated wallet response events */
14
12
  export type WalletResponseEvent = KnownEvent<typeof WALLET_RESPONSE_KIND>;
15
- /** Error object for wallet responses */
16
- export interface WalletResponseError {
17
- type: WalletErrorCode;
18
- message: string;
19
- }
20
- /** Base response structure for all NIP-47 responses */
21
- export type BaseWalletResponse<TResultType extends WalletMethod, TResult> = {
22
- /** Indicates the structure of the result field */
23
- result_type: TResultType;
24
- /** Error object, non-null in case of error */
25
- error: WalletResponseError;
26
- result: null;
27
- } | {
28
- /** Indicates the structure of the result field */
29
- result_type: TResultType;
30
- error: null;
31
- /** Result object, null in case of error */
32
- result: TResult;
33
- };
34
- /** Transaction object used in multiple response types */
35
- export interface Transaction {
36
- /** Type of transaction */
37
- type: "incoming" | "outgoing";
38
- /** State of the transaction */
39
- state: "pending" | "settled" | "expired" | "failed";
40
- /** Value in msats */
41
- amount: number;
42
- /** Value in msats */
43
- fees_paid: number;
44
- /** Invoice/payment creation unix timestamp */
45
- created_at: number;
46
- /** Encoded invoice, optional */
47
- invoice?: string;
48
- /** Invoice's description, optional */
49
- description?: string;
50
- /** Invoice's description hash, optional */
51
- description_hash?: string;
52
- /** Payment's preimage, optional if unpaid */
53
- preimage?: string;
54
- /** Payment hash for the payment, optional */
55
- payment_hash?: string;
56
- /** Invoice expiration unix timestamp, optional if not applicable */
57
- expires_at?: number;
58
- /** Invoice/payment settlement unix timestamp, optional if unpaid */
59
- settled_at?: number;
60
- /** Generic metadata that can be used to add things like zap/boostagram details */
61
- metadata?: Record<string, any>;
62
- }
63
- /** Response for pay_invoice method */
64
- export interface PayInvoiceResult {
65
- /** Preimage of the payment */
66
- preimage: string;
67
- /** Value in msats, optional */
68
- fees_paid?: number;
69
- }
70
- export type PayInvoiceResponse = BaseWalletResponse<"pay_invoice", PayInvoiceResult>;
71
- /** Response for multi_pay_invoice method */
72
- export interface MultiPayInvoiceResult {
73
- /** Preimage of the payment */
74
- preimage: string;
75
- /** Value in msats, optional */
76
- fees_paid?: number;
77
- }
78
- export type MultiPayInvoiceResponse = BaseWalletResponse<"multi_pay_invoice", MultiPayInvoiceResult>;
79
- /** Response for pay_keysend method */
80
- export interface PayKeysendResult {
81
- /** Preimage of the payment */
82
- preimage: string;
83
- /** Value in msats, optional */
84
- fees_paid?: number;
85
- }
86
- export type PayKeysendResponse = BaseWalletResponse<"pay_keysend", PayKeysendResult>;
87
- /** Response for multi_pay_keysend method */
88
- export interface MultiPayKeysendResult {
89
- /** Preimage of the payment */
90
- preimage: string;
91
- /** Value in msats, optional */
92
- fees_paid?: number;
93
- }
94
- export type MultiPayKeysendResponse = BaseWalletResponse<"multi_pay_keysend", MultiPayKeysendResult>;
95
- /** Response for make_invoice method */
96
- export type MakeInvoiceResult = Transaction;
97
- export type MakeInvoiceResponse = BaseWalletResponse<"make_invoice", MakeInvoiceResult>;
98
- /** Response for lookup_invoice method */
99
- export type LookupInvoiceResult = Transaction;
100
- export type LookupInvoiceResponse = BaseWalletResponse<"lookup_invoice", LookupInvoiceResult>;
101
- /** Response for list_transactions method */
102
- export interface ListTransactionsResult {
103
- /** Array of transactions */
104
- transactions: Transaction[];
105
- }
106
- export type ListTransactionsResponse = BaseWalletResponse<"list_transactions", ListTransactionsResult>;
107
- /** Response for get_balance method */
108
- export interface GetBalanceResult {
109
- /** User's balance in msats */
110
- balance: number;
111
- }
112
- export type GetBalanceResponse = BaseWalletResponse<"get_balance", GetBalanceResult>;
113
- /** Response for get_info method */
114
- export interface GetInfoResult {
115
- /** Node alias */
116
- alias: string;
117
- /** Node color as hex string */
118
- color: string;
119
- /** Node public key as hex string */
120
- pubkey: string;
121
- /** Network type */
122
- network: "mainnet" | "testnet" | "signet" | "regtest";
123
- /** Current block height */
124
- block_height: number;
125
- /** Current block hash as hex string */
126
- block_hash: string;
127
- /** List of supported methods for this connection */
128
- methods: WalletMethod[];
129
- /** List of supported notifications for this connection, optional */
130
- notifications?: NotificationType[];
131
- }
132
- export type GetInfoResponse = BaseWalletResponse<"get_info", GetInfoResult>;
133
- /** Union type for all NIP-47 response types */
134
- export type WalletResponse = PayInvoiceResponse | MultiPayInvoiceResponse | PayKeysendResponse | MultiPayKeysendResponse | MakeInvoiceResponse | LookupInvoiceResponse | ListTransactionsResponse | GetBalanceResponse | GetInfoResponse;
135
13
  /** Checks if a kind 23195 event is locked */
136
- export declare function isWalletResponseUnlocked(response: any): response is UnlockedWalletResponse;
14
+ export declare function isWalletResponseUnlocked<Method extends TWalletMethod = TWalletMethod>(response: any): response is UnlockedWalletResponse<Method>;
137
15
  /** Unlocks a kind 23195 event */
138
- export declare function unlockWalletResponse(response: NostrEvent, signer: HiddenContentSigner, override?: EncryptionMethod): Promise<WalletResponse | undefined>;
16
+ export declare function unlockWalletResponse<Method extends TWalletMethod = TWalletMethod>(response: NostrEvent, signer: HiddenContentSigner, override?: EncryptionMethod): Promise<Method["response"] | undefined>;
139
17
  /** Gets the wallet response from a kind 23195 event */
140
- export declare function getWalletResponse(response: NostrEvent): WalletResponse | undefined;
18
+ export declare function getWalletResponse<Method extends TWalletMethod = TWalletMethod>(response: NostrEvent): Method["response"] | undefined;
141
19
  /** Returns the client pubkey of client this response is for */
142
20
  export declare function getWalletResponseClientPubkey(response: WalletResponseEvent): string;
143
21
  export declare function getWalletResponseClientPubkey(response: NostrEvent): string | undefined;
@@ -1,21 +1,21 @@
1
1
  import { NostrEvent } from "nostr-tools";
2
2
  import { WalletConnectEncryptionMethod } from "./encryption.js";
3
- import { NotificationType as NotificationType } from "./notification.js";
3
+ import { TWalletMethod } from "./methods.js";
4
+ import { NotificationType } from "./notification.js";
4
5
  export declare const WALLET_INFO_KIND = 13194;
5
6
  /** A symbol used to cache the wallet info on the event */
6
7
  export declare const WalletInfoSymbol: unique symbol;
7
- export type WalletMethod = "pay_invoice" | "multi_pay_invoice" | "pay_keysend" | "multi_pay_keysend" | "make_invoice" | "lookup_invoice" | "list_transactions" | "get_balance" | "get_info";
8
8
  /** Wallet service capabilities and information */
9
- export interface WalletSupport {
9
+ export interface WalletSupport<Methods extends TWalletMethod = TWalletMethod> {
10
10
  /** List of supported methods for this wallet service */
11
- methods: WalletMethod[];
11
+ methods: Array<Methods["method"]>;
12
12
  /** List of supported encryption methods */
13
13
  encryption: WalletConnectEncryptionMethod[];
14
14
  /** List of supported notifications, optional */
15
15
  notifications?: NotificationType[];
16
16
  }
17
17
  /** Gets the wallet info from a kind 13194 event */
18
- export declare function getWalletSupport(info: NostrEvent): WalletSupport | null;
18
+ export declare function getWalletSupport<Methods extends TWalletMethod = TWalletMethod>(info: NostrEvent): WalletSupport<Methods> | null;
19
19
  /** Gets the encryption methods from a wallet info event */
20
20
  export declare function getEncryptionMethods(info: NostrEvent | WalletSupport): WalletConnectEncryptionMethod[];
21
21
  /** Checks if the wallet service supports a specific encryption method */
@@ -23,12 +23,12 @@ export declare function supportsEncryption(info: NostrEvent | WalletSupport, enc
23
23
  /** Gets the preferred encryption method (nip44_v2 preferred over nip04) */
24
24
  export declare function getPreferredEncryption(info: NostrEvent | WalletSupport): WalletConnectEncryptionMethod;
25
25
  /** Checks if the wallet service supports a specific method */
26
- export declare function supportsMethod(info: NostrEvent | WalletSupport, method: WalletMethod): boolean;
26
+ export declare function supportsMethod(info: NostrEvent | WalletSupport, method: string): boolean;
27
27
  /** Checks if the wallet service supports notifications */
28
28
  export declare function supportsNotifications(info: NostrEvent | WalletSupport): boolean;
29
29
  /** Checks if the wallet service supports a specific notification type */
30
30
  export declare function supportsNotificationType(info: NostrEvent | WalletSupport, notificationType: NotificationType): boolean;
31
31
  /** Gets all supported methods from the wallet info */
32
- export declare function getSupportedMethods(info: NostrEvent | WalletSupport): WalletMethod[];
32
+ export declare function getSupportedMethods(info: NostrEvent | WalletSupport): string[];
33
33
  /** Gets all supported notifications from the wallet info */
34
34
  export declare function getSupportedNotifications(info: NostrEvent | WalletSupport): NotificationType[];
@@ -12,20 +12,7 @@ export function getWalletSupport(info) {
12
12
  return null;
13
13
  // Parse methods from content (space-separated)
14
14
  const contentParts = content.split(/\s+/);
15
- const methods = contentParts
16
- .filter((part) => [
17
- "pay_invoice",
18
- "multi_pay_invoice",
19
- "pay_keysend",
20
- "multi_pay_keysend",
21
- "make_invoice",
22
- "lookup_invoice",
23
- "list_transactions",
24
- "get_balance",
25
- "get_info",
26
- "notifications",
27
- ].includes(part))
28
- .filter((part) => part !== "notifications");
15
+ const methods = contentParts.filter((part) => part !== "notifications");
29
16
  // Parse encryption methods from encryption tag
30
17
  const encryptionTag = getTagValue(info, "encryption");
31
18
  const encryption = encryptionTag
@@ -2,7 +2,8 @@ import { EncryptionMethod } from "applesauce-core/helpers";
2
2
  import { EventSigner } from "applesauce-factory";
3
3
  import { NostrEvent } from "nostr-tools";
4
4
  import { BehaviorSubject, Observable, Subscription } from "rxjs";
5
- import { GetBalanceResult, GetInfoResult, ListTransactionsResult, LookupInvoiceResult, MakeInvoiceParams, MakeInvoiceResult, NotificationType, PayInvoiceResult, PayKeysendResult, WalletAuthURI, WalletConnectEncryptionMethod, WalletConnectURI, WalletMethod, WalletNotification, WalletNotificationEvent, WalletRequest, WalletResponse, WalletResponseEvent, WalletSupport } from "./helpers/index.js";
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
7
  import { NostrConnectionMethodsOptions, NostrPool, NostrPublishMethod, NostrSubscriptionMethod } from "./interop.js";
7
8
  export type SerializedWalletConnect = WalletConnectURI;
8
9
  export type WalletConnectOptions = NostrConnectionMethodsOptions & {
@@ -17,7 +18,7 @@ export type WalletConnectOptions = NostrConnectionMethodsOptions & {
17
18
  /** Whether to accept the relay hint from the wallet service */
18
19
  acceptRelayHint?: boolean;
19
20
  };
20
- export declare class WalletConnect {
21
+ export declare class WalletConnect<Methods extends TWalletMethod = CommonWalletMethods> {
21
22
  /** A fallback method to use for subscriptionMethod if none is passed in when creating the client */
22
23
  static subscriptionMethod: NostrSubscriptionMethod | undefined;
23
24
  /** A fallback method to use for publishMethod if none is passed in when creating the client */
@@ -53,43 +54,65 @@ export declare class WalletConnect {
53
54
  protected waitForService$: Observable<string>;
54
55
  constructor(options: WalletConnectOptions);
55
56
  /** Process response events and return WalletResponse or throw error */
56
- protected handleResponseEvent(event: WalletResponseEvent, encryption?: EncryptionMethod): Promise<WalletResponse>;
57
+ protected handleResponseEvent<Method extends Methods>(event: WalletResponseEvent, encryption?: EncryptionMethod): Promise<Method["response"]>;
57
58
  /** Handle notification events */
58
59
  protected handleNotificationEvent(event: WalletNotificationEvent): Promise<WalletNotification>;
59
- /** Core RPC method that makes a request and returns the response */
60
- request(request: WalletRequest, options?: {
60
+ /** Generic call method with generic type */
61
+ genericCall<Method extends TWalletMethod>(method: Method["method"], params: Method["request"]["params"], options?: {
61
62
  timeout?: number;
62
- }): Observable<WalletResponse>;
63
+ }): Observable<Method["response"] | Method["error"]>;
64
+ /** Request method with generic type */
65
+ genericRequest<Method extends TWalletMethod>(method: Method["method"], params: Method["request"]["params"], options?: {
66
+ timeout?: number;
67
+ }): Promise<Method["response"]["result"]>;
68
+ /** Call a method and return an observable of results */
69
+ call<K extends Methods["method"]>(method: K, params: Extract<Methods, {
70
+ method: K;
71
+ }>["request"]["params"], options?: {
72
+ timeout?: number;
73
+ }): Observable<Extract<Methods, {
74
+ method: K;
75
+ }>["response"] | Extract<Methods, {
76
+ method: K;
77
+ }>["error"]>;
78
+ /** Typed request method, returns the result or throws and error */
79
+ request<K extends Methods["method"]>(method: K, params: Extract<Methods, {
80
+ method: K;
81
+ }>["request"]["params"], options?: {
82
+ timeout?: number;
83
+ }): Promise<Extract<Methods, {
84
+ method: K;
85
+ }>["response"]["result"]>;
63
86
  /**
64
87
  * Listen for a type of notification
65
88
  * @returns a method to unsubscribe the listener
66
89
  */
67
90
  notification<T extends WalletNotification>(type: T["notification_type"], listener: (notification: T["notification"]) => any): Subscription;
68
91
  /** Gets the nostr+walletauth URI for the connection */
69
- getAuthURI(parts?: Omit<WalletAuthURI, "client" | "relays">): string;
92
+ getAuthURI(parts?: Omit<WalletAuthURI<Methods>, "client" | "relays">): string;
70
93
  /** Wait for the wallet service to connect */
71
94
  waitForService(abortSignal?: AbortSignal): Promise<string>;
72
95
  /** Get the wallet support info */
73
96
  getSupport(): Promise<WalletSupport | null>;
74
97
  /** Check if the wallet supports a method */
75
- supportsMethod(method: WalletMethod): Promise<boolean>;
98
+ supportsMethod(method: string): Promise<boolean>;
76
99
  /** Check if the wallet supports notifications */
77
100
  supportsNotifications(): Promise<boolean>;
78
101
  /** Check if the wallet supports a notification type */
79
102
  supportsNotificationType(type: NotificationType): Promise<boolean>;
80
103
  /** Pay a lightning invoice */
81
- payInvoice(invoice: string, amount?: number): Promise<PayInvoiceResult>;
104
+ payInvoice(invoice: string, amount?: number): Promise<PayInvoiceMethod["response"]["result"]>;
82
105
  /** Pay multiple lightning invoices */
83
106
  payMultipleInvoices(invoices: Array<{
84
107
  id?: string;
85
108
  invoice: string;
86
109
  amount?: number;
87
- }>): Promise<PayInvoiceResult[]>;
110
+ }>): Promise<MultiPayInvoiceMethod["response"]["result"][]>;
88
111
  /** Send a keysend payment */
89
112
  payKeysend(pubkey: string, amount: number, preimage?: string, tlv_records?: Array<{
90
113
  type: number;
91
114
  value: string;
92
- }>): Promise<PayKeysendResult>;
115
+ }>): Promise<PayKeysendMethod["response"]["result"]>;
93
116
  /** Send multiple keysend payments */
94
117
  payMultipleKeysend(keysends: Array<{
95
118
  id?: string;
@@ -100,11 +123,11 @@ export declare class WalletConnect {
100
123
  type: number;
101
124
  value: string;
102
125
  }>;
103
- }>): Promise<PayKeysendResult[]>;
126
+ }>): Promise<MultiPayKeysendMethod["response"]["result"][]>;
104
127
  /** Create a new invoice */
105
- makeInvoice(amount: number, options?: Omit<MakeInvoiceParams, "amount">): Promise<MakeInvoiceResult>;
128
+ makeInvoice(amount: number, options?: Omit<MakeInvoiceMethod["request"]["params"], "amount">): Promise<MakeInvoiceMethod["response"]["result"]>;
106
129
  /** Look up an invoice by payment hash or invoice string */
107
- lookupInvoice(payment_hash?: string, invoice?: string): Promise<LookupInvoiceResult>;
130
+ lookupInvoice(payment_hash?: string, invoice?: string): Promise<LookupInvoiceMethod["response"]["result"]>;
108
131
  /** List transactions */
109
132
  listTransactions(params?: {
110
133
  from?: number;
@@ -113,15 +136,15 @@ export declare class WalletConnect {
113
136
  offset?: number;
114
137
  unpaid?: boolean;
115
138
  type?: "incoming" | "outgoing";
116
- }): Promise<ListTransactionsResult>;
139
+ }): Promise<ListTransactionsMethod["response"]["result"]>;
117
140
  /** Get wallet balance */
118
- getBalance(): Promise<GetBalanceResult>;
141
+ getBalance(): Promise<GetBalanceMethod["response"]["result"]>;
119
142
  /** Get wallet info */
120
- getInfo(): Promise<GetInfoResult>;
143
+ getInfo(): Promise<GetInfoMethod["response"]["result"]>;
121
144
  /** Serialize the WalletConnect instance */
122
145
  toJSON(): SerializedWalletConnect;
123
146
  /** Create a new WalletConnect instance from a serialized object */
124
147
  static fromJSON(json: SerializedWalletConnect, options?: Omit<WalletConnectOptions, "secret" | "relays" | "service">): WalletConnect;
125
148
  /** Create a new WalletConnect instance from a connection string */
126
- static fromConnectURI(connectionString: string, options?: Omit<WalletConnectOptions, "secret" | "relays" | "service">): WalletConnect;
149
+ static fromConnectURI<Methods extends TWalletMethod = CommonWalletMethods>(connectionString: string, options?: Omit<WalletConnectOptions, "secret" | "relays" | "service">): WalletConnect<Methods>;
127
150
  }
@@ -157,8 +157,8 @@ export class WalletConnect {
157
157
  throw new Error("Failed to decrypt or parse notification");
158
158
  return notification;
159
159
  }
160
- /** Core RPC method that makes a request and returns the response */
161
- request(request, options = {}) {
160
+ /** Generic call method with generic type */
161
+ genericCall(method, params, options = {}) {
162
162
  if (!this.service)
163
163
  throw new Error("WalletConnect is not connected to a service");
164
164
  // Create the request event
@@ -166,7 +166,7 @@ export class WalletConnect {
166
166
  // Get the preferred encryption method for the wallet
167
167
  const encryption = await firstValueFrom(this.encryption$);
168
168
  // Create the request event
169
- const draft = await create({ signer: this.signer }, WalletRequestBlueprint, this.service, request, encryption);
169
+ const draft = await create({ signer: this.signer }, WalletRequestBlueprint, this.service, { method, params }, encryption);
170
170
  // Sign the request event
171
171
  return await this.signer.signEvent(draft);
172
172
  }).pipe(
@@ -182,6 +182,23 @@ export class WalletConnect {
182
182
  return merge(request$, responses$);
183
183
  }));
184
184
  }
185
+ /** Request method with generic type */
186
+ async genericRequest(method, params, options = {}) {
187
+ const result = await firstValueFrom(this.genericCall(method, params, options));
188
+ if (result.result_type !== method)
189
+ throw new Error(`Unexpected response type: ${result.result_type}`);
190
+ if (result.error)
191
+ throw createWalletError(result.error.type, result.error.message);
192
+ return result.result;
193
+ }
194
+ /** Call a method and return an observable of results */
195
+ call(method, params, options = {}) {
196
+ return this.genericCall(method, params, options);
197
+ }
198
+ /** Typed request method, returns the result or throws and error */
199
+ async request(method, params, options = {}) {
200
+ return this.genericRequest(method, params, options);
201
+ }
185
202
  /**
186
203
  * Listen for a type of notification
187
204
  * @returns a method to unsubscribe the listener
@@ -224,18 +241,14 @@ export class WalletConnect {
224
241
  const support = await this.getSupport();
225
242
  return support ? supportsNotificationType(support, type) : false;
226
243
  }
244
+ // Methods for common types
227
245
  /** Pay a lightning invoice */
228
246
  async payInvoice(invoice, amount) {
229
- const response = await firstValueFrom(this.request({ method: "pay_invoice", params: { invoice, amount } }));
230
- if (response.result_type !== "pay_invoice")
231
- throw new Error(`Unexpected response type: ${response.result_type}`);
232
- if (response.error)
233
- throw createWalletError(response.error.type, response.error.message);
234
- return response.result;
247
+ return await this.genericRequest("pay_invoice", { invoice, amount });
235
248
  }
236
249
  /** Pay multiple lightning invoices */
237
250
  async payMultipleInvoices(invoices) {
238
- return await lastValueFrom(this.request({ method: "multi_pay_invoice", params: { invoices } })
251
+ return await lastValueFrom(this.genericCall("multi_pay_invoice", { invoices })
239
252
  .pipe(map((response) => {
240
253
  if (response.result_type !== "multi_pay_invoice")
241
254
  throw new Error(`Unexpected response type: ${response.result_type}`);
@@ -247,16 +260,11 @@ export class WalletConnect {
247
260
  }
248
261
  /** Send a keysend payment */
249
262
  async payKeysend(pubkey, amount, preimage, tlv_records) {
250
- const response = await firstValueFrom(this.request({ method: "pay_keysend", params: { pubkey, amount, preimage, tlv_records } }));
251
- if (response.result_type !== "pay_keysend")
252
- throw new Error(`Unexpected response type: ${response.result_type}`);
253
- if (response.error)
254
- throw createWalletError(response.error.type, response.error.message);
255
- return response.result;
263
+ return await this.genericRequest("pay_keysend", { pubkey, amount, preimage, tlv_records });
256
264
  }
257
265
  /** Send multiple keysend payments */
258
266
  async payMultipleKeysend(keysends) {
259
- return lastValueFrom(this.request({ method: "multi_pay_keysend", params: { keysends } }).pipe(map((response) => {
267
+ return lastValueFrom(this.genericCall("multi_pay_keysend", { keysends }).pipe(map((response) => {
260
268
  if (response.result_type !== "multi_pay_keysend")
261
269
  throw new Error(`Unexpected response type: ${response.result_type}`);
262
270
  if (response.error)
@@ -266,48 +274,23 @@ export class WalletConnect {
266
274
  }
267
275
  /** Create a new invoice */
268
276
  async makeInvoice(amount, options) {
269
- const response = await firstValueFrom(this.request({ method: "make_invoice", params: { amount, ...options } }));
270
- if (response.result_type !== "make_invoice")
271
- throw new Error(`Unexpected response type: ${response.result_type}`);
272
- if (response.error)
273
- throw createWalletError(response.error.type, response.error.message);
274
- return response.result;
277
+ return await this.genericRequest("make_invoice", { amount, ...options });
275
278
  }
276
279
  /** Look up an invoice by payment hash or invoice string */
277
280
  async lookupInvoice(payment_hash, invoice) {
278
- const response = await firstValueFrom(this.request({ method: "lookup_invoice", params: { payment_hash, invoice } }));
279
- if (response.result_type !== "lookup_invoice")
280
- throw new Error(`Unexpected response type: ${response.result_type}`);
281
- if (response.error)
282
- throw createWalletError(response.error.type, response.error.message);
283
- return response.result;
281
+ return await this.genericRequest("lookup_invoice", { payment_hash, invoice });
284
282
  }
285
283
  /** List transactions */
286
284
  async listTransactions(params) {
287
- const response = await firstValueFrom(this.request({ method: "list_transactions", params: params || {} }));
288
- if (response.result_type !== "list_transactions")
289
- throw new Error(`Unexpected response type: ${response.result_type}`);
290
- if (response.error)
291
- throw createWalletError(response.error.type, response.error.message);
292
- return response.result;
285
+ return await this.genericRequest("list_transactions", params || {});
293
286
  }
294
287
  /** Get wallet balance */
295
288
  async getBalance() {
296
- const response = await firstValueFrom(this.request({ method: "get_balance", params: {} }));
297
- if (response.result_type !== "get_balance")
298
- throw new Error(`Unexpected response type: ${response.result_type}`);
299
- if (response.error)
300
- throw createWalletError(response.error.type, response.error.message);
301
- return response.result;
289
+ return await this.genericRequest("get_balance", {});
302
290
  }
303
291
  /** Get wallet info */
304
292
  async getInfo() {
305
- const response = await firstValueFrom(this.request({ method: "get_info", params: {} }));
306
- if (response.result_type !== "get_info")
307
- throw new Error(`Unexpected response type: ${response.result_type}`);
308
- if (response.error)
309
- throw createWalletError(response.error.type, response.error.message);
310
- return response.result;
293
+ return await this.genericRequest("get_info", {});
311
294
  }
312
295
  /** Serialize the WalletConnect instance */
313
296
  toJSON() {
@@ -2,49 +2,30 @@ import { EventSigner } from "applesauce-factory";
2
2
  import { Observable, Subscription } from "rxjs";
3
3
  import { WalletAuthURI } from "./helpers/auth-uri.js";
4
4
  import { WalletErrorCode } from "./helpers/error.js";
5
+ import { CommonWalletMethods, TWalletMethod, WalletInfo } from "./helpers/methods.js";
5
6
  import { NotificationType, WalletNotification } from "./helpers/notification.js";
6
- import { GetBalanceParams, GetInfoParams, ListTransactionsParams, LookupInvoiceParams, MakeInvoiceParams, MultiPayInvoiceParams, MultiPayKeysendParams, PayInvoiceParams, PayKeysendParams, WalletRequest, WalletRequestEvent } from "./helpers/request.js";
7
- import { GetBalanceResult, GetInfoResult, ListTransactionsResult, LookupInvoiceResult, MakeInvoiceResult, MultiPayInvoiceResult, MultiPayKeysendResult, PayInvoiceResult, PayKeysendResult, WalletResponse } from "./helpers/response.js";
7
+ import { WalletRequestEvent } from "./helpers/request.js";
8
8
  import { WalletSupport } from "./helpers/support.js";
9
9
  import { NostrConnectionMethodsOptions, NostrPool, NostrPublishMethod, NostrSubscriptionMethod } from "./interop.js";
10
- /** Handler function for pay_invoice method */
11
- export type PayInvoiceHandler = (params: PayInvoiceParams) => Promise<PayInvoiceResult>;
12
- /** Handler function for multi_pay_invoice method */
13
- export type MultiPayInvoiceHandler = (params: MultiPayInvoiceParams) => Promise<MultiPayInvoiceResult[]>;
14
- /** Handler function for pay_keysend method */
15
- export type PayKeysendHandler = (params: PayKeysendParams) => Promise<PayKeysendResult>;
16
- /** Handler function for multi_pay_keysend method */
17
- export type MultiPayKeysendHandler = (params: MultiPayKeysendParams) => Promise<MultiPayKeysendResult[]>;
18
- /** Handler function for make_invoice method */
19
- export type MakeInvoiceHandler = (params: MakeInvoiceParams) => Promise<MakeInvoiceResult>;
20
- /** Handler function for lookup_invoice method */
21
- export type LookupInvoiceHandler = (params: LookupInvoiceParams) => Promise<LookupInvoiceResult>;
22
- /** Handler function for list_transactions method */
23
- export type ListTransactionsHandler = (params: ListTransactionsParams) => Promise<ListTransactionsResult>;
24
- /** Handler function for get_balance method */
25
- export type GetBalanceHandler = (params: GetBalanceParams) => Promise<GetBalanceResult>;
26
- /** Handler function for get_info method */
27
- export type GetInfoHandler = (params: GetInfoParams) => Promise<GetInfoResult>;
28
- /** Map of method handlers for the wallet service */
29
- export interface WalletServiceHandlers {
30
- pay_invoice?: PayInvoiceHandler;
31
- multi_pay_invoice?: MultiPayInvoiceHandler;
32
- pay_keysend?: PayKeysendHandler;
33
- multi_pay_keysend?: MultiPayKeysendHandler;
34
- make_invoice?: MakeInvoiceHandler;
35
- lookup_invoice?: LookupInvoiceHandler;
36
- list_transactions?: ListTransactionsHandler;
37
- get_balance?: GetBalanceHandler;
38
- get_info?: GetInfoHandler;
39
- }
10
+ /** Generic type for wallet method handlers */
11
+ export type WalletMethodHandler<Method extends TWalletMethod> = (params: Method["request"]["params"]) => Promise<Method["response"]["result"]>;
12
+ /** Map of method handlers for the wallet service for a specific set of methods */
13
+ export type WalletServiceHandlers<Methods extends TWalletMethod = TWalletMethod> = {
14
+ [K in Methods["method"]]?: WalletMethodHandler<Extract<Methods, {
15
+ method: K;
16
+ }>>;
17
+ };
18
+ /** Serialized wallet service */
40
19
  export type SerializedWalletService = {
41
20
  /** The client's public key */
42
21
  client: string;
43
22
  /** The relays to use for the service */
44
23
  relays: string[];
45
24
  };
25
+ /** Only the necessary info for the getInfo method on wallet service */
26
+ export type WalletServiceInfo = Partial<Omit<WalletInfo, "methods" | "notifications">>;
46
27
  /** Options for creating a WalletService */
47
- export interface WalletServiceOptions extends NostrConnectionMethodsOptions {
28
+ export interface WalletServiceOptions<Methods extends TWalletMethod = CommonWalletMethods> extends NostrConnectionMethodsOptions {
48
29
  /** The relays to use for the service */
49
30
  relays: string[];
50
31
  /** The signer to use for creating and unlocking events */
@@ -53,13 +34,15 @@ export interface WalletServiceOptions extends NostrConnectionMethodsOptions {
53
34
  secret?: Uint8Array;
54
35
  /** The client's public key (used for restoring the service) */
55
36
  client?: string;
37
+ /** A method for getting the general wallet information (Can be overwritten if get_info is set in handlers) */
38
+ getInfo?: () => Promise<WalletServiceInfo>;
56
39
  /** Map of method handlers */
57
- handlers: WalletServiceHandlers;
40
+ handlers: WalletServiceHandlers<Methods>;
58
41
  /** An array of notifications this wallet supports */
59
42
  notifications?: NotificationType[];
60
43
  }
61
44
  /** NIP-47 Wallet Service implementation */
62
- export declare class WalletService {
45
+ export declare class WalletService<Methods extends TWalletMethod = CommonWalletMethods> {
63
46
  /** A fallback method to use for subscriptionMethod if none is passed in when creating the client */
64
47
  static subscriptionMethod: NostrSubscriptionMethod | undefined;
65
48
  /** A fallback method to use for publishMethod if none is passed in when creating the client */
@@ -71,14 +54,16 @@ export declare class WalletService {
71
54
  /** A method for publishing events */
72
55
  protected readonly publishMethod: NostrPublishMethod;
73
56
  protected log: import("debug").Debugger;
57
+ /** A special method for getting the generic wallet information */
58
+ getInfo?: () => Promise<WalletServiceInfo>;
74
59
  /** The relays to use for the service */
75
60
  readonly relays: string[];
76
61
  /** The signer used for creating and unlocking events */
77
62
  protected readonly signer: EventSigner;
78
63
  /** Map of method handlers */
79
- protected readonly handlers: WalletServiceHandlers;
64
+ protected readonly handlers: WalletServiceHandlers<Methods>;
80
65
  /** Wallet support information */
81
- protected readonly support: WalletSupport;
66
+ protected readonly support: WalletSupport<Methods>;
82
67
  /** The service's public key */
83
68
  pubkey: string | null;
84
69
  /** The client's secret key */
@@ -91,7 +76,7 @@ export declare class WalletService {
91
76
  protected subscription: Subscription | null;
92
77
  /** Whether the service is currently running */
93
78
  running: boolean;
94
- constructor(options: WalletServiceOptions);
79
+ constructor(options: WalletServiceOptions<Methods>);
95
80
  /** Start the wallet service */
96
81
  start(): Promise<void>;
97
82
  /** Stop the wallet service */
@@ -107,16 +92,16 @@ export declare class WalletService {
107
92
  /** Handle a wallet request event */
108
93
  protected handleRequestEvent(requestEvent: WalletRequestEvent): Promise<void>;
109
94
  /** Process a decrypted wallet request */
110
- protected processRequest(requestEvent: WalletRequestEvent, request: WalletRequest): Promise<void>;
95
+ protected processRequest<Method extends Methods>(requestEvent: WalletRequestEvent, request: Method["request"]): Promise<void>;
111
96
  /** Send a success response */
112
- protected sendSuccessResponse<T extends WalletResponse>(requestEvent: WalletRequestEvent, method: T["result_type"], result: T["result"]): Promise<void>;
97
+ protected sendSuccessResponse<Method extends Methods>(requestEvent: WalletRequestEvent, method: Method["response"]["result_type"], result: Method["response"]["result"]): Promise<void>;
113
98
  /** Send an error response */
114
- protected sendErrorResponse(requestEvent: WalletRequestEvent, errorType: WalletErrorCode, errorMessage: string): Promise<void>;
99
+ protected sendErrorResponse<Method extends Methods>(requestEvent: WalletRequestEvent, errorType: WalletErrorCode, errorMessage: string): Promise<void>;
115
100
  /** Send a response event */
116
- protected sendResponse(requestEvent: WalletRequestEvent, response: WalletResponse): Promise<void>;
101
+ protected sendResponse<Method extends Methods>(requestEvent: WalletRequestEvent, response: Method["response"] | Method["error"]): Promise<void>;
117
102
  /** Creates a service for a nostr+walletauth URI */
118
- static fromAuthURI(uri: string | WalletAuthURI, options: Omit<WalletServiceOptions, "relays"> & {
103
+ static fromAuthURI<Methods extends TWalletMethod = CommonWalletMethods>(uri: string | WalletAuthURI, options: Omit<WalletServiceOptions<Methods>, "relays"> & {
119
104
  /** A relay or method to select a single relay for the client and service to communicate over */
120
105
  overrideRelay?: string | ((relays: string[]) => string);
121
- }): WalletService;
106
+ }): WalletService<Methods>;
122
107
  }
@@ -7,7 +7,7 @@ import { WalletLegacyNotificationBlueprint, WalletNotificationBlueprint } from "
7
7
  import { WalletResponseBlueprint } from "./blueprints/response.js";
8
8
  import { WalletSupportBlueprint } from "./blueprints/support.js";
9
9
  import { parseWalletAuthURI } from "./helpers/auth-uri.js";
10
- import { WalletBaseError } from "./helpers/error.js";
10
+ import { NotImplementedError, WalletBaseError } from "./helpers/error.js";
11
11
  import { getWalletRequest, isValidWalletRequest, isWalletRequestExpired, unlockWalletRequest, WALLET_REQUEST_KIND, } from "./helpers/request.js";
12
12
  import { getConnectionMethods, } from "./interop.js";
13
13
  /** NIP-47 Wallet Service implementation */
@@ -23,6 +23,8 @@ export class WalletService {
23
23
  /** A method for publishing events */
24
24
  publishMethod;
25
25
  log = logger.extend("WalletService");
26
+ /** A special method for getting the generic wallet information */
27
+ getInfo;
26
28
  /** The relays to use for the service */
27
29
  relays;
28
30
  /** The signer used for creating and unlocking events */
@@ -164,7 +166,7 @@ export class WalletService {
164
166
  try {
165
167
  // Tell the client which relay to use if there is only one (for nostr+walletauth URI connections)
166
168
  const overrideRelay = this.relays.length === 1 ? this.relays[0] : undefined;
167
- const draft = await create({ signer: this.signer }, WalletSupportBlueprint, this.support, this.client, overrideRelay);
169
+ const draft = await create({ signer: this.signer }, (WalletSupportBlueprint), this.support, this.client, overrideRelay);
168
170
  const event = await this.signer.signEvent(draft);
169
171
  await this.publishMethod(this.relays, event);
170
172
  }
@@ -194,44 +196,27 @@ export class WalletService {
194
196
  /** Process a decrypted wallet request */
195
197
  async processRequest(requestEvent, request) {
196
198
  const handler = this.handlers[request.method];
197
- if (!handler) {
198
- await this.sendErrorResponse(requestEvent, "NOT_IMPLEMENTED", `Method ${request.method} not supported`);
199
- return;
200
- }
201
199
  try {
202
- let result;
203
- const method = request.method; // Store method for use in catch block
204
- switch (method) {
205
- case "pay_invoice":
206
- result = await handler(request.params);
207
- break;
208
- case "multi_pay_invoice":
209
- result = await handler(request.params);
210
- break;
211
- case "pay_keysend":
212
- result = await handler(request.params);
213
- break;
214
- case "multi_pay_keysend":
215
- result = await handler(request.params);
216
- break;
217
- case "make_invoice":
218
- result = await handler(request.params);
219
- break;
220
- case "lookup_invoice":
221
- result = await handler(request.params);
222
- break;
223
- case "list_transactions":
224
- result = await handler(request.params);
225
- break;
226
- case "get_balance":
227
- result = await handler(request.params);
228
- break;
229
- case "get_info":
230
- result = await handler(request.params);
231
- break;
200
+ let result = undefined;
201
+ // If the user has not implemented the method
202
+ if (!handler) {
203
+ // If its the get_info try to use the builtin getInfo method
204
+ if (request.method === "get_info") {
205
+ result = { ...(this.getInfo?.() ?? {}), ...this.support };
206
+ }
207
+ else {
208
+ // Else throw not supported error
209
+ throw new NotImplementedError(`Method ${request.method} not supported`);
210
+ }
232
211
  }
212
+ // Otherwise use the user provided handler
213
+ if (!result && handler)
214
+ result = await handler(request.params);
215
+ // Throw if failed to get result
216
+ if (!result)
217
+ throw new NotImplementedError(`Method ${request.method} not supported`);
233
218
  // Send success response
234
- await this.sendSuccessResponse(requestEvent, method, result);
219
+ await this.sendSuccessResponse(requestEvent, request.method, result);
235
220
  }
236
221
  catch (error) {
237
222
  this.log(`Error executing ${request.method}:`, error);
@@ -275,7 +260,7 @@ export class WalletService {
275
260
  /** Send a response event */
276
261
  async sendResponse(requestEvent, response) {
277
262
  try {
278
- const draft = await create({ signer: this.signer }, WalletResponseBlueprint, requestEvent, response);
263
+ const draft = await create({ signer: this.signer }, WalletResponseBlueprint(requestEvent, response));
279
264
  const event = await this.signer.signEvent(draft);
280
265
  await this.publishMethod(this.relays, event);
281
266
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "applesauce-wallet-connect",
3
- "version": "0.0.0-next-20251009095925",
3
+ "version": "0.0.0-next-20251012142625",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",