@turnkey/core 1.0.0-beta.2 → 1.0.0-beta.4

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 (77) hide show
  1. package/dist/__clients__/core.d.ts +75 -2
  2. package/dist/__clients__/core.d.ts.map +1 -1
  3. package/dist/__clients__/core.js +637 -503
  4. package/dist/__clients__/core.js.map +1 -1
  5. package/dist/__clients__/core.mjs +640 -506
  6. package/dist/__clients__/core.mjs.map +1 -1
  7. package/dist/__generated__/sdk-client-base.d.ts +1 -1
  8. package/dist/__generated__/sdk-client-base.d.ts.map +1 -1
  9. package/dist/__generated__/sdk-client-base.js +156 -250
  10. package/dist/__generated__/sdk-client-base.js.map +1 -1
  11. package/dist/__generated__/sdk-client-base.mjs +156 -250
  12. package/dist/__generated__/sdk-client-base.mjs.map +1 -1
  13. package/dist/__generated__/version.d.ts +1 -1
  14. package/dist/__generated__/version.js +1 -1
  15. package/dist/__generated__/version.mjs +1 -1
  16. package/dist/__types__/base.d.ts +1 -1
  17. package/dist/__wallet__/base.d.ts +11 -0
  18. package/dist/__wallet__/base.d.ts.map +1 -1
  19. package/dist/__wallet__/base.js +12 -1
  20. package/dist/__wallet__/base.js.map +1 -1
  21. package/dist/__wallet__/base.mjs +12 -1
  22. package/dist/__wallet__/base.mjs.map +1 -1
  23. package/dist/__wallet__/connector.d.ts +31 -4
  24. package/dist/__wallet__/connector.d.ts.map +1 -1
  25. package/dist/__wallet__/connector.js +35 -5
  26. package/dist/__wallet__/connector.js.map +1 -1
  27. package/dist/__wallet__/connector.mjs +35 -5
  28. package/dist/__wallet__/connector.mjs.map +1 -1
  29. package/dist/__wallet__/mobile/manager.d.ts +21 -5
  30. package/dist/__wallet__/mobile/manager.d.ts.map +1 -1
  31. package/dist/__wallet__/mobile/manager.js +28 -11
  32. package/dist/__wallet__/mobile/manager.js.map +1 -1
  33. package/dist/__wallet__/mobile/manager.mjs +28 -11
  34. package/dist/__wallet__/mobile/manager.mjs.map +1 -1
  35. package/dist/__wallet__/stamper.d.ts +73 -2
  36. package/dist/__wallet__/stamper.d.ts.map +1 -1
  37. package/dist/__wallet__/stamper.js +79 -13
  38. package/dist/__wallet__/stamper.js.map +1 -1
  39. package/dist/__wallet__/stamper.mjs +79 -13
  40. package/dist/__wallet__/stamper.mjs.map +1 -1
  41. package/dist/__wallet__/wallet-connect/base.d.ts +99 -19
  42. package/dist/__wallet__/wallet-connect/base.d.ts.map +1 -1
  43. package/dist/__wallet__/wallet-connect/base.js +172 -75
  44. package/dist/__wallet__/wallet-connect/base.js.map +1 -1
  45. package/dist/__wallet__/wallet-connect/base.mjs +172 -75
  46. package/dist/__wallet__/wallet-connect/base.mjs.map +1 -1
  47. package/dist/__wallet__/wallet-connect/client.d.ts +22 -14
  48. package/dist/__wallet__/wallet-connect/client.d.ts.map +1 -1
  49. package/dist/__wallet__/wallet-connect/client.js +22 -14
  50. package/dist/__wallet__/wallet-connect/client.js.map +1 -1
  51. package/dist/__wallet__/wallet-connect/client.mjs +22 -14
  52. package/dist/__wallet__/wallet-connect/client.mjs.map +1 -1
  53. package/dist/__wallet__/web/manager.d.ts +20 -12
  54. package/dist/__wallet__/web/manager.d.ts.map +1 -1
  55. package/dist/__wallet__/web/manager.js +29 -21
  56. package/dist/__wallet__/web/manager.js.map +1 -1
  57. package/dist/__wallet__/web/manager.mjs +29 -21
  58. package/dist/__wallet__/web/manager.mjs.map +1 -1
  59. package/dist/__wallet__/web/native/ethereum.d.ts +45 -11
  60. package/dist/__wallet__/web/native/ethereum.d.ts.map +1 -1
  61. package/dist/__wallet__/web/native/ethereum.js +58 -17
  62. package/dist/__wallet__/web/native/ethereum.js.map +1 -1
  63. package/dist/__wallet__/web/native/ethereum.mjs +58 -17
  64. package/dist/__wallet__/web/native/ethereum.mjs.map +1 -1
  65. package/dist/__wallet__/web/native/solana.d.ts +56 -3
  66. package/dist/__wallet__/web/native/solana.d.ts.map +1 -1
  67. package/dist/__wallet__/web/native/solana.js +95 -36
  68. package/dist/__wallet__/web/native/solana.js.map +1 -1
  69. package/dist/__wallet__/web/native/solana.mjs +95 -36
  70. package/dist/__wallet__/web/native/solana.mjs.map +1 -1
  71. package/dist/utils.d.ts +24 -1
  72. package/dist/utils.d.ts.map +1 -1
  73. package/dist/utils.js +54 -0
  74. package/dist/utils.js.map +1 -1
  75. package/dist/utils.mjs +54 -1
  76. package/dist/utils.mjs.map +1 -1
  77. package/package.json +7 -7
@@ -32,7 +32,7 @@ class TurnkeyClient {
32
32
  * @throws {TurnkeyError} If there is an error during passkey creation, or if the platform is unsupported.
33
33
  */
34
34
  this.createPasskey = async (params) => {
35
- try {
35
+ return utils.withTurnkeyErrorHandling(async () => {
36
36
  const name = params?.name || "A Passkey";
37
37
  const displayName = params?.displayName || "A Passkey";
38
38
  let passkey;
@@ -70,16 +70,16 @@ class TurnkeyClient {
70
70
  throw new sdkTypes.TurnkeyError("Unsupported platform for passkey creation", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
71
71
  }
72
72
  return passkey;
73
- }
74
- catch (error) {
75
- if (error?.message?.includes("timed out or was not allowed")) {
76
- throw new sdkTypes.TurnkeyError("Passkey creation was cancelled by the user.", sdkTypes.TurnkeyErrorCodes.SELECT_PASSKEY_CANCELLED, error);
77
- }
78
- else if (error instanceof sdkTypes.TurnkeyError) {
79
- throw error;
80
- }
81
- throw new sdkTypes.TurnkeyError(`Failed to create passkey`, sdkTypes.TurnkeyErrorCodes.CREATE_PASSKEY_ERROR, error);
82
- }
73
+ }, {
74
+ errorMessage: "Failed to create passkey",
75
+ errorCode: sdkTypes.TurnkeyErrorCodes.CREATE_PASSKEY_ERROR,
76
+ customMessageByMessages: {
77
+ "timed out or was not allowed": {
78
+ message: "Passkey creation was cancelled by the user.",
79
+ code: sdkTypes.TurnkeyErrorCodes.SELECT_PASSKEY_CANCELLED,
80
+ },
81
+ },
82
+ });
83
83
  };
84
84
  /**
85
85
  * Logs out the current client session.
@@ -93,7 +93,7 @@ class TurnkeyClient {
93
93
  * @throws {TurnkeyError} If there is no active session or if there is an error during the logout process.
94
94
  */
95
95
  this.logout = async (params) => {
96
- try {
96
+ utils.withTurnkeyErrorHandling(async () => {
97
97
  if (params?.sessionKey) {
98
98
  const session = await this.storageManager.getSession(params.sessionKey);
99
99
  this.storageManager.clearSession(params.sessionKey);
@@ -110,12 +110,10 @@ class TurnkeyClient {
110
110
  throw new sdkTypes.TurnkeyError("No active session found to log out from.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
111
111
  }
112
112
  }
113
- }
114
- catch (error) {
115
- if (error instanceof sdkTypes.TurnkeyError)
116
- throw error;
117
- throw new sdkTypes.TurnkeyError(`Failed to log out`, sdkTypes.TurnkeyErrorCodes.LOGOUT_ERROR, error);
118
- }
113
+ }, {
114
+ errorMessage: "Failed to log out",
115
+ errorCode: sdkTypes.TurnkeyErrorCodes.LOGOUT_ERROR,
116
+ });
119
117
  };
120
118
  /**
121
119
  * Logs in a user using a passkey, optionally specifying the public key, session key, and session expiration.
@@ -133,16 +131,17 @@ class TurnkeyClient {
133
131
  * @throws {TurnkeyError} If there is an error during the passkey login process or if the user cancels the passkey prompt.
134
132
  */
135
133
  this.loginWithPasskey = async (params) => {
136
- let generatedKeyPair = null;
137
- try {
138
- const publicKey = params?.publicKey || (await this.apiKeyStamper?.createKeyPair());
134
+ let generatedKeyPair = undefined;
135
+ return await utils.withTurnkeyErrorHandling(async () => {
136
+ generatedKeyPair =
137
+ params?.publicKey || (await this.apiKeyStamper?.createKeyPair());
139
138
  const sessionKey = params?.sessionKey || base.SessionKey.DefaultSessionkey;
140
139
  const expirationSeconds = params?.expirationSeconds || base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
141
- if (!publicKey) {
140
+ if (!generatedKeyPair) {
142
141
  throw new sdkTypes.TurnkeyError("A publickey could not be found or generated.", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
143
142
  }
144
143
  const sessionResponse = await this.httpClient.stampLogin({
145
- publicKey,
144
+ publicKey: generatedKeyPair,
146
145
  organizationId: this.config.organizationId,
147
146
  expirationSeconds,
148
147
  }, base.StamperType.Passkey);
@@ -150,28 +149,29 @@ class TurnkeyClient {
150
149
  sessionToken: sessionResponse.session,
151
150
  sessionKey,
152
151
  });
153
- // Key pair was successfully used, set to null to prevent cleanup
154
- generatedKeyPair = null;
152
+ generatedKeyPair = undefined; // Key pair was successfully used, set to null to prevent cleanup
155
153
  return sessionResponse.session;
156
- }
157
- catch (error) {
158
- if (error?.message?.includes("timed out or was not allowed"))
159
- throw new sdkTypes.TurnkeyError("Passkey login was cancelled by the user.", sdkTypes.TurnkeyErrorCodes.SELECT_PASSKEY_CANCELLED, error);
160
- if (error instanceof sdkTypes.TurnkeyError)
161
- throw error;
162
- throw new sdkTypes.TurnkeyError(`Unable to log in with the provided passkey`, sdkTypes.TurnkeyErrorCodes.PASSKEY_LOGIN_AUTH_ERROR, error);
163
- }
164
- finally {
165
- // Clean up the generated key pair if it wasn't successfully used
166
- if (generatedKeyPair) {
167
- try {
168
- await this.apiKeyStamper?.deleteKeyPair(generatedKeyPair);
169
- }
170
- catch (cleanupError) {
171
- throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
154
+ }, {
155
+ errorMessage: "Unable to log in with the provided passkey",
156
+ errorCode: sdkTypes.TurnkeyErrorCodes.PASSKEY_LOGIN_AUTH_ERROR,
157
+ customMessageByMessages: {
158
+ "timed out or was not allowed": {
159
+ message: "Passkey login was cancelled by the user.",
160
+ code: sdkTypes.TurnkeyErrorCodes.SELECT_PASSKEY_CANCELLED,
161
+ },
162
+ },
163
+ }, {
164
+ finallyFn: async () => {
165
+ if (generatedKeyPair) {
166
+ try {
167
+ await this.apiKeyStamper?.deleteKeyPair(generatedKeyPair);
168
+ }
169
+ catch (cleanupError) {
170
+ throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
171
+ }
172
172
  }
173
- }
174
- }
173
+ },
174
+ });
175
175
  };
176
176
  /**
177
177
  * Signs up a user using a passkey, creating a new sub-organization and session.
@@ -191,8 +191,8 @@ class TurnkeyClient {
191
191
  */
192
192
  this.signUpWithPasskey = async (params) => {
193
193
  const { createSubOrgParams, passkeyDisplayName, sessionKey = base.SessionKey.DefaultSessionkey, expirationSeconds = base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params || {};
194
- let generatedKeyPair = null;
195
- try {
194
+ let generatedKeyPair = undefined;
195
+ return utils.withTurnkeyErrorHandling(async () => {
196
196
  generatedKeyPair = await this.apiKeyStamper?.createKeyPair();
197
197
  const passkeyName = passkeyDisplayName || `passkey-${Date.now()}`;
198
198
  // A passkey will be created automatically when you call this function. The name is passed in
@@ -241,26 +241,24 @@ class TurnkeyClient {
241
241
  sessionToken: sessionResponse.session,
242
242
  sessionKey,
243
243
  });
244
- generatedKeyPair = null; // Key pair was successfully used, set to null to prevent cleanup
244
+ generatedKeyPair = undefined; // Key pair was successfully used, set to null to prevent cleanup
245
245
  return sessionResponse.session;
246
- }
247
- catch (error) {
248
- if (error instanceof sdkTypes.TurnkeyError)
249
- throw error;
250
- throw new sdkTypes.TurnkeyError(`Failed to sign up with passkey`, sdkTypes.TurnkeyErrorCodes.PASSKEY_SIGNUP_AUTH_ERROR, error);
251
- }
252
- finally {
253
- // Clean up the generated key pair if it wasn't successfully used
254
- this.apiKeyStamper?.clearPublicKeyOverride();
255
- if (generatedKeyPair) {
256
- try {
257
- await this.apiKeyStamper?.deleteKeyPair(generatedKeyPair);
258
- }
259
- catch (cleanupError) {
260
- throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
246
+ }, {
247
+ errorCode: sdkTypes.TurnkeyErrorCodes.PASSKEY_SIGNUP_AUTH_ERROR,
248
+ errorMessage: "Failed to sign up with passkey",
249
+ }, {
250
+ finallyFn: async () => {
251
+ this.apiKeyStamper?.clearPublicKeyOverride();
252
+ if (generatedKeyPair) {
253
+ try {
254
+ await this.apiKeyStamper?.deleteKeyPair(generatedKeyPair);
255
+ }
256
+ catch (cleanupError) {
257
+ throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
258
+ }
261
259
  }
262
- }
263
- }
260
+ },
261
+ });
264
262
  };
265
263
  /**
266
264
  * Retrieves wallet providers from the initialized wallet manager.
@@ -273,15 +271,15 @@ class TurnkeyClient {
273
271
  * @throws {TurnkeyError} If the wallet manager is uninitialized or provider retrieval fails.
274
272
  */
275
273
  this.getWalletProviders = async (chain) => {
276
- try {
274
+ return utils.withTurnkeyErrorHandling(async () => {
277
275
  if (!this.walletManager) {
278
276
  throw new sdkTypes.TurnkeyError("Wallet manager is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
279
277
  }
280
278
  return await this.walletManager.getProviders(chain);
281
- }
282
- catch (error) {
283
- throw new sdkTypes.TurnkeyError(`Unable to get wallet providers`, sdkTypes.TurnkeyErrorCodes.FETCH_WALLETS_ERROR, error);
284
- }
279
+ }, {
280
+ errorMessage: "Unable to get wallet providers",
281
+ errorCode: sdkTypes.TurnkeyErrorCodes.FETCH_WALLETS_ERROR,
282
+ });
285
283
  };
286
284
  /**
287
285
  * Connects the specified wallet account.
@@ -293,15 +291,15 @@ class TurnkeyClient {
293
291
  * @throws {TurnkeyError} If the wallet manager is uninitialized or the connection fails.
294
292
  */
295
293
  this.connectWalletAccount = async (walletProvider) => {
296
- if (!this.walletManager?.connector) {
297
- throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
298
- }
299
- try {
294
+ return utils.withTurnkeyErrorHandling(async () => {
295
+ if (!this.walletManager?.connector) {
296
+ throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
297
+ }
300
298
  await this.walletManager.connector.connectWalletAccount(walletProvider);
301
- }
302
- catch (error) {
303
- throw new sdkTypes.TurnkeyError("Unable to connect wallet account", sdkTypes.TurnkeyErrorCodes.CONNECT_WALLET_ACCOUNT_ERROR, error);
304
- }
299
+ }, {
300
+ errorMessage: "Unable to connect wallet account",
301
+ errorCode: sdkTypes.TurnkeyErrorCodes.CONNECT_WALLET_ACCOUNT_ERROR,
302
+ });
305
303
  };
306
304
  /**
307
305
  * Disconnects the specified wallet account.
@@ -313,15 +311,15 @@ class TurnkeyClient {
313
311
  * @throws {TurnkeyError} If the wallet manager is uninitialized or the disconnection fails.
314
312
  */
315
313
  this.disconnectWalletAccount = async (walletProvider) => {
316
- if (!this.walletManager?.connector) {
317
- throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
318
- }
319
- try {
314
+ return utils.withTurnkeyErrorHandling(async () => {
315
+ if (!this.walletManager?.connector) {
316
+ throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
317
+ }
320
318
  await this.walletManager.connector.disconnectWalletAccount(walletProvider);
321
- }
322
- catch (error) {
323
- throw new sdkTypes.TurnkeyError("Unable to disconnect wallet account", sdkTypes.TurnkeyErrorCodes.DISCONNECT_WALLET_ACCOUNT_ERROR, error);
324
- }
319
+ }, {
320
+ errorMessage: "Unable to disconnect wallet account",
321
+ errorCode: sdkTypes.TurnkeyErrorCodes.DISCONNECT_WALLET_ACCOUNT_ERROR,
322
+ });
325
323
  };
326
324
  /**
327
325
  * Switches the specified wallet provider to a different blockchain chain.
@@ -336,22 +334,22 @@ class TurnkeyClient {
336
334
  * @throws {TurnkeyError} If the wallet manager is uninitialized, the provider is not connected, or the switch fails.
337
335
  */
338
336
  this.switchWalletProviderChain = async (walletProvider, chainOrId) => {
339
- if (!this.walletManager?.connector) {
340
- throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
341
- }
342
- if (walletProvider.connectedAddresses.length === 0) {
343
- throw new sdkTypes.TurnkeyError("You can not switch chains for a provider that is not connected", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
344
- }
345
- // if the wallet provider is already on the desired chain, do nothing
346
- if (walletProvider.chainInfo.namespace === chainOrId) {
347
- return;
348
- }
349
- try {
337
+ return utils.withTurnkeyErrorHandling(async () => {
338
+ if (!this.walletManager?.connector) {
339
+ throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
340
+ }
341
+ if (walletProvider.connectedAddresses.length === 0) {
342
+ throw new sdkTypes.TurnkeyError("You can not switch chains for a provider that is not connected", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
343
+ }
344
+ // if the wallet provider is already on the desired chain, do nothing
345
+ if (walletProvider.chainInfo.namespace === chainOrId) {
346
+ return;
347
+ }
350
348
  await this.walletManager.connector.switchChain(walletProvider, chainOrId);
351
- }
352
- catch (error) {
353
- throw new sdkTypes.TurnkeyError("Unable to switch wallet account chain", sdkTypes.TurnkeyErrorCodes.SWITCH_WALLET_CHAIN_ERROR, error);
354
- }
349
+ }, {
350
+ errorMessage: "Unable to switch wallet account chain",
351
+ errorCode: sdkTypes.TurnkeyErrorCodes.SWITCH_WALLET_CHAIN_ERROR,
352
+ });
355
353
  };
356
354
  /**
357
355
  * Logs in a user using the specified wallet provider.
@@ -370,11 +368,11 @@ class TurnkeyClient {
370
368
  * @throws {TurnkeyError} If the wallet stamper is uninitialized, a public key cannot be found or generated, or login fails.
371
369
  */
372
370
  this.loginWithWallet = async (params) => {
373
- if (!this.walletManager?.stamper) {
374
- throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
375
- }
376
- try {
377
- const publicKey = params.publicKey || (await this.apiKeyStamper?.createKeyPair());
371
+ let publicKey = params.publicKey || (await this.apiKeyStamper?.createKeyPair());
372
+ return utils.withTurnkeyErrorHandling(async () => {
373
+ if (!this.walletManager?.stamper) {
374
+ throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
375
+ }
378
376
  const sessionKey = params.sessionKey || base.SessionKey.DefaultSessionkey;
379
377
  const walletProvider = params.walletProvider;
380
378
  const expirationSeconds = params?.expirationSeconds || base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
@@ -392,12 +390,23 @@ class TurnkeyClient {
392
390
  sessionKey,
393
391
  });
394
392
  return sessionResponse.session;
395
- }
396
- catch (error) {
397
- if (error instanceof sdkTypes.TurnkeyError)
398
- throw error;
399
- throw new sdkTypes.TurnkeyError(`Unable to log in with the provided wallet`, sdkTypes.TurnkeyErrorCodes.WALLET_LOGIN_AUTH_ERROR, error);
400
- }
393
+ }, {
394
+ errorMessage: "Unable to log in with the provided wallet",
395
+ errorCode: sdkTypes.TurnkeyErrorCodes.WALLET_LOGIN_AUTH_ERROR,
396
+ }, {
397
+ finallyFn: async () => {
398
+ // Clean up the generated key pair if it wasn't successfully used
399
+ this.apiKeyStamper?.clearPublicKeyOverride();
400
+ if (publicKey) {
401
+ try {
402
+ await this.apiKeyStamper?.deleteKeyPair(publicKey);
403
+ }
404
+ catch (cleanupError) {
405
+ throw new sdkTypes.TurnkeyError("Failed to clean up generated key pair", sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
406
+ }
407
+ }
408
+ },
409
+ });
401
410
  };
402
411
  /**
403
412
  * Signs up a user using a wallet, creating a new sub-organization and session.
@@ -417,11 +426,11 @@ class TurnkeyClient {
417
426
  */
418
427
  this.signUpWithWallet = async (params) => {
419
428
  const { walletProvider, createSubOrgParams, sessionKey = base.SessionKey.DefaultSessionkey, expirationSeconds = base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS, } = params;
420
- if (!this.walletManager?.stamper) {
421
- throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
422
- }
423
- let generatedKeyPair = null;
424
- try {
429
+ let generatedKeyPair = undefined;
430
+ return utils.withTurnkeyErrorHandling(async () => {
431
+ if (!this.walletManager?.stamper) {
432
+ throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
433
+ }
425
434
  generatedKeyPair = await this.apiKeyStamper?.createKeyPair();
426
435
  this.walletManager.stamper.setProvider(walletProvider.interfaceType, walletProvider);
427
436
  const publicKey = await this.walletManager.stamper.getPublicKey(walletProvider.interfaceType, walletProvider);
@@ -464,24 +473,25 @@ class TurnkeyClient {
464
473
  sessionToken: sessionResponse.session,
465
474
  sessionKey,
466
475
  });
467
- generatedKeyPair = null; // Key pair was successfully used, set to null to prevent cleanup
476
+ generatedKeyPair = undefined; // Key pair was successfully used, set to null to prevent cleanup
468
477
  return sessionResponse.session;
469
- }
470
- catch (error) {
471
- throw new sdkTypes.TurnkeyError("Failed to sign up with wallet", sdkTypes.TurnkeyErrorCodes.WALLET_SIGNUP_AUTH_ERROR, error);
472
- }
473
- finally {
474
- // Clean up the generated key pair if it wasn't successfully used
475
- this.apiKeyStamper?.clearPublicKeyOverride();
476
- if (generatedKeyPair) {
477
- try {
478
- await this.apiKeyStamper?.deleteKeyPair(generatedKeyPair);
479
- }
480
- catch (cleanupError) {
481
- throw new sdkTypes.TurnkeyError("Failed to clean up generated key pair", sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
478
+ }, {
479
+ errorMessage: "Failed to sign up with wallet",
480
+ errorCode: sdkTypes.TurnkeyErrorCodes.WALLET_SIGNUP_AUTH_ERROR,
481
+ }, {
482
+ finallyFn: async () => {
483
+ // Clean up the generated key pair if it wasn't successfully used
484
+ this.apiKeyStamper?.clearPublicKeyOverride();
485
+ if (generatedKeyPair) {
486
+ try {
487
+ await this.apiKeyStamper?.deleteKeyPair(generatedKeyPair);
488
+ }
489
+ catch (cleanupError) {
490
+ throw new sdkTypes.TurnkeyError("Failed to clean up generated key pair", sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
491
+ }
482
492
  }
483
- }
484
- }
493
+ },
494
+ });
485
495
  };
486
496
  /**
487
497
  * Logs in an existing user or signs up a new user using a wallet, creating a new sub-organization if needed.
@@ -501,25 +511,36 @@ class TurnkeyClient {
501
511
  * @throws {TurnkeyError} If there is an error during wallet authentication, sub-organization creation, or session storage.
502
512
  */
503
513
  this.loginOrSignupWithWallet = async (params) => {
504
- if (!this.walletManager?.stamper) {
505
- throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
506
- }
507
514
  const createSubOrgParams = params.createSubOrgParams;
508
515
  const sessionKey = params.sessionKey || base.SessionKey.DefaultSessionkey;
509
516
  const walletProvider = params.walletProvider;
510
517
  const expirationSeconds = params.expirationSeconds || base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
511
- let generatedKeyPair = null;
512
- try {
518
+ let generatedKeyPair = undefined;
519
+ return utils.withTurnkeyErrorHandling(async () => {
520
+ if (!this.walletManager?.stamper) {
521
+ throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
522
+ }
513
523
  generatedKeyPair = await this.apiKeyStamper?.createKeyPair();
514
524
  this.walletManager.stamper.setProvider(walletProvider.interfaceType, walletProvider);
515
525
  // here we sign the request with the wallet, but we don't send it to the Turnkey yet
516
526
  // this is because we need to check if the subOrg exists first, and create one if it doesn't
517
527
  // once we have the subOrg for the publicKey, we then can send the request to the Turnkey
518
- const signedRequest = await this.httpClient.stampStampLogin({
519
- publicKey: generatedKeyPair,
520
- organizationId: this.config.organizationId,
521
- expirationSeconds,
522
- }, base.StamperType.Wallet);
528
+ const signedRequest = await utils.withTurnkeyErrorHandling(async () => {
529
+ return this.httpClient.stampStampLogin({
530
+ publicKey: generatedKeyPair,
531
+ organizationId: this.config.organizationId,
532
+ expirationSeconds,
533
+ }, base.StamperType.Wallet);
534
+ }, {
535
+ errorMessage: "Failed to create stamped request for wallet login",
536
+ errorCode: sdkTypes.TurnkeyErrorCodes.WALLET_LOGIN_OR_SIGNUP_ERROR,
537
+ customMessageByMessages: {
538
+ "Failed to sign the message": {
539
+ message: "Wallet auth was cancelled by the user.",
540
+ code: sdkTypes.TurnkeyErrorCodes.CONNECT_WALLET_CANCELLED,
541
+ },
542
+ },
543
+ });
523
544
  if (!signedRequest) {
524
545
  throw new sdkTypes.TurnkeyError("Failed to create stamped request for wallet login", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
525
546
  }
@@ -597,10 +618,20 @@ class TurnkeyClient {
597
618
  sessionKey,
598
619
  });
599
620
  return sessionToken;
600
- }
601
- catch (error) {
602
- throw new sdkTypes.TurnkeyError(`Unable to log in or signup with the provided wallet`, sdkTypes.TurnkeyErrorCodes.WALLET_LOGIN_OR_SIGNUP_ERROR, error);
603
- }
621
+ }, {
622
+ errorCode: sdkTypes.TurnkeyErrorCodes.WALLET_LOGIN_OR_SIGNUP_ERROR,
623
+ errorMessage: "Failed to log in or sign up with wallet",
624
+ catchFn: async () => {
625
+ if (generatedKeyPair) {
626
+ try {
627
+ await this.apiKeyStamper?.deleteKeyPair(generatedKeyPair);
628
+ }
629
+ catch (cleanupError) {
630
+ throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
631
+ }
632
+ }
633
+ },
634
+ });
604
635
  };
605
636
  /**
606
637
  * Initializes the OTP process by sending an OTP code to the provided contact.
@@ -615,23 +646,22 @@ class TurnkeyClient {
615
646
  * @throws {TurnkeyError} If there is an error during the OTP initialization process or if the maximum number of OTPs has been reached.
616
647
  */
617
648
  this.initOtp = async (params) => {
618
- try {
649
+ return utils.withTurnkeyErrorHandling(async () => {
619
650
  const initOtpRes = await this.httpClient.proxyInitOtp(params);
620
651
  if (!initOtpRes || !initOtpRes.otpId) {
621
652
  throw new sdkTypes.TurnkeyError("Failed to initialize OTP: otpId is missing", sdkTypes.TurnkeyErrorCodes.INIT_OTP_ERROR);
622
653
  }
623
654
  return initOtpRes.otpId;
624
- }
625
- catch (error) {
626
- if (error instanceof sdkTypes.TurnkeyNetworkError) {
627
- if (error.message.includes("Max number of OTPs have been initiated")) {
628
- throw new sdkTypes.TurnkeyError("Max number of OTPs have been initiated", sdkTypes.TurnkeyErrorCodes.MAX_OTP_INITIATED_ERROR);
629
- }
630
- }
631
- if (error instanceof sdkTypes.TurnkeyError)
632
- throw error;
633
- throw new sdkTypes.TurnkeyError(`Failed to initialize OTP`, sdkTypes.TurnkeyErrorCodes.INIT_OTP_ERROR, error);
634
- }
655
+ }, {
656
+ errorMessage: "Failed to initialize OTP",
657
+ errorCode: sdkTypes.TurnkeyErrorCodes.INIT_OTP_ERROR,
658
+ customMessageByMessages: {
659
+ "Max number of OTPs have been initiated": {
660
+ message: "Maximum number of OTPs has been reached for this contact.",
661
+ code: sdkTypes.TurnkeyErrorCodes.MAX_OTP_INITIATED_ERROR,
662
+ },
663
+ },
664
+ });
635
665
  };
636
666
  /**
637
667
  * Verifies the OTP code sent to the user.
@@ -652,7 +682,7 @@ class TurnkeyClient {
652
682
  */
653
683
  this.verifyOtp = async (params) => {
654
684
  const { otpId, otpCode, contact, otpType } = params;
655
- try {
685
+ return utils.withTurnkeyErrorHandling(async () => {
656
686
  const verifyOtpRes = await this.httpClient.proxyVerifyOtp({
657
687
  otpId: otpId,
658
688
  otpCode: otpCode,
@@ -672,16 +702,16 @@ class TurnkeyClient {
672
702
  subOrganizationId: subOrganizationId,
673
703
  verificationToken: verifyOtpRes.verificationToken,
674
704
  };
675
- }
676
- catch (error) {
677
- if (error instanceof base.TurnkeyRequestError &&
678
- error.message.includes("Invalid OTP code")) {
679
- throw new sdkTypes.TurnkeyError("Invalid OTP code provided", sdkTypes.TurnkeyErrorCodes.INVALID_OTP_CODE, error.message);
680
- }
681
- else if (error instanceof sdkTypes.TurnkeyError)
682
- throw error;
683
- throw new sdkTypes.TurnkeyError(`Failed to verify OTP`, sdkTypes.TurnkeyErrorCodes.VERIFY_OTP_ERROR, error);
684
- }
705
+ }, {
706
+ errorMessage: "Failed to verify OTP",
707
+ errorCode: sdkTypes.TurnkeyErrorCodes.VERIFY_OTP_ERROR,
708
+ customMessageByMessages: {
709
+ "Invalid OTP code": {
710
+ message: "The provided OTP code is invalid.",
711
+ code: sdkTypes.TurnkeyErrorCodes.INVALID_OTP_CODE,
712
+ },
713
+ },
714
+ });
685
715
  };
686
716
  /**
687
717
  * Logs in a user using an OTP verification token.
@@ -701,7 +731,7 @@ class TurnkeyClient {
701
731
  */
702
732
  this.loginWithOtp = async (params) => {
703
733
  const { verificationToken, invalidateExisting = false, publicKey = await this.apiKeyStamper?.createKeyPair(), sessionKey = base.SessionKey.DefaultSessionkey, } = params;
704
- try {
734
+ return utils.withTurnkeyErrorHandling(async () => {
705
735
  const res = await this.httpClient.proxyOtpLogin({
706
736
  verificationToken,
707
737
  publicKey: publicKey,
@@ -719,21 +749,21 @@ class TurnkeyClient {
719
749
  sessionKey,
720
750
  });
721
751
  return loginRes.session;
722
- }
723
- catch (error) {
724
- if (error instanceof sdkTypes.TurnkeyError)
725
- throw error;
726
- // Clean up the generated key pair if it wasn't successfully used
727
- if (publicKey) {
728
- try {
729
- await this.apiKeyStamper?.deleteKeyPair(publicKey);
730
- }
731
- catch (cleanupError) {
732
- throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
752
+ }, {
753
+ errorMessage: "Failed to log in with OTP",
754
+ errorCode: sdkTypes.TurnkeyErrorCodes.OTP_LOGIN_ERROR,
755
+ catchFn: async () => {
756
+ // Clean up the generated key pair if it wasn't successfully used
757
+ if (publicKey) {
758
+ try {
759
+ await this.apiKeyStamper?.deleteKeyPair(publicKey);
760
+ }
761
+ catch (cleanupError) {
762
+ throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
763
+ }
733
764
  }
734
- }
735
- throw new sdkTypes.TurnkeyError(`Failed to log in with OTP`, sdkTypes.TurnkeyErrorCodes.OTP_LOGIN_ERROR, error);
736
- }
765
+ },
766
+ });
737
767
  };
738
768
  /**
739
769
  * Signs up a user using an OTP verification token.
@@ -764,8 +794,8 @@ class TurnkeyClient {
764
794
  verificationToken,
765
795
  },
766
796
  });
767
- const generatedKeyPair = await this.apiKeyStamper?.createKeyPair();
768
- try {
797
+ return utils.withTurnkeyErrorHandling(async () => {
798
+ const generatedKeyPair = await this.apiKeyStamper?.createKeyPair();
769
799
  const res = await this.httpClient.proxySignup(signUpBody);
770
800
  if (!res) {
771
801
  throw new sdkTypes.TurnkeyError(`Auth proxy OTP sign up failed`, sdkTypes.TurnkeyErrorCodes.OTP_SIGNUP_ERROR);
@@ -776,12 +806,10 @@ class TurnkeyClient {
776
806
  ...(invalidateExisting && { invalidateExisting }),
777
807
  ...(sessionKey && { sessionKey }),
778
808
  });
779
- }
780
- catch (error) {
781
- if (error instanceof sdkTypes.TurnkeyError)
782
- throw error;
783
- throw new sdkTypes.TurnkeyError(`Failed to sign up with OTP`, sdkTypes.TurnkeyErrorCodes.OTP_SIGNUP_ERROR, error);
784
- }
809
+ }, {
810
+ errorCode: sdkTypes.TurnkeyErrorCodes.OTP_SIGNUP_ERROR,
811
+ errorMessage: "Failed to sign up with OTP",
812
+ });
785
813
  };
786
814
  /**
787
815
  * Completes the OTP authentication flow by verifying the OTP code and then either signing up or logging in the user.
@@ -805,7 +833,7 @@ class TurnkeyClient {
805
833
  */
806
834
  this.completeOtp = async (params) => {
807
835
  const { otpId, otpCode, contact, otpType, publicKey, invalidateExisting = false, sessionKey, createSubOrgParams, } = params;
808
- try {
836
+ return utils.withTurnkeyErrorHandling(async () => {
809
837
  const { subOrganizationId, verificationToken } = await this.verifyOtp({
810
838
  otpId: otpId,
811
839
  otpCode: otpCode,
@@ -835,12 +863,10 @@ class TurnkeyClient {
835
863
  ...(sessionKey && { sessionKey }),
836
864
  });
837
865
  }
838
- }
839
- catch (error) {
840
- if (error instanceof sdkTypes.TurnkeyError)
841
- throw error;
842
- throw new sdkTypes.TurnkeyError(`Failed to complete OTP process`, sdkTypes.TurnkeyErrorCodes.OTP_COMPLETION_ERROR, error);
843
- }
866
+ }, {
867
+ errorMessage: "Failed to complete OTP process",
868
+ errorCode: sdkTypes.TurnkeyErrorCodes.OTP_COMPLETION_ERROR,
869
+ });
844
870
  };
845
871
  /**
846
872
  * Completes the OAuth authentication flow by either signing up or logging in the user, depending on whether a sub-organization already exists for the provided OIDC token.
@@ -862,7 +888,7 @@ class TurnkeyClient {
862
888
  */
863
889
  this.completeOauth = async (params) => {
864
890
  const { oidcToken, publicKey, createSubOrgParams, providerName = "OpenID Connect Provider" + Date.now(), sessionKey = base.SessionKey.DefaultSessionkey, invalidateExisting = false, } = params;
865
- try {
891
+ return utils.withTurnkeyErrorHandling(async () => {
866
892
  const accountRes = await this.httpClient.proxyGetAccount({
867
893
  filterType: "OIDC_TOKEN",
868
894
  filterValue: oidcToken,
@@ -889,12 +915,10 @@ class TurnkeyClient {
889
915
  }),
890
916
  });
891
917
  }
892
- }
893
- catch (error) {
894
- if (error instanceof sdkTypes.TurnkeyError)
895
- throw error;
896
- throw new sdkTypes.TurnkeyError(`Failed to handle Google OAuth login`, sdkTypes.TurnkeyErrorCodes.OAUTH_LOGIN_ERROR, error);
897
- }
918
+ }, {
919
+ errorMessage: "Failed to complete OAuth process",
920
+ errorCode: sdkTypes.TurnkeyErrorCodes.OAUTH_LOGIN_ERROR,
921
+ });
898
922
  };
899
923
  /**
900
924
  * Logs in a user using OAuth authentication.
@@ -913,10 +937,10 @@ class TurnkeyClient {
913
937
  */
914
938
  this.loginWithOauth = async (params) => {
915
939
  const { oidcToken, invalidateExisting = false, publicKey, sessionKey = base.SessionKey.DefaultSessionkey, } = params;
916
- if (!publicKey) {
917
- throw new sdkTypes.TurnkeyError("Public key must be provided to log in with OAuth. Please create a key pair first.", sdkTypes.TurnkeyErrorCodes.MISSING_PARAMS);
918
- }
919
- try {
940
+ return utils.withTurnkeyErrorHandling(async () => {
941
+ if (!publicKey) {
942
+ throw new sdkTypes.TurnkeyError("Public key must be provided to log in with OAuth. Please create a key pair first.", sdkTypes.TurnkeyErrorCodes.MISSING_PARAMS);
943
+ }
920
944
  const loginRes = await this.httpClient.proxyOAuthLogin({
921
945
  oidcToken,
922
946
  publicKey,
@@ -933,21 +957,27 @@ class TurnkeyClient {
933
957
  sessionKey,
934
958
  });
935
959
  return loginRes.session;
936
- }
937
- catch (error) {
938
- if (error instanceof sdkTypes.TurnkeyError)
939
- throw error;
940
- // Clean up the generated key pair if it wasn't successfully used
941
- if (publicKey) {
942
- try {
943
- await this.apiKeyStamper?.deleteKeyPair(publicKey);
944
- }
945
- catch (cleanupError) {
946
- throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
960
+ }, {
961
+ errorMessage: "Failed to complete OAuth login",
962
+ errorCode: sdkTypes.TurnkeyErrorCodes.OAUTH_LOGIN_ERROR,
963
+ customMessageByMessages: {
964
+ "OAUTH disallowed": {
965
+ message: "OAuth is disabled on the dashboard for this organization.",
966
+ code: sdkTypes.TurnkeyErrorCodes.AUTH_METHOD_NOT_ENABLED,
967
+ },
968
+ },
969
+ catchFn: async () => {
970
+ // Clean up the generated key pair if it wasn't successfully used
971
+ if (publicKey) {
972
+ try {
973
+ await this.apiKeyStamper?.deleteKeyPair(publicKey);
974
+ }
975
+ catch (cleanupError) {
976
+ throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
977
+ }
947
978
  }
948
- }
949
- throw new sdkTypes.TurnkeyError(`Failed to log in with oauth`, sdkTypes.TurnkeyErrorCodes.OAUTH_LOGIN_ERROR, error);
950
- }
979
+ },
980
+ });
951
981
  };
952
982
  /**
953
983
  * Signs up a user using OAuth authentication.
@@ -967,7 +997,7 @@ class TurnkeyClient {
967
997
  */
968
998
  this.signUpWithOauth = async (params) => {
969
999
  const { oidcToken, publicKey, providerName, createSubOrgParams } = params;
970
- try {
1000
+ return utils.withTurnkeyErrorHandling(async () => {
971
1001
  const signUpBody = utils.buildSignUpBody({
972
1002
  createSubOrgParams: {
973
1003
  ...createSubOrgParams,
@@ -987,12 +1017,10 @@ class TurnkeyClient {
987
1017
  oidcToken,
988
1018
  publicKey: publicKey,
989
1019
  });
990
- }
991
- catch (error) {
992
- if (error instanceof sdkTypes.TurnkeyError)
993
- throw error;
994
- throw new sdkTypes.TurnkeyError(`Failed to sign up with OAuth`, sdkTypes.TurnkeyErrorCodes.OAUTH_SIGNUP_ERROR, error);
995
- }
1020
+ }, {
1021
+ errorMessage: "Failed to sign up with OAuth",
1022
+ errorCode: sdkTypes.TurnkeyErrorCodes.OAUTH_SIGNUP_ERROR,
1023
+ });
996
1024
  };
997
1025
  /**
998
1026
  * Fetches all wallets for the current user, including both embedded and connected wallets.
@@ -1013,7 +1041,7 @@ class TurnkeyClient {
1013
1041
  if (!session) {
1014
1042
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1015
1043
  }
1016
- try {
1044
+ return utils.withTurnkeyErrorHandling(async () => {
1017
1045
  const res = await this.httpClient.getWallets({ organizationId: session.organizationId }, stampWith);
1018
1046
  if (!res || !res.wallets) {
1019
1047
  throw new sdkTypes.TurnkeyError("No wallets found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1037,7 +1065,8 @@ class TurnkeyClient {
1037
1065
  const providers = await this.getWalletProviders();
1038
1066
  const groupedProviders = new Map();
1039
1067
  for (const provider of providers) {
1040
- const walletId = provider.info?.name?.toLowerCase().replace(/\s+/g, "-") || "unknown";
1068
+ const walletId = provider.info?.name?.toLowerCase().replace(/\s+/g, "-") ||
1069
+ "unknown";
1041
1070
  const group = groupedProviders.get(walletId) || [];
1042
1071
  group.push(provider);
1043
1072
  groupedProviders.set(walletId, group);
@@ -1063,12 +1092,10 @@ class TurnkeyClient {
1063
1092
  return wallet;
1064
1093
  }))).filter((wallet) => wallet.accounts.length > 0);
1065
1094
  return [...embedded, ...connected];
1066
- }
1067
- catch (error) {
1068
- if (error instanceof sdkTypes.TurnkeyError)
1069
- throw error;
1070
- throw new sdkTypes.TurnkeyError("Failed to fetch wallets", sdkTypes.TurnkeyErrorCodes.FETCH_WALLETS_ERROR, error);
1071
- }
1095
+ }, {
1096
+ errorMessage: "Failed to fetch wallets",
1097
+ errorCode: sdkTypes.TurnkeyErrorCodes.FETCH_WALLETS_ERROR,
1098
+ });
1072
1099
  };
1073
1100
  /**
1074
1101
  * Fetches all accounts for a specific wallet, including both embedded and connected wallet accounts.
@@ -1092,58 +1119,65 @@ class TurnkeyClient {
1092
1119
  if (!session) {
1093
1120
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1094
1121
  }
1095
- // this is an embedded wallet so we fetch accounts from Turnkey
1096
- if (wallet.source === base.WalletSource.Embedded) {
1097
- const embedded = [];
1098
- const res = await this.httpClient.getWalletAccounts({
1099
- walletId: wallet.walletId,
1100
- organizationId: session.organizationId,
1101
- paginationOptions: paginationOptions || { limit: "100" },
1102
- }, stampWith);
1103
- if (!res || !res.accounts) {
1104
- throw new sdkTypes.TurnkeyError("No wallet accounts found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1105
- }
1106
- for (const account of res.accounts) {
1107
- embedded.push({
1108
- ...account,
1109
- source: base.WalletSource.Embedded,
1110
- });
1111
- }
1112
- return embedded;
1113
- }
1114
- // this is an external wallet so we fetch accounts from the connected wallet provider
1115
- // if wallet connecting is disabled we return only embedded wallets
1116
- // we should never reach this point if wallet connecting is disabled
1117
- if (!this.walletManager?.connector)
1118
- return [];
1119
- const connected = [];
1120
- const providers = walletProviders ?? (await this.getWalletProviders());
1121
- const matching = providers.filter((p) => p.info?.name?.toLowerCase().replace(/\s+/g, "-") === wallet.walletId &&
1122
- p.connectedAddresses.length > 0);
1123
- for (const provider of matching) {
1124
- const timestamp = utils.toExternalTimestamp();
1125
- for (const address of provider.connectedAddresses) {
1126
- const account = {
1127
- walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1128
- organizationId: session.organizationId,
1122
+ return utils.withTurnkeyErrorHandling(async () => {
1123
+ // this is an embedded wallet so we fetch accounts from Turnkey
1124
+ if (wallet.source === base.WalletSource.Embedded) {
1125
+ const embedded = [];
1126
+ const res = await this.httpClient.getWalletAccounts({
1129
1127
  walletId: wallet.walletId,
1130
- curve: utils.isEthereumWallet(provider) ? base.Curve.SECP256K1 : base.Curve.ED25519,
1131
- pathFormat: "PATH_FORMAT_BIP32",
1132
- path: base.WalletSource.Connected,
1133
- source: base.WalletSource.Connected,
1134
- addressFormat: utils.isEthereumWallet(provider)
1135
- ? "ADDRESS_FORMAT_ETHEREUM"
1136
- : "ADDRESS_FORMAT_SOLANA",
1137
- address,
1138
- createdAt: timestamp,
1139
- updatedAt: timestamp,
1140
- ...utils.getWalletAccountMethods(this.walletManager.connector.sign.bind(this.walletManager.connector), provider),
1141
- ...(utils.isSolanaWallet(provider) && { publicKey: address }),
1142
- };
1143
- connected.push(account);
1128
+ organizationId: session.organizationId,
1129
+ paginationOptions: paginationOptions || { limit: "100" },
1130
+ }, stampWith);
1131
+ if (!res || !res.accounts) {
1132
+ throw new sdkTypes.TurnkeyError("No wallet accounts found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1133
+ }
1134
+ for (const account of res.accounts) {
1135
+ embedded.push({
1136
+ ...account,
1137
+ source: base.WalletSource.Embedded,
1138
+ });
1139
+ }
1140
+ return embedded;
1144
1141
  }
1145
- }
1146
- return connected;
1142
+ // this is an external wallet so we fetch accounts from the connected wallet provider
1143
+ // if wallet connecting is disabled we return only embedded wallets
1144
+ // we should never reach this point if wallet connecting is disabled
1145
+ if (!this.walletManager?.connector)
1146
+ return [];
1147
+ const connected = [];
1148
+ const providers = walletProviders ?? (await this.getWalletProviders());
1149
+ const matching = providers.filter((p) => p.info?.name?.toLowerCase().replace(/\s+/g, "-") ===
1150
+ wallet.walletId && p.connectedAddresses.length > 0);
1151
+ for (const provider of matching) {
1152
+ const timestamp = utils.toExternalTimestamp();
1153
+ for (const address of provider.connectedAddresses) {
1154
+ const account = {
1155
+ walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1156
+ organizationId: session.organizationId,
1157
+ walletId: wallet.walletId,
1158
+ curve: utils.isEthereumWallet(provider)
1159
+ ? base.Curve.SECP256K1
1160
+ : base.Curve.ED25519,
1161
+ pathFormat: "PATH_FORMAT_BIP32",
1162
+ path: base.WalletSource.Connected,
1163
+ source: base.WalletSource.Connected,
1164
+ addressFormat: utils.isEthereumWallet(provider)
1165
+ ? "ADDRESS_FORMAT_ETHEREUM"
1166
+ : "ADDRESS_FORMAT_SOLANA",
1167
+ address,
1168
+ createdAt: timestamp,
1169
+ updatedAt: timestamp,
1170
+ ...utils.getWalletAccountMethods(this.walletManager.connector.sign.bind(this.walletManager.connector), provider),
1171
+ ...(utils.isSolanaWallet(provider) && { publicKey: address }),
1172
+ };
1173
+ connected.push(account);
1174
+ }
1175
+ }
1176
+ return connected;
1177
+ }, {
1178
+ errorMessage: "Failed to fetch wallet accounts",
1179
+ errorCode: sdkTypes.TurnkeyErrorCodes.FETCH_WALLET_ACCOUNTS_ERROR,
1180
+ });
1147
1181
  };
1148
1182
  /**
1149
1183
  * Signs a message using the specified wallet account.
@@ -1177,7 +1211,7 @@ class TurnkeyClient {
1177
1211
  const { message, walletAccount, stampWith, addEthereumPrefix } = params;
1178
1212
  const hashFunction = params.hashFunction || utils.getHashFunction(walletAccount.addressFormat);
1179
1213
  const payloadEncoding = params.encoding || utils.getEncodingType(walletAccount.addressFormat);
1180
- try {
1214
+ return utils.withTurnkeyErrorHandling(async () => {
1181
1215
  const isEthereum = walletAccount.addressFormat === "ADDRESS_FORMAT_ETHEREUM";
1182
1216
  if (walletAccount.source === base.WalletSource.Connected) {
1183
1217
  // this is a connected wallet
@@ -1209,12 +1243,10 @@ class TurnkeyClient {
1209
1243
  }
1210
1244
  return response.activity.result
1211
1245
  .signRawPayloadResult;
1212
- }
1213
- catch (error) {
1214
- if (error instanceof sdkTypes.TurnkeyError)
1215
- throw error;
1216
- throw new sdkTypes.TurnkeyError(`Failed to sign message - ${error?.message ? error.message : "Unknown error"}`, sdkTypes.TurnkeyErrorCodes.SIGN_MESSAGE_ERROR);
1217
- }
1246
+ }, {
1247
+ errorMessage: "Failed to sign message",
1248
+ errorCode: sdkTypes.TurnkeyErrorCodes.SIGN_MESSAGE_ERROR,
1249
+ });
1218
1250
  };
1219
1251
  /**
1220
1252
  * Signs a transaction using the specified wallet account.
@@ -1234,7 +1266,7 @@ class TurnkeyClient {
1234
1266
  */
1235
1267
  this.signTransaction = async (params) => {
1236
1268
  const { walletAccount, unsignedTransaction, transactionType, stampWith } = params;
1237
- try {
1269
+ return utils.withTurnkeyErrorHandling(async () => {
1238
1270
  if (walletAccount.source === base.WalletSource.Connected) {
1239
1271
  // this is a connected wallet account
1240
1272
  if (!walletAccount.signTransaction) {
@@ -1253,12 +1285,10 @@ class TurnkeyClient {
1253
1285
  type: transactionType,
1254
1286
  }, stampWith);
1255
1287
  return signTransaction.signedTransaction;
1256
- }
1257
- catch (error) {
1258
- if (error instanceof sdkTypes.TurnkeyError)
1259
- throw error;
1260
- throw new sdkTypes.TurnkeyError(`Failed to sign transaction`, sdkTypes.TurnkeyErrorCodes.SIGN_TRANSACTION_ERROR, error);
1261
- }
1288
+ }, {
1289
+ errorMessage: "Failed to sign transaction",
1290
+ errorCode: sdkTypes.TurnkeyErrorCodes.SIGN_TRANSACTION_ERROR,
1291
+ });
1262
1292
  };
1263
1293
  /**
1264
1294
  * Signs and broadcasts a transaction using the specified wallet account.
@@ -1282,7 +1312,7 @@ class TurnkeyClient {
1282
1312
  */
1283
1313
  this.signAndSendTransaction = async (params) => {
1284
1314
  const { walletAccount, unsignedTransaction, transactionType, rpcUrl, stampWith, } = params;
1285
- try {
1315
+ return utils.withTurnkeyErrorHandling(async () => {
1286
1316
  if (walletAccount.source === base.WalletSource.Connected) {
1287
1317
  // this is a connected wallet account
1288
1318
  switch (transactionType) {
@@ -1326,12 +1356,10 @@ class TurnkeyClient {
1326
1356
  transactionType,
1327
1357
  });
1328
1358
  return txHash;
1329
- }
1330
- catch (error) {
1331
- if (error instanceof sdkTypes.TurnkeyError)
1332
- throw error;
1333
- throw new sdkTypes.TurnkeyError(`Failed to sign and send transaction`, sdkTypes.TurnkeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR, error);
1334
- }
1359
+ }, {
1360
+ errorMessage: "Failed to sign and send transaction",
1361
+ errorCode: sdkTypes.TurnkeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR,
1362
+ });
1335
1363
  };
1336
1364
  /**
1337
1365
  * Fetches the user details for the current session or a specified user.
@@ -1359,18 +1387,16 @@ class TurnkeyClient {
1359
1387
  throw new sdkTypes.TurnkeyError("User ID must be provided to fetch user", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1360
1388
  }
1361
1389
  const organizationId = params?.organizationId || session.organizationId;
1362
- try {
1390
+ return utils.withTurnkeyErrorHandling(async () => {
1363
1391
  const userResponse = await this.httpClient.getUser({ organizationId, userId }, stampWith);
1364
1392
  if (!userResponse || !userResponse.user) {
1365
1393
  throw new sdkTypes.TurnkeyError("No user found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1366
1394
  }
1367
1395
  return userResponse.user;
1368
- }
1369
- catch (error) {
1370
- if (error instanceof sdkTypes.TurnkeyError)
1371
- throw error;
1372
- throw new sdkTypes.TurnkeyError(`Failed to fetch user`, sdkTypes.TurnkeyErrorCodes.FETCH_USER_ERROR, error);
1373
- }
1396
+ }, {
1397
+ errorMessage: "Failed to fetch user",
1398
+ errorCode: sdkTypes.TurnkeyErrorCodes.FETCH_USER_ERROR,
1399
+ });
1374
1400
  };
1375
1401
  /**
1376
1402
  * Updates the user's email address.
@@ -1395,7 +1421,7 @@ class TurnkeyClient {
1395
1421
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1396
1422
  }
1397
1423
  const userId = params?.userId || session.userId;
1398
- try {
1424
+ return utils.withTurnkeyErrorHandling(async () => {
1399
1425
  const existingUser = await this.httpClient.proxyGetAccount({
1400
1426
  filterType: base.FilterType.Email,
1401
1427
  filterValue: email,
@@ -1412,12 +1438,10 @@ class TurnkeyClient {
1412
1438
  throw new sdkTypes.TurnkeyError("No user ID found in the update user email response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1413
1439
  }
1414
1440
  return res.userId;
1415
- }
1416
- catch (error) {
1417
- if (error instanceof sdkTypes.TurnkeyError)
1418
- throw error;
1419
- throw new sdkTypes.TurnkeyError(`Failed to update user email`, sdkTypes.TurnkeyErrorCodes.UPDATE_USER_EMAIL_ERROR, error);
1420
- }
1441
+ }, {
1442
+ errorMessage: "Failed to update user email",
1443
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_EMAIL_ERROR,
1444
+ });
1421
1445
  };
1422
1446
  /**
1423
1447
  * Removes the user's email address.
@@ -1438,15 +1462,20 @@ class TurnkeyClient {
1438
1462
  if (!session) {
1439
1463
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1440
1464
  }
1441
- const userId = params?.userId || session.userId;
1442
- const res = await this.httpClient.updateUserEmail({
1443
- userId: userId,
1444
- userEmail: "",
1445
- }, stampWith);
1446
- if (!res || !res.userId) {
1447
- throw new sdkTypes.TurnkeyError("No user ID found in the remove user email response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1448
- }
1449
- return res.userId;
1465
+ return utils.withTurnkeyErrorHandling(async () => {
1466
+ const userId = params?.userId || session.userId;
1467
+ const res = await this.httpClient.updateUserEmail({
1468
+ userId: userId,
1469
+ userEmail: "",
1470
+ }, stampWith);
1471
+ if (!res || !res.userId) {
1472
+ throw new sdkTypes.TurnkeyError("No user ID found in the remove user email response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1473
+ }
1474
+ return res.userId;
1475
+ }, {
1476
+ errorMessage: "Failed to remove user email",
1477
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_EMAIL_ERROR,
1478
+ });
1450
1479
  };
1451
1480
  /**
1452
1481
  * Updates the user's phone number.
@@ -1471,7 +1500,7 @@ class TurnkeyClient {
1471
1500
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1472
1501
  }
1473
1502
  const userId = params?.userId || session.userId;
1474
- try {
1503
+ return utils.withTurnkeyErrorHandling(async () => {
1475
1504
  const res = await this.httpClient.updateUserPhoneNumber({
1476
1505
  userId,
1477
1506
  userPhoneNumber: phoneNumber,
@@ -1481,12 +1510,10 @@ class TurnkeyClient {
1481
1510
  throw new sdkTypes.TurnkeyError("Failed to update user phone number", sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
1482
1511
  }
1483
1512
  return res.userId;
1484
- }
1485
- catch (error) {
1486
- if (error instanceof sdkTypes.TurnkeyError)
1487
- throw error;
1488
- throw new sdkTypes.TurnkeyError(`Failed to update user phone number`, sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR, error);
1489
- }
1513
+ }, {
1514
+ errorMessage: "Failed to update user phone number",
1515
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR,
1516
+ });
1490
1517
  };
1491
1518
  /**
1492
1519
  * Removes the user's phone number.
@@ -1508,14 +1535,19 @@ class TurnkeyClient {
1508
1535
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1509
1536
  }
1510
1537
  const userId = params?.userId || session.userId;
1511
- const res = await this.httpClient.updateUserPhoneNumber({
1512
- userId,
1513
- userPhoneNumber: "",
1514
- }, stampWith);
1515
- if (!res || !res.userId) {
1516
- throw new sdkTypes.TurnkeyError("Failed to remove user phone number", sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
1517
- }
1518
- return res.userId;
1538
+ return utils.withTurnkeyErrorHandling(async () => {
1539
+ const res = await this.httpClient.updateUserPhoneNumber({
1540
+ userId,
1541
+ userPhoneNumber: "",
1542
+ }, stampWith);
1543
+ if (!res || !res.userId) {
1544
+ throw new sdkTypes.TurnkeyError("Failed to remove user phone number", sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
1545
+ }
1546
+ return res.userId;
1547
+ }, {
1548
+ errorMessage: "Failed to remove user phone number",
1549
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR,
1550
+ });
1519
1551
  };
1520
1552
  /**
1521
1553
  * Updates the user's name.
@@ -1539,7 +1571,7 @@ class TurnkeyClient {
1539
1571
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1540
1572
  }
1541
1573
  const userId = params?.userId || session.userId;
1542
- try {
1574
+ return utils.withTurnkeyErrorHandling(async () => {
1543
1575
  const res = await this.httpClient.updateUserName({
1544
1576
  userId,
1545
1577
  userName,
@@ -1548,12 +1580,10 @@ class TurnkeyClient {
1548
1580
  throw new sdkTypes.TurnkeyError("No user ID found in the update user name response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1549
1581
  }
1550
1582
  return res.userId;
1551
- }
1552
- catch (error) {
1553
- if (error instanceof sdkTypes.TurnkeyError)
1554
- throw error;
1555
- throw new sdkTypes.TurnkeyError(`Failed to update user name`, sdkTypes.TurnkeyErrorCodes.UPDATE_USER_NAME_ERROR, error);
1556
- }
1583
+ }, {
1584
+ errorMessage: "Failed to update user name",
1585
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_NAME_ERROR,
1586
+ });
1557
1587
  };
1558
1588
  /**
1559
1589
  * Adds an OAuth provider to the user.
@@ -1578,7 +1608,7 @@ class TurnkeyClient {
1578
1608
  if (!session) {
1579
1609
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1580
1610
  }
1581
- try {
1611
+ return utils.withTurnkeyErrorHandling(async () => {
1582
1612
  const accountRes = await this.httpClient.proxyGetAccount({
1583
1613
  filterType: "OIDC_TOKEN",
1584
1614
  filterValue: oidcToken,
@@ -1622,12 +1652,10 @@ class TurnkeyClient {
1622
1652
  throw new sdkTypes.TurnkeyError("Failed to create OAuth provider", sdkTypes.TurnkeyErrorCodes.ADD_OAUTH_PROVIDER_ERROR);
1623
1653
  }
1624
1654
  return createProviderRes?.providerIds || [];
1625
- }
1626
- catch (error) {
1627
- if (error instanceof sdkTypes.TurnkeyError)
1628
- throw error;
1629
- throw new sdkTypes.TurnkeyError(`Failed to fetch account for OAuth provider`, sdkTypes.TurnkeyErrorCodes.ACCOUNT_FETCH_ERROR, error);
1630
- }
1655
+ }, {
1656
+ errorMessage: "Failed to add OAuth provider",
1657
+ errorCode: sdkTypes.TurnkeyErrorCodes.ADD_OAUTH_PROVIDER_ERROR,
1658
+ });
1631
1659
  };
1632
1660
  /**
1633
1661
  * Removes a list of OAuth providers from the user.
@@ -1651,14 +1679,19 @@ class TurnkeyClient {
1651
1679
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1652
1680
  }
1653
1681
  const userId = params?.userId || session.userId;
1654
- const res = await this.httpClient.deleteOauthProviders({
1655
- userId,
1656
- providerIds,
1657
- }, stampWith);
1658
- if (!res) {
1659
- throw new sdkTypes.TurnkeyError("Failed to remove OAuth provider", sdkTypes.TurnkeyErrorCodes.REMOVE_OAUTH_PROVIDER_ERROR);
1660
- }
1661
- return res.providerIds;
1682
+ return utils.withTurnkeyErrorHandling(async () => {
1683
+ const res = await this.httpClient.deleteOauthProviders({
1684
+ userId,
1685
+ providerIds,
1686
+ }, stampWith);
1687
+ if (!res) {
1688
+ throw new sdkTypes.TurnkeyError("Failed to remove OAuth provider", sdkTypes.TurnkeyErrorCodes.REMOVE_OAUTH_PROVIDER_ERROR);
1689
+ }
1690
+ return res.providerIds;
1691
+ }, {
1692
+ errorMessage: "Failed to remove OAuth provider",
1693
+ errorCode: sdkTypes.TurnkeyErrorCodes.REMOVE_OAUTH_PROVIDER_ERROR,
1694
+ });
1662
1695
  };
1663
1696
  /**
1664
1697
  * Adds a new passkey authenticator for the user.
@@ -1680,7 +1713,7 @@ class TurnkeyClient {
1680
1713
  const { stampWith } = params || {};
1681
1714
  const name = params?.name || `Turnkey Passkey-${Date.now()}`;
1682
1715
  const displayName = params?.displayName || name;
1683
- try {
1716
+ return utils.withTurnkeyErrorHandling(async () => {
1684
1717
  const session = await this.storageManager.getActiveSession();
1685
1718
  if (!session) {
1686
1719
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
@@ -1705,12 +1738,10 @@ class TurnkeyClient {
1705
1738
  ],
1706
1739
  }, stampWith);
1707
1740
  return res?.authenticatorIds || [];
1708
- }
1709
- catch (error) {
1710
- if (error instanceof sdkTypes.TurnkeyError)
1711
- throw error;
1712
- throw new sdkTypes.TurnkeyError(`Failed to add passkey`, sdkTypes.TurnkeyErrorCodes.ADD_PASSKEY_ERROR, error);
1713
- }
1741
+ }, {
1742
+ errorMessage: "Failed to add passkey",
1743
+ errorCode: sdkTypes.TurnkeyErrorCodes.ADD_PASSKEY_ERROR,
1744
+ });
1714
1745
  };
1715
1746
  /**
1716
1747
  * Removes passkeys (authenticator) from the user.
@@ -1734,14 +1765,19 @@ class TurnkeyClient {
1734
1765
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1735
1766
  }
1736
1767
  const userId = params?.userId || session.userId;
1737
- const res = await this.httpClient.deleteAuthenticators({
1738
- userId,
1739
- authenticatorIds,
1740
- }, stampWith);
1741
- if (!res) {
1742
- throw new sdkTypes.TurnkeyError("Failed to remove passkey", sdkTypes.TurnkeyErrorCodes.REMOVE_PASSKEY_ERROR);
1743
- }
1744
- return res.authenticatorIds;
1768
+ return utils.withTurnkeyErrorHandling(async () => {
1769
+ const res = await this.httpClient.deleteAuthenticators({
1770
+ userId,
1771
+ authenticatorIds,
1772
+ }, stampWith);
1773
+ if (!res) {
1774
+ throw new sdkTypes.TurnkeyError("No response found in the remove passkey response", sdkTypes.TurnkeyErrorCodes.REMOVE_PASSKEY_ERROR);
1775
+ }
1776
+ return res.authenticatorIds;
1777
+ }, {
1778
+ errorMessage: "Failed to remove passkey",
1779
+ errorCode: sdkTypes.TurnkeyErrorCodes.REMOVE_PASSKEY_ERROR,
1780
+ });
1745
1781
  };
1746
1782
  /**
1747
1783
  * Creates a new wallet for sub-organization.
@@ -1780,7 +1816,7 @@ class TurnkeyClient {
1780
1816
  ...turnkeyHelpers.DEFAULT_SOLANA_ACCOUNTS,
1781
1817
  ];
1782
1818
  }
1783
- try {
1819
+ return utils.withTurnkeyErrorHandling(async () => {
1784
1820
  const res = await this.httpClient.createWallet({
1785
1821
  organizationId: organizationId || session.organizationId,
1786
1822
  walletName,
@@ -1791,12 +1827,10 @@ class TurnkeyClient {
1791
1827
  throw new sdkTypes.TurnkeyError("No wallet found in the create wallet response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1792
1828
  }
1793
1829
  return res.walletId;
1794
- }
1795
- catch (error) {
1796
- if (error instanceof sdkTypes.TurnkeyError)
1797
- throw error;
1798
- throw new sdkTypes.TurnkeyError(`Failed to create wallet`, sdkTypes.TurnkeyErrorCodes.CREATE_WALLET_ERROR, error);
1799
- }
1830
+ }, {
1831
+ errorMessage: "Failed to create wallet",
1832
+ errorCode: sdkTypes.TurnkeyErrorCodes.CREATE_WALLET_ERROR,
1833
+ });
1800
1834
  };
1801
1835
  /**
1802
1836
  * Creates new accounts in the specified wallet.
@@ -1821,7 +1855,7 @@ class TurnkeyClient {
1821
1855
  if (!session) {
1822
1856
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1823
1857
  }
1824
- try {
1858
+ return utils.withTurnkeyErrorHandling(async () => {
1825
1859
  let walletAccounts = [];
1826
1860
  if (accounts && !utils.isWalletAccountArray(accounts)) {
1827
1861
  // Query existing wallet accounts to avoid duplicates
@@ -1847,12 +1881,10 @@ class TurnkeyClient {
1847
1881
  throw new sdkTypes.TurnkeyError("No account found in the create wallet account response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1848
1882
  }
1849
1883
  return res.addresses;
1850
- }
1851
- catch (error) {
1852
- if (error instanceof sdkTypes.TurnkeyError)
1853
- throw error;
1854
- throw new sdkTypes.TurnkeyError(`Failed to create wallet account`, sdkTypes.TurnkeyErrorCodes.CREATE_WALLET_ACCOUNT_ERROR, error);
1855
- }
1884
+ }, {
1885
+ errorMessage: "Failed to create wallet account",
1886
+ errorCode: sdkTypes.TurnkeyErrorCodes.CREATE_WALLET_ACCOUNT_ERROR,
1887
+ });
1856
1888
  };
1857
1889
  /**
1858
1890
  * Exports a wallet as an encrypted bundle.
@@ -1877,7 +1909,7 @@ class TurnkeyClient {
1877
1909
  if (!session) {
1878
1910
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1879
1911
  }
1880
- try {
1912
+ return utils.withTurnkeyErrorHandling(async () => {
1881
1913
  const res = await this.httpClient.exportWallet({
1882
1914
  walletId,
1883
1915
  targetPublicKey,
@@ -1887,12 +1919,85 @@ class TurnkeyClient {
1887
1919
  throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1888
1920
  }
1889
1921
  return res.exportBundle;
1922
+ }, {
1923
+ errorMessage: "Failed to export wallet",
1924
+ errorCode: sdkTypes.TurnkeyErrorCodes.EXPORT_WALLET_ERROR,
1925
+ });
1926
+ };
1927
+ /**
1928
+ * Exports a private key as an encrypted bundle.
1929
+ *
1930
+ * - This function exports the specified private key as an encrypted bundle, suitable for backup or transfer.
1931
+ * - The exported bundle contains the private key's key material, encrypted to the provided target public key.
1932
+ * - If a targetPublicKey is provided, the bundle will be encrypted to that public key; otherwise, an error will be thrown.
1933
+ * - If an organizationId is provided, the private key will be exported under that sub-organization; otherwise, the current session's organizationId is used.
1934
+ * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1935
+ *
1936
+ * @param params.privateKeyId - ID of the private key to export.
1937
+ * @param params.targetPublicKey - public key to encrypt the bundle to (required).
1938
+ * @param params.organizationId - organization ID to export the private key under a specific sub
1939
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1940
+ * @returns A promise that resolves to an `ExportBundle` object containing the encrypted private key and metadata.
1941
+ * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the private key.
1942
+ */
1943
+ this.exportPrivateKey = async (params) => {
1944
+ const { privateKeyId, targetPublicKey, stampWith, organizationId } = params;
1945
+ const session = await this.storageManager.getActiveSession();
1946
+ if (!session) {
1947
+ throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1890
1948
  }
1891
- catch (error) {
1892
- if (error instanceof sdkTypes.TurnkeyError)
1893
- throw error;
1894
- throw new sdkTypes.TurnkeyError(`Failed to export wallet`, sdkTypes.TurnkeyErrorCodes.EXPORT_WALLET_ERROR, error);
1949
+ return utils.withTurnkeyErrorHandling(async () => {
1950
+ const res = await this.httpClient.exportPrivateKey({
1951
+ privateKeyId,
1952
+ targetPublicKey,
1953
+ organizationId: organizationId || session.organizationId,
1954
+ }, stampWith);
1955
+ if (!res.exportBundle) {
1956
+ throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1957
+ }
1958
+ return res.exportBundle;
1959
+ }, {
1960
+ errorMessage: "Failed to export private key",
1961
+ errorCode: sdkTypes.TurnkeyErrorCodes.EXPORT_PRIVATE_KEY_ERROR,
1962
+ });
1963
+ };
1964
+ /**
1965
+ * Exports a wallet account as an encrypted bundle.
1966
+ *
1967
+ * - This function exports the specified wallet account as an encrypted bundle, suitable for backup or transfer.
1968
+ * - The exported bundle contains the wallet account's key material, encrypted to the provided target public key.
1969
+ * - If a targetPublicKey is provided, the bundle will be encrypted to that public key; otherwise, an error will be thrown.
1970
+ * - If an organizationId is provided, the wallet account will be exported under that sub-organization; otherwise, the current session's organizationId is used.
1971
+ * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1972
+ *
1973
+ * @param params.address - address of the wallet account to export.
1974
+ * @param params.targetPublicKey - public key to encrypt the bundle to.
1975
+ * @param params.organizationId - organization ID to export the wallet account under a specific sub-organization.
1976
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1977
+ * @returns A promise that resolves to an `ExportBundle` object containing the encrypted wallet account and metadata.
1978
+ * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the wallet account.
1979
+ *
1980
+ */
1981
+ this.exportWalletAccount = async (params) => {
1982
+ const { address, targetPublicKey, stampWith, organizationId } = params;
1983
+ const session = await this.storageManager.getActiveSession();
1984
+ if (!session) {
1985
+ throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1895
1986
  }
1987
+ return utils.withTurnkeyErrorHandling(async () => {
1988
+ const res = await this.httpClient.exportWalletAccount({
1989
+ address,
1990
+ targetPublicKey,
1991
+ organizationId: organizationId || session.organizationId,
1992
+ }, stampWith);
1993
+ if (!res.exportBundle) {
1994
+ throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1995
+ }
1996
+ return res.exportBundle;
1997
+ }, {
1998
+ errorMessage: "Failed to export wallet account",
1999
+ errorCode: sdkTypes.TurnkeyErrorCodes.EXPORT_WALLET_ACCOUNT_ERROR,
2000
+ });
1896
2001
  };
1897
2002
  /**
1898
2003
  * Imports a wallet from an encrypted bundle.
@@ -1900,7 +2005,7 @@ class TurnkeyClient {
1900
2005
  * - This function imports a wallet using the provided encrypted bundle and creates accounts based on the provided parameters.
1901
2006
  * - If a userId is provided, the wallet will be imported for that specific user; otherwise, it uses the current session's userId.
1902
2007
  * - If an accounts array is provided, those accounts will be created in the imported wallet; otherwise, default Ethereum and Solana accounts will be created.
1903
- * - The encrypted bunlde MUST be encrypted to
2008
+ * - The encrypted bundle MUST be encrypted to
1904
2009
  * - Automatically ensures an active session exists before making the request.
1905
2010
  * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1906
2011
  *
@@ -1918,7 +2023,7 @@ class TurnkeyClient {
1918
2023
  if (!session) {
1919
2024
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1920
2025
  }
1921
- try {
2026
+ return utils.withTurnkeyErrorHandling(async () => {
1922
2027
  const res = await this.httpClient.importWallet({
1923
2028
  organizationId: session.organizationId,
1924
2029
  userId: userId || session.userId,
@@ -1933,12 +2038,66 @@ class TurnkeyClient {
1933
2038
  throw new sdkTypes.TurnkeyError("No wallet ID found in the import response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1934
2039
  }
1935
2040
  return res.walletId;
2041
+ }, {
2042
+ errorMessage: "Failed to import wallet",
2043
+ errorCode: sdkTypes.TurnkeyErrorCodes.IMPORT_WALLET_ERROR,
2044
+ customMessageByMessages: {
2045
+ "invalid mnemonic": {
2046
+ message: "Invalid mnemonic input",
2047
+ code: sdkTypes.TurnkeyErrorCodes.BAD_REQUEST,
2048
+ },
2049
+ },
2050
+ });
2051
+ };
2052
+ /**
2053
+ * Imports a private key from an encrypted bundle.
2054
+ *
2055
+ * - This function imports a private key using the provided encrypted bundle.
2056
+ * - If a userId is provided, the private key will be imported for that specific user; otherwise, it uses the current session's userId.
2057
+ * - Requires address formats to
2058
+ * - Automatically infers the cryptographic curve used to generate the private key based on the address format (can be optionally overriden if needed).
2059
+ * - The encrypted bundle MUST be encrypted to ensure security.
2060
+ * - Automatically ensures an active session exists before making the request.
2061
+ * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2062
+ *
2063
+ * @param params.encryptedBundle - encrypted bundle containing the private key key material and metadata.
2064
+ * @param params.privateKeyName - name of the private key to create upon import.
2065
+ * @param params.curve - the cryptographic curve used to generate a given private key
2066
+ * @param params.addressFormat - address format of the private key to import.
2067
+ * @param params.userId - user ID to import the wallet for a specific user (defaults to the current session's userId).
2068
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2069
+ * @returns A promise that resolves to the ID of the imported wallet.
2070
+ * @throws {TurnkeyError} If there is no active session, if the encrypted bundle is invalid, or if there is an error importing the wallet.
2071
+ */
2072
+ this.importPrivateKey = async (params) => {
2073
+ const { encryptedBundle, privateKeyName, addressFormats, curve, userId, stampWith, } = params;
2074
+ const session = await this.storageManager.getActiveSession();
2075
+ if (!session) {
2076
+ throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1936
2077
  }
1937
- catch (error) {
1938
- if (error instanceof sdkTypes.TurnkeyError)
1939
- throw error;
1940
- throw new sdkTypes.TurnkeyError(`Failed to import wallet`, sdkTypes.TurnkeyErrorCodes.IMPORT_WALLET_ERROR, error);
1941
- }
2078
+ return utils.withTurnkeyErrorHandling(async () => {
2079
+ const res = await this.httpClient.importPrivateKey({
2080
+ organizationId: session.organizationId,
2081
+ userId: userId || session.userId,
2082
+ encryptedBundle,
2083
+ privateKeyName,
2084
+ curve,
2085
+ addressFormats,
2086
+ }, stampWith);
2087
+ if (!res || !res.privateKeyId) {
2088
+ throw new sdkTypes.TurnkeyError("No wallet ID found in the import response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
2089
+ }
2090
+ return res.privateKeyId;
2091
+ }, {
2092
+ errorMessage: "Failed to import wallet",
2093
+ errorCode: sdkTypes.TurnkeyErrorCodes.IMPORT_WALLET_ERROR,
2094
+ customMessageByMessages: {
2095
+ "invalid mnemonic": {
2096
+ message: "Invalid mnemonic input",
2097
+ code: sdkTypes.TurnkeyErrorCodes.BAD_REQUEST,
2098
+ },
2099
+ },
2100
+ });
1942
2101
  };
1943
2102
  /**
1944
2103
  * Deletes the current sub-organization (sub-org) for the active session.
@@ -1960,14 +2119,12 @@ class TurnkeyClient {
1960
2119
  if (!session) {
1961
2120
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1962
2121
  }
1963
- try {
2122
+ return utils.withTurnkeyErrorHandling(async () => {
1964
2123
  return await this.httpClient.deleteSubOrganization({ deleteWithoutExport }, stampWith);
1965
- }
1966
- catch (error) {
1967
- if (error instanceof sdkTypes.TurnkeyError)
1968
- throw error;
1969
- throw new sdkTypes.TurnkeyError(`Failed to delete sub-organization`, sdkTypes.TurnkeyErrorCodes.DELETE_SUB_ORGANIZATION_ERROR, error);
1970
- }
2124
+ }, {
2125
+ errorMessage: "Failed to delete sub-organization",
2126
+ errorCode: sdkTypes.TurnkeyErrorCodes.DELETE_SUB_ORGANIZATION_ERROR,
2127
+ });
1971
2128
  };
1972
2129
  /**
1973
2130
  * Stores a session token and updates the session associated with the specified session key, or by default the active session.
@@ -1987,21 +2144,18 @@ class TurnkeyClient {
1987
2144
  const { sessionToken, sessionKey = base.SessionKey.DefaultSessionkey } = params;
1988
2145
  if (!sessionToken)
1989
2146
  return;
1990
- try {
2147
+ utils.withTurnkeyErrorHandling(async () => {
1991
2148
  const sessionToReplace = await this.storageManager.getSession(sessionKey);
1992
2149
  await this.storageManager.storeSession(sessionToken, sessionKey);
1993
2150
  if (sessionToReplace) {
1994
2151
  await this.apiKeyStamper?.deleteKeyPair(sessionToReplace.publicKey);
1995
2152
  }
1996
- }
1997
- catch (error) {
1998
- if (error instanceof sdkTypes.TurnkeyError)
1999
- throw error;
2000
- throw new sdkTypes.TurnkeyError(`Failed to store session`, sdkTypes.TurnkeyErrorCodes.STORE_SESSION_ERROR, error);
2001
- }
2002
- finally {
2003
- await this.clearUnusedKeyPairs();
2004
- }
2153
+ }, {
2154
+ errorMessage: "Failed to store session",
2155
+ errorCode: sdkTypes.TurnkeyErrorCodes.STORE_SESSION_ERROR,
2156
+ }, {
2157
+ finallyFn: async () => await this.clearUnusedKeyPairs(),
2158
+ });
2005
2159
  };
2006
2160
  /**
2007
2161
  * Clears the session associated with the specified session key, or the active session by default.
@@ -2017,7 +2171,7 @@ class TurnkeyClient {
2017
2171
  */
2018
2172
  this.clearSession = async (params) => {
2019
2173
  const { sessionKey = base.SessionKey.DefaultSessionkey } = params || {};
2020
- try {
2174
+ utils.withTurnkeyErrorHandling(async () => {
2021
2175
  const session = await this.storageManager.getSession(sessionKey);
2022
2176
  if (session) {
2023
2177
  await this.apiKeyStamper?.deleteKeyPair(session.publicKey);
@@ -2026,12 +2180,10 @@ class TurnkeyClient {
2026
2180
  else {
2027
2181
  throw new sdkTypes.TurnkeyError(`No session found with key: ${sessionKey}`, sdkTypes.TurnkeyErrorCodes.NOT_FOUND);
2028
2182
  }
2029
- }
2030
- catch (error) {
2031
- if (error instanceof sdkTypes.TurnkeyError)
2032
- throw error;
2033
- throw new sdkTypes.TurnkeyError(`Failed to delete session`, sdkTypes.TurnkeyErrorCodes.CLEAR_SESSION_ERROR, error);
2034
- }
2183
+ }, {
2184
+ errorMessage: "Failed to delete session",
2185
+ errorCode: sdkTypes.TurnkeyErrorCodes.CLEAR_SESSION_ERROR,
2186
+ });
2035
2187
  };
2036
2188
  /**
2037
2189
  * Clears all sessions and resets the active session state.
@@ -2045,7 +2197,7 @@ class TurnkeyClient {
2045
2197
  * @throws {TurnkeyError} If no sessions exist or if there is an error clearing all sessions.
2046
2198
  */
2047
2199
  this.clearAllSessions = async () => {
2048
- try {
2200
+ utils.withTurnkeyErrorHandling(async () => {
2049
2201
  const sessionKeys = await this.storageManager.listSessionKeys();
2050
2202
  if (sessionKeys.length === 0) {
2051
2203
  throw new sdkTypes.TurnkeyError("No sessions found to clear.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
@@ -2053,12 +2205,10 @@ class TurnkeyClient {
2053
2205
  for (const sessionKey of sessionKeys) {
2054
2206
  this.clearSession({ sessionKey });
2055
2207
  }
2056
- }
2057
- catch (error) {
2058
- if (error instanceof sdkTypes.TurnkeyError)
2059
- throw error;
2060
- throw new sdkTypes.TurnkeyError(`Failed to clear all sessions`, sdkTypes.TurnkeyErrorCodes.CLEAR_ALL_SESSIONS_ERROR, error);
2061
- }
2208
+ }, {
2209
+ errorMessage: "Failed to clear all sessions",
2210
+ errorCode: sdkTypes.TurnkeyErrorCodes.CLEAR_ALL_SESSIONS_ERROR,
2211
+ });
2062
2212
  };
2063
2213
  /**
2064
2214
  * Refreshes the session associated with the specified session key, or the active session by default.
@@ -2093,7 +2243,7 @@ class TurnkeyClient {
2093
2243
  throw new sdkTypes.TurnkeyError("HTTP client is not initialized. Please initialize the client before refreshing the session.", sdkTypes.TurnkeyErrorCodes.CLIENT_NOT_INITIALIZED);
2094
2244
  }
2095
2245
  let keyPair;
2096
- try {
2246
+ return utils.withTurnkeyErrorHandling(async () => {
2097
2247
  keyPair = publicKey ?? (await this.apiKeyStamper?.createKeyPair());
2098
2248
  if (!keyPair) {
2099
2249
  throw new sdkTypes.TurnkeyError("Failed to create new key pair.", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
@@ -2111,12 +2261,10 @@ class TurnkeyClient {
2111
2261
  ...(sessionKey && { sessionKey }),
2112
2262
  });
2113
2263
  return res;
2114
- }
2115
- catch (error) {
2116
- if (error instanceof sdkTypes.TurnkeyError)
2117
- throw error;
2118
- throw new sdkTypes.TurnkeyError(`Failed to refresh session`, sdkTypes.TurnkeyErrorCodes.REFRESH_SESSION_ERROR, error);
2119
- }
2264
+ }, {
2265
+ errorMessage: "Failed to refresh session",
2266
+ errorCode: sdkTypes.TurnkeyErrorCodes.REFRESH_SESSION_ERROR,
2267
+ });
2120
2268
  };
2121
2269
  /**
2122
2270
  * Retrieves the session associated with the specified session key, or the active session by default.
@@ -2130,15 +2278,13 @@ class TurnkeyClient {
2130
2278
  * @throws {TurnkeyError} If there is an error retrieving the session from storage.
2131
2279
  */
2132
2280
  this.getSession = async (params) => {
2133
- try {
2281
+ return utils.withTurnkeyErrorHandling(async () => {
2134
2282
  const { sessionKey = await this.storageManager.getActiveSessionKey() } = params || {};
2135
2283
  return this.storageManager.getSession(sessionKey);
2136
- }
2137
- catch (error) {
2138
- if (error instanceof sdkTypes.TurnkeyError)
2139
- throw error;
2140
- throw new sdkTypes.TurnkeyError(`Failed to get session with key`, sdkTypes.TurnkeyErrorCodes.GET_SESSION_ERROR, error);
2141
- }
2284
+ }, {
2285
+ errorMessage: "Failed to get session with key " + params?.sessionKey,
2286
+ errorCode: sdkTypes.TurnkeyErrorCodes.GET_SESSION_ERROR,
2287
+ });
2142
2288
  };
2143
2289
  /**
2144
2290
  * Retrieves all sessions stored in persistent storage.
@@ -2152,7 +2298,7 @@ class TurnkeyClient {
2152
2298
  * @throws {TurnkeyError} If there is an error retrieving sessions from storage.
2153
2299
  */
2154
2300
  this.getAllSessions = async () => {
2155
- try {
2301
+ return utils.withTurnkeyErrorHandling(async () => {
2156
2302
  const sessionKeys = await this.storageManager.listSessionKeys();
2157
2303
  if (!sessionKeys || sessionKeys.length === 0) {
2158
2304
  return undefined;
@@ -2164,13 +2310,11 @@ class TurnkeyClient {
2164
2310
  sessions[sessionKey] = session;
2165
2311
  }
2166
2312
  }
2167
- return sessions;
2168
- }
2169
- catch (error) {
2170
- if (error instanceof sdkTypes.TurnkeyError)
2171
- throw error;
2172
- throw new sdkTypes.TurnkeyError(`Failed to get all sessions`, sdkTypes.TurnkeyErrorCodes.GET_ALL_SESSIONS_ERROR, error);
2173
- }
2313
+ return sessions || undefined;
2314
+ }, {
2315
+ errorMessage: "Failed to get all sessions",
2316
+ errorCode: sdkTypes.TurnkeyErrorCodes.GET_ALL_SESSIONS_ERROR,
2317
+ });
2174
2318
  };
2175
2319
  /**
2176
2320
  * Sets the active session to the specified session key.
@@ -2186,14 +2330,12 @@ class TurnkeyClient {
2186
2330
  */
2187
2331
  this.setActiveSession = async (params) => {
2188
2332
  const { sessionKey } = params;
2189
- try {
2333
+ return utils.withTurnkeyErrorHandling(async () => {
2190
2334
  await this.storageManager.setActiveSessionKey(sessionKey);
2191
- }
2192
- catch (error) {
2193
- if (error instanceof sdkTypes.TurnkeyError)
2194
- throw error;
2195
- throw new sdkTypes.TurnkeyError(`Failed to set active session`, sdkTypes.TurnkeyErrorCodes.SET_ACTIVE_SESSION_ERROR, error);
2196
- }
2335
+ }, {
2336
+ errorMessage: "Failed to set active session",
2337
+ errorCode: sdkTypes.TurnkeyErrorCodes.SET_ACTIVE_SESSION_ERROR,
2338
+ });
2197
2339
  };
2198
2340
  /**
2199
2341
  * Retrieves the active session key currently set in persistent storage.
@@ -2207,14 +2349,12 @@ class TurnkeyClient {
2207
2349
  * @throws {TurnkeyError} If there is an error retrieving the active session key from storage.
2208
2350
  */
2209
2351
  this.getActiveSessionKey = async () => {
2210
- try {
2352
+ return utils.withTurnkeyErrorHandling(async () => {
2211
2353
  return await this.storageManager.getActiveSessionKey();
2212
- }
2213
- catch (error) {
2214
- if (error instanceof sdkTypes.TurnkeyError)
2215
- throw error;
2216
- throw new sdkTypes.TurnkeyError(`Failed to get active session key`, sdkTypes.TurnkeyErrorCodes.GET_ACTIVE_SESSION_KEY_ERROR, error);
2217
- }
2354
+ }, {
2355
+ errorMessage: "Failed to get active session key",
2356
+ errorCode: sdkTypes.TurnkeyErrorCodes.GET_ACTIVE_SESSION_KEY_ERROR,
2357
+ });
2218
2358
  };
2219
2359
  /**
2220
2360
  * Clears any unused API key pairs from persistent storage.
@@ -2228,7 +2368,7 @@ class TurnkeyClient {
2228
2368
  * @throws {TurnkeyError} If there is an error listing, checking, or deleting unused key pairs.
2229
2369
  */
2230
2370
  this.clearUnusedKeyPairs = async () => {
2231
- try {
2371
+ utils.withTurnkeyErrorHandling(async () => {
2232
2372
  const publicKeys = await this.apiKeyStamper?.listKeyPairs();
2233
2373
  if (!publicKeys || publicKeys.length === 0) {
2234
2374
  return;
@@ -2251,12 +2391,10 @@ class TurnkeyClient {
2251
2391
  }
2252
2392
  }
2253
2393
  }
2254
- }
2255
- catch (error) {
2256
- if (error instanceof sdkTypes.TurnkeyError)
2257
- throw error;
2258
- throw new sdkTypes.TurnkeyError(`Failed to clear unused key pairs`, sdkTypes.TurnkeyErrorCodes.CLEAR_UNUSED_KEY_PAIRS_ERROR, error);
2259
- }
2394
+ }, {
2395
+ errorMessage: "Failed to clear unused key pairs",
2396
+ errorCode: sdkTypes.TurnkeyErrorCodes.CLEAR_UNUSED_KEY_PAIRS_ERROR,
2397
+ });
2260
2398
  };
2261
2399
  /**
2262
2400
  * Creates a new API key pair and returns the public key.
@@ -2273,23 +2411,21 @@ class TurnkeyClient {
2273
2411
  * @throws {TurnkeyError} If the API key stamper is not initialized or if there is an error during key pair creation or storage.
2274
2412
  */
2275
2413
  this.createApiKeyPair = async (params) => {
2276
- if (!this.apiKeyStamper) {
2277
- throw new sdkTypes.TurnkeyError("API Key Stamper is not initialized.", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
2278
- }
2279
- const externalKeyPair = params?.externalKeyPair;
2280
- const storeOverride = params?.storeOverride ?? false;
2281
- try {
2414
+ return utils.withTurnkeyErrorHandling(async () => {
2415
+ const externalKeyPair = params?.externalKeyPair;
2416
+ const storeOverride = params?.storeOverride ?? false;
2417
+ if (!this.apiKeyStamper) {
2418
+ throw new sdkTypes.TurnkeyError("API Key Stamper is not initialized.", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
2419
+ }
2282
2420
  const publicKey = await this.apiKeyStamper.createKeyPair(externalKeyPair ? externalKeyPair : undefined);
2283
2421
  if (storeOverride && publicKey) {
2284
2422
  await this.apiKeyStamper.setPublicKeyOverride(publicKey);
2285
2423
  }
2286
2424
  return publicKey;
2287
- }
2288
- catch (error) {
2289
- if (error instanceof sdkTypes.TurnkeyError)
2290
- throw error;
2291
- throw new sdkTypes.TurnkeyError(`Failed to create API key pair`, sdkTypes.TurnkeyErrorCodes.CREATE_API_KEY_PAIR_ERROR, error);
2292
- }
2425
+ }, {
2426
+ errorMessage: "Failed to create API key pair",
2427
+ errorCode: sdkTypes.TurnkeyErrorCodes.CREATE_API_KEY_PAIR_ERROR,
2428
+ });
2293
2429
  };
2294
2430
  /**
2295
2431
  * Fetches the WalletKit proxy authentication configuration from the auth proxy.
@@ -2303,18 +2439,16 @@ class TurnkeyClient {
2303
2439
  * @throws {TurnkeyError} If there is an error retrieving the proxy authentication configuration from the auth proxy.
2304
2440
  */
2305
2441
  this.getProxyAuthConfig = async () => {
2306
- try {
2442
+ return utils.withTurnkeyErrorHandling(async () => {
2307
2443
  const res = await this.httpClient.proxyGetWalletKitConfig({});
2308
2444
  if (!res) {
2309
2445
  throw new sdkTypes.TurnkeyError(`Failed to fetch auth proxy config`, sdkTypes.TurnkeyErrorCodes.GET_PROXY_AUTH_CONFIG_ERROR);
2310
2446
  }
2311
2447
  return res;
2312
- }
2313
- catch (error) {
2314
- if (error instanceof sdkTypes.TurnkeyError)
2315
- throw error;
2316
- throw new sdkTypes.TurnkeyError(`Failed to get auth proxy config`, sdkTypes.TurnkeyErrorCodes.GET_PROXY_AUTH_CONFIG_ERROR, error);
2317
- }
2448
+ }, {
2449
+ errorMessage: "Failed to get auth proxy config",
2450
+ errorCode: sdkTypes.TurnkeyErrorCodes.GET_PROXY_AUTH_CONFIG_ERROR,
2451
+ });
2318
2452
  };
2319
2453
  this.config = config;
2320
2454
  // Just store any explicitly provided stampers