@aztec/wallet-sdk 0.0.1-commit.21caa21 → 0.0.1-commit.2ed92850

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.
Files changed (73) hide show
  1. package/README.md +228 -331
  2. package/dest/base-wallet/base_wallet.d.ts +23 -13
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +59 -24
  5. package/dest/crypto.d.ts +192 -0
  6. package/dest/crypto.d.ts.map +1 -0
  7. package/dest/crypto.js +394 -0
  8. package/dest/emoji_alphabet.d.ts +35 -0
  9. package/dest/emoji_alphabet.d.ts.map +1 -0
  10. package/dest/emoji_alphabet.js +299 -0
  11. package/dest/extension/handlers/background_connection_handler.d.ts +158 -0
  12. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -0
  13. package/dest/extension/handlers/background_connection_handler.js +258 -0
  14. package/dest/extension/handlers/content_script_connection_handler.d.ts +56 -0
  15. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -0
  16. package/dest/extension/handlers/content_script_connection_handler.js +174 -0
  17. package/dest/extension/handlers/index.d.ts +12 -0
  18. package/dest/extension/handlers/index.d.ts.map +1 -0
  19. package/dest/extension/handlers/index.js +10 -0
  20. package/dest/extension/handlers/internal_message_types.d.ts +63 -0
  21. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -0
  22. package/dest/extension/handlers/internal_message_types.js +22 -0
  23. package/dest/extension/provider/extension_provider.d.ts +107 -0
  24. package/dest/extension/provider/extension_provider.d.ts.map +1 -0
  25. package/dest/extension/provider/extension_provider.js +160 -0
  26. package/dest/extension/provider/extension_wallet.d.ts +131 -0
  27. package/dest/extension/provider/extension_wallet.d.ts.map +1 -0
  28. package/dest/extension/provider/extension_wallet.js +271 -0
  29. package/dest/extension/provider/index.d.ts +3 -0
  30. package/dest/extension/provider/index.d.ts.map +1 -0
  31. package/dest/manager/index.d.ts +2 -7
  32. package/dest/manager/index.d.ts.map +1 -1
  33. package/dest/manager/index.js +0 -4
  34. package/dest/manager/types.d.ts +108 -5
  35. package/dest/manager/types.d.ts.map +1 -1
  36. package/dest/manager/types.js +17 -1
  37. package/dest/manager/wallet_manager.d.ts +50 -7
  38. package/dest/manager/wallet_manager.d.ts.map +1 -1
  39. package/dest/manager/wallet_manager.js +178 -29
  40. package/dest/types.d.ts +123 -0
  41. package/dest/types.d.ts.map +1 -0
  42. package/dest/types.js +11 -0
  43. package/package.json +15 -12
  44. package/src/base-wallet/base_wallet.ts +82 -41
  45. package/src/crypto.ts +499 -0
  46. package/src/emoji_alphabet.ts +317 -0
  47. package/src/extension/handlers/background_connection_handler.ts +423 -0
  48. package/src/extension/handlers/content_script_connection_handler.ts +246 -0
  49. package/src/extension/handlers/index.ts +25 -0
  50. package/src/extension/handlers/internal_message_types.ts +69 -0
  51. package/src/extension/provider/extension_provider.ts +233 -0
  52. package/src/extension/provider/extension_wallet.ts +321 -0
  53. package/src/extension/provider/index.ts +7 -0
  54. package/src/manager/index.ts +3 -15
  55. package/src/manager/types.ts +112 -4
  56. package/src/manager/wallet_manager.ts +204 -31
  57. package/src/types.ts +132 -0
  58. package/dest/providers/extension/extension_provider.d.ts +0 -17
  59. package/dest/providers/extension/extension_provider.d.ts.map +0 -1
  60. package/dest/providers/extension/extension_provider.js +0 -56
  61. package/dest/providers/extension/extension_wallet.d.ts +0 -23
  62. package/dest/providers/extension/extension_wallet.d.ts.map +0 -1
  63. package/dest/providers/extension/extension_wallet.js +0 -96
  64. package/dest/providers/extension/index.d.ts +0 -4
  65. package/dest/providers/extension/index.d.ts.map +0 -1
  66. package/dest/providers/types.d.ts +0 -67
  67. package/dest/providers/types.d.ts.map +0 -1
  68. package/dest/providers/types.js +0 -3
  69. package/src/providers/extension/extension_provider.ts +0 -72
  70. package/src/providers/extension/extension_wallet.ts +0 -124
  71. package/src/providers/extension/index.ts +0 -3
  72. package/src/providers/types.ts +0 -71
  73. /package/dest/{providers/extension → extension/provider}/index.js +0 -0
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Internal message types for content script ↔ background communication.
3
+ * These are NOT part of the public wallet protocol - they are implementation
4
+ * details for coordinating between extension components.
5
+ */
6
+ export const InternalMessageType = {
7
+ // Content script → Background
8
+ DISCOVERY_REQUEST: 'discovery-request',
9
+ KEY_EXCHANGE_REQUEST: 'key-exchange-request',
10
+ SECURE_MESSAGE: 'secure-message',
11
+ DISCONNECT_REQUEST: 'disconnect-request',
12
+ // Background → Content script
13
+ DISCOVERY_APPROVED: 'discovery-approved',
14
+ KEY_EXCHANGE_RESPONSE: 'key-exchange-response',
15
+ SECURE_RESPONSE: 'secure-response',
16
+ SESSION_DISCONNECTED: 'session-disconnected',
17
+ } as const;
18
+
19
+ /**
20
+ * Message origins for internal extension communication.
21
+ */
22
+ export const MessageOrigin = {
23
+ BACKGROUND: 'background',
24
+ CONTENT_SCRIPT: 'content-script',
25
+ } as const;
26
+
27
+ /** Union type of message origins. */
28
+ export type MessageOriginType = (typeof MessageOrigin)[keyof typeof MessageOrigin];
29
+
30
+ /**
31
+ * Message sent from content script to background.
32
+ */
33
+ export interface ContentScriptMessage {
34
+ /** Message source identifier. */
35
+ origin: typeof MessageOrigin.CONTENT_SCRIPT;
36
+ /** Message type. */
37
+ type: string;
38
+ /** Optional session identifier. */
39
+ sessionId?: string;
40
+ /** Optional message payload. */
41
+ content?: unknown;
42
+ }
43
+
44
+ /**
45
+ * Message sent from background to content script.
46
+ */
47
+ export interface BackgroundMessage {
48
+ /** Message source identifier. */
49
+ origin: typeof MessageOrigin.BACKGROUND;
50
+ /** Message type. */
51
+ type: string;
52
+ /** Session identifier. */
53
+ sessionId: string;
54
+ /** Optional message payload. */
55
+ content?: unknown;
56
+ }
57
+
58
+ /**
59
+ * Sender information for messages from browser runtime.
60
+ */
61
+ export interface MessageSender {
62
+ /** Tab information if available. */
63
+ tab?: {
64
+ /** Tab identifier. */
65
+ id?: number;
66
+ /** Tab URL. */
67
+ url?: string;
68
+ };
69
+ }
@@ -0,0 +1,233 @@
1
+ import type { ChainInfo } from '@aztec/aztec.js/account';
2
+ import { jsonStringify } from '@aztec/foundation/json-rpc';
3
+ import { promiseWithResolvers } from '@aztec/foundation/promise';
4
+
5
+ import { deriveSessionKeys, exportPublicKey, generateKeyPair, importPublicKey } from '../../crypto.js';
6
+ import {
7
+ type ConnectedWalletInfo,
8
+ type DiscoveryRequest,
9
+ type DiscoveryResponse,
10
+ type KeyExchangeRequest,
11
+ type KeyExchangeResponse,
12
+ type WalletInfo,
13
+ WalletMessageType,
14
+ } from '../../types.js';
15
+
16
+ /** Default discovery timeout - long to give users time to approve */
17
+ const DEFAULT_DISCOVERY_TIMEOUT_MS = 60000; // 60 seconds
18
+
19
+ /** Key exchange timeout - short, wallet should respond quickly after discovery approval */
20
+ const KEY_EXCHANGE_TIMEOUT_MS = 2000; // 2 seconds
21
+
22
+ /**
23
+ * A discovered wallet before key exchange.
24
+ * Has basic info and MessagePort, but no shared key yet.
25
+ *
26
+ * Call {@link establishSecureChannel} to perform key exchange and get a connected wallet.
27
+ */
28
+ export class DiscoveredWallet {
29
+ constructor(
30
+ /** Basic wallet information (id, name, icon, version) */
31
+ public readonly info: WalletInfo,
32
+ /** The MessagePort for private communication with the wallet */
33
+ public readonly port: MessagePort,
34
+ /** Request ID for correlation */
35
+ public readonly requestId: string,
36
+ ) {}
37
+
38
+ /**
39
+ * Establishes a secure connection with this wallet.
40
+ *
41
+ * This method:
42
+ * 1. Generates an ECDH key pair
43
+ * 2. Sends public key to wallet over the MessagePort
44
+ * 3. Receives wallet's public key
45
+ * 4. Derives shared secret and computes verification hash locally
46
+ *
47
+ * **IMPORTANT**: Has a 2 second timeout for MITM defense.
48
+ * Both parties must exchange keys relatively quickly.
49
+ *
50
+ * The verification hash is computed independently by both parties
51
+ * and should be displayed to the user for visual comparison.
52
+ *
53
+ * @returns Connected wallet with shared key and verification hash
54
+ * @throws Error if key exchange fails or times out
55
+ */
56
+ async establishSecureChannel(): Promise<ConnectedWallet> {
57
+ const keyPair = await generateKeyPair();
58
+ const exportedPublicKey = await exportPublicKey(keyPair.publicKey);
59
+
60
+ const { promise, resolve, reject } = promiseWithResolvers<ConnectedWallet>();
61
+
62
+ const timeoutId = setTimeout(() => {
63
+ reject(new Error('Key exchange timeout'));
64
+ }, KEY_EXCHANGE_TIMEOUT_MS);
65
+
66
+ this.port.onmessage = async (event: MessageEvent) => {
67
+ const data = event.data as KeyExchangeResponse;
68
+
69
+ if (data.type === WalletMessageType.KEY_EXCHANGE_RESPONSE && data.requestId === this.requestId) {
70
+ clearTimeout(timeoutId);
71
+
72
+ try {
73
+ const walletPublicKey = await importPublicKey(data.publicKey);
74
+ const session = await deriveSessionKeys(keyPair, walletPublicKey, true);
75
+
76
+ const connectedInfo: ConnectedWalletInfo = {
77
+ ...this.info,
78
+ publicKey: data.publicKey,
79
+ verificationHash: session.verificationHash,
80
+ };
81
+
82
+ resolve({
83
+ info: connectedInfo,
84
+ port: this.port,
85
+ sharedKey: session.encryptionKey,
86
+ });
87
+ } catch (err) {
88
+ reject(new Error(`Key exchange failed: ${err}`));
89
+ }
90
+ }
91
+ };
92
+
93
+ this.port.start();
94
+
95
+ const keyExchangeRequest: KeyExchangeRequest = {
96
+ type: WalletMessageType.KEY_EXCHANGE_REQUEST,
97
+ requestId: this.requestId,
98
+ publicKey: exportedPublicKey,
99
+ };
100
+ this.port.postMessage(keyExchangeRequest);
101
+
102
+ return promise;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * A fully connected wallet with secure channel established.
108
+ * Available after key exchange completes.
109
+ */
110
+ export interface ConnectedWallet {
111
+ /** Full wallet info including public key and verification hash */
112
+ info: ConnectedWalletInfo;
113
+ /** The MessagePort for encrypted communication */
114
+ port: MessagePort;
115
+ /** The derived AES-256-GCM shared key for encryption */
116
+ sharedKey: CryptoKey;
117
+ }
118
+
119
+ /**
120
+ * Options for wallet discovery.
121
+ */
122
+ export interface DiscoveryOptions {
123
+ /** Application ID making the request */
124
+ appId: string;
125
+ /** How long to wait for user approval (ms). Default: 60000 (60s) */
126
+ timeout?: number;
127
+ /**
128
+ * Callback invoked when a wallet is discovered.
129
+ * Wallets are streamed as users approve them.
130
+ */
131
+ onWalletDiscovered?: (wallet: DiscoveredWallet) => void;
132
+ /**
133
+ * AbortSignal for cancelling discovery early.
134
+ * When aborted, cleanup happens immediately instead of waiting for timeout.
135
+ */
136
+ signal?: AbortSignal;
137
+ }
138
+
139
+ /**
140
+ * Provider for discovering Aztec wallet extensions.
141
+ *
142
+ * NOTE: Most users should use WalletManager instead of this class directly.
143
+ * WalletManager provides a higher-level API with streaming support.
144
+ *
145
+ * The connection flow is split into two phases for security:
146
+ *
147
+ * 1. **Discovery Phase** ({@link discoverWallets}):
148
+ * - Broadcasts a discovery request (NO public keys)
149
+ * - Wallet shows pending request to user
150
+ * - User must approve before wallet reveals itself
151
+ * - Wallets are streamed via callback as they're approved
152
+ *
153
+ * 2. **Secure Channel Phase** ({@link DiscoveredWallet.establishSecureChannel}):
154
+ * - Performs ECDH key exchange over private MessageChannel
155
+ * - Both parties compute verification hash locally
156
+ * - Has a 2s timeout for MITM defense
157
+ * - Returns connected wallet with shared key and verification hash
158
+ */
159
+ export class ExtensionProvider {
160
+ /**
161
+ * Discovers wallet extensions that user has approved.
162
+ *
163
+ * Wallets are streamed via the `onWalletDiscovered` callback as users approve them.
164
+ * The promise resolves when the timeout expires or signal is aborted.
165
+ *
166
+ * @param chainInfo - Chain information to check if extensions support this network
167
+ * @param options - Discovery options including appId, appName, timeout, and callback
168
+ * @returns Promise that resolves when discovery completes
169
+ */
170
+ static discoverWallets(chainInfo: ChainInfo, options: DiscoveryOptions): Promise<void> {
171
+ if (options.signal?.aborted) {
172
+ return Promise.resolve();
173
+ }
174
+ const timeout = options.timeout ?? DEFAULT_DISCOVERY_TIMEOUT_MS;
175
+
176
+ return new Promise(resolve => {
177
+ const requestId = globalThis.crypto.randomUUID();
178
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
179
+ let completed = false;
180
+
181
+ const finish = () => {
182
+ if (completed) {
183
+ return;
184
+ }
185
+ completed = true;
186
+
187
+ if (timeoutId !== null) {
188
+ clearTimeout(timeoutId);
189
+ }
190
+ window.removeEventListener('message', onMessage);
191
+ options.signal?.removeEventListener('abort', onAbort);
192
+ resolve();
193
+ };
194
+
195
+ const onAbort = () => finish();
196
+
197
+ const onMessage = (event: MessageEvent) => {
198
+ if (completed || event.source !== window) {
199
+ return;
200
+ }
201
+
202
+ let data: DiscoveryResponse;
203
+ try {
204
+ data = JSON.parse(event.data);
205
+ } catch {
206
+ return;
207
+ }
208
+
209
+ if (data.type !== WalletMessageType.DISCOVERY_RESPONSE || data.requestId !== requestId) {
210
+ return;
211
+ }
212
+
213
+ const port = event.ports?.[0];
214
+ if (port) {
215
+ options.onWalletDiscovered?.(new DiscoveredWallet(data.walletInfo, port, requestId));
216
+ }
217
+ };
218
+
219
+ options.signal?.addEventListener('abort', onAbort, { once: true });
220
+ window.addEventListener('message', onMessage);
221
+
222
+ const discoveryMessage: DiscoveryRequest = {
223
+ type: WalletMessageType.DISCOVERY,
224
+ requestId,
225
+ appId: options.appId,
226
+ chainInfo,
227
+ };
228
+ window.postMessage(jsonStringify(discoveryMessage), '*');
229
+
230
+ timeoutId = setTimeout(finish, timeout);
231
+ });
232
+ }
233
+ }
@@ -0,0 +1,321 @@
1
+ import type { ChainInfo } from '@aztec/aztec.js/account';
2
+ import { type Wallet, WalletSchema } from '@aztec/aztec.js/wallet';
3
+ import { jsonStringify } from '@aztec/foundation/json-rpc';
4
+ import { type PromiseWithResolvers, promiseWithResolvers } from '@aztec/foundation/promise';
5
+ import { schemaHasMethod } from '@aztec/foundation/schemas';
6
+ import type { FunctionsOf } from '@aztec/foundation/types';
7
+
8
+ import { type EncryptedPayload, decrypt, encrypt } from '../../crypto.js';
9
+ import { type WalletMessage, WalletMessageType, type WalletResponse } from '../../types.js';
10
+
11
+ /**
12
+ * Internal type representing a wallet method call before encryption.
13
+ * @internal
14
+ */
15
+ type WalletMethodCall = {
16
+ /** The wallet method name to invoke */
17
+ type: keyof FunctionsOf<Wallet>;
18
+ /** Arguments to pass to the wallet method */
19
+ args: unknown[];
20
+ };
21
+
22
+ /**
23
+ * Callback type for wallet disconnect events.
24
+ */
25
+ export type DisconnectCallback = () => void;
26
+
27
+ /**
28
+ * A wallet implementation that communicates with browser extension wallets
29
+ * using an encrypted MessageChannel.
30
+ *
31
+ * This class uses a secure channel established after discovery:
32
+ *
33
+ * 1. **MessageChannel**: Created during discovery and transferred via window.postMessage.
34
+ * Note: The port transfer is visible to page scripts, but security comes from encryption.
35
+ *
36
+ * 2. **ECDH Key Exchange**: The shared secret was derived after discovery using
37
+ * Elliptic Curve Diffie-Hellman key exchange over the MessagePort.
38
+ *
39
+ * 3. **AES-GCM Encryption**: All messages are encrypted using AES-256-GCM,
40
+ * providing both confidentiality and authenticity. This is what secures the channel.
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * // Discover and establish secure channel to a wallet
45
+ * const discoveredWallets = await ExtensionProvider.discoverWallets(chainInfo, { appId: 'my-dapp' });
46
+ * const connection = await discoveredWallets[0].establishSecureChannel();
47
+ *
48
+ * // User can verify emoji if desired
49
+ * console.log('Verify:', hashToEmoji(connection.info.verificationHash!));
50
+ *
51
+ * // Create wallet using the connection
52
+ * const wallet = ExtensionWallet.create(connection.info.id, connection.port, connection.sharedKey, chainInfo, 'my-dapp');
53
+ *
54
+ * // All subsequent calls are encrypted
55
+ * const accounts = await wallet.getAccounts();
56
+ * ```
57
+ */
58
+ export class ExtensionWallet {
59
+ /** Map of pending requests awaiting responses, keyed by message ID */
60
+ private inFlight = new Map<string, PromiseWithResolvers<unknown>>();
61
+ private disconnected = false;
62
+ private disconnectCallbacks: DisconnectCallback[] = [];
63
+
64
+ /**
65
+ * Private constructor - use {@link ExtensionWallet.create} to instantiate.
66
+ * @param chainInfo - The chain information (chainId and version)
67
+ * @param appId - Application identifier for the requesting dApp
68
+ * @param extensionId - The unique identifier of the target wallet extension
69
+ * @param port - The MessagePort for private communication with the wallet
70
+ * @param sharedKey - The derived AES-256-GCM shared key for encryption
71
+ */
72
+ private constructor(
73
+ private chainInfo: ChainInfo,
74
+ private appId: string,
75
+ private extensionId: string,
76
+ private port: MessagePort,
77
+ private sharedKey: CryptoKey,
78
+ ) {}
79
+
80
+ /**
81
+ * Creates a Wallet that communicates with a browser extension
82
+ * over a secure encrypted MessageChannel.
83
+ *
84
+ * @param extensionId - The unique identifier of the wallet extension
85
+ * @param port - The MessagePort for encrypted communication with the wallet
86
+ * @param sharedKey - The derived AES-256-GCM shared key for encryption
87
+ * @param chainInfo - The chain information (chainId and version) for request context
88
+ * @param appId - Application identifier used to identify the requesting dApp to the wallet
89
+ * @returns A Wallet interface where all method calls are encrypted
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * const discoveredWallets = await ExtensionProvider.discoverWallets(chainInfo, { appId: 'my-defi-app' });
94
+ * const connection = await discoveredWallets[0].establishSecureChannel();
95
+ * const wallet = ExtensionWallet.create(
96
+ * connection.info.id,
97
+ * connection.port,
98
+ * connection.sharedKey,
99
+ * chainInfo,
100
+ * 'my-defi-app'
101
+ * );
102
+ *
103
+ * const accounts = await wallet.getAccounts();
104
+ * ```
105
+ */
106
+ static create(
107
+ extensionId: string,
108
+ port: MessagePort,
109
+ sharedKey: CryptoKey,
110
+ chainInfo: ChainInfo,
111
+ appId: string,
112
+ ): Wallet {
113
+ const wallet = new ExtensionWallet(chainInfo, appId, extensionId, port, sharedKey);
114
+
115
+ // Set up message handler for encrypted responses and unencrypted control messages
116
+ wallet.port.onmessage = (event: MessageEvent) => {
117
+ const data = event.data;
118
+ // Check for unencrypted disconnect notification
119
+ if (data && typeof data === 'object' && 'type' in data && data.type === WalletMessageType.DISCONNECT) {
120
+ wallet.handleDisconnect();
121
+ return;
122
+ }
123
+ // Otherwise treat as encrypted payload
124
+ void wallet.handleEncryptedResponse(data as EncryptedPayload);
125
+ };
126
+
127
+ wallet.port.start();
128
+
129
+ return new Proxy(wallet, {
130
+ get: (target, prop) => {
131
+ if (schemaHasMethod(WalletSchema, prop.toString())) {
132
+ return async (...args: unknown[]) => {
133
+ const result = await target.postMessage({
134
+ type: prop.toString() as keyof FunctionsOf<Wallet>,
135
+ args,
136
+ });
137
+ return WalletSchema[prop.toString() as keyof typeof WalletSchema].returnType().parseAsync(result);
138
+ };
139
+ } else {
140
+ return target[prop as keyof ExtensionWallet];
141
+ }
142
+ },
143
+ }) as unknown as Wallet;
144
+ }
145
+
146
+ /**
147
+ * Handles an encrypted response received from the wallet extension.
148
+ *
149
+ * Decrypts the response using the shared AES key and resolves or rejects
150
+ * the corresponding pending promise based on the response content.
151
+ *
152
+ * @param encrypted - The encrypted response from the wallet
153
+ */
154
+ private async handleEncryptedResponse(encrypted: EncryptedPayload): Promise<void> {
155
+ if (!this.sharedKey) {
156
+ return;
157
+ }
158
+
159
+ try {
160
+ const response = await decrypt<WalletResponse>(this.sharedKey, encrypted);
161
+
162
+ const { messageId, result, error, walletId: responseWalletId } = response;
163
+
164
+ if (!messageId || !responseWalletId) {
165
+ return;
166
+ }
167
+
168
+ if (this.extensionId !== responseWalletId) {
169
+ return;
170
+ }
171
+
172
+ if (!this.inFlight.has(messageId)) {
173
+ return;
174
+ }
175
+
176
+ const { resolve, reject } = this.inFlight.get(messageId)!;
177
+
178
+ if (error) {
179
+ reject(new Error(jsonStringify(error)));
180
+ } else {
181
+ resolve(result);
182
+ }
183
+ this.inFlight.delete(messageId);
184
+ // eslint-disable-next-line no-empty
185
+ } catch {}
186
+ }
187
+
188
+ /**
189
+ * Sends an encrypted wallet method call over the secure MessageChannel.
190
+ *
191
+ * The message is encrypted using AES-256-GCM with the shared key derived
192
+ * during discovery. A unique message ID is generated to correlate
193
+ * the response.
194
+ *
195
+ * @param call - The wallet method call containing method name and arguments
196
+ * @returns A Promise that resolves with the decrypted result from the wallet
197
+ *
198
+ * @throws Error if the secure channel has not been established or wallet is disconnected
199
+ */
200
+ private async postMessage(call: WalletMethodCall): Promise<unknown> {
201
+ if (this.disconnected) {
202
+ throw new Error('Wallet has been disconnected');
203
+ }
204
+ if (!this.port || !this.sharedKey) {
205
+ throw new Error('Secure channel not established');
206
+ }
207
+
208
+ const messageId = globalThis.crypto.randomUUID();
209
+ const message: WalletMessage = {
210
+ type: call.type,
211
+ args: call.args,
212
+ messageId,
213
+ chainInfo: this.chainInfo,
214
+ appId: this.appId,
215
+ walletId: this.extensionId,
216
+ };
217
+
218
+ const encrypted = await encrypt(this.sharedKey, jsonStringify(message));
219
+ this.port.postMessage(encrypted);
220
+
221
+ const { promise, resolve, reject } = promiseWithResolvers<unknown>();
222
+ this.inFlight.set(messageId, { promise, resolve, reject });
223
+ return promise;
224
+ }
225
+
226
+ /**
227
+ * Handles wallet disconnection.
228
+ * Rejects all pending requests and notifies registered callbacks.
229
+ * @internal
230
+ */
231
+ private handleDisconnect(): void {
232
+ if (this.disconnected) {
233
+ return;
234
+ }
235
+ this.disconnected = true;
236
+
237
+ if (this.port) {
238
+ this.port.onmessage = null;
239
+ this.port.close();
240
+ }
241
+
242
+ const error = new Error('Wallet disconnected');
243
+ for (const { reject } of this.inFlight.values()) {
244
+ reject(error);
245
+ }
246
+ this.inFlight.clear();
247
+
248
+ for (const callback of this.disconnectCallbacks) {
249
+ try {
250
+ callback();
251
+ } catch {
252
+ // Ignore errors on disconnect callbacks
253
+ }
254
+ }
255
+ }
256
+
257
+ /**
258
+ * Registers a callback to be invoked when the wallet disconnects.
259
+ *
260
+ * @param callback - Function to call when wallet disconnects
261
+ * @returns A function to unregister the callback
262
+ *
263
+ * @example
264
+ * ```typescript
265
+ * const wallet = await ExtensionWallet.create(...);
266
+ * const unsubscribe = wallet.onDisconnect(() => {
267
+ * console.log('Wallet disconnected! Please reconnect.');
268
+ * // Clean up UI, prompt user to reconnect, etc.
269
+ * });
270
+ * // Later: unsubscribe(); to stop receiving notifications
271
+ * ```
272
+ */
273
+ onDisconnect(callback: DisconnectCallback): () => void {
274
+ this.disconnectCallbacks.push(callback);
275
+ return () => {
276
+ const index = this.disconnectCallbacks.indexOf(callback);
277
+ if (index !== -1) {
278
+ this.disconnectCallbacks.splice(index, 1);
279
+ }
280
+ };
281
+ }
282
+
283
+ /**
284
+ * Returns whether the wallet has been disconnected.
285
+ *
286
+ * @returns true if the wallet is no longer connected
287
+ */
288
+ isDisconnected(): boolean {
289
+ return this.disconnected;
290
+ }
291
+
292
+ /**
293
+ * Disconnects from the wallet and cleans up resources.
294
+ *
295
+ * This method notifies the wallet extension that the session is ending,
296
+ * allowing it to clean up its state. After calling this method, the wallet
297
+ * instance can no longer be used and any pending requests will be rejected.
298
+ *
299
+ * @example
300
+ * ```typescript
301
+ * const extensionWallet = ExtensionWallet.create(extensionId, port, sharedKey, chainInfo, 'my-app');
302
+ * // ... use wallet ...
303
+ * await extensionWallet.disconnect(); // Clean disconnect when done
304
+ * ```
305
+ */
306
+ // eslint-disable-next-line require-await -- async for interface compatibility
307
+ async disconnect(): Promise<void> {
308
+ if (this.disconnected) {
309
+ return;
310
+ }
311
+
312
+ if (this.port) {
313
+ // Send unencrypted disconnect - control messages don't need encryption
314
+ this.port.postMessage({
315
+ type: WalletMessageType.DISCONNECT,
316
+ });
317
+ }
318
+
319
+ this.handleDisconnect();
320
+ }
321
+ }
@@ -0,0 +1,7 @@
1
+ export { ExtensionWallet, type DisconnectCallback } from './extension_wallet.js';
2
+ export {
3
+ ExtensionProvider,
4
+ type DiscoveredWallet,
5
+ type ConnectedWallet,
6
+ type DiscoveryOptions,
7
+ } from './extension_provider.js';
@@ -5,20 +5,8 @@ export type {
5
5
  WebWalletConfig,
6
6
  WalletProviderType,
7
7
  WalletProvider,
8
+ PendingConnection,
9
+ ProviderDisconnectionCallback,
8
10
  DiscoverWalletsOptions,
11
+ DiscoverySession,
9
12
  } from './types.js';
10
-
11
- // Re-export types from providers for convenience
12
- export type {
13
- WalletInfo,
14
- WalletMessage,
15
- WalletResponse,
16
- DiscoveryRequest,
17
- DiscoveryResponse,
18
- } from '../providers/types.js';
19
-
20
- // Re-export commonly needed utilities for wallet integration
21
- export { ChainInfoSchema } from '@aztec/aztec.js/account';
22
- export type { ChainInfo } from '@aztec/aztec.js/account';
23
- export { WalletSchema } from '@aztec/aztec.js/wallet';
24
- export { jsonStringify } from '@aztec/foundation/json-rpc';