@aztec/wallet-sdk 0.0.1-commit.9ef841308 → 0.0.1-commit.a5db02d

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 (46) hide show
  1. package/README.md +125 -0
  2. package/dest/base-wallet/base_wallet.d.ts +65 -35
  3. package/dest/base-wallet/base_wallet.d.ts.map +1 -1
  4. package/dest/base-wallet/base_wallet.js +187 -81
  5. package/dest/base-wallet/get_gas_limits.d.ts +36 -0
  6. package/dest/base-wallet/get_gas_limits.d.ts.map +1 -0
  7. package/dest/base-wallet/get_gas_limits.js +55 -0
  8. package/dest/base-wallet/index.d.ts +3 -2
  9. package/dest/base-wallet/index.d.ts.map +1 -1
  10. package/dest/base-wallet/index.js +1 -0
  11. package/dest/base-wallet/utils.d.ts +7 -4
  12. package/dest/base-wallet/utils.d.ts.map +1 -1
  13. package/dest/base-wallet/utils.js +11 -5
  14. package/dest/extension/handlers/background_connection_handler.d.ts +12 -2
  15. package/dest/extension/handlers/background_connection_handler.d.ts.map +1 -1
  16. package/dest/extension/handlers/background_connection_handler.js +44 -8
  17. package/dest/extension/handlers/content_script_connection_handler.d.ts +2 -1
  18. package/dest/extension/handlers/content_script_connection_handler.d.ts.map +1 -1
  19. package/dest/extension/handlers/content_script_connection_handler.js +19 -0
  20. package/dest/extension/handlers/internal_message_types.d.ts +3 -1
  21. package/dest/extension/handlers/internal_message_types.d.ts.map +1 -1
  22. package/dest/extension/handlers/internal_message_types.js +3 -1
  23. package/dest/extension/provider/extension_wallet.d.ts +26 -3
  24. package/dest/extension/provider/extension_wallet.d.ts.map +1 -1
  25. package/dest/extension/provider/extension_wallet.js +80 -9
  26. package/dest/iframe/handlers/iframe_connection_handler.d.ts +6 -2
  27. package/dest/iframe/handlers/iframe_connection_handler.d.ts.map +1 -1
  28. package/dest/iframe/handlers/iframe_connection_handler.js +18 -7
  29. package/dest/iframe/provider/iframe_wallet.d.ts +20 -3
  30. package/dest/iframe/provider/iframe_wallet.d.ts.map +1 -1
  31. package/dest/iframe/provider/iframe_wallet.js +79 -10
  32. package/dest/types.d.ts +52 -2
  33. package/dest/types.d.ts.map +1 -1
  34. package/dest/types.js +25 -0
  35. package/package.json +8 -8
  36. package/src/base-wallet/base_wallet.ts +221 -108
  37. package/src/base-wallet/get_gas_limits.ts +88 -0
  38. package/src/base-wallet/index.ts +7 -1
  39. package/src/base-wallet/utils.ts +15 -5
  40. package/src/extension/handlers/background_connection_handler.ts +42 -9
  41. package/src/extension/handlers/content_script_connection_handler.ts +18 -0
  42. package/src/extension/handlers/internal_message_types.ts +2 -0
  43. package/src/extension/provider/extension_wallet.ts +94 -8
  44. package/src/iframe/handlers/iframe_connection_handler.ts +21 -8
  45. package/src/iframe/provider/iframe_wallet.ts +103 -9
  46. package/src/types.ts +59 -0
@@ -1,4 +1,5 @@
1
1
  import type { AztecNode } from '@aztec/aztec.js/node';
2
+ import { TxSimulationResultWithAppOffset } from '@aztec/aztec.js/wallet';
2
3
  import { MAX_ENQUEUED_CALLS_PER_CALL } from '@aztec/constants';
3
4
  import type { ChainInfo } from '@aztec/entrypoints/interfaces';
4
5
  import { makeTuple } from '@aztec/foundation/array';
@@ -24,6 +25,7 @@ import {
24
25
  PrivateCallExecutionResult,
25
26
  PrivateExecutionResult,
26
27
  PublicSimulationOutput,
28
+ type SimulationOverrides,
27
29
  Tx,
28
30
  TxContext,
29
31
  TxSimulationResult,
@@ -64,6 +66,8 @@ export function extractOptimizablePublicStaticCalls(payload: ExecutionPayload):
64
66
  * @param gasSettings - Gas settings for the transaction.
65
67
  * @param blockHeader - Block header to use as anchor.
66
68
  * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
69
+ * @param getContractName - Resolver for contract names (used for debug log display).
70
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
67
71
  * @returns TxSimulationResult with public return values.
68
72
  */
69
73
  async function simulateBatchViaNode(
@@ -75,6 +79,7 @@ async function simulateBatchViaNode(
75
79
  blockHeader: BlockHeader,
76
80
  skipFeeEnforcement: boolean,
77
81
  getContractName: ContractNameResolver,
82
+ overrides?: SimulationOverrides,
78
83
  ): Promise<TxSimulationResult> {
79
84
  const txContext = new TxContext(chainInfo.chainId, chainInfo.version, gasSettings);
80
85
 
@@ -142,7 +147,7 @@ async function simulateBatchViaNode(
142
147
  publicFunctionCalldata: publicFunctionCalldata,
143
148
  });
144
149
 
145
- const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement);
150
+ const publicOutput = await node.simulatePublicCalls(tx, skipFeeEnforcement, overrides);
146
151
 
147
152
  if (publicOutput.revertReason) {
148
153
  throw publicOutput.revertReason;
@@ -165,6 +170,8 @@ async function simulateBatchViaNode(
165
170
  * @param gasSettings - Gas settings for the transaction.
166
171
  * @param blockHeader - Block header to use as anchor.
167
172
  * @param skipFeeEnforcement - Whether to skip fee enforcement during simulation.
173
+ * @param getContractName - Resolver for contract names (used for debug log display).
174
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
168
175
  * @returns Array of TxSimulationResult, one per batch.
169
176
  */
170
177
  export async function simulateViaNode(
@@ -176,6 +183,7 @@ export async function simulateViaNode(
176
183
  blockHeader: BlockHeader,
177
184
  skipFeeEnforcement: boolean = true,
178
185
  getContractName: ContractNameResolver,
186
+ overrides?: SimulationOverrides,
179
187
  ): Promise<TxSimulationResult[]> {
180
188
  const batches: FunctionCall[][] = [];
181
189
 
@@ -195,6 +203,7 @@ export async function simulateViaNode(
195
203
  blockHeader,
196
204
  skipFeeEnforcement,
197
205
  getContractName,
206
+ overrides,
198
207
  );
199
208
  results.push(result);
200
209
  }
@@ -214,13 +223,13 @@ export async function simulateViaNode(
214
223
  */
215
224
  export function buildMergedSimulationResult(
216
225
  optimizedResults: TxSimulationResult[],
217
- normalResult: TxSimulationResult | null,
218
- ): TxSimulationResult {
226
+ normalResult: TxSimulationResultWithAppOffset | null,
227
+ ): TxSimulationResultWithAppOffset {
219
228
  const optimizedReturnValues = optimizedResults.flatMap(r => r.publicOutput?.publicReturnValues ?? []);
220
229
  const normalReturnValues = normalResult?.publicOutput?.publicReturnValues ?? [];
221
230
  const allReturnValues = [...optimizedReturnValues, ...normalReturnValues];
222
231
 
223
- const baseResult = normalResult ?? optimizedResults[0];
232
+ const baseResult: TxSimulationResult = normalResult ?? optimizedResults[0];
224
233
 
225
234
  const mergedPublicOutput: PublicSimulationOutput | undefined = baseResult.publicOutput
226
235
  ? {
@@ -229,10 +238,11 @@ export function buildMergedSimulationResult(
229
238
  }
230
239
  : undefined;
231
240
 
232
- return new TxSimulationResult(
241
+ const merged = new TxSimulationResult(
233
242
  baseResult.privateExecutionResult,
234
243
  baseResult.publicInputs,
235
244
  mergedPublicOutput,
236
245
  normalResult?.stats,
237
246
  );
247
+ return TxSimulationResultWithAppOffset.fromResultAndOffset(merged, normalResult?.appCallOffset ?? 0);
238
248
  }
@@ -17,6 +17,7 @@ import {
17
17
  type WalletMessage,
18
18
  WalletMessageType,
19
19
  type WalletResponse,
20
+ type WalletSdkLogger,
20
21
  } from '../../types.js';
21
22
  import {
22
23
  type BackgroundMessage,
@@ -131,6 +132,8 @@ export interface BackgroundConnectionConfig {
131
132
  walletVersion: string;
132
133
  /** Optional wallet icon URL. */
133
134
  walletIcon?: string;
135
+ /** Logger used for diagnostics. */
136
+ logger: WalletSdkLogger;
134
137
  }
135
138
 
136
139
  /**
@@ -149,6 +152,7 @@ export interface BackgroundConnectionConfig {
149
152
  * walletId: 'my-wallet',
150
153
  * walletName: 'My Wallet',
151
154
  * walletVersion: '1.0.0',
155
+ * logger: console,
152
156
  * },
153
157
  * {
154
158
  * sendToTab: (tabId, message) => browser.tabs.sendMessage(tabId, message),
@@ -167,12 +171,15 @@ export interface BackgroundConnectionConfig {
167
171
  export class BackgroundConnectionHandler {
168
172
  private pendingDiscoveries = new Map<string, PendingDiscovery>();
169
173
  private activeSessions = new Map<string, ActiveSession>();
174
+ private log: WalletSdkLogger;
170
175
 
171
176
  constructor(
172
177
  private config: BackgroundConnectionConfig,
173
178
  private transport: BackgroundTransport,
174
179
  private callbacks: BackgroundConnectionCallbacks = {},
175
- ) {}
180
+ ) {
181
+ this.log = config.logger;
182
+ }
176
183
 
177
184
  initialize(): void {
178
185
  this.transport.addContentListener(this.handleMessage);
@@ -198,8 +205,8 @@ export class BackgroundConnectionHandler {
198
205
  break;
199
206
  case InternalMessageType.KEY_EXCHANGE_REQUEST:
200
207
  if (sessionId) {
201
- this.handleKeyExchangeRequest(sessionId, content as KeyExchangeRequest).catch(() => {
202
- // Key exchange failed - session won't be established
208
+ this.handleKeyExchangeRequest(sessionId, content as KeyExchangeRequest).catch(err => {
209
+ this.log.warn('Key exchange failed session will not be established', { sessionId, err });
203
210
  });
204
211
  }
205
212
  break;
@@ -213,9 +220,31 @@ export class BackgroundConnectionHandler {
213
220
  void this.handleEncryptedMessage(sessionId, content as EncryptedPayload);
214
221
  }
215
222
  break;
223
+ case InternalMessageType.PING:
224
+ if (sessionId) {
225
+ this.handlePing(sessionId);
226
+ }
227
+ break;
216
228
  }
217
229
  };
218
230
 
231
+ /**
232
+ * Reply to a dApp PING with a PONG. Used as a liveness probe so the dApp can
233
+ * tell the difference between a slow request and a dead extension.
234
+ * @param sessionId - The session that sent the PING.
235
+ */
236
+ private handlePing(sessionId: string): void {
237
+ const session = this.activeSessions.get(sessionId);
238
+ if (!session) {
239
+ return;
240
+ }
241
+ this.transport.sendToTab(session.tabId, {
242
+ origin: MessageOrigin.BACKGROUND,
243
+ type: InternalMessageType.PONG,
244
+ sessionId,
245
+ });
246
+ }
247
+
219
248
  getWalletInfo(): WalletInfo {
220
249
  return {
221
250
  id: this.config.walletId,
@@ -315,8 +344,8 @@ export class BackgroundConnectionHandler {
315
344
  });
316
345
 
317
346
  this.callbacks.onSessionEstablished?.(session);
318
- } catch {
319
- // Key exchange failed silently - session won't be established
347
+ } catch (err) {
348
+ this.log.warn('Key exchange failed session will not be established', { sessionId, err });
320
349
  }
321
350
  }
322
351
 
@@ -329,8 +358,8 @@ export class BackgroundConnectionHandler {
329
358
  try {
330
359
  const message = await decrypt<WalletMessage>(session.sharedKey, encrypted);
331
360
  this.callbacks.onWalletMessage?.(session, message);
332
- } catch {
333
- // Decryption failed - ignore malformed message
361
+ } catch (err) {
362
+ this.log.warn('Failed to decrypt incoming wallet message', { sessionId, err });
334
363
  }
335
364
  }
336
365
 
@@ -348,8 +377,12 @@ export class BackgroundConnectionHandler {
348
377
  sessionId,
349
378
  content: encrypted,
350
379
  });
351
- } catch {
352
- // Encryption failed - response won't be sent
380
+ } catch (err) {
381
+ this.log.error('Failed to encrypt wallet response response will not be sent', {
382
+ sessionId,
383
+ messageId: response.messageId,
384
+ err,
385
+ });
353
386
  }
354
387
  }
355
388
 
@@ -139,9 +139,20 @@ export class ContentScriptConnectionHandler {
139
139
  case InternalMessageType.SESSION_DISCONNECTED:
140
140
  this.handleSessionDisconnected(sessionId);
141
141
  break;
142
+ case InternalMessageType.PONG:
143
+ this.handlePong(sessionId);
144
+ break;
142
145
  }
143
146
  };
144
147
 
148
+ private handlePong(sessionId: string): void {
149
+ const connection = this.ports.get(sessionId);
150
+ if (!connection) {
151
+ return;
152
+ }
153
+ connection.port.postMessage({ type: WalletMessageType.PONG });
154
+ }
155
+
145
156
  private handleDiscoveryRequest(request: DiscoveryRequest): void {
146
157
  this.transport.sendToBackground({
147
158
  origin: MessageOrigin.CONTENT_SCRIPT,
@@ -178,6 +189,13 @@ export class ContentScriptConnectionHandler {
178
189
  content: data,
179
190
  });
180
191
  break;
192
+ case WalletMessageType.PING:
193
+ this.transport.sendToBackground({
194
+ origin: MessageOrigin.CONTENT_SCRIPT,
195
+ type: InternalMessageType.PING,
196
+ sessionId,
197
+ });
198
+ break;
181
199
  default:
182
200
  this.transport.sendToBackground({
183
201
  origin: MessageOrigin.CONTENT_SCRIPT,
@@ -9,11 +9,13 @@ export const InternalMessageType = {
9
9
  KEY_EXCHANGE_REQUEST: 'key-exchange-request',
10
10
  SECURE_MESSAGE: 'secure-message',
11
11
  DISCONNECT_REQUEST: 'disconnect-request',
12
+ PING: 'ping',
12
13
  // Background → Content script
13
14
  DISCOVERY_APPROVED: 'discovery-approved',
14
15
  KEY_EXCHANGE_RESPONSE: 'key-exchange-response',
15
16
  SECURE_RESPONSE: 'secure-response',
16
17
  SESSION_DISCONNECTED: 'session-disconnected',
18
+ PONG: 'pong',
17
19
  } as const;
18
20
 
19
21
  /**
@@ -2,11 +2,21 @@ import type { ChainInfo } from '@aztec/aztec.js/account';
2
2
  import { type Wallet, WalletSchema } from '@aztec/aztec.js/wallet';
3
3
  import { jsonStringify } from '@aztec/foundation/json-rpc';
4
4
  import { type PromiseWithResolvers, promiseWithResolvers } from '@aztec/foundation/promise';
5
- import { schemaHasMethod } from '@aztec/foundation/schemas';
5
+ import { getSchemaReturnType, schemaHasMethod } from '@aztec/foundation/schemas';
6
6
  import type { FunctionsOf } from '@aztec/foundation/types';
7
7
 
8
8
  import { type EncryptedPayload, decrypt, encrypt } from '../../crypto.js';
9
- import { type DisconnectCallback, type WalletMessage, WalletMessageType, type WalletResponse } from '../../types.js';
9
+ import {
10
+ DEFAULT_HEARTBEAT_DEAD_AFTER_MS,
11
+ DEFAULT_HEARTBEAT_INTERVAL_MS,
12
+ type DisconnectCallback,
13
+ type HeartbeatOptions,
14
+ NOOP_LOGGER,
15
+ type WalletMessage,
16
+ WalletMessageType,
17
+ type WalletResponse,
18
+ type WalletSdkLogger,
19
+ } from '../../types.js';
10
20
 
11
21
  /**
12
22
  * Internal type representing a wallet method call before encryption.
@@ -55,6 +65,11 @@ export class ExtensionWallet {
55
65
  private inFlight = new Map<string, PromiseWithResolvers<unknown>>();
56
66
  private disconnected = false;
57
67
  private disconnectCallbacks: DisconnectCallback[] = [];
68
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
69
+ private lastInboundAt = 0;
70
+ private log: WalletSdkLogger;
71
+ private heartbeatIntervalMs: number;
72
+ private heartbeatDeadAfterMs: number;
58
73
 
59
74
  /**
60
75
  * Private constructor - use {@link ExtensionWallet.create} to instantiate.
@@ -63,6 +78,8 @@ export class ExtensionWallet {
63
78
  * @param extensionId - The unique identifier of the target wallet extension
64
79
  * @param port - The MessagePort for private communication with the wallet
65
80
  * @param sharedKey - The derived AES-256-GCM shared key for encryption
81
+ * @param logger - Optional logger; defaults to a no-op logger
82
+ * @param heartbeatOptions - Optional heartbeat tuning (mostly useful for tests)
66
83
  */
67
84
  private constructor(
68
85
  private chainInfo: ChainInfo,
@@ -70,7 +87,13 @@ export class ExtensionWallet {
70
87
  private extensionId: string,
71
88
  private port: MessagePort,
72
89
  private sharedKey: CryptoKey,
73
- ) {}
90
+ logger?: WalletSdkLogger,
91
+ heartbeatOptions?: HeartbeatOptions,
92
+ ) {
93
+ this.log = logger ?? NOOP_LOGGER;
94
+ this.heartbeatIntervalMs = heartbeatOptions?.intervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS;
95
+ this.heartbeatDeadAfterMs = heartbeatOptions?.deadAfterMs ?? DEFAULT_HEARTBEAT_DEAD_AFTER_MS;
96
+ }
74
97
 
75
98
  /**
76
99
  * Creates a Wallet that communicates with a browser extension
@@ -81,6 +104,8 @@ export class ExtensionWallet {
81
104
  * @param sharedKey - The derived AES-256-GCM shared key for encryption
82
105
  * @param chainInfo - The chain information (chainId and version) for request context
83
106
  * @param appId - Application identifier used to identify the requesting dApp to the wallet
107
+ * @param logger - Optional logger; defaults to a no-op logger to keep extension/page bundles small
108
+ * @param heartbeatOptions - Optional override for heartbeat tuning (mostly useful for tests)
84
109
  * @returns A Wallet interface where all method calls are encrypted
85
110
  *
86
111
  * @example
@@ -104,13 +129,17 @@ export class ExtensionWallet {
104
129
  sharedKey: CryptoKey,
105
130
  chainInfo: ChainInfo,
106
131
  appId: string,
132
+ logger?: WalletSdkLogger,
133
+ heartbeatOptions?: HeartbeatOptions,
107
134
  ): ExtensionWallet {
108
- const wallet = new ExtensionWallet(chainInfo, appId, extensionId, port, sharedKey);
135
+ const wallet = new ExtensionWallet(chainInfo, appId, extensionId, port, sharedKey, logger, heartbeatOptions);
109
136
 
110
137
  // Set up message handler for encrypted responses and unencrypted control messages
111
138
  wallet.port.onmessage = (event: MessageEvent) => {
112
139
  const data = event.data;
113
- // Check for unencrypted disconnect notification
140
+ // Any inbound traffic counts as proof of liveness.
141
+ wallet.lastInboundAt = Date.now();
142
+
114
143
  if (data && typeof data === 'object' && 'type' in data && data.type === WalletMessageType.DISCONNECT) {
115
144
  wallet.handleDisconnect();
116
145
  return;
@@ -131,7 +160,7 @@ export class ExtensionWallet {
131
160
  type: prop.toString() as keyof FunctionsOf<Wallet>,
132
161
  args,
133
162
  });
134
- return WalletSchema[prop.toString() as keyof typeof WalletSchema].returnType().parseAsync(result);
163
+ return getSchemaReturnType(WalletSchema[prop.toString() as keyof typeof WalletSchema]).parseAsync(result);
135
164
  };
136
165
  } else {
137
166
  return target[prop as keyof ExtensionWallet];
@@ -184,8 +213,10 @@ export class ExtensionWallet {
184
213
  resolve(result);
185
214
  }
186
215
  this.inFlight.delete(messageId);
187
- // eslint-disable-next-line no-empty
188
- } catch {}
216
+ this.maybeStopHeartbeat();
217
+ } catch (err) {
218
+ this.log.warn('Failed to decrypt wallet response', { err });
219
+ }
189
220
  }
190
221
 
191
222
  /**
@@ -223,9 +254,59 @@ export class ExtensionWallet {
223
254
 
224
255
  const { promise, resolve, reject } = promiseWithResolvers<unknown>();
225
256
  this.inFlight.set(messageId, { promise, resolve, reject });
257
+ this.startHeartbeat();
226
258
  return promise;
227
259
  }
228
260
 
261
+ /**
262
+ * Start the heartbeat probe loop while at least one request is in flight.
263
+ * Idempotent — calling while already running is a no-op.
264
+ *
265
+ * Heartbeat is opt-in via wire protocol: PINGs are unencrypted control messages
266
+ * (like DISCONNECT). Older wallets that do not understand PING simply drop it,
267
+ * which is safe — we only declare disconnect when **no** inbound traffic of any
268
+ * kind (PONG, encrypted response, DISCONNECT) arrives within the dead window.
269
+ * A wallet that is processing a slow request will reset the timer when it
270
+ * eventually responds, so this never causes false disconnects on legacy peers.
271
+ */
272
+ private startHeartbeat(): void {
273
+ if (this.heartbeatTimer !== null || this.disconnected) {
274
+ return;
275
+ }
276
+ this.lastInboundAt = Date.now();
277
+ this.heartbeatTimer = setInterval(() => this.heartbeatTick(), this.heartbeatIntervalMs);
278
+ }
279
+
280
+ private maybeStopHeartbeat(): void {
281
+ if (this.inFlight.size === 0 && this.heartbeatTimer !== null) {
282
+ clearInterval(this.heartbeatTimer);
283
+ this.heartbeatTimer = null;
284
+ }
285
+ }
286
+
287
+ private heartbeatTick(): void {
288
+ if (this.disconnected || this.inFlight.size === 0) {
289
+ this.maybeStopHeartbeat();
290
+ return;
291
+ }
292
+
293
+ const idleMs = Date.now() - this.lastInboundAt;
294
+ if (idleMs >= this.heartbeatDeadAfterMs) {
295
+ this.log.warn('Wallet channel unresponsive — declaring disconnect', {
296
+ idleMs,
297
+ inFlight: this.inFlight.size,
298
+ });
299
+ this.handleDisconnect();
300
+ return;
301
+ }
302
+
303
+ try {
304
+ this.port.postMessage({ type: WalletMessageType.PING });
305
+ } catch (err) {
306
+ this.log.warn('Failed to send heartbeat PING', { err });
307
+ }
308
+ }
309
+
229
310
  /**
230
311
  * Handles wallet disconnection.
231
312
  * Rejects all pending requests and notifies registered callbacks.
@@ -237,6 +318,11 @@ export class ExtensionWallet {
237
318
  }
238
319
  this.disconnected = true;
239
320
 
321
+ if (this.heartbeatTimer !== null) {
322
+ clearInterval(this.heartbeatTimer);
323
+ this.heartbeatTimer = null;
324
+ }
325
+
240
326
  if (this.port) {
241
327
  this.port.onmessage = null;
242
328
  this.port.close();
@@ -14,11 +14,10 @@
14
14
  * so the dApp knows it can send a discovery request.
15
15
  */
16
16
  import type { ChainInfo } from '@aztec/aztec.js/account';
17
- import { createLogger } from '@aztec/aztec.js/log';
18
17
  import type { Wallet } from '@aztec/aztec.js/wallet';
19
18
  import { WalletSchema } from '@aztec/aztec.js/wallet';
20
19
  import { jsonStringify } from '@aztec/foundation/json-rpc';
21
- import { parseWithOptionals, schemaHasMethod } from '@aztec/foundation/schemas';
20
+ import { getSchemaParameters, parseWithOptionals, schemaHasMethod } from '@aztec/foundation/schemas';
22
21
 
23
22
  import {
24
23
  type EncryptedPayload,
@@ -29,7 +28,7 @@ import {
29
28
  generateKeyPair,
30
29
  importPublicKey,
31
30
  } from '../../crypto.js';
32
- import { type WalletMessage, WalletMessageType, type WalletResponse } from '../../types.js';
31
+ import { type WalletMessage, WalletMessageType, type WalletResponse, type WalletSdkLogger } from '../../types.js';
33
32
 
34
33
  /**
35
34
  * A pending discovery request from a dApp (before user approval).
@@ -75,6 +74,8 @@ export interface IframeConnectionConfig {
75
74
  walletIcon?: string;
76
75
  /** Origins allowed to connect. If empty or undefined, all origins are allowed (dev mode). */
77
76
  allowedOrigins?: string[];
77
+ /** Logger used for diagnostics. */
78
+ logger: WalletSdkLogger;
78
79
  }
79
80
 
80
81
  /**
@@ -105,7 +106,7 @@ export interface IframeConnectionCallbacks {
105
106
  * @example
106
107
  * ```typescript
107
108
  * const handler = new IframeConnectionHandler(
108
- * { walletId: 'my-wallet', walletName: 'My Wallet', walletVersion: '1.0.0' },
109
+ * { walletId: 'my-wallet', walletName: 'My Wallet', walletVersion: '1.0.0', logger: console },
109
110
  * {
110
111
  * onPendingDiscovery: (session) => showApprovalUI(session),
111
112
  * getWallet: (appId, chainInfo) => createWalletForApp(appId, chainInfo),
@@ -117,12 +118,14 @@ export interface IframeConnectionCallbacks {
117
118
  export class IframeConnectionHandler {
118
119
  private pendingSessions = new Map<string, PendingSession>();
119
120
  private activeSessions = new Map<string, ActiveSession>();
120
- private log = createLogger('wallet:iframe-handler');
121
+ private log: WalletSdkLogger;
121
122
 
122
123
  constructor(
123
124
  private config: IframeConnectionConfig,
124
125
  private callbacks: IframeConnectionCallbacks,
125
- ) {}
126
+ ) {
127
+ this.log = config.logger;
128
+ }
126
129
 
127
130
  start(): void {
128
131
  window.addEventListener('message', this.handleMessage);
@@ -203,7 +206,18 @@ export class IframeConnectionHandler {
203
206
  case WalletMessageType.DISCONNECT:
204
207
  this.terminateSession(msg.sessionId);
205
208
  break;
209
+ case WalletMessageType.PING:
210
+ this.handlePing(msg.sessionId);
211
+ break;
212
+ }
213
+ }
214
+
215
+ private handlePing(sessionId: string): void {
216
+ const session = this.activeSessions.get(sessionId);
217
+ if (!session) {
218
+ return;
206
219
  }
220
+ this.postToOrigin(session.origin, { type: WalletMessageType.PONG, sessionId });
207
221
  }
208
222
 
209
223
  private handleDiscoveryRequest(msg: Record<string, unknown>, origin: string): void {
@@ -287,8 +301,7 @@ export class IframeConnectionHandler {
287
301
  if (!schemaHasMethod(WalletSchema, type)) {
288
302
  throw new Error(`Unknown wallet method: ${type}`);
289
303
  }
290
- // Zod's AnyZodTuple rejects optional tuple items typed as `T | undefined`
291
- const sanitizedArgs = await parseWithOptionals(args, WalletSchema[type].parameters() as any);
304
+ const sanitizedArgs = await parseWithOptionals(args, getSchemaParameters(WalletSchema[type]));
292
305
  result = await (wallet as Record<string, (...a: unknown[]) => Promise<unknown>>)[type](...sanitizedArgs);
293
306
  } catch (err: unknown) {
294
307
  error = err instanceof Error ? err.message : String(err);