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

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 (89) hide show
  1. package/dist/__clients__/core.d.ts +92 -9
  2. package/dist/__clients__/core.d.ts.map +1 -1
  3. package/dist/__clients__/core.js +699 -535
  4. package/dist/__clients__/core.js.map +1 -1
  5. package/dist/__clients__/core.mjs +702 -538
  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 -253
  10. package/dist/__generated__/sdk-client-base.js.map +1 -1
  11. package/dist/__generated__/sdk-client-base.mjs +156 -253
  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/__inputs__/public_api.types.d.ts +377 -504
  17. package/dist/__inputs__/public_api.types.d.ts.map +1 -1
  18. package/dist/__types__/base.d.ts +193 -75
  19. package/dist/__types__/base.d.ts.map +1 -1
  20. package/dist/__types__/base.js +14 -13
  21. package/dist/__types__/base.js.map +1 -1
  22. package/dist/__types__/base.mjs +15 -14
  23. package/dist/__types__/base.mjs.map +1 -1
  24. package/dist/__wallet__/base.d.ts +11 -0
  25. package/dist/__wallet__/base.d.ts.map +1 -1
  26. package/dist/__wallet__/base.js +12 -1
  27. package/dist/__wallet__/base.js.map +1 -1
  28. package/dist/__wallet__/base.mjs +12 -1
  29. package/dist/__wallet__/base.mjs.map +1 -1
  30. package/dist/__wallet__/connector.d.ts +31 -4
  31. package/dist/__wallet__/connector.d.ts.map +1 -1
  32. package/dist/__wallet__/connector.js +35 -5
  33. package/dist/__wallet__/connector.js.map +1 -1
  34. package/dist/__wallet__/connector.mjs +35 -5
  35. package/dist/__wallet__/connector.mjs.map +1 -1
  36. package/dist/__wallet__/mobile/manager.d.ts +21 -5
  37. package/dist/__wallet__/mobile/manager.d.ts.map +1 -1
  38. package/dist/__wallet__/mobile/manager.js +28 -11
  39. package/dist/__wallet__/mobile/manager.js.map +1 -1
  40. package/dist/__wallet__/mobile/manager.mjs +28 -11
  41. package/dist/__wallet__/mobile/manager.mjs.map +1 -1
  42. package/dist/__wallet__/stamper.d.ts +73 -2
  43. package/dist/__wallet__/stamper.d.ts.map +1 -1
  44. package/dist/__wallet__/stamper.js +81 -15
  45. package/dist/__wallet__/stamper.js.map +1 -1
  46. package/dist/__wallet__/stamper.mjs +82 -16
  47. package/dist/__wallet__/stamper.mjs.map +1 -1
  48. package/dist/__wallet__/wallet-connect/base.d.ts +102 -19
  49. package/dist/__wallet__/wallet-connect/base.d.ts.map +1 -1
  50. package/dist/__wallet__/wallet-connect/base.js +198 -77
  51. package/dist/__wallet__/wallet-connect/base.js.map +1 -1
  52. package/dist/__wallet__/wallet-connect/base.mjs +198 -77
  53. package/dist/__wallet__/wallet-connect/base.mjs.map +1 -1
  54. package/dist/__wallet__/wallet-connect/client.d.ts +50 -17
  55. package/dist/__wallet__/wallet-connect/client.d.ts.map +1 -1
  56. package/dist/__wallet__/wallet-connect/client.js +76 -19
  57. package/dist/__wallet__/wallet-connect/client.js.map +1 -1
  58. package/dist/__wallet__/wallet-connect/client.mjs +76 -19
  59. package/dist/__wallet__/wallet-connect/client.mjs.map +1 -1
  60. package/dist/__wallet__/web/manager.d.ts +20 -12
  61. package/dist/__wallet__/web/manager.d.ts.map +1 -1
  62. package/dist/__wallet__/web/manager.js +29 -21
  63. package/dist/__wallet__/web/manager.js.map +1 -1
  64. package/dist/__wallet__/web/manager.mjs +29 -21
  65. package/dist/__wallet__/web/manager.mjs.map +1 -1
  66. package/dist/__wallet__/web/native/ethereum.d.ts +45 -11
  67. package/dist/__wallet__/web/native/ethereum.d.ts.map +1 -1
  68. package/dist/__wallet__/web/native/ethereum.js +58 -17
  69. package/dist/__wallet__/web/native/ethereum.js.map +1 -1
  70. package/dist/__wallet__/web/native/ethereum.mjs +58 -17
  71. package/dist/__wallet__/web/native/ethereum.mjs.map +1 -1
  72. package/dist/__wallet__/web/native/solana.d.ts +56 -3
  73. package/dist/__wallet__/web/native/solana.d.ts.map +1 -1
  74. package/dist/__wallet__/web/native/solana.js +95 -36
  75. package/dist/__wallet__/web/native/solana.js.map +1 -1
  76. package/dist/__wallet__/web/native/solana.mjs +95 -36
  77. package/dist/__wallet__/web/native/solana.mjs.map +1 -1
  78. package/dist/index.d.ts +2 -1
  79. package/dist/index.d.ts.map +1 -1
  80. package/dist/index.js +2 -10
  81. package/dist/index.js.map +1 -1
  82. package/dist/index.mjs +2 -2
  83. package/dist/utils.d.ts +59 -13
  84. package/dist/utils.d.ts.map +1 -1
  85. package/dist/utils.js +105 -30
  86. package/dist/utils.js.map +1 -1
  87. package/dist/utils.mjs +103 -29
  88. package/dist/utils.mjs.map +1 -1
  89. package/package.json +8 -8
@@ -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,45 +311,55 @@ 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
- * Switches the specified wallet provider to a different blockchain chain.
325
+ * Switches the wallet provider associated with a given wallet account
326
+ * to a different chain.
328
327
  *
329
- * - Requires the wallet manager and its connector to be initialized.
330
- * - The wallet provider must have at least one connected address.
331
- * - Does nothing if the wallet provider is already on the desired chain.
328
+ * - Requires the wallet manager and its connector to be initialized
329
+ * - Only works for connected wallet accounts
330
+ * - Looks up the provider for the given account address
331
+ * - Does nothing if the provider is already on the desired chain.
332
332
  *
333
- * @param walletProvider - wallet provider to switch.
334
- * @param chainOrId - target chain as a chain ID string or SwitchableChain object.
333
+ * @param params.walletAccount - The wallet account whose provider should be switched.
334
+ * @param params.chainOrId - The target chain, specified as a chain ID string or a SwitchableChain object.
335
+ * @param params.walletProviders - Optional list of wallet providers to search; falls back to `getWalletProviders()` if omitted.
335
336
  * @returns A promise that resolves once the chain switch is complete.
337
+ *
336
338
  * @throws {TurnkeyError} If the wallet manager is uninitialized, the provider is not connected, or the switch fails.
337
339
  */
338
- 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 {
340
+ this.switchWalletAccountChain = async (params) => {
341
+ const { walletAccount, chainOrId, walletProviders } = params;
342
+ return utils.withTurnkeyErrorHandling(async () => {
343
+ if (!this.walletManager?.connector) {
344
+ throw new sdkTypes.TurnkeyError("Wallet connector is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
345
+ }
346
+ if (walletAccount.source === base.WalletSource.Embedded) {
347
+ throw new sdkTypes.TurnkeyError("You can only switch chains for connected wallet accounts", sdkTypes.TurnkeyErrorCodes.NOT_FOUND);
348
+ }
349
+ const providers = walletProviders ?? (await this.getWalletProviders());
350
+ const walletProvider = utils.findWalletProviderFromAddress(walletAccount.address, providers);
351
+ if (!walletProvider) {
352
+ throw new sdkTypes.TurnkeyError("Wallet provider not found", sdkTypes.TurnkeyErrorCodes.SWITCH_WALLET_CHAIN_ERROR);
353
+ }
354
+ // if the wallet provider is already on the desired chain, do nothing
355
+ if (walletProvider.chainInfo.namespace === chainOrId) {
356
+ return;
357
+ }
350
358
  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
- }
359
+ }, {
360
+ errorMessage: "Unable to switch wallet account chain",
361
+ errorCode: sdkTypes.TurnkeyErrorCodes.SWITCH_WALLET_CHAIN_ERROR,
362
+ });
355
363
  };
356
364
  /**
357
365
  * Logs in a user using the specified wallet provider.
@@ -370,11 +378,11 @@ class TurnkeyClient {
370
378
  * @throws {TurnkeyError} If the wallet stamper is uninitialized, a public key cannot be found or generated, or login fails.
371
379
  */
372
380
  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());
381
+ let publicKey = params.publicKey || (await this.apiKeyStamper?.createKeyPair());
382
+ return utils.withTurnkeyErrorHandling(async () => {
383
+ if (!this.walletManager?.stamper) {
384
+ throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
385
+ }
378
386
  const sessionKey = params.sessionKey || base.SessionKey.DefaultSessionkey;
379
387
  const walletProvider = params.walletProvider;
380
388
  const expirationSeconds = params?.expirationSeconds || base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
@@ -392,12 +400,23 @@ class TurnkeyClient {
392
400
  sessionKey,
393
401
  });
394
402
  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
- }
403
+ }, {
404
+ errorMessage: "Unable to log in with the provided wallet",
405
+ errorCode: sdkTypes.TurnkeyErrorCodes.WALLET_LOGIN_AUTH_ERROR,
406
+ }, {
407
+ finallyFn: async () => {
408
+ // Clean up the generated key pair if it wasn't successfully used
409
+ this.apiKeyStamper?.clearPublicKeyOverride();
410
+ if (publicKey) {
411
+ try {
412
+ await this.apiKeyStamper?.deleteKeyPair(publicKey);
413
+ }
414
+ catch (cleanupError) {
415
+ throw new sdkTypes.TurnkeyError("Failed to clean up generated key pair", sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
416
+ }
417
+ }
418
+ },
419
+ });
401
420
  };
402
421
  /**
403
422
  * Signs up a user using a wallet, creating a new sub-organization and session.
@@ -417,11 +436,11 @@ class TurnkeyClient {
417
436
  */
418
437
  this.signUpWithWallet = async (params) => {
419
438
  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 {
439
+ let generatedKeyPair = undefined;
440
+ return utils.withTurnkeyErrorHandling(async () => {
441
+ if (!this.walletManager?.stamper) {
442
+ throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
443
+ }
425
444
  generatedKeyPair = await this.apiKeyStamper?.createKeyPair();
426
445
  this.walletManager.stamper.setProvider(walletProvider.interfaceType, walletProvider);
427
446
  const publicKey = await this.walletManager.stamper.getPublicKey(walletProvider.interfaceType, walletProvider);
@@ -435,7 +454,7 @@ class TurnkeyClient {
435
454
  {
436
455
  apiKeyName: `wallet-auth:${publicKey}`,
437
456
  publicKey: publicKey,
438
- curveType: utils.isEthereumWallet(walletProvider)
457
+ curveType: utils.isEthereumProvider(walletProvider)
439
458
  ? "API_KEY_CURVE_SECP256K1"
440
459
  : "API_KEY_CURVE_ED25519",
441
460
  },
@@ -464,24 +483,25 @@ class TurnkeyClient {
464
483
  sessionToken: sessionResponse.session,
465
484
  sessionKey,
466
485
  });
467
- generatedKeyPair = null; // Key pair was successfully used, set to null to prevent cleanup
486
+ generatedKeyPair = undefined; // Key pair was successfully used, set to null to prevent cleanup
468
487
  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);
488
+ }, {
489
+ errorMessage: "Failed to sign up with wallet",
490
+ errorCode: sdkTypes.TurnkeyErrorCodes.WALLET_SIGNUP_AUTH_ERROR,
491
+ }, {
492
+ finallyFn: async () => {
493
+ // Clean up the generated key pair if it wasn't successfully used
494
+ this.apiKeyStamper?.clearPublicKeyOverride();
495
+ if (generatedKeyPair) {
496
+ try {
497
+ await this.apiKeyStamper?.deleteKeyPair(generatedKeyPair);
498
+ }
499
+ catch (cleanupError) {
500
+ throw new sdkTypes.TurnkeyError("Failed to clean up generated key pair", sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
501
+ }
482
502
  }
483
- }
484
- }
503
+ },
504
+ });
485
505
  };
486
506
  /**
487
507
  * Logs in an existing user or signs up a new user using a wallet, creating a new sub-organization if needed.
@@ -501,25 +521,36 @@ class TurnkeyClient {
501
521
  * @throws {TurnkeyError} If there is an error during wallet authentication, sub-organization creation, or session storage.
502
522
  */
503
523
  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
524
  const createSubOrgParams = params.createSubOrgParams;
508
525
  const sessionKey = params.sessionKey || base.SessionKey.DefaultSessionkey;
509
526
  const walletProvider = params.walletProvider;
510
527
  const expirationSeconds = params.expirationSeconds || base.DEFAULT_SESSION_EXPIRATION_IN_SECONDS;
511
- let generatedKeyPair = null;
512
- try {
528
+ let generatedKeyPair = undefined;
529
+ return utils.withTurnkeyErrorHandling(async () => {
530
+ if (!this.walletManager?.stamper) {
531
+ throw new sdkTypes.TurnkeyError("Wallet stamper is not initialized", sdkTypes.TurnkeyErrorCodes.WALLET_MANAGER_COMPONENT_NOT_INITIALIZED);
532
+ }
513
533
  generatedKeyPair = await this.apiKeyStamper?.createKeyPair();
514
534
  this.walletManager.stamper.setProvider(walletProvider.interfaceType, walletProvider);
515
535
  // here we sign the request with the wallet, but we don't send it to the Turnkey yet
516
536
  // this is because we need to check if the subOrg exists first, and create one if it doesn't
517
537
  // 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);
538
+ const signedRequest = await utils.withTurnkeyErrorHandling(async () => {
539
+ return this.httpClient.stampStampLogin({
540
+ publicKey: generatedKeyPair,
541
+ organizationId: this.config.organizationId,
542
+ expirationSeconds,
543
+ }, base.StamperType.Wallet);
544
+ }, {
545
+ errorMessage: "Failed to create stamped request for wallet login",
546
+ errorCode: sdkTypes.TurnkeyErrorCodes.WALLET_LOGIN_OR_SIGNUP_ERROR,
547
+ customMessageByMessages: {
548
+ "Failed to sign the message": {
549
+ message: "Wallet auth was cancelled by the user.",
550
+ code: sdkTypes.TurnkeyErrorCodes.CONNECT_WALLET_CANCELLED,
551
+ },
552
+ },
553
+ });
523
554
  if (!signedRequest) {
524
555
  throw new sdkTypes.TurnkeyError("Failed to create stamped request for wallet login", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
525
556
  }
@@ -561,7 +592,7 @@ class TurnkeyClient {
561
592
  {
562
593
  apiKeyName: `wallet-auth:${publicKey}`,
563
594
  publicKey: publicKey,
564
- curveType: utils.isEthereumWallet(walletProvider)
595
+ curveType: utils.isEthereumProvider(walletProvider)
565
596
  ? "API_KEY_CURVE_SECP256K1"
566
597
  : "API_KEY_CURVE_ED25519",
567
598
  },
@@ -597,10 +628,20 @@ class TurnkeyClient {
597
628
  sessionKey,
598
629
  });
599
630
  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
- }
631
+ }, {
632
+ errorCode: sdkTypes.TurnkeyErrorCodes.WALLET_LOGIN_OR_SIGNUP_ERROR,
633
+ errorMessage: "Failed to log in or sign up with wallet",
634
+ catchFn: async () => {
635
+ if (generatedKeyPair) {
636
+ try {
637
+ await this.apiKeyStamper?.deleteKeyPair(generatedKeyPair);
638
+ }
639
+ catch (cleanupError) {
640
+ throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
641
+ }
642
+ }
643
+ },
644
+ });
604
645
  };
605
646
  /**
606
647
  * Initializes the OTP process by sending an OTP code to the provided contact.
@@ -615,23 +656,22 @@ class TurnkeyClient {
615
656
  * @throws {TurnkeyError} If there is an error during the OTP initialization process or if the maximum number of OTPs has been reached.
616
657
  */
617
658
  this.initOtp = async (params) => {
618
- try {
659
+ return utils.withTurnkeyErrorHandling(async () => {
619
660
  const initOtpRes = await this.httpClient.proxyInitOtp(params);
620
661
  if (!initOtpRes || !initOtpRes.otpId) {
621
662
  throw new sdkTypes.TurnkeyError("Failed to initialize OTP: otpId is missing", sdkTypes.TurnkeyErrorCodes.INIT_OTP_ERROR);
622
663
  }
623
664
  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
- }
665
+ }, {
666
+ errorMessage: "Failed to initialize OTP",
667
+ errorCode: sdkTypes.TurnkeyErrorCodes.INIT_OTP_ERROR,
668
+ customMessageByMessages: {
669
+ "Max number of OTPs have been initiated": {
670
+ message: "Maximum number of OTPs has been reached for this contact.",
671
+ code: sdkTypes.TurnkeyErrorCodes.MAX_OTP_INITIATED_ERROR,
672
+ },
673
+ },
674
+ });
635
675
  };
636
676
  /**
637
677
  * Verifies the OTP code sent to the user.
@@ -652,7 +692,7 @@ class TurnkeyClient {
652
692
  */
653
693
  this.verifyOtp = async (params) => {
654
694
  const { otpId, otpCode, contact, otpType } = params;
655
- try {
695
+ return utils.withTurnkeyErrorHandling(async () => {
656
696
  const verifyOtpRes = await this.httpClient.proxyVerifyOtp({
657
697
  otpId: otpId,
658
698
  otpCode: otpCode,
@@ -672,16 +712,16 @@ class TurnkeyClient {
672
712
  subOrganizationId: subOrganizationId,
673
713
  verificationToken: verifyOtpRes.verificationToken,
674
714
  };
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
- }
715
+ }, {
716
+ errorMessage: "Failed to verify OTP",
717
+ errorCode: sdkTypes.TurnkeyErrorCodes.VERIFY_OTP_ERROR,
718
+ customMessageByMessages: {
719
+ "Invalid OTP code": {
720
+ message: "The provided OTP code is invalid.",
721
+ code: sdkTypes.TurnkeyErrorCodes.INVALID_OTP_CODE,
722
+ },
723
+ },
724
+ });
685
725
  };
686
726
  /**
687
727
  * Logs in a user using an OTP verification token.
@@ -701,7 +741,7 @@ class TurnkeyClient {
701
741
  */
702
742
  this.loginWithOtp = async (params) => {
703
743
  const { verificationToken, invalidateExisting = false, publicKey = await this.apiKeyStamper?.createKeyPair(), sessionKey = base.SessionKey.DefaultSessionkey, } = params;
704
- try {
744
+ return utils.withTurnkeyErrorHandling(async () => {
705
745
  const res = await this.httpClient.proxyOtpLogin({
706
746
  verificationToken,
707
747
  publicKey: publicKey,
@@ -719,21 +759,21 @@ class TurnkeyClient {
719
759
  sessionKey,
720
760
  });
721
761
  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);
762
+ }, {
763
+ errorMessage: "Failed to log in with OTP",
764
+ errorCode: sdkTypes.TurnkeyErrorCodes.OTP_LOGIN_ERROR,
765
+ catchFn: async () => {
766
+ // Clean up the generated key pair if it wasn't successfully used
767
+ if (publicKey) {
768
+ try {
769
+ await this.apiKeyStamper?.deleteKeyPair(publicKey);
770
+ }
771
+ catch (cleanupError) {
772
+ throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
773
+ }
733
774
  }
734
- }
735
- throw new sdkTypes.TurnkeyError(`Failed to log in with OTP`, sdkTypes.TurnkeyErrorCodes.OTP_LOGIN_ERROR, error);
736
- }
775
+ },
776
+ });
737
777
  };
738
778
  /**
739
779
  * Signs up a user using an OTP verification token.
@@ -764,8 +804,8 @@ class TurnkeyClient {
764
804
  verificationToken,
765
805
  },
766
806
  });
767
- const generatedKeyPair = await this.apiKeyStamper?.createKeyPair();
768
- try {
807
+ return utils.withTurnkeyErrorHandling(async () => {
808
+ const generatedKeyPair = await this.apiKeyStamper?.createKeyPair();
769
809
  const res = await this.httpClient.proxySignup(signUpBody);
770
810
  if (!res) {
771
811
  throw new sdkTypes.TurnkeyError(`Auth proxy OTP sign up failed`, sdkTypes.TurnkeyErrorCodes.OTP_SIGNUP_ERROR);
@@ -776,12 +816,10 @@ class TurnkeyClient {
776
816
  ...(invalidateExisting && { invalidateExisting }),
777
817
  ...(sessionKey && { sessionKey }),
778
818
  });
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
- }
819
+ }, {
820
+ errorCode: sdkTypes.TurnkeyErrorCodes.OTP_SIGNUP_ERROR,
821
+ errorMessage: "Failed to sign up with OTP",
822
+ });
785
823
  };
786
824
  /**
787
825
  * Completes the OTP authentication flow by verifying the OTP code and then either signing up or logging in the user.
@@ -805,7 +843,7 @@ class TurnkeyClient {
805
843
  */
806
844
  this.completeOtp = async (params) => {
807
845
  const { otpId, otpCode, contact, otpType, publicKey, invalidateExisting = false, sessionKey, createSubOrgParams, } = params;
808
- try {
846
+ return utils.withTurnkeyErrorHandling(async () => {
809
847
  const { subOrganizationId, verificationToken } = await this.verifyOtp({
810
848
  otpId: otpId,
811
849
  otpCode: otpCode,
@@ -835,12 +873,10 @@ class TurnkeyClient {
835
873
  ...(sessionKey && { sessionKey }),
836
874
  });
837
875
  }
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
- }
876
+ }, {
877
+ errorMessage: "Failed to complete OTP process",
878
+ errorCode: sdkTypes.TurnkeyErrorCodes.OTP_COMPLETION_ERROR,
879
+ });
844
880
  };
845
881
  /**
846
882
  * 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 +898,7 @@ class TurnkeyClient {
862
898
  */
863
899
  this.completeOauth = async (params) => {
864
900
  const { oidcToken, publicKey, createSubOrgParams, providerName = "OpenID Connect Provider" + Date.now(), sessionKey = base.SessionKey.DefaultSessionkey, invalidateExisting = false, } = params;
865
- try {
901
+ return utils.withTurnkeyErrorHandling(async () => {
866
902
  const accountRes = await this.httpClient.proxyGetAccount({
867
903
  filterType: "OIDC_TOKEN",
868
904
  filterValue: oidcToken,
@@ -889,12 +925,10 @@ class TurnkeyClient {
889
925
  }),
890
926
  });
891
927
  }
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
- }
928
+ }, {
929
+ errorMessage: "Failed to complete OAuth process",
930
+ errorCode: sdkTypes.TurnkeyErrorCodes.OAUTH_LOGIN_ERROR,
931
+ });
898
932
  };
899
933
  /**
900
934
  * Logs in a user using OAuth authentication.
@@ -913,10 +947,10 @@ class TurnkeyClient {
913
947
  */
914
948
  this.loginWithOauth = async (params) => {
915
949
  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 {
950
+ return utils.withTurnkeyErrorHandling(async () => {
951
+ if (!publicKey) {
952
+ throw new sdkTypes.TurnkeyError("Public key must be provided to log in with OAuth. Please create a key pair first.", sdkTypes.TurnkeyErrorCodes.MISSING_PARAMS);
953
+ }
920
954
  const loginRes = await this.httpClient.proxyOAuthLogin({
921
955
  oidcToken,
922
956
  publicKey,
@@ -933,21 +967,27 @@ class TurnkeyClient {
933
967
  sessionKey,
934
968
  });
935
969
  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);
970
+ }, {
971
+ errorMessage: "Failed to complete OAuth login",
972
+ errorCode: sdkTypes.TurnkeyErrorCodes.OAUTH_LOGIN_ERROR,
973
+ customMessageByMessages: {
974
+ "OAUTH disallowed": {
975
+ message: "OAuth is disabled on the dashboard for this organization.",
976
+ code: sdkTypes.TurnkeyErrorCodes.AUTH_METHOD_NOT_ENABLED,
977
+ },
978
+ },
979
+ catchFn: async () => {
980
+ // Clean up the generated key pair if it wasn't successfully used
981
+ if (publicKey) {
982
+ try {
983
+ await this.apiKeyStamper?.deleteKeyPair(publicKey);
984
+ }
985
+ catch (cleanupError) {
986
+ throw new sdkTypes.TurnkeyError(`Failed to clean up generated key pair`, sdkTypes.TurnkeyErrorCodes.KEY_PAIR_CLEANUP_ERROR, cleanupError);
987
+ }
947
988
  }
948
- }
949
- throw new sdkTypes.TurnkeyError(`Failed to log in with oauth`, sdkTypes.TurnkeyErrorCodes.OAUTH_LOGIN_ERROR, error);
950
- }
989
+ },
990
+ });
951
991
  };
952
992
  /**
953
993
  * Signs up a user using OAuth authentication.
@@ -967,7 +1007,7 @@ class TurnkeyClient {
967
1007
  */
968
1008
  this.signUpWithOauth = async (params) => {
969
1009
  const { oidcToken, publicKey, providerName, createSubOrgParams } = params;
970
- try {
1010
+ return utils.withTurnkeyErrorHandling(async () => {
971
1011
  const signUpBody = utils.buildSignUpBody({
972
1012
  createSubOrgParams: {
973
1013
  ...createSubOrgParams,
@@ -987,12 +1027,10 @@ class TurnkeyClient {
987
1027
  oidcToken,
988
1028
  publicKey: publicKey,
989
1029
  });
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
- }
1030
+ }, {
1031
+ errorMessage: "Failed to sign up with OAuth",
1032
+ errorCode: sdkTypes.TurnkeyErrorCodes.OAUTH_SIGNUP_ERROR,
1033
+ });
996
1034
  };
997
1035
  /**
998
1036
  * Fetches all wallets for the current user, including both embedded and connected wallets.
@@ -1008,12 +1046,12 @@ class TurnkeyClient {
1008
1046
  * @throws {TurnkeyError} If no active session is found or if there is an error fetching wallets.
1009
1047
  */
1010
1048
  this.fetchWallets = async (params) => {
1011
- const { stampWith } = params || {};
1049
+ const { stampWith, walletProviders } = params || {};
1012
1050
  const session = await this.storageManager.getActiveSession();
1013
1051
  if (!session) {
1014
1052
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1015
1053
  }
1016
- try {
1054
+ return utils.withTurnkeyErrorHandling(async () => {
1017
1055
  const res = await this.httpClient.getWallets({ organizationId: session.organizationId }, stampWith);
1018
1056
  if (!res || !res.wallets) {
1019
1057
  throw new sdkTypes.TurnkeyError("No wallets found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
@@ -1034,10 +1072,11 @@ class TurnkeyClient {
1034
1072
  // if wallet connecting is disabled we return only embedded wallets
1035
1073
  if (!this.walletManager?.connector)
1036
1074
  return embedded;
1037
- const providers = await this.getWalletProviders();
1075
+ const providers = walletProviders ?? (await this.getWalletProviders());
1038
1076
  const groupedProviders = new Map();
1039
1077
  for (const provider of providers) {
1040
- const walletId = provider.info?.name?.toLowerCase().replace(/\s+/g, "-") || "unknown";
1078
+ const walletId = provider.info?.name?.toLowerCase().replace(/\s+/g, "-") ||
1079
+ "unknown";
1041
1080
  const group = groupedProviders.get(walletId) || [];
1042
1081
  group.push(provider);
1043
1082
  groupedProviders.set(walletId, group);
@@ -1063,12 +1102,10 @@ class TurnkeyClient {
1063
1102
  return wallet;
1064
1103
  }))).filter((wallet) => wallet.accounts.length > 0);
1065
1104
  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
- }
1105
+ }, {
1106
+ errorMessage: "Failed to fetch wallets",
1107
+ errorCode: sdkTypes.TurnkeyErrorCodes.FETCH_WALLETS_ERROR,
1108
+ });
1072
1109
  };
1073
1110
  /**
1074
1111
  * Fetches all accounts for a specific wallet, including both embedded and connected wallet accounts.
@@ -1092,58 +1129,90 @@ class TurnkeyClient {
1092
1129
  if (!session) {
1093
1130
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1094
1131
  }
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,
1132
+ return utils.withTurnkeyErrorHandling(async () => {
1133
+ // this is an embedded wallet so we fetch accounts from Turnkey
1134
+ if (wallet.source === base.WalletSource.Embedded) {
1135
+ const embedded = [];
1136
+ const res = await this.httpClient.getWalletAccounts({
1129
1137
  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);
1138
+ organizationId: session.organizationId,
1139
+ paginationOptions: paginationOptions || { limit: "100" },
1140
+ }, stampWith);
1141
+ if (!res || !res.accounts) {
1142
+ throw new sdkTypes.TurnkeyError("No wallet accounts found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1143
+ }
1144
+ for (const account of res.accounts) {
1145
+ embedded.push({
1146
+ ...account,
1147
+ source: base.WalletSource.Embedded,
1148
+ });
1149
+ }
1150
+ return embedded;
1144
1151
  }
1145
- }
1146
- return connected;
1152
+ // this is an external wallet so we fetch accounts from the connected wallet provider
1153
+ // if wallet connecting is disabled we return only embedded wallets
1154
+ // we should never reach this point if wallet connecting is disabled
1155
+ if (!this.walletManager?.connector)
1156
+ return [];
1157
+ const connected = [];
1158
+ const providers = walletProviders ?? (await this.getWalletProviders());
1159
+ const matching = providers.filter((p) => p.info?.name?.toLowerCase().replace(/\s+/g, "-") ===
1160
+ wallet.walletId && p.connectedAddresses.length > 0);
1161
+ const sign = this.walletManager.connector.sign.bind(this.walletManager.connector);
1162
+ for (const provider of matching) {
1163
+ const timestamp = utils.toExternalTimestamp();
1164
+ for (const address of provider.connectedAddresses) {
1165
+ if (utils.isEthereumProvider(provider)) {
1166
+ const evmAccount = {
1167
+ walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1168
+ organizationId: session.organizationId,
1169
+ walletId: wallet.walletId,
1170
+ pathFormat: "PATH_FORMAT_BIP32",
1171
+ path: base.WalletSource.Connected,
1172
+ source: base.WalletSource.Connected,
1173
+ address,
1174
+ createdAt: timestamp,
1175
+ updatedAt: timestamp,
1176
+ // ethereum specific
1177
+ curve: base.Curve.SECP256K1,
1178
+ addressFormat: "ADDRESS_FORMAT_ETHEREUM",
1179
+ chainInfo: provider.chainInfo,
1180
+ signMessage: (msg) => sign(msg, provider, base.SignIntent.SignMessage),
1181
+ signAndSendTransaction: (tx) => sign(tx, provider, base.SignIntent.SignAndSendTransaction),
1182
+ };
1183
+ connected.push(evmAccount);
1184
+ continue;
1185
+ }
1186
+ if (utils.isSolanaProvider(provider)) {
1187
+ const solAccount = {
1188
+ walletAccountId: `${wallet.walletId}-${provider.interfaceType}-${address}`,
1189
+ organizationId: session.organizationId,
1190
+ walletId: wallet.walletId,
1191
+ pathFormat: "PATH_FORMAT_BIP32",
1192
+ path: base.WalletSource.Connected,
1193
+ source: base.WalletSource.Connected,
1194
+ address,
1195
+ createdAt: timestamp,
1196
+ updatedAt: timestamp,
1197
+ // solana specific
1198
+ publicKey: address,
1199
+ curve: base.Curve.ED25519,
1200
+ addressFormat: "ADDRESS_FORMAT_SOLANA",
1201
+ chainInfo: provider.chainInfo,
1202
+ signMessage: (msg) => sign(msg, provider, base.SignIntent.SignMessage),
1203
+ signTransaction: (tx) => sign(tx, provider, base.SignIntent.SignTransaction),
1204
+ };
1205
+ connected.push(solAccount);
1206
+ continue;
1207
+ }
1208
+ throw new Error(`Unsupported wallet chain: ${provider.chainInfo}. Supported chains are Ethereum and Solana.`);
1209
+ }
1210
+ }
1211
+ return connected;
1212
+ }, {
1213
+ errorMessage: "Failed to fetch wallet accounts",
1214
+ errorCode: sdkTypes.TurnkeyErrorCodes.FETCH_WALLET_ACCOUNTS_ERROR,
1215
+ });
1147
1216
  };
1148
1217
  /**
1149
1218
  * Signs a message using the specified wallet account.
@@ -1177,7 +1246,7 @@ class TurnkeyClient {
1177
1246
  const { message, walletAccount, stampWith, addEthereumPrefix } = params;
1178
1247
  const hashFunction = params.hashFunction || utils.getHashFunction(walletAccount.addressFormat);
1179
1248
  const payloadEncoding = params.encoding || utils.getEncodingType(walletAccount.addressFormat);
1180
- try {
1249
+ return utils.withTurnkeyErrorHandling(async () => {
1181
1250
  const isEthereum = walletAccount.addressFormat === "ADDRESS_FORMAT_ETHEREUM";
1182
1251
  if (walletAccount.source === base.WalletSource.Connected) {
1183
1252
  // this is a connected wallet
@@ -1209,12 +1278,10 @@ class TurnkeyClient {
1209
1278
  }
1210
1279
  return response.activity.result
1211
1280
  .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
- }
1281
+ }, {
1282
+ errorMessage: "Failed to sign message",
1283
+ errorCode: sdkTypes.TurnkeyErrorCodes.SIGN_MESSAGE_ERROR,
1284
+ });
1218
1285
  };
1219
1286
  /**
1220
1287
  * Signs a transaction using the specified wallet account.
@@ -1234,17 +1301,18 @@ class TurnkeyClient {
1234
1301
  */
1235
1302
  this.signTransaction = async (params) => {
1236
1303
  const { walletAccount, unsignedTransaction, transactionType, stampWith } = params;
1237
- try {
1304
+ return utils.withTurnkeyErrorHandling(async () => {
1238
1305
  if (walletAccount.source === base.WalletSource.Connected) {
1239
- // this is a connected wallet account
1240
- if (!walletAccount.signTransaction) {
1241
- const isEthereum = walletAccount.addressFormat === "ADDRESS_FORMAT_ETHEREUM";
1242
- const reason = isEthereum
1243
- ? "Ethereum connected wallets do not support raw transaction signing due to EIP-1193 limitations."
1244
- : "This connected wallet does not support raw transaction signing.";
1245
- throw new sdkTypes.TurnkeyError(`Failed to sign transaction: ${reason} ${isEthereum ? "Use signAndSendTransaction instead." : ""}`, sdkTypes.TurnkeyErrorCodes.SIGN_TRANSACTION_ERROR);
1306
+ switch (walletAccount.chainInfo.namespace) {
1307
+ case base.Chain.Ethereum:
1308
+ throw new sdkTypes.TurnkeyError("Ethereum connected wallets do not support raw transaction signing. Use signAndSendTransaction instead.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1309
+ case base.Chain.Solana:
1310
+ // not sure why typescript isn't inferring the type here
1311
+ // if namespace is Chain.Solana, then it must be a ConnectedSolanaWalletAccount
1312
+ return walletAccount.signTransaction(unsignedTransaction);
1313
+ default:
1314
+ throw new sdkTypes.TurnkeyError("Unsupported connected wallet type.", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1246
1315
  }
1247
- return await walletAccount?.signTransaction(unsignedTransaction);
1248
1316
  }
1249
1317
  // this is an embedded wallet account
1250
1318
  const signTransaction = await this.httpClient.signTransaction({
@@ -1253,12 +1321,10 @@ class TurnkeyClient {
1253
1321
  type: transactionType,
1254
1322
  }, stampWith);
1255
1323
  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
- }
1324
+ }, {
1325
+ errorMessage: "Failed to sign transaction",
1326
+ errorCode: sdkTypes.TurnkeyErrorCodes.SIGN_TRANSACTION_ERROR,
1327
+ });
1262
1328
  };
1263
1329
  /**
1264
1330
  * Signs and broadcasts a transaction using the specified wallet account.
@@ -1282,22 +1348,20 @@ class TurnkeyClient {
1282
1348
  */
1283
1349
  this.signAndSendTransaction = async (params) => {
1284
1350
  const { walletAccount, unsignedTransaction, transactionType, rpcUrl, stampWith, } = params;
1285
- try {
1351
+ return utils.withTurnkeyErrorHandling(async () => {
1286
1352
  if (walletAccount.source === base.WalletSource.Connected) {
1287
1353
  // this is a connected wallet account
1288
- switch (transactionType) {
1289
- case "TRANSACTION_TYPE_ETHEREUM":
1290
- if (!walletAccount.signAndSendTransaction) {
1291
- throw new sdkTypes.TurnkeyError("This connected wallet does not support signAndSendTransaction.", sdkTypes.TurnkeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR);
1292
- }
1354
+ switch (walletAccount.chainInfo.namespace) {
1355
+ case base.Chain.Ethereum:
1356
+ // not sure why typescript isn't inferring the type here
1357
+ // if namespace is Chain.Ethereum, then it must be a ConnectedEthereumWalletAccount
1293
1358
  return await walletAccount.signAndSendTransaction(unsignedTransaction);
1294
- case "TRANSACTION_TYPE_SOLANA":
1359
+ case base.Chain.Solana:
1295
1360
  if (!rpcUrl) {
1296
1361
  throw new sdkTypes.TurnkeyError("Missing rpcUrl: connected Solana wallets require an RPC URL to broadcast transactions.", sdkTypes.TurnkeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR);
1297
1362
  }
1298
- if (!walletAccount.signTransaction) {
1299
- throw new sdkTypes.TurnkeyError("This connected wallet does not support signAndSendTransaction.", sdkTypes.TurnkeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR);
1300
- }
1363
+ // not sure why typescript isn't inferring the type here
1364
+ // if namespace is Chain.Solana, then it must be a ConnectedSolanaWalletAccount
1301
1365
  const signature = await walletAccount.signTransaction(unsignedTransaction);
1302
1366
  return await utils.broadcastTransaction({
1303
1367
  signedTransaction: signature,
@@ -1326,12 +1390,10 @@ class TurnkeyClient {
1326
1390
  transactionType,
1327
1391
  });
1328
1392
  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
- }
1393
+ }, {
1394
+ errorMessage: "Failed to sign and send transaction",
1395
+ errorCode: sdkTypes.TurnkeyErrorCodes.SIGN_AND_SEND_TRANSACTION_ERROR,
1396
+ });
1335
1397
  };
1336
1398
  /**
1337
1399
  * Fetches the user details for the current session or a specified user.
@@ -1359,18 +1421,16 @@ class TurnkeyClient {
1359
1421
  throw new sdkTypes.TurnkeyError("User ID must be provided to fetch user", sdkTypes.TurnkeyErrorCodes.INVALID_REQUEST);
1360
1422
  }
1361
1423
  const organizationId = params?.organizationId || session.organizationId;
1362
- try {
1424
+ return utils.withTurnkeyErrorHandling(async () => {
1363
1425
  const userResponse = await this.httpClient.getUser({ organizationId, userId }, stampWith);
1364
1426
  if (!userResponse || !userResponse.user) {
1365
1427
  throw new sdkTypes.TurnkeyError("No user found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1366
1428
  }
1367
1429
  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
- }
1430
+ }, {
1431
+ errorMessage: "Failed to fetch user",
1432
+ errorCode: sdkTypes.TurnkeyErrorCodes.FETCH_USER_ERROR,
1433
+ });
1374
1434
  };
1375
1435
  /**
1376
1436
  * Updates the user's email address.
@@ -1395,7 +1455,7 @@ class TurnkeyClient {
1395
1455
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1396
1456
  }
1397
1457
  const userId = params?.userId || session.userId;
1398
- try {
1458
+ return utils.withTurnkeyErrorHandling(async () => {
1399
1459
  const existingUser = await this.httpClient.proxyGetAccount({
1400
1460
  filterType: base.FilterType.Email,
1401
1461
  filterValue: email,
@@ -1412,12 +1472,10 @@ class TurnkeyClient {
1412
1472
  throw new sdkTypes.TurnkeyError("No user ID found in the update user email response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1413
1473
  }
1414
1474
  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
- }
1475
+ }, {
1476
+ errorMessage: "Failed to update user email",
1477
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_EMAIL_ERROR,
1478
+ });
1421
1479
  };
1422
1480
  /**
1423
1481
  * Removes the user's email address.
@@ -1438,15 +1496,20 @@ class TurnkeyClient {
1438
1496
  if (!session) {
1439
1497
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1440
1498
  }
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;
1499
+ return utils.withTurnkeyErrorHandling(async () => {
1500
+ const userId = params?.userId || session.userId;
1501
+ const res = await this.httpClient.updateUserEmail({
1502
+ userId: userId,
1503
+ userEmail: "",
1504
+ }, stampWith);
1505
+ if (!res || !res.userId) {
1506
+ throw new sdkTypes.TurnkeyError("No user ID found in the remove user email response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1507
+ }
1508
+ return res.userId;
1509
+ }, {
1510
+ errorMessage: "Failed to remove user email",
1511
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_EMAIL_ERROR,
1512
+ });
1450
1513
  };
1451
1514
  /**
1452
1515
  * Updates the user's phone number.
@@ -1471,7 +1534,7 @@ class TurnkeyClient {
1471
1534
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1472
1535
  }
1473
1536
  const userId = params?.userId || session.userId;
1474
- try {
1537
+ return utils.withTurnkeyErrorHandling(async () => {
1475
1538
  const res = await this.httpClient.updateUserPhoneNumber({
1476
1539
  userId,
1477
1540
  userPhoneNumber: phoneNumber,
@@ -1481,12 +1544,10 @@ class TurnkeyClient {
1481
1544
  throw new sdkTypes.TurnkeyError("Failed to update user phone number", sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
1482
1545
  }
1483
1546
  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
- }
1547
+ }, {
1548
+ errorMessage: "Failed to update user phone number",
1549
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR,
1550
+ });
1490
1551
  };
1491
1552
  /**
1492
1553
  * Removes the user's phone number.
@@ -1508,14 +1569,19 @@ class TurnkeyClient {
1508
1569
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1509
1570
  }
1510
1571
  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;
1572
+ return utils.withTurnkeyErrorHandling(async () => {
1573
+ const res = await this.httpClient.updateUserPhoneNumber({
1574
+ userId,
1575
+ userPhoneNumber: "",
1576
+ }, stampWith);
1577
+ if (!res || !res.userId) {
1578
+ throw new sdkTypes.TurnkeyError("Failed to remove user phone number", sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR);
1579
+ }
1580
+ return res.userId;
1581
+ }, {
1582
+ errorMessage: "Failed to remove user phone number",
1583
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_PHONE_NUMBER_ERROR,
1584
+ });
1519
1585
  };
1520
1586
  /**
1521
1587
  * Updates the user's name.
@@ -1539,7 +1605,7 @@ class TurnkeyClient {
1539
1605
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1540
1606
  }
1541
1607
  const userId = params?.userId || session.userId;
1542
- try {
1608
+ return utils.withTurnkeyErrorHandling(async () => {
1543
1609
  const res = await this.httpClient.updateUserName({
1544
1610
  userId,
1545
1611
  userName,
@@ -1548,12 +1614,10 @@ class TurnkeyClient {
1548
1614
  throw new sdkTypes.TurnkeyError("No user ID found in the update user name response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1549
1615
  }
1550
1616
  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
- }
1617
+ }, {
1618
+ errorMessage: "Failed to update user name",
1619
+ errorCode: sdkTypes.TurnkeyErrorCodes.UPDATE_USER_NAME_ERROR,
1620
+ });
1557
1621
  };
1558
1622
  /**
1559
1623
  * Adds an OAuth provider to the user.
@@ -1578,7 +1642,7 @@ class TurnkeyClient {
1578
1642
  if (!session) {
1579
1643
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1580
1644
  }
1581
- try {
1645
+ return utils.withTurnkeyErrorHandling(async () => {
1582
1646
  const accountRes = await this.httpClient.proxyGetAccount({
1583
1647
  filterType: "OIDC_TOKEN",
1584
1648
  filterValue: oidcToken,
@@ -1622,12 +1686,10 @@ class TurnkeyClient {
1622
1686
  throw new sdkTypes.TurnkeyError("Failed to create OAuth provider", sdkTypes.TurnkeyErrorCodes.ADD_OAUTH_PROVIDER_ERROR);
1623
1687
  }
1624
1688
  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
- }
1689
+ }, {
1690
+ errorMessage: "Failed to add OAuth provider",
1691
+ errorCode: sdkTypes.TurnkeyErrorCodes.ADD_OAUTH_PROVIDER_ERROR,
1692
+ });
1631
1693
  };
1632
1694
  /**
1633
1695
  * Removes a list of OAuth providers from the user.
@@ -1651,14 +1713,19 @@ class TurnkeyClient {
1651
1713
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1652
1714
  }
1653
1715
  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;
1716
+ return utils.withTurnkeyErrorHandling(async () => {
1717
+ const res = await this.httpClient.deleteOauthProviders({
1718
+ userId,
1719
+ providerIds,
1720
+ }, stampWith);
1721
+ if (!res) {
1722
+ throw new sdkTypes.TurnkeyError("Failed to remove OAuth provider", sdkTypes.TurnkeyErrorCodes.REMOVE_OAUTH_PROVIDER_ERROR);
1723
+ }
1724
+ return res.providerIds;
1725
+ }, {
1726
+ errorMessage: "Failed to remove OAuth provider",
1727
+ errorCode: sdkTypes.TurnkeyErrorCodes.REMOVE_OAUTH_PROVIDER_ERROR,
1728
+ });
1662
1729
  };
1663
1730
  /**
1664
1731
  * Adds a new passkey authenticator for the user.
@@ -1680,7 +1747,7 @@ class TurnkeyClient {
1680
1747
  const { stampWith } = params || {};
1681
1748
  const name = params?.name || `Turnkey Passkey-${Date.now()}`;
1682
1749
  const displayName = params?.displayName || name;
1683
- try {
1750
+ return utils.withTurnkeyErrorHandling(async () => {
1684
1751
  const session = await this.storageManager.getActiveSession();
1685
1752
  if (!session) {
1686
1753
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
@@ -1705,12 +1772,10 @@ class TurnkeyClient {
1705
1772
  ],
1706
1773
  }, stampWith);
1707
1774
  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
- }
1775
+ }, {
1776
+ errorMessage: "Failed to add passkey",
1777
+ errorCode: sdkTypes.TurnkeyErrorCodes.ADD_PASSKEY_ERROR,
1778
+ });
1714
1779
  };
1715
1780
  /**
1716
1781
  * Removes passkeys (authenticator) from the user.
@@ -1734,14 +1799,19 @@ class TurnkeyClient {
1734
1799
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1735
1800
  }
1736
1801
  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;
1802
+ return utils.withTurnkeyErrorHandling(async () => {
1803
+ const res = await this.httpClient.deleteAuthenticators({
1804
+ userId,
1805
+ authenticatorIds,
1806
+ }, stampWith);
1807
+ if (!res) {
1808
+ throw new sdkTypes.TurnkeyError("No response found in the remove passkey response", sdkTypes.TurnkeyErrorCodes.REMOVE_PASSKEY_ERROR);
1809
+ }
1810
+ return res.authenticatorIds;
1811
+ }, {
1812
+ errorMessage: "Failed to remove passkey",
1813
+ errorCode: sdkTypes.TurnkeyErrorCodes.REMOVE_PASSKEY_ERROR,
1814
+ });
1745
1815
  };
1746
1816
  /**
1747
1817
  * Creates a new wallet for sub-organization.
@@ -1780,7 +1850,7 @@ class TurnkeyClient {
1780
1850
  ...turnkeyHelpers.DEFAULT_SOLANA_ACCOUNTS,
1781
1851
  ];
1782
1852
  }
1783
- try {
1853
+ return utils.withTurnkeyErrorHandling(async () => {
1784
1854
  const res = await this.httpClient.createWallet({
1785
1855
  organizationId: organizationId || session.organizationId,
1786
1856
  walletName,
@@ -1791,12 +1861,10 @@ class TurnkeyClient {
1791
1861
  throw new sdkTypes.TurnkeyError("No wallet found in the create wallet response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1792
1862
  }
1793
1863
  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
- }
1864
+ }, {
1865
+ errorMessage: "Failed to create wallet",
1866
+ errorCode: sdkTypes.TurnkeyErrorCodes.CREATE_WALLET_ERROR,
1867
+ });
1800
1868
  };
1801
1869
  /**
1802
1870
  * Creates new accounts in the specified wallet.
@@ -1821,7 +1889,7 @@ class TurnkeyClient {
1821
1889
  if (!session) {
1822
1890
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1823
1891
  }
1824
- try {
1892
+ return utils.withTurnkeyErrorHandling(async () => {
1825
1893
  let walletAccounts = [];
1826
1894
  if (accounts && !utils.isWalletAccountArray(accounts)) {
1827
1895
  // Query existing wallet accounts to avoid duplicates
@@ -1847,12 +1915,10 @@ class TurnkeyClient {
1847
1915
  throw new sdkTypes.TurnkeyError("No account found in the create wallet account response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1848
1916
  }
1849
1917
  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
- }
1918
+ }, {
1919
+ errorMessage: "Failed to create wallet account",
1920
+ errorCode: sdkTypes.TurnkeyErrorCodes.CREATE_WALLET_ACCOUNT_ERROR,
1921
+ });
1856
1922
  };
1857
1923
  /**
1858
1924
  * Exports a wallet as an encrypted bundle.
@@ -1877,7 +1943,7 @@ class TurnkeyClient {
1877
1943
  if (!session) {
1878
1944
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1879
1945
  }
1880
- try {
1946
+ return utils.withTurnkeyErrorHandling(async () => {
1881
1947
  const res = await this.httpClient.exportWallet({
1882
1948
  walletId,
1883
1949
  targetPublicKey,
@@ -1887,12 +1953,85 @@ class TurnkeyClient {
1887
1953
  throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1888
1954
  }
1889
1955
  return res.exportBundle;
1956
+ }, {
1957
+ errorMessage: "Failed to export wallet",
1958
+ errorCode: sdkTypes.TurnkeyErrorCodes.EXPORT_WALLET_ERROR,
1959
+ });
1960
+ };
1961
+ /**
1962
+ * Exports a private key as an encrypted bundle.
1963
+ *
1964
+ * - This function exports the specified private key as an encrypted bundle, suitable for backup or transfer.
1965
+ * - The exported bundle contains the private key's key material, encrypted to the provided target public key.
1966
+ * - If a targetPublicKey is provided, the bundle will be encrypted to that public key; otherwise, an error will be thrown.
1967
+ * - If an organizationId is provided, the private key will be exported under that sub-organization; otherwise, the current session's organizationId is used.
1968
+ * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1969
+ *
1970
+ * @param params.privateKeyId - ID of the private key to export.
1971
+ * @param params.targetPublicKey - public key to encrypt the bundle to (required).
1972
+ * @param params.organizationId - organization ID to export the private key under a specific sub
1973
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1974
+ * @returns A promise that resolves to an `ExportBundle` object containing the encrypted private key and metadata.
1975
+ * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the private key.
1976
+ */
1977
+ this.exportPrivateKey = async (params) => {
1978
+ const { privateKeyId, targetPublicKey, stampWith, organizationId } = params;
1979
+ const session = await this.storageManager.getActiveSession();
1980
+ if (!session) {
1981
+ throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1890
1982
  }
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);
1983
+ return utils.withTurnkeyErrorHandling(async () => {
1984
+ const res = await this.httpClient.exportPrivateKey({
1985
+ privateKeyId,
1986
+ targetPublicKey,
1987
+ organizationId: organizationId || session.organizationId,
1988
+ }, stampWith);
1989
+ if (!res.exportBundle) {
1990
+ throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1991
+ }
1992
+ return res.exportBundle;
1993
+ }, {
1994
+ errorMessage: "Failed to export private key",
1995
+ errorCode: sdkTypes.TurnkeyErrorCodes.EXPORT_PRIVATE_KEY_ERROR,
1996
+ });
1997
+ };
1998
+ /**
1999
+ * Exports a wallet account as an encrypted bundle.
2000
+ *
2001
+ * - This function exports the specified wallet account as an encrypted bundle, suitable for backup or transfer.
2002
+ * - The exported bundle contains the wallet account's key material, encrypted to the provided target public key.
2003
+ * - If a targetPublicKey is provided, the bundle will be encrypted to that public key; otherwise, an error will be thrown.
2004
+ * - If an organizationId is provided, the wallet account will be exported under that sub-organization; otherwise, the current session's organizationId is used.
2005
+ * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2006
+ *
2007
+ * @param params.address - address of the wallet account to export.
2008
+ * @param params.targetPublicKey - public key to encrypt the bundle to.
2009
+ * @param params.organizationId - organization ID to export the wallet account under a specific sub-organization.
2010
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2011
+ * @returns A promise that resolves to an `ExportBundle` object containing the encrypted wallet account and metadata.
2012
+ * @throws {TurnkeyError} If there is no active session, if the targetPublicKey is missing, or if there is an error exporting the wallet account.
2013
+ *
2014
+ */
2015
+ this.exportWalletAccount = async (params) => {
2016
+ const { address, targetPublicKey, stampWith, organizationId } = params;
2017
+ const session = await this.storageManager.getActiveSession();
2018
+ if (!session) {
2019
+ throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1895
2020
  }
2021
+ return utils.withTurnkeyErrorHandling(async () => {
2022
+ const res = await this.httpClient.exportWalletAccount({
2023
+ address,
2024
+ targetPublicKey,
2025
+ organizationId: organizationId || session.organizationId,
2026
+ }, stampWith);
2027
+ if (!res.exportBundle) {
2028
+ throw new sdkTypes.TurnkeyError("No export bundle found in the response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
2029
+ }
2030
+ return res.exportBundle;
2031
+ }, {
2032
+ errorMessage: "Failed to export wallet account",
2033
+ errorCode: sdkTypes.TurnkeyErrorCodes.EXPORT_WALLET_ACCOUNT_ERROR,
2034
+ });
1896
2035
  };
1897
2036
  /**
1898
2037
  * Imports a wallet from an encrypted bundle.
@@ -1900,7 +2039,7 @@ class TurnkeyClient {
1900
2039
  * - This function imports a wallet using the provided encrypted bundle and creates accounts based on the provided parameters.
1901
2040
  * - If a userId is provided, the wallet will be imported for that specific user; otherwise, it uses the current session's userId.
1902
2041
  * - 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
2042
+ * - The encrypted bundle MUST be encrypted to
1904
2043
  * - Automatically ensures an active session exists before making the request.
1905
2044
  * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
1906
2045
  *
@@ -1918,7 +2057,7 @@ class TurnkeyClient {
1918
2057
  if (!session) {
1919
2058
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1920
2059
  }
1921
- try {
2060
+ return utils.withTurnkeyErrorHandling(async () => {
1922
2061
  const res = await this.httpClient.importWallet({
1923
2062
  organizationId: session.organizationId,
1924
2063
  userId: userId || session.userId,
@@ -1933,12 +2072,66 @@ class TurnkeyClient {
1933
2072
  throw new sdkTypes.TurnkeyError("No wallet ID found in the import response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
1934
2073
  }
1935
2074
  return res.walletId;
2075
+ }, {
2076
+ errorMessage: "Failed to import wallet",
2077
+ errorCode: sdkTypes.TurnkeyErrorCodes.IMPORT_WALLET_ERROR,
2078
+ customMessageByMessages: {
2079
+ "invalid mnemonic": {
2080
+ message: "Invalid mnemonic input",
2081
+ code: sdkTypes.TurnkeyErrorCodes.BAD_REQUEST,
2082
+ },
2083
+ },
2084
+ });
2085
+ };
2086
+ /**
2087
+ * Imports a private key from an encrypted bundle.
2088
+ *
2089
+ * - This function imports a private key using the provided encrypted bundle.
2090
+ * - If a userId is provided, the private key will be imported for that specific user; otherwise, it uses the current session's userId.
2091
+ * - Requires address formats to
2092
+ * - Automatically infers the cryptographic curve used to generate the private key based on the address format (can be optionally overriden if needed).
2093
+ * - The encrypted bundle MUST be encrypted to ensure security.
2094
+ * - Automatically ensures an active session exists before making the request.
2095
+ * - Optionally allows stamping the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2096
+ *
2097
+ * @param params.encryptedBundle - encrypted bundle containing the private key key material and metadata.
2098
+ * @param params.privateKeyName - name of the private key to create upon import.
2099
+ * @param params.curve - the cryptographic curve used to generate a given private key
2100
+ * @param params.addressFormat - address format of the private key to import.
2101
+ * @param params.userId - user ID to import the wallet for a specific user (defaults to the current session's userId).
2102
+ * @param params.stampWith - parameter to stamp the request with a specific stamper (StamperType.Passkey, StamperType.ApiKey, or StamperType.Wallet).
2103
+ * @returns A promise that resolves to the ID of the imported wallet.
2104
+ * @throws {TurnkeyError} If there is no active session, if the encrypted bundle is invalid, or if there is an error importing the wallet.
2105
+ */
2106
+ this.importPrivateKey = async (params) => {
2107
+ const { encryptedBundle, privateKeyName, addressFormats, curve, userId, stampWith, } = params;
2108
+ const session = await this.storageManager.getActiveSession();
2109
+ if (!session) {
2110
+ throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1936
2111
  }
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
- }
2112
+ return utils.withTurnkeyErrorHandling(async () => {
2113
+ const res = await this.httpClient.importPrivateKey({
2114
+ organizationId: session.organizationId,
2115
+ userId: userId || session.userId,
2116
+ encryptedBundle,
2117
+ privateKeyName,
2118
+ curve,
2119
+ addressFormats,
2120
+ }, stampWith);
2121
+ if (!res || !res.privateKeyId) {
2122
+ throw new sdkTypes.TurnkeyError("No wallet ID found in the import response", sdkTypes.TurnkeyErrorCodes.BAD_RESPONSE);
2123
+ }
2124
+ return res.privateKeyId;
2125
+ }, {
2126
+ errorMessage: "Failed to import wallet",
2127
+ errorCode: sdkTypes.TurnkeyErrorCodes.IMPORT_WALLET_ERROR,
2128
+ customMessageByMessages: {
2129
+ "invalid mnemonic": {
2130
+ message: "Invalid mnemonic input",
2131
+ code: sdkTypes.TurnkeyErrorCodes.BAD_REQUEST,
2132
+ },
2133
+ },
2134
+ });
1942
2135
  };
1943
2136
  /**
1944
2137
  * Deletes the current sub-organization (sub-org) for the active session.
@@ -1960,14 +2153,12 @@ class TurnkeyClient {
1960
2153
  if (!session) {
1961
2154
  throw new sdkTypes.TurnkeyError("No active session found. Please log in first.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
1962
2155
  }
1963
- try {
2156
+ return utils.withTurnkeyErrorHandling(async () => {
1964
2157
  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
- }
2158
+ }, {
2159
+ errorMessage: "Failed to delete sub-organization",
2160
+ errorCode: sdkTypes.TurnkeyErrorCodes.DELETE_SUB_ORGANIZATION_ERROR,
2161
+ });
1971
2162
  };
1972
2163
  /**
1973
2164
  * Stores a session token and updates the session associated with the specified session key, or by default the active session.
@@ -1987,21 +2178,14 @@ class TurnkeyClient {
1987
2178
  const { sessionToken, sessionKey = base.SessionKey.DefaultSessionkey } = params;
1988
2179
  if (!sessionToken)
1989
2180
  return;
1990
- try {
1991
- const sessionToReplace = await this.storageManager.getSession(sessionKey);
2181
+ utils.withTurnkeyErrorHandling(async () => {
1992
2182
  await this.storageManager.storeSession(sessionToken, sessionKey);
1993
- if (sessionToReplace) {
1994
- await this.apiKeyStamper?.deleteKeyPair(sessionToReplace.publicKey);
1995
- }
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
- }
2183
+ }, {
2184
+ errorMessage: "Failed to store session",
2185
+ errorCode: sdkTypes.TurnkeyErrorCodes.STORE_SESSION_ERROR,
2186
+ }, {
2187
+ finallyFn: async () => await this.clearUnusedKeyPairs(),
2188
+ });
2005
2189
  };
2006
2190
  /**
2007
2191
  * Clears the session associated with the specified session key, or the active session by default.
@@ -2017,7 +2201,7 @@ class TurnkeyClient {
2017
2201
  */
2018
2202
  this.clearSession = async (params) => {
2019
2203
  const { sessionKey = base.SessionKey.DefaultSessionkey } = params || {};
2020
- try {
2204
+ utils.withTurnkeyErrorHandling(async () => {
2021
2205
  const session = await this.storageManager.getSession(sessionKey);
2022
2206
  if (session) {
2023
2207
  await this.apiKeyStamper?.deleteKeyPair(session.publicKey);
@@ -2026,12 +2210,10 @@ class TurnkeyClient {
2026
2210
  else {
2027
2211
  throw new sdkTypes.TurnkeyError(`No session found with key: ${sessionKey}`, sdkTypes.TurnkeyErrorCodes.NOT_FOUND);
2028
2212
  }
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
- }
2213
+ }, {
2214
+ errorMessage: "Failed to delete session",
2215
+ errorCode: sdkTypes.TurnkeyErrorCodes.CLEAR_SESSION_ERROR,
2216
+ });
2035
2217
  };
2036
2218
  /**
2037
2219
  * Clears all sessions and resets the active session state.
@@ -2045,7 +2227,7 @@ class TurnkeyClient {
2045
2227
  * @throws {TurnkeyError} If no sessions exist or if there is an error clearing all sessions.
2046
2228
  */
2047
2229
  this.clearAllSessions = async () => {
2048
- try {
2230
+ utils.withTurnkeyErrorHandling(async () => {
2049
2231
  const sessionKeys = await this.storageManager.listSessionKeys();
2050
2232
  if (sessionKeys.length === 0) {
2051
2233
  throw new sdkTypes.TurnkeyError("No sessions found to clear.", sdkTypes.TurnkeyErrorCodes.NO_SESSION_FOUND);
@@ -2053,12 +2235,10 @@ class TurnkeyClient {
2053
2235
  for (const sessionKey of sessionKeys) {
2054
2236
  this.clearSession({ sessionKey });
2055
2237
  }
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
- }
2238
+ }, {
2239
+ errorMessage: "Failed to clear all sessions",
2240
+ errorCode: sdkTypes.TurnkeyErrorCodes.CLEAR_ALL_SESSIONS_ERROR,
2241
+ });
2062
2242
  };
2063
2243
  /**
2064
2244
  * Refreshes the session associated with the specified session key, or the active session by default.
@@ -2093,7 +2273,7 @@ class TurnkeyClient {
2093
2273
  throw new sdkTypes.TurnkeyError("HTTP client is not initialized. Please initialize the client before refreshing the session.", sdkTypes.TurnkeyErrorCodes.CLIENT_NOT_INITIALIZED);
2094
2274
  }
2095
2275
  let keyPair;
2096
- try {
2276
+ return utils.withTurnkeyErrorHandling(async () => {
2097
2277
  keyPair = publicKey ?? (await this.apiKeyStamper?.createKeyPair());
2098
2278
  if (!keyPair) {
2099
2279
  throw new sdkTypes.TurnkeyError("Failed to create new key pair.", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
@@ -2111,12 +2291,10 @@ class TurnkeyClient {
2111
2291
  ...(sessionKey && { sessionKey }),
2112
2292
  });
2113
2293
  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
- }
2294
+ }, {
2295
+ errorMessage: "Failed to refresh session",
2296
+ errorCode: sdkTypes.TurnkeyErrorCodes.REFRESH_SESSION_ERROR,
2297
+ });
2120
2298
  };
2121
2299
  /**
2122
2300
  * Retrieves the session associated with the specified session key, or the active session by default.
@@ -2130,15 +2308,13 @@ class TurnkeyClient {
2130
2308
  * @throws {TurnkeyError} If there is an error retrieving the session from storage.
2131
2309
  */
2132
2310
  this.getSession = async (params) => {
2133
- try {
2311
+ return utils.withTurnkeyErrorHandling(async () => {
2134
2312
  const { sessionKey = await this.storageManager.getActiveSessionKey() } = params || {};
2135
2313
  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
- }
2314
+ }, {
2315
+ errorMessage: "Failed to get session with key " + params?.sessionKey,
2316
+ errorCode: sdkTypes.TurnkeyErrorCodes.GET_SESSION_ERROR,
2317
+ });
2142
2318
  };
2143
2319
  /**
2144
2320
  * Retrieves all sessions stored in persistent storage.
@@ -2152,7 +2328,7 @@ class TurnkeyClient {
2152
2328
  * @throws {TurnkeyError} If there is an error retrieving sessions from storage.
2153
2329
  */
2154
2330
  this.getAllSessions = async () => {
2155
- try {
2331
+ return utils.withTurnkeyErrorHandling(async () => {
2156
2332
  const sessionKeys = await this.storageManager.listSessionKeys();
2157
2333
  if (!sessionKeys || sessionKeys.length === 0) {
2158
2334
  return undefined;
@@ -2164,13 +2340,11 @@ class TurnkeyClient {
2164
2340
  sessions[sessionKey] = session;
2165
2341
  }
2166
2342
  }
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
- }
2343
+ return sessions || undefined;
2344
+ }, {
2345
+ errorMessage: "Failed to get all sessions",
2346
+ errorCode: sdkTypes.TurnkeyErrorCodes.GET_ALL_SESSIONS_ERROR,
2347
+ });
2174
2348
  };
2175
2349
  /**
2176
2350
  * Sets the active session to the specified session key.
@@ -2186,14 +2360,12 @@ class TurnkeyClient {
2186
2360
  */
2187
2361
  this.setActiveSession = async (params) => {
2188
2362
  const { sessionKey } = params;
2189
- try {
2363
+ return utils.withTurnkeyErrorHandling(async () => {
2190
2364
  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
- }
2365
+ }, {
2366
+ errorMessage: "Failed to set active session",
2367
+ errorCode: sdkTypes.TurnkeyErrorCodes.SET_ACTIVE_SESSION_ERROR,
2368
+ });
2197
2369
  };
2198
2370
  /**
2199
2371
  * Retrieves the active session key currently set in persistent storage.
@@ -2207,14 +2379,12 @@ class TurnkeyClient {
2207
2379
  * @throws {TurnkeyError} If there is an error retrieving the active session key from storage.
2208
2380
  */
2209
2381
  this.getActiveSessionKey = async () => {
2210
- try {
2382
+ return utils.withTurnkeyErrorHandling(async () => {
2211
2383
  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
- }
2384
+ }, {
2385
+ errorMessage: "Failed to get active session key",
2386
+ errorCode: sdkTypes.TurnkeyErrorCodes.GET_ACTIVE_SESSION_KEY_ERROR,
2387
+ });
2218
2388
  };
2219
2389
  /**
2220
2390
  * Clears any unused API key pairs from persistent storage.
@@ -2228,7 +2398,7 @@ class TurnkeyClient {
2228
2398
  * @throws {TurnkeyError} If there is an error listing, checking, or deleting unused key pairs.
2229
2399
  */
2230
2400
  this.clearUnusedKeyPairs = async () => {
2231
- try {
2401
+ utils.withTurnkeyErrorHandling(async () => {
2232
2402
  const publicKeys = await this.apiKeyStamper?.listKeyPairs();
2233
2403
  if (!publicKeys || publicKeys.length === 0) {
2234
2404
  return;
@@ -2251,12 +2421,10 @@ class TurnkeyClient {
2251
2421
  }
2252
2422
  }
2253
2423
  }
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
- }
2424
+ }, {
2425
+ errorMessage: "Failed to clear unused key pairs",
2426
+ errorCode: sdkTypes.TurnkeyErrorCodes.CLEAR_UNUSED_KEY_PAIRS_ERROR,
2427
+ });
2260
2428
  };
2261
2429
  /**
2262
2430
  * Creates a new API key pair and returns the public key.
@@ -2273,23 +2441,21 @@ class TurnkeyClient {
2273
2441
  * @throws {TurnkeyError} If the API key stamper is not initialized or if there is an error during key pair creation or storage.
2274
2442
  */
2275
2443
  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 {
2444
+ return utils.withTurnkeyErrorHandling(async () => {
2445
+ const externalKeyPair = params?.externalKeyPair;
2446
+ const storeOverride = params?.storeOverride ?? false;
2447
+ if (!this.apiKeyStamper) {
2448
+ throw new sdkTypes.TurnkeyError("API Key Stamper is not initialized.", sdkTypes.TurnkeyErrorCodes.INTERNAL_ERROR);
2449
+ }
2282
2450
  const publicKey = await this.apiKeyStamper.createKeyPair(externalKeyPair ? externalKeyPair : undefined);
2283
2451
  if (storeOverride && publicKey) {
2284
2452
  await this.apiKeyStamper.setPublicKeyOverride(publicKey);
2285
2453
  }
2286
2454
  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
- }
2455
+ }, {
2456
+ errorMessage: "Failed to create API key pair",
2457
+ errorCode: sdkTypes.TurnkeyErrorCodes.CREATE_API_KEY_PAIR_ERROR,
2458
+ });
2293
2459
  };
2294
2460
  /**
2295
2461
  * Fetches the WalletKit proxy authentication configuration from the auth proxy.
@@ -2303,18 +2469,16 @@ class TurnkeyClient {
2303
2469
  * @throws {TurnkeyError} If there is an error retrieving the proxy authentication configuration from the auth proxy.
2304
2470
  */
2305
2471
  this.getProxyAuthConfig = async () => {
2306
- try {
2472
+ return utils.withTurnkeyErrorHandling(async () => {
2307
2473
  const res = await this.httpClient.proxyGetWalletKitConfig({});
2308
2474
  if (!res) {
2309
2475
  throw new sdkTypes.TurnkeyError(`Failed to fetch auth proxy config`, sdkTypes.TurnkeyErrorCodes.GET_PROXY_AUTH_CONFIG_ERROR);
2310
2476
  }
2311
2477
  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
- }
2478
+ }, {
2479
+ errorMessage: "Failed to get auth proxy config",
2480
+ errorCode: sdkTypes.TurnkeyErrorCodes.GET_PROXY_AUTH_CONFIG_ERROR,
2481
+ });
2318
2482
  };
2319
2483
  this.config = config;
2320
2484
  // Just store any explicitly provided stampers