@dynamic-labs-wallet/browser 0.0.0-preview.160.0 → 0.0.1-paolo-1

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 (71) hide show
  1. package/index.cjs.js +2035 -1056
  2. package/index.esm.js +2020 -1057
  3. package/internal/core/bip340.cjs +1 -0
  4. package/internal/core/common.cjs +1 -0
  5. package/internal/core/ecdsa.cjs +1 -0
  6. package/internal/core/ed25519.cjs +1 -0
  7. package/internal/core/ed25519_exportable.cjs +1 -0
  8. package/internal/core/index.cjs +1 -0
  9. package/internal/core/sr25519.cjs +1 -0
  10. package/internal/core/types.cjs +1 -0
  11. package/internal/web/generated/libmpc_executor.js +2 -2
  12. package/internal/web/index.d.ts +1 -1
  13. package/internal/web/index.js +1 -1
  14. package/package.json +21 -8
  15. package/src/backup/encryption/argon2.d.ts +10 -0
  16. package/src/backup/encryption/argon2.d.ts.map +1 -0
  17. package/src/backup/encryption/config.d.ts +39 -0
  18. package/src/backup/encryption/config.d.ts.map +1 -0
  19. package/src/backup/encryption/constants.d.ts +35 -0
  20. package/src/backup/encryption/constants.d.ts.map +1 -0
  21. package/src/backup/encryption/core.d.ts +27 -0
  22. package/src/backup/encryption/core.d.ts.map +1 -0
  23. package/src/backup/encryption/pbkdf2.d.ts +10 -0
  24. package/src/backup/encryption/pbkdf2.d.ts.map +1 -0
  25. package/src/backup/encryption/types.d.ts +46 -0
  26. package/src/backup/encryption/types.d.ts.map +1 -0
  27. package/src/backup/encryption/utils.d.ts +9 -0
  28. package/src/backup/encryption/utils.d.ts.map +1 -0
  29. package/src/backup/utils.d.ts +0 -23
  30. package/src/backup/utils.d.ts.map +1 -1
  31. package/src/client.d.ts +203 -122
  32. package/src/client.d.ts.map +1 -1
  33. package/src/constants.d.ts +4 -1
  34. package/src/constants.d.ts.map +1 -1
  35. package/src/errorConstants.d.ts +10 -0
  36. package/src/errorConstants.d.ts.map +1 -0
  37. package/src/index.d.ts +7 -4
  38. package/src/index.d.ts.map +1 -1
  39. package/src/mpc/index.d.ts +3 -3
  40. package/src/mpc/index.d.ts.map +1 -1
  41. package/src/mpc/mpc.d.ts +3 -3
  42. package/src/mpc/mpc.d.ts.map +1 -1
  43. package/src/mpc/types.d.ts +4 -4
  44. package/src/mpc/types.d.ts.map +1 -1
  45. package/src/services/axiosErrorResponse.d.ts +4 -0
  46. package/src/services/axiosErrorResponse.d.ts.map +1 -0
  47. package/src/services/encryption.d.ts +19 -0
  48. package/src/services/encryption.d.ts.map +1 -0
  49. package/src/services/logger.d.ts +13 -0
  50. package/src/services/logger.d.ts.map +1 -1
  51. package/src/types.d.ts +30 -4
  52. package/src/types.d.ts.map +1 -1
  53. package/src/utils.d.ts +12 -16
  54. package/src/utils.d.ts.map +1 -1
  55. package/internal/core/bip340.js +0 -1
  56. package/internal/core/common.js +0 -1
  57. package/internal/core/ecdsa.js +0 -1
  58. package/internal/core/ed25519.js +0 -1
  59. package/internal/core/ed25519_exportable.js +0 -1
  60. package/internal/core/index.js +0 -1
  61. package/internal/core/sr25519.js +0 -1
  62. package/internal/core/types.js +0 -1
  63. package/src/backup/encryption.d.ts +0 -22
  64. package/src/backup/encryption.d.ts.map +0 -1
  65. package/src/services/iframeDisplay.d.ts +0 -9
  66. package/src/services/iframeDisplay.d.ts.map +0 -1
  67. package/src/services/iframeLocalStorage.d.ts +0 -13
  68. package/src/services/iframeLocalStorage.d.ts.map +0 -1
  69. package/src/services/messageTransportBridge.d.ts +0 -3
  70. package/src/services/messageTransportBridge.d.ts.map +0 -1
  71. /package/internal/core/{native.js → native.cjs} +0 -0
package/index.cjs.js CHANGED
@@ -1,10 +1,14 @@
1
1
  'use strict';
2
2
 
3
3
  var core = require('@dynamic-labs-wallet/core');
4
- var web = require('./internal/web');
5
- var sdkApiCore = require('@dynamic-labs/sdk-api-core');
4
+ var web = require('#internal/web');
5
+ var semver = require('semver');
6
+ var uuid = require('uuid');
6
7
  var logger$1 = require('@dynamic-labs/logger');
7
- var messageTransport = require('@dynamic-labs/message-transport');
8
+ var loadArgon2idWasm = require('argon2id');
9
+ var axios = require('axios');
10
+ var createHttpError = require('http-errors');
11
+ var sdkApiCore = require('@dynamic-labs/sdk-api-core');
8
12
 
9
13
  function _extends() {
10
14
  _extends = Object.assign || function assign(target) {
@@ -22,7 +26,7 @@ const getMPCSignatureScheme = ({ signingAlgorithm, baseRelayUrl = core.MPC_RELAY
22
26
  case core.SigningAlgorithm.ECDSA:
23
27
  return new web.Ecdsa(baseRelayUrl);
24
28
  case core.SigningAlgorithm.ED25519:
25
- return new web.Ed25519(baseRelayUrl);
29
+ return new web.ExportableEd25519(baseRelayUrl);
26
30
  case core.SigningAlgorithm.BIP340:
27
31
  return new web.BIP340(baseRelayUrl);
28
32
  default:
@@ -38,13 +42,118 @@ const getMPCSigner = ({ chainName, baseRelayUrl })=>{
38
42
  return signatureScheme;
39
43
  };
40
44
 
41
- const DEFAULT_LOG_LEVEL = 'INFO';
42
- const STORAGE_KEY = 'dynamic-waas-wallet-client';
43
- const CLIENT_KEYSHARE_EXPORT_FILENAME_PREFIX = 'dynamicWalletKeyShareBackup';
45
+ /**
46
+ * Encryption version identifiers
47
+ */ var EncryptionVersion = /*#__PURE__*/ function(EncryptionVersion) {
48
+ EncryptionVersion["V1_LEGACY"] = "v1";
49
+ EncryptionVersion["V2_PBKDF2"] = "v2";
50
+ EncryptionVersion["V3_ARGON2"] = "v3";
51
+ return EncryptionVersion;
52
+ }({});
53
+ /**
54
+ * Current default version for new encryptions
55
+ */ const ENCRYPTION_VERSION_CURRENT = "v3";
56
+ /**
57
+ * Algorithm constants
58
+ */ const PBKDF2_ALGORITHM = 'PBKDF2';
59
+ const HASH_ALGORITHM = 'SHA-256'; // Generic hash algorithm constant
60
+ const ARGON2_ALGORITHM = 'Argon2id';
61
+ const AES_GCM_ALGORITHM = 'AES-GCM';
62
+ const AES_GCM_LENGTH = 256;
63
+ /**
64
+ * Argon2 configuration constants, values were chosen based on RFC (https://www.rfc-editor.org/rfc/rfc9106.html#name-parameter-choice)
65
+ * taking into account that this runs in the client, possibly in smartphones with limited resources
66
+ */ const ARGON2_MEMORY_SIZE = 65536; // 64 MB in KiB
67
+ const ARGON2_ITERATIONS = 3;
68
+ const ARGON2_PARALLELISM = 2;
69
+ const ARGON2_HASH_LENGTH = 32;
70
+ /**
71
+ * PBKDF2 configuration constants
72
+ */ const PBKDF2_ITERATIONS_V1 = 100000;
73
+ const PBKDF2_ITERATIONS_V2 = 1000000;
74
+
75
+ /**
76
+ * Derives a key using Argon2id algorithm
77
+ * @param params - Key derivation parameters
78
+ * @param encryptionConfig - Encryption configuration
79
+ * @returns Promise<CryptoKey>
80
+ */ const deriveArgon2Key = async ({ password, salt }, encryptionConfig)=>{
81
+ const argon2id = await loadArgon2idWasm();
82
+ const argon2Config = encryptionConfig;
83
+ const passwordBytes = new TextEncoder().encode(password);
84
+ const hash = argon2id({
85
+ password: passwordBytes,
86
+ salt: salt,
87
+ parallelism: argon2Config.parallelism || ARGON2_PARALLELISM,
88
+ passes: argon2Config.iterations,
89
+ memorySize: argon2Config.memorySize || ARGON2_MEMORY_SIZE,
90
+ tagLength: argon2Config.hashLength || ARGON2_HASH_LENGTH
91
+ });
92
+ return crypto.subtle.importKey('raw', new Uint8Array(hash), {
93
+ name: encryptionConfig.algorithm,
94
+ length: encryptionConfig.algorithmLength
95
+ }, false, [
96
+ 'encrypt',
97
+ 'decrypt'
98
+ ]);
99
+ };
44
100
 
45
- const logger = new logger$1.Logger('DynamicWaasWalletClient');
101
+ /**
102
+ * Encryption configuration for each version
103
+ */ const ENCRYPTION_VERSIONS = {
104
+ [EncryptionVersion.V1_LEGACY]: {
105
+ version: EncryptionVersion.V1_LEGACY,
106
+ algorithm: AES_GCM_ALGORITHM,
107
+ keyDerivation: PBKDF2_ALGORITHM,
108
+ iterations: PBKDF2_ITERATIONS_V1,
109
+ hashAlgorithm: HASH_ALGORITHM,
110
+ algorithmLength: AES_GCM_LENGTH
111
+ },
112
+ [EncryptionVersion.V2_PBKDF2]: {
113
+ version: EncryptionVersion.V2_PBKDF2,
114
+ algorithm: AES_GCM_ALGORITHM,
115
+ keyDerivation: PBKDF2_ALGORITHM,
116
+ iterations: PBKDF2_ITERATIONS_V2,
117
+ hashAlgorithm: HASH_ALGORITHM,
118
+ algorithmLength: AES_GCM_LENGTH
119
+ },
120
+ [EncryptionVersion.V3_ARGON2]: {
121
+ version: EncryptionVersion.V3_ARGON2,
122
+ algorithm: AES_GCM_ALGORITHM,
123
+ keyDerivation: ARGON2_ALGORITHM,
124
+ iterations: ARGON2_ITERATIONS,
125
+ hashAlgorithm: ARGON2_ALGORITHM,
126
+ algorithmLength: AES_GCM_LENGTH,
127
+ memorySize: ARGON2_MEMORY_SIZE,
128
+ parallelism: ARGON2_PARALLELISM,
129
+ hashLength: ARGON2_HASH_LENGTH
130
+ }
131
+ };
132
+ /**
133
+ * Helper function to get encryption configuration by version string
134
+ * @param version - The version string (e.g., 'v1', 'v2', 'v3')
135
+ * @returns The encryption configuration for the specified version
136
+ */ const getEncryptionConfig = (version)=>{
137
+ // If no version specified, use legacy for backward compatibility
138
+ if (!version) {
139
+ return ENCRYPTION_VERSIONS[EncryptionVersion.V1_LEGACY];
140
+ }
141
+ const config = ENCRYPTION_VERSIONS[version];
142
+ if (!config) {
143
+ throw new Error(`Unsupported encryption version: ${version}`);
144
+ }
145
+ return config;
146
+ };
147
+ /**
148
+ * Check if a configuration uses Argon2
149
+ */ const isArgon2Config = (config)=>{
150
+ return config.keyDerivation === ARGON2_ALGORITHM;
151
+ };
46
152
 
47
- const bytesToBase64 = (arr)=>{
153
+ /**
154
+ * Utility functions for encryption operations
155
+ * These functions are separated to avoid circular dependencies
156
+ */ const bytesToBase64 = (arr)=>{
48
157
  return btoa(Array.from(arr, (b)=>String.fromCharCode(b)).join(''));
49
158
  };
50
159
  const stringToBytes = (str)=>{
@@ -57,149 +166,13 @@ const base64ToBytes = (base64)=>{
57
166
  const ensureBase64Padding = (str)=>{
58
167
  return str.padEnd(Math.ceil(str.length / 4) * 4, '=');
59
168
  };
60
- const isBrowser = ()=>typeof window !== 'undefined';
61
- const isHexString = (str)=>{
62
- // Remove 0x prefix if present
63
- const hex = str.startsWith('0x') ? str.slice(2) : str;
64
- // Check if string contains only hex characters
65
- return /^[0-9A-Fa-f]+$/.test(hex);
66
- };
67
- const getClientKeyShareExportFileName = ({ thresholdSignatureScheme, accountAddress })=>{
68
- return `${CLIENT_KEYSHARE_EXPORT_FILENAME_PREFIX}-${thresholdSignatureScheme}-${accountAddress}.json`;
69
- };
70
- const getClientKeyShareBackupInfo = (params)=>{
71
- var _params_walletProperties, _params_walletProperties_keyShares_;
72
- const backups = {
73
- [core.BackupLocation.DYNAMIC]: [],
74
- [core.BackupLocation.GOOGLE_DRIVE]: [],
75
- [core.BackupLocation.ICLOUD]: [],
76
- [core.BackupLocation.USER]: [],
77
- [core.BackupLocation.EXTERNAL]: []
78
- };
79
- if (!(params == null ? void 0 : (_params_walletProperties = params.walletProperties) == null ? void 0 : _params_walletProperties.keyShares)) {
80
- return {
81
- backups,
82
- passwordEncrypted: false
83
- };
84
- }
85
- params.walletProperties.keyShares.forEach((keyShare)=>{
86
- if (backups[keyShare.backupLocation]) {
87
- backups[keyShare.backupLocation].push(keyShare.id);
88
- }
89
- });
90
- const passwordEncrypted = Boolean((_params_walletProperties_keyShares_ = params.walletProperties.keyShares[0]) == null ? void 0 : _params_walletProperties_keyShares_.passwordEncrypted);
91
- return {
92
- backups,
93
- passwordEncrypted
94
- };
95
- };
96
- /**
97
- * Helper function to merge keyshares and remove duplicates based on pubkey and secretShare
98
- * @param existingKeyShares - Array of existing keyshares
99
- * @param newKeyShares - Array of new keyshares to merge
100
- * @returns Array of merged unique keyshares
101
- */ const mergeUniqueKeyShares = (existingKeyShares, newKeyShares)=>{
102
- const uniqueKeyShares = newKeyShares.filter((newShare)=>!existingKeyShares.some((existingShare)=>{
103
- if (!(newShare == null ? void 0 : newShare.pubkey) || !(existingShare == null ? void 0 : existingShare.pubkey)) return false;
104
- return newShare.pubkey.toString() === existingShare.pubkey.toString() && newShare.secretShare === existingShare.secretShare;
105
- }));
106
- return [
107
- ...existingKeyShares,
108
- ...uniqueKeyShares
109
- ];
110
- };
111
- const timeoutPromise = ({ timeInMs, activity = 'Ceremony' })=>{
112
- return new Promise((_, reject)=>setTimeout(()=>reject(new Error(`${activity} did not complete in ${timeInMs}ms`)), timeInMs));
113
- };
114
- /**
115
- * Generic helper function to retry a promise-based operations
116
- *
117
- * @param operation - The async operation to retry
118
- * @param config - Configuration options for retry behavior
119
- * @returns Promise with the operation result
120
- * @throws Last error encountered after all retries are exhausted
121
- */ async function retryPromise(operation, { maxAttempts = 5, retryInterval = 500, operationName = 'operation', logContext = {} } = {}) {
122
- let attempts = 0;
123
- while(attempts < maxAttempts){
124
- try {
125
- return await operation();
126
- } catch (error) {
127
- attempts++;
128
- if (attempts === maxAttempts) {
129
- logger.error(`Failed to execute ${operationName} after ${maxAttempts} attempts`, _extends({}, logContext, {
130
- error
131
- }));
132
- throw error;
133
- }
134
- // Calculate exponential backoff delay
135
- const exponentialDelay = retryInterval * 2 ** (attempts - 1);
136
- await new Promise((resolve)=>setTimeout(resolve, exponentialDelay));
137
- }
138
- }
139
- // TypeScript needs this even though it's unreachable
140
- throw new Error('Unreachable code');
141
- }
142
- const formatEvmMessage = (message)=>{
143
- if (typeof message === 'string' && message.startsWith('0x')) {
144
- const serializedTxBytes = Uint8Array.from(Buffer.from(message.slice(2), 'hex'));
145
- return web.MessageHash.keccak256(serializedTxBytes);
146
- }
147
- return web.MessageHash.keccak256(message);
148
- };
149
- const formatSolanaMessage = (message)=>{
150
- if (typeof message === 'string') {
151
- if (!isHexString(message)) {
152
- return Buffer.from(message).toString('hex');
153
- } else {
154
- return new Uint8Array(Buffer.from(message, 'hex'));
155
- }
156
- } else {
157
- return message;
158
- }
159
- };
160
- const formatMessage = (chainName, message)=>{
161
- switch(chainName){
162
- case 'EVM':
163
- return formatEvmMessage(message);
164
- case 'SOL':
165
- return formatSolanaMessage(message);
166
- case 'SUI':
167
- return message;
168
- default:
169
- throw new Error('Unsupported chain name');
170
- }
171
- };
172
- const getGoogleOAuthAccountId = (verifiedCredentials)=>{
173
- const googleVerifiedCredential = verifiedCredentials == null ? void 0 : verifiedCredentials.find((credential)=>credential.oauthProvider === sdkApiCore.ProviderEnum.Google);
174
- return googleVerifiedCredential == null ? void 0 : googleVerifiedCredential.id;
175
- };
176
- const createBackupData = ({ encryptedKeyShares, accountAddress, thresholdSignatureScheme, hasPassword = true })=>{
177
- return {
178
- keyShares: encryptedKeyShares,
179
- metadata: {
180
- version: '1.0',
181
- createdAt: new Date().toISOString(),
182
- accountAddress,
183
- thresholdSignatureScheme,
184
- hasPassword,
185
- encryption: {
186
- algorithm: AES_GCM_ALGORITHM,
187
- keyDerivation: PBKDF2_ALGORITHM,
188
- iterations: PBKDF2_ITERATIONS,
189
- hashAlgorithm: PBKDF2_HASH_ALGORITHM,
190
- algorithmLength: AES_GCM_LENGTH
191
- },
192
- shareCount: encryptedKeyShares.length
193
- }
194
- };
195
- };
196
169
 
197
- const PBKDF2_ALGORITHM = 'PBKDF2';
198
- const PBKDF2_ITERATIONS = 100000;
199
- const PBKDF2_HASH_ALGORITHM = 'SHA-256';
200
- const AES_GCM_ALGORITHM = 'AES-GCM';
201
- const AES_GCM_LENGTH = 256;
202
- const getKey = async ({ password, salt })=>{
170
+ /**
171
+ * Derives a key using PBKDF2 algorithm
172
+ * @param params - Key derivation parameters
173
+ * @param encryptionConfig - Encryption configuration
174
+ * @returns Promise<CryptoKey>
175
+ */ const derivePBKDF2Key = async ({ password, salt }, encryptionConfig)=>{
203
176
  const passwordBytes = stringToBytes(password);
204
177
  const initialKey = await crypto.subtle.importKey('raw', passwordBytes, {
205
178
  name: 'PBKDF2'
@@ -207,19 +180,34 @@ const getKey = async ({ password, salt })=>{
207
180
  'deriveKey'
208
181
  ]);
209
182
  return crypto.subtle.deriveKey({
210
- name: PBKDF2_ALGORITHM,
211
- salt,
212
- iterations: PBKDF2_ITERATIONS,
213
- hash: PBKDF2_HASH_ALGORITHM
183
+ name: encryptionConfig.keyDerivation,
184
+ salt: salt,
185
+ iterations: encryptionConfig.iterations,
186
+ hash: encryptionConfig.hashAlgorithm
214
187
  }, initialKey, {
215
- name: AES_GCM_ALGORITHM,
216
- length: AES_GCM_LENGTH
188
+ name: encryptionConfig.algorithm,
189
+ length: encryptionConfig.algorithmLength
217
190
  }, false, [
218
191
  'encrypt',
219
192
  'decrypt'
220
193
  ]);
221
194
  };
222
- const encryptData = async ({ data, password })=>{
195
+
196
+ /**
197
+ * Get the appropriate key derivation function based on the encryption config
198
+ */ const getKey = async (params, encryptionConfig)=>{
199
+ // Use Argon2 for v3, PBKDF2 for v1 and v2
200
+ if (encryptionConfig.keyDerivation === ARGON2_ALGORITHM) {
201
+ return deriveArgon2Key(params, encryptionConfig);
202
+ } else {
203
+ return derivePBKDF2Key(params, encryptionConfig);
204
+ }
205
+ };
206
+ /**
207
+ * Encrypts data using the specified encryption version.
208
+ * Always uses the latest encryption configuration for new encryptions by default.
209
+ */ const encryptData = async ({ data, password, version = ENCRYPTION_VERSION_CURRENT })=>{
210
+ const encryptionConfig = getEncryptionConfig(version);
223
211
  try {
224
212
  // Generate a random salt and IV
225
213
  const salt = crypto.getRandomValues(new Uint8Array(16));
@@ -227,7 +215,7 @@ const encryptData = async ({ data, password })=>{
227
215
  const key = await getKey({
228
216
  password,
229
217
  salt
230
- });
218
+ }, encryptionConfig);
231
219
  // Convert the input string to bytes
232
220
  const dataBytes = new TextEncoder().encode(data);
233
221
  // Encrypt the data
@@ -239,34 +227,86 @@ const encryptData = async ({ data, password })=>{
239
227
  return {
240
228
  salt: bytesToBase64(salt),
241
229
  iv: bytesToBase64(iv),
242
- cipher: bytesToBase64(new Uint8Array(encryptedData))
230
+ cipher: bytesToBase64(new Uint8Array(encryptedData)),
231
+ version
243
232
  };
244
233
  } catch (error) {
245
- throw new Error('Error encrypting data');
234
+ const errorMessage = error instanceof Error ? error.message : String(error);
235
+ throw new Error(`Error encrypting data: ${errorMessage} (version: ${version})`);
246
236
  }
247
237
  };
248
- const decryptData = async ({ data, password })=>{
238
+ /**
239
+ * Decrypts data with version-based configuration.
240
+ * Uses the version field from the data to determine encryption parameters.
241
+ * Falls back to legacy version for backward compatibility if no version is specified.
242
+ * For v3 (Argon2), retries with parallelism=1 if an OperationError occurs.
243
+ */ const decryptData = async ({ data, password })=>{
244
+ const { salt, iv, cipher, version } = data;
245
+ // Ensure proper base64 padding for all values
246
+ const paddedSalt = ensureBase64Padding(salt);
247
+ const paddedIv = ensureBase64Padding(iv);
248
+ const paddedCipher = ensureBase64Padding(cipher);
249
+ const saltBytes = base64ToBytes(paddedSalt);
250
+ const ivBytes = base64ToBytes(paddedIv);
251
+ const cipherBytes = base64ToBytes(paddedCipher);
252
+ // Determine which encryption configuration to use
253
+ const encryptionConfig = getEncryptionConfig(version);
249
254
  try {
250
- const { salt, iv, cipher } = data;
251
- // Ensure proper base64 padding for all values
252
- const paddedSalt = ensureBase64Padding(salt);
253
- const paddedIv = ensureBase64Padding(iv);
254
- const paddedCipher = ensureBase64Padding(cipher);
255
- const saltBytes = base64ToBytes(paddedSalt);
256
- const ivBytes = base64ToBytes(paddedIv);
257
- const cipherBytes = base64ToBytes(paddedCipher);
258
255
  const key = await getKey({
259
256
  password,
260
257
  salt: saltBytes
261
- });
258
+ }, encryptionConfig);
262
259
  const decryptedData = await crypto.subtle.decrypt({
263
260
  name: AES_GCM_ALGORITHM,
264
261
  iv: ivBytes
265
262
  }, key, cipherBytes);
266
263
  return new TextDecoder().decode(decryptedData);
267
264
  } catch (error) {
268
- throw new Error('Decryption failed');
265
+ // For a short period of time we lowered the parallelism for v3 (Argon2) to 1 to try to fix issues
266
+ // for users with limited resources, however this introduced a new issue that the decryption would fail
267
+ // for existing users with v3 (Argon2) encryption, this is a fallback for a few users.
268
+ if (error instanceof Error && error.name === 'OperationError' && version === 'v3' && isArgon2Config(encryptionConfig)) {
269
+ try {
270
+ // Create a modified config with parallelism=1
271
+ const modifiedConfig = _extends({}, encryptionConfig, {
272
+ parallelism: 1
273
+ });
274
+ const key = await getKey({
275
+ password,
276
+ salt: saltBytes
277
+ }, modifiedConfig);
278
+ const decryptedData = await crypto.subtle.decrypt({
279
+ name: AES_GCM_ALGORITHM,
280
+ iv: ivBytes
281
+ }, key, cipherBytes);
282
+ return new TextDecoder().decode(decryptedData);
283
+ } catch (retryError) {
284
+ // If retry also fails, throw the original error with additional context
285
+ throw new Error(`Decryption failed after retry with parallelism=1: ${retryError}`);
286
+ }
287
+ }
288
+ throw new Error('Decryption failed: ' + error);
289
+ }
290
+ };
291
+ /**
292
+ * Gets encryption metadata for a specific version.
293
+ * Used when we need to include metadata in legacy systems or APIs that require it.
294
+ */ const getEncryptionMetadataForVersion = (version)=>{
295
+ const encryptionConfig = getEncryptionConfig(version);
296
+ const metadata = {
297
+ algorithm: encryptionConfig.algorithm,
298
+ keyDerivation: encryptionConfig.keyDerivation,
299
+ iterations: encryptionConfig.iterations,
300
+ hashAlgorithm: encryptionConfig.hashAlgorithm,
301
+ algorithmLength: encryptionConfig.algorithmLength
302
+ };
303
+ // Add Argon2-specific metadata if applicable
304
+ if (isArgon2Config(encryptionConfig)) {
305
+ metadata.memorySize = encryptionConfig.memorySize;
306
+ metadata.parallelism = encryptionConfig.parallelism;
307
+ metadata.hashLength = encryptionConfig.hashLength;
269
308
  }
309
+ return metadata;
270
310
  };
271
311
 
272
312
  const GOOGLE_DRIVE_UPLOAD_API = 'https://www.googleapis.com';
@@ -365,172 +405,222 @@ const downloadFileFromGoogleDrive = async ({ accessToken, fileName })=>{
365
405
  }
366
406
  };
367
407
 
368
- const localStorageWriteTest = {
369
- tested: false,
370
- writable: false
371
- };
372
- /**
373
- * Checks whether localStorage is supported on this browser.
374
- */ const supportsLocalStorage = ()=>{
375
- if (!isBrowser()) {
376
- return false;
377
- }
378
- try {
379
- if (typeof globalThis.localStorage !== 'object') {
380
- return false;
381
- }
382
- } catch (e) {
383
- // DOM exception when accessing `localStorage`
384
- return false;
385
- }
386
- if (localStorageWriteTest.tested) {
387
- return localStorageWriteTest.writable;
408
+ const handleAxiosError = (error, message, context)=>{
409
+ var _error_response, _error_response1, _error_response2;
410
+ logger.error('[DynamicWaasWalletClient] Axios error: ', {
411
+ message,
412
+ error: (_error_response = error.response) == null ? void 0 : _error_response.data,
413
+ status: (_error_response1 = error.response) == null ? void 0 : _error_response1.status,
414
+ context
415
+ });
416
+ switch((_error_response2 = error.response) == null ? void 0 : _error_response2.status){
417
+ case 400:
418
+ throw createHttpError(400, 'Invalid request');
419
+ case 401:
420
+ throw createHttpError(401, 'Authorization header or cookie is required');
421
+ case 403:
422
+ throw createHttpError(403, 'Forbidden');
423
+ case 422:
424
+ throw createHttpError(422, 'Unprocessable content');
425
+ case 500:
426
+ throw createHttpError(500, 'Internal server error');
427
+ default:
428
+ throw createHttpError(500, 'Internal server error');
388
429
  }
389
- const randomKey = `lswt-${Math.random()}${Math.random()}`;
430
+ };
431
+
432
+ const logger = new logger$1.Logger('DynamicWaasWalletClient', logger$1.LogLevel.DEBUG);
433
+ const setLoggerContext = ({ environmentId, authMode = core.AuthMode.HEADER, sessionId = undefined, userId = undefined })=>{
390
434
  try {
391
- globalThis.localStorage.setItem(randomKey, randomKey);
392
- globalThis.localStorage.removeItem(randomKey);
393
- localStorageWriteTest.tested = true;
394
- localStorageWriteTest.writable = true;
395
- } catch (e) {
396
- // localStorage can't be written to
397
- localStorageWriteTest.tested = true;
398
- localStorageWriteTest.writable = false;
435
+ logger$1.Logger.setEnvironmentId(environmentId);
436
+ logger$1.Logger.globalMetaData.set('sid', sessionId);
437
+ logger$1.Logger.globalMetaData.set('user_id', userId);
438
+ logger$1.Logger.globalMetaData.set('auth_mode', authMode);
439
+ } catch (error) {
440
+ logError({
441
+ message: '[DynamicWaasWalletClient] Error setting logger context',
442
+ error: error,
443
+ context: {}
444
+ });
399
445
  }
400
- return localStorageWriteTest.writable;
401
446
  };
402
- /**
403
- * Provides safe access to the globalThis.localStorage property.
404
- */ const localStorageAdapter = {
405
- getItem: (key)=>{
406
- if (!supportsLocalStorage()) {
407
- return null;
408
- }
409
- return globalThis.localStorage.getItem(key);
410
- },
411
- removeItem: (key)=>{
412
- if (!supportsLocalStorage()) {
413
- return;
414
- }
415
- globalThis.localStorage.removeItem(key);
416
- },
417
- setItem: (key, value)=>{
418
- if (!supportsLocalStorage()) {
419
- return;
420
- }
421
- globalThis.localStorage.setItem(key, value);
447
+ const logError = ({ message, error, context })=>{
448
+ if (error instanceof axios.AxiosError) {
449
+ handleAxiosError(error, message, context);
422
450
  }
423
- };
424
- /**
425
- * Returns a localStorage-like object that stores the key-value pairs in
426
- * memory.
427
- */ const memoryLocalStorageAdapter = (store = {})=>({
428
- getItem: (key)=>store[key] || null,
429
- removeItem: (key)=>{
430
- delete store[key];
431
- },
432
- setItem: (key, value)=>{
433
- store[key] = value;
434
- }
451
+ logger.error('[DynamicWaasWalletClient] Error in browser client', {
452
+ error: error instanceof Error ? error.message : String(error),
453
+ context
435
454
  });
455
+ };
436
456
 
437
- /**
438
- * StorageRequestChannelAdapter.getItem() sends a message within host domain
439
- * the bridge on host will capture this request and forwards it to the iframe via contentWindow.postMessage()
440
- */ class StorageRequestChannelAdapter {
441
- async getItem(key) {
442
- const item = await this.requestChannel.request('getItem', {
443
- source: 'localStorage',
444
- key
445
- });
446
- return item ? JSON.parse(item) : null;
447
- }
448
- async setItem(key, value) {
449
- const stringifiedValue = typeof value === 'object' ? JSON.stringify(value) : value;
450
- return this.requestChannel.request('setItem', {
451
- source: 'localStorage',
452
- key,
453
- data: stringifiedValue
454
- });
455
- }
456
- async removeItem(key) {
457
- return this.requestChannel.request('deleteItem', {
458
- source: 'localStorage',
459
- key
460
- });
461
- }
462
- constructor(messageTransport$1){
463
- this.requestChannel = messageTransport.createRequestChannel(messageTransport$1);
464
- }
465
- }
457
+ const DEFAULT_LOG_LEVEL = logger$1.LogLevel.DEBUG; //todo: change back to info when done debugging
458
+ const STORAGE_KEY = 'dynamic-waas-wallet-client';
459
+ const CLIENT_KEYSHARE_EXPORT_FILENAME_PREFIX = 'dynamicWalletKeyShareBackup';
460
+ const SIGNED_SESSION_ID_MIN_VERSION = '4.25.4';
461
+ // Namespace-specific version requirements
462
+ const SIGNED_SESSION_ID_MIN_VERSION_BY_NAMESPACE = {
463
+ WalletKit: '4.25.4',
464
+ ClientSDK: '0.1.0-alpha.0'
465
+ };
466
466
 
467
- const setupMessageTransportBridge = (messageTransport$1, iframe, iframeOrigin)=>{
468
- if (!(iframe == null ? void 0 : iframe.contentWindow)) {
469
- throw new Error('Iframe or contentWindow not available');
470
- }
471
- const logger = new logger$1.Logger('debug');
472
- messageTransport$1.on((message)=>{
473
- // Forward the message to webview via postMessage
474
- if (message.origin === 'host') {
475
- var _iframe_contentWindow;
476
- iframe == null ? void 0 : (_iframe_contentWindow = iframe.contentWindow) == null ? void 0 : _iframe_contentWindow.postMessage(message, iframeOrigin);
477
- }
478
- });
479
- const handleIncomingMessage = (message)=>{
480
- const { data } = message;
481
- if (!data) return;
482
- if ((data == null ? void 0 : data.origin) !== 'webview') {
483
- return;
484
- }
485
- if (typeof data !== 'object') {
486
- return;
467
+ const isBrowser = ()=>typeof window !== 'undefined';
468
+ const getClientKeyShareExportFileName = ({ thresholdSignatureScheme, accountAddress, isGoogleDrive = false })=>{
469
+ const suffix = isGoogleDrive ? '-google-drive' : '';
470
+ return `${CLIENT_KEYSHARE_EXPORT_FILENAME_PREFIX}-${thresholdSignatureScheme}-${accountAddress}${suffix}.json`;
471
+ };
472
+ const getClientKeyShareBackupInfo = (params)=>{
473
+ var _params_walletProperties, _params_walletProperties_keyShares_;
474
+ const backups = {
475
+ [core.BackupLocation.DYNAMIC]: [],
476
+ [core.BackupLocation.GOOGLE_DRIVE]: [],
477
+ [core.BackupLocation.ICLOUD]: [],
478
+ [core.BackupLocation.USER]: [],
479
+ [core.BackupLocation.EXTERNAL]: [],
480
+ [core.BackupLocation.DELEGATED]: []
481
+ };
482
+ if (!(params == null ? void 0 : (_params_walletProperties = params.walletProperties) == null ? void 0 : _params_walletProperties.keyShares)) {
483
+ return {
484
+ backups,
485
+ passwordEncrypted: false
486
+ };
487
+ }
488
+ params.walletProperties.keyShares.forEach((keyShare)=>{
489
+ if (backups[keyShare.backupLocation]) {
490
+ backups[keyShare.backupLocation].push({
491
+ location: keyShare.backupLocation,
492
+ keyShareId: keyShare.id,
493
+ externalKeyShareId: keyShare == null ? void 0 : keyShare.externalKeyShareId
494
+ });
487
495
  }
496
+ });
497
+ const passwordEncrypted = Boolean((_params_walletProperties_keyShares_ = params.walletProperties.keyShares[0]) == null ? void 0 : _params_walletProperties_keyShares_.passwordEncrypted);
498
+ return {
499
+ backups,
500
+ passwordEncrypted
501
+ };
502
+ };
503
+ /**
504
+ * Helper function to merge keyshares and remove duplicates based on pubkey and secretShare
505
+ * @param existingKeyShares - Array of existing keyshares
506
+ * @param newKeyShares - Array of new keyshares to merge
507
+ * @returns Array of merged unique keyshares
508
+ */ const mergeUniqueKeyShares = (existingKeyShares, newKeyShares)=>{
509
+ const uniqueKeyShares = newKeyShares.filter((newShare)=>!existingKeyShares.some((existingShare)=>{
510
+ if (!(newShare == null ? void 0 : newShare.pubkey) || !(existingShare == null ? void 0 : existingShare.pubkey)) return false;
511
+ return newShare.pubkey.toString() === existingShare.pubkey.toString() && newShare.secretShare === existingShare.secretShare;
512
+ }));
513
+ return [
514
+ ...existingKeyShares,
515
+ ...uniqueKeyShares
516
+ ];
517
+ };
518
+ const timeoutPromise = ({ timeInMs, activity = 'Ceremony' })=>{
519
+ return new Promise((_, reject)=>setTimeout(()=>reject(new Error(`${activity} did not complete in ${timeInMs}ms`)), timeInMs));
520
+ };
521
+ /**
522
+ * Generic helper function to retry a promise-based operations
523
+ *
524
+ * @param operation - The async operation to retry
525
+ * @param config - Configuration options for retry behavior
526
+ * @returns Promise with the operation result
527
+ * @throws Last error encountered after all retries are exhausted
528
+ */ async function retryPromise(operation, { maxAttempts = 5, retryInterval = 500, operationName = 'operation', logContext = {} } = {}) {
529
+ let attempts = 0;
530
+ while(attempts < maxAttempts){
488
531
  try {
489
- const message = messageTransport.parseMessageTransportData(data);
490
- messageTransport$1.emit(message);
532
+ return await operation();
491
533
  } catch (error) {
492
- if (!(error instanceof SyntaxError)) {
493
- logger.error('Error handling incoming message:', error);
534
+ var _error_response;
535
+ attempts++;
536
+ logger.warn(`Failed to execute ${operationName} on attempt ${attempts}`, _extends({}, logContext, {
537
+ error: error instanceof Error ? error.message : 'Unknown error',
538
+ axiosError: error instanceof axios.AxiosError ? (_error_response = error.response) == null ? void 0 : _error_response.data : undefined
539
+ }));
540
+ if (attempts === maxAttempts) {
541
+ var _error_response1;
542
+ logger.error(`Failed to execute ${operationName} after ${maxAttempts} attempts`, _extends({}, logContext, {
543
+ error: error instanceof Error ? error.message : 'Unknown error',
544
+ axiosError: error instanceof axios.AxiosError ? (_error_response1 = error.response) == null ? void 0 : _error_response1.data : undefined
545
+ }));
546
+ throw error;
494
547
  }
548
+ // Calculate exponential backoff delay
549
+ const exponentialDelay = retryInterval * 2 ** (attempts - 1);
550
+ await new Promise((resolve)=>setTimeout(resolve, exponentialDelay));
495
551
  }
496
- };
497
- /**
498
- * Handle incoming message from android client
499
- */ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
500
- // @ts-ignore
501
- document.addEventListener('message', handleIncomingMessage);
502
- /**
503
- * Handle incoming message from iOS client
504
- */ window.addEventListener('message', handleIncomingMessage);
505
- };
506
-
507
- class IframeDisplayChannelAdapter {
508
- async displayClientShares(clientKeyShares) {
509
- await this.requestChannel.request('displayClientShares', clientKeyShares);
510
552
  }
511
- async displayPrivateKey(privateKey) {
512
- await this.requestChannel.request('displayPrivateKey', privateKey);
553
+ // TypeScript needs this even though it's unreachable
554
+ throw new Error('Unreachable code');
555
+ }
556
+ const formatEvmMessage = (message)=>{
557
+ if (typeof message === 'string' && message.startsWith('0x')) {
558
+ const serializedTxBytes = Uint8Array.from(Buffer.from(message.slice(2), 'hex'));
559
+ return web.MessageHash.keccak256(serializedTxBytes);
560
+ }
561
+ return web.MessageHash.keccak256(message);
562
+ };
563
+ const isHexString = (str)=>{
564
+ // Remove 0x prefix if present
565
+ const hex = str.startsWith('0x') ? str.slice(2) : str;
566
+ // Check if string contains only hex characters
567
+ return /^[0-9A-Fa-f]+$/.test(hex);
568
+ };
569
+ const formatSolanaMessage = (message)=>{
570
+ if (typeof message === 'string') {
571
+ if (!isHexString(message)) {
572
+ return Buffer.from(message).toString('hex');
573
+ } else {
574
+ return new Uint8Array(Buffer.from(message, 'hex'));
575
+ }
576
+ } else {
577
+ return message;
513
578
  }
514
- constructor(messageTransport$1){
515
- this.requestChannel = messageTransport.createRequestChannel(messageTransport$1);
579
+ };
580
+ const formatMessage = (chainName, message)=>{
581
+ switch(chainName){
582
+ case 'EVM':
583
+ return formatEvmMessage(message);
584
+ case 'SVM':
585
+ return formatSolanaMessage(message);
586
+ case 'SUI':
587
+ return message;
588
+ default:
589
+ throw new Error('Unsupported chain name');
516
590
  }
517
- }
518
-
519
- /**
520
- * Updates the wallet map with backup information after successful backup to Google Drive
521
- * @param data - Response data containing key shares information
522
- * @param walletMap - The wallet map to update
523
- * @param accountAddress - The account address associated with the wallet
524
- * @param backupLocation - The location where the backup is stored
525
- * @param storage - Storage interface for persisting the updated wallet map
526
- * @param storageKey - Key used to store the wallet map
527
- * @returns The array of key share IDs that were backed up
528
- */ const updateWalletMapWithBackupInfo = async ({ data, walletMap, accountAddress, storage, storageKey })=>{
529
- const ids = data.keyShares.map((keyShare)=>keyShare.id);
530
- walletMap[accountAddress].clientKeySharesBackupInfo.backups[core.BackupLocation.GOOGLE_DRIVE] = ids;
531
- await storage.setItem(storageKey, JSON.stringify(walletMap));
532
- return ids;
533
591
  };
592
+ const getGoogleOAuthAccountId = (verifiedCredentials)=>{
593
+ const googleVerifiedCredential = verifiedCredentials == null ? void 0 : verifiedCredentials.find((credential)=>credential.oauthProvider === sdkApiCore.ProviderEnum.Google);
594
+ return googleVerifiedCredential == null ? void 0 : googleVerifiedCredential.id;
595
+ };
596
+ const createBackupData = ({ encryptedKeyShares, accountAddress, thresholdSignatureScheme, hasPassword = true })=>{
597
+ return {
598
+ keyShares: encryptedKeyShares,
599
+ metadata: {
600
+ createdAt: new Date().toISOString(),
601
+ accountAddress,
602
+ thresholdSignatureScheme,
603
+ hasPassword,
604
+ encryption: getEncryptionMetadataForVersion(ENCRYPTION_VERSION_CURRENT),
605
+ encryptionVersion: ENCRYPTION_VERSION_CURRENT,
606
+ shareCount: encryptedKeyShares.length
607
+ }
608
+ };
609
+ };
610
+ const downloadStringAsFile = ({ filename, content, mimeType = 'application/json' })=>{
611
+ const blob = new Blob([
612
+ content
613
+ ], {
614
+ type: mimeType
615
+ });
616
+ const url = URL.createObjectURL(blob);
617
+ const a = document.createElement('a');
618
+ a.href = url;
619
+ a.download = filename;
620
+ a.click();
621
+ URL.revokeObjectURL(url);
622
+ };
623
+
534
624
  /**
535
625
  * Uploads a backup to Google Drive App
536
626
  * @param accessToken - The access token for the Google Drive API
@@ -538,257 +628,357 @@ class IframeDisplayChannelAdapter {
538
628
  * @param backupData - The data to upload
539
629
  * @param accountAddress - The account address associated with the backup
540
630
  */ const uploadBackupToGoogleDrive = async ({ accessToken, fileName, backupData, accountAddress })=>{
541
- try {
542
- await retryPromise(()=>uploadFileToGoogleDriveAppStorage({
631
+ const uploadPromises = [
632
+ retryPromise(()=>uploadFileToGoogleDriveAppStorage({
543
633
  accessToken,
544
634
  fileName,
545
635
  jsonData: backupData
546
- }));
547
- } catch (error) {
548
- logger.error('Failed to upload keyshares to Google Drive App Storage', {
636
+ })),
637
+ retryPromise(()=>uploadFileToGoogleDrivePersonal({
638
+ accessToken,
639
+ fileName,
640
+ jsonData: backupData
641
+ }))
642
+ ];
643
+ const results = await Promise.allSettled(uploadPromises);
644
+ const errors = [];
645
+ // Check App Storage result
646
+ if (results[0].status === 'rejected') {
647
+ const error = results[0].reason;
648
+ logger.error('[DynamicWaasWalletClient] Failed to upload keyshares to Google Drive App Storage', {
549
649
  accountAddress,
550
650
  error
551
651
  });
552
- throw new Error(`Failed to backup keyshares to Google Drive App Storage: ${error instanceof Error ? error.message : String(error)}`);
652
+ errors.push(`Failed to backup keyshares to Google Drive App Storage: ${error instanceof Error ? error.message : String(error)}`);
553
653
  }
554
- try {
555
- await retryPromise(()=>uploadFileToGoogleDrivePersonal({
556
- accessToken,
557
- fileName,
558
- jsonData: backupData
559
- }));
560
- } catch (error) {
561
- logger.error('Failed to upload keyshares to Google Drive Personal', {
654
+ // Check Personal Drive result
655
+ if (results[1].status === 'rejected') {
656
+ const error = results[1].reason;
657
+ logger.error('[DynamicWaasWalletClient] Failed to upload keyshares to Google Drive Personal', {
562
658
  accountAddress,
563
659
  error
564
660
  });
565
- throw new Error(`Failed to backup keyshares to Google Drive Personal: ${error instanceof Error ? error.message : String(error)}`);
661
+ errors.push(`Failed to backup keyshares to Google Drive Personal: ${error instanceof Error ? error.message : String(error)}`);
662
+ }
663
+ // Throw if any uploads failed
664
+ if (errors.length > 0) {
665
+ throw new Error(`[DynamicWaasWalletClient] ${errors.join('; ')}`);
566
666
  }
567
667
  };
568
668
 
569
- class DynamicWalletClient {
570
- async initialize() {
571
- if (this.initializePromise) {
572
- return await this.initializePromise;
573
- }
574
- this.logger.debug('Initializing Dynamic Waas Wallet SDK');
575
- this.initializePromise = this._initialize();
576
- const result = await this.initializePromise;
577
- this.logger.debug('Dynamic Waas Wallet SDK initialized');
578
- return result;
669
+ const ALG_LABEL_RSA = 'HYBRID-RSA-AES-256';
670
+ /**
671
+ * Convert base64 to base64url encoding
672
+ */ const toBase64Url = (buffer)=>{
673
+ const base64 = Buffer.from(buffer).toString('base64');
674
+ return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
675
+ };
676
+ /**
677
+ * Convert ArrayBuffer to base64url
678
+ */ const arrayBufferToBase64Url = (buffer)=>{
679
+ return toBase64Url(buffer);
680
+ };
681
+ /**
682
+ * Import RSA public key from PEM format
683
+ */ const importRSAPublicKey = async (publicKeyPem)=>{
684
+ // Remove PEM headers and decode base64
685
+ const pemHeader = '-----BEGIN PUBLIC KEY-----';
686
+ const pemFooter = '-----END PUBLIC KEY-----';
687
+ const pemContents = publicKeyPem.replace(pemHeader, '').replace(pemFooter, '').replace(/\s/g, '');
688
+ const binaryDer = Buffer.from(pemContents, 'base64').toString('binary');
689
+ const keyData = new Uint8Array(binaryDer.length);
690
+ for(let i = 0; i < binaryDer.length; i++){
691
+ keyData[i] = binaryDer.charCodeAt(i);
692
+ }
693
+ return await crypto.subtle.importKey('spki', keyData, {
694
+ name: 'RSA-OAEP',
695
+ hash: 'SHA-256'
696
+ }, false, [
697
+ 'encrypt'
698
+ ]);
699
+ };
700
+ // encodedEnvelopeBytes intentionally omitted; alg/ct/ek/iv/tag/kid is sufficient
701
+ /**
702
+ * Encrypts data using HYBRID-RSA-AES-256 encryption scheme with Web Crypto API.
703
+ * 1. Generate random AES-256 key
704
+ * 2. Encrypt AES key with RSA public key
705
+ * 3. Encrypt data with AES-256-GCM
706
+ */ const encryptDelegatedKeyShare = async (data, publicKeyPem, keyId)=>{
707
+ try {
708
+ // Step 1: Generate a random AES-256 key and 16-byte IV
709
+ const aesKey = await crypto.subtle.generateKey({
710
+ name: 'AES-GCM',
711
+ length: 256
712
+ }, true, [
713
+ 'encrypt'
714
+ ]);
715
+ const iv = crypto.getRandomValues(new Uint8Array(16)); // 128-bit IV for GCM
716
+ // Step 2: Encrypt the data with AES-256-GCM
717
+ const plaintext = new TextEncoder().encode(data);
718
+ const encryptedData = await crypto.subtle.encrypt({
719
+ name: 'AES-GCM',
720
+ iv: iv
721
+ }, aesKey, plaintext);
722
+ // Extract the auth tag from the encrypted data (last 16 bytes)
723
+ const encryptedDataArray = new Uint8Array(encryptedData);
724
+ const authTag = encryptedDataArray.slice(-16);
725
+ const ciphertext = encryptedDataArray.slice(0, -16);
726
+ // Step 3: Encrypt the AES key with RSA public key
727
+ const rsaPublicKey = await importRSAPublicKey(publicKeyPem);
728
+ // Export the AES key to encrypt it
729
+ const aesKeyData = await crypto.subtle.exportKey('raw', aesKey);
730
+ const encryptedAesKey = await crypto.subtle.encrypt({
731
+ name: 'RSA-OAEP'
732
+ }, rsaPublicKey, aesKeyData);
733
+ return _extends({
734
+ alg: ALG_LABEL_RSA,
735
+ iv: arrayBufferToBase64Url(iv.buffer),
736
+ ct: arrayBufferToBase64Url(ciphertext.buffer),
737
+ tag: arrayBufferToBase64Url(authTag.buffer),
738
+ ek: arrayBufferToBase64Url(encryptedAesKey)
739
+ }, keyId ? {
740
+ kid: keyId
741
+ } : {});
742
+ } catch (error) {
743
+ throw new Error(`Encryption failed: ${error instanceof Error ? error.message : String(error)}`);
579
744
  }
580
- /**
581
- * Initializes the iframe display for a specific container.
582
- *
583
- * @param {HTMLElement} container - The container to which the iframe will be attached.
584
- * @returns {Promise<{
585
- * iframe: HTMLIFrameElement;
586
- * iframeDisplay: IframeDisplayChannelAdapter;
587
- * cleanup: () => void;
588
- * }>} A promise that resolves when the iframe is loaded.
589
- */ async initializeIframeDisplayForContainer({ container }) {
590
- try {
591
- const iframe = await this.loadIframeForContainer(container);
592
- const transport = messageTransport.applyDefaultMessageOrigin({
593
- defaultOrigin: 'host',
594
- messageTransport: messageTransport.createMessageTransport()
595
- });
596
- setupMessageTransportBridge(transport, iframe, this.iframeDomain);
597
- const iframeDisplay = new IframeDisplayChannelAdapter(transport);
598
- return {
599
- iframe,
600
- iframeDisplay,
601
- cleanup: ()=>{
602
- container.removeChild(iframe);
603
- }
604
- };
605
- } catch (error) {
606
- this.logger.error('Error initializing iframe:', error);
607
- throw error;
745
+ };
746
+
747
+ const localStorageWriteTest = {
748
+ tested: false,
749
+ writable: false
750
+ };
751
+ /**
752
+ * Checks whether localStorage is supported on this browser.
753
+ */ const supportsLocalStorage = ()=>{
754
+ if (!isBrowser()) {
755
+ return false;
756
+ }
757
+ try {
758
+ if (typeof globalThis.localStorage !== 'object') {
759
+ return false;
608
760
  }
761
+ } catch (e) {
762
+ // DOM exception when accessing `localStorage`
763
+ return false;
609
764
  }
610
- /**
611
- * this is called on class construction time
612
- * @returns {Promise<void>} that resolves when the iframe is loaded and the message transport and iframe storage are initialized
613
- */ initializeIframeCommunication() {
614
- if (!this.iframeLoadPromise) {
615
- this.iframeLoadPromise = this.doInitializeIframeCommunication();
765
+ if (localStorageWriteTest.tested) {
766
+ return localStorageWriteTest.writable;
767
+ }
768
+ const randomKey = `lswt-${Math.random()}${Math.random()}`;
769
+ try {
770
+ globalThis.localStorage.setItem(randomKey, randomKey);
771
+ globalThis.localStorage.removeItem(randomKey);
772
+ localStorageWriteTest.tested = true;
773
+ localStorageWriteTest.writable = true;
774
+ } catch (e) {
775
+ // localStorage can't be written to
776
+ localStorageWriteTest.tested = true;
777
+ localStorageWriteTest.writable = false;
778
+ }
779
+ return localStorageWriteTest.writable;
780
+ };
781
+ /**
782
+ * Provides safe access to the globalThis.localStorage property.
783
+ */ const localStorageAdapter = {
784
+ getItem: (key)=>{
785
+ if (!supportsLocalStorage()) {
786
+ return null;
787
+ }
788
+ return globalThis.localStorage.getItem(key);
789
+ },
790
+ removeItem: (key)=>{
791
+ if (!supportsLocalStorage()) {
792
+ return;
616
793
  }
617
- return this.iframeLoadPromise;
794
+ globalThis.localStorage.removeItem(key);
795
+ },
796
+ setItem: (key, value)=>{
797
+ if (!supportsLocalStorage()) {
798
+ return;
799
+ }
800
+ globalThis.localStorage.setItem(key, value);
618
801
  }
619
- /**
620
- * initialize the iframe communication by awaiting the iframe load promise
621
- * and initializing the message transport and iframe storage after iframe is successfully loaded
622
- */ async doInitializeIframeCommunication() {
802
+ };
803
+ /**
804
+ * Returns a localStorage-like object that stores the key-value pairs in
805
+ * memory.
806
+ */ const memoryLocalStorageAdapter = (store = {})=>({
807
+ getItem: (key)=>store[key] || null,
808
+ removeItem: (key)=>{
809
+ delete store[key];
810
+ },
811
+ setItem: (key, value)=>{
812
+ store[key] = value;
813
+ }
814
+ });
815
+
816
+ const createDelegationWithGoogleDriveDistribution = ({ existingShares, delegatedShare })=>({
817
+ dynamicBackendShares: existingShares,
818
+ googleDriveShares: existingShares,
819
+ delegatedShare
820
+ });
821
+ const createDelegationOnlyDistribution = ({ existingShares, delegatedShare })=>({
822
+ dynamicBackendShares: existingShares,
823
+ googleDriveShares: [],
824
+ delegatedShare
825
+ });
826
+ const createGoogleDriveOnlyDistribution = ({ allShares })=>({
827
+ dynamicBackendShares: allShares.slice(0, -1),
828
+ googleDriveShares: allShares.slice(-1)
829
+ });
830
+ const createDynamicOnlyDistribution = ({ allShares })=>({
831
+ dynamicBackendShares: allShares,
832
+ googleDriveShares: []
833
+ });
834
+ const hasGoogleDriveBackup = (backupInfo)=>{
835
+ var _backupInfo_backups_BackupLocation_GOOGLE_DRIVE, _backupInfo_backups;
836
+ var _backupInfo_backups_BackupLocation_GOOGLE_DRIVE_length;
837
+ return ((_backupInfo_backups_BackupLocation_GOOGLE_DRIVE_length = backupInfo == null ? void 0 : (_backupInfo_backups = backupInfo.backups) == null ? void 0 : (_backupInfo_backups_BackupLocation_GOOGLE_DRIVE = _backupInfo_backups[core.BackupLocation.GOOGLE_DRIVE]) == null ? void 0 : _backupInfo_backups_BackupLocation_GOOGLE_DRIVE.length) != null ? _backupInfo_backups_BackupLocation_GOOGLE_DRIVE_length : 0) > 0;
838
+ };
839
+ const hasDelegatedBackup = (backupInfo)=>{
840
+ var _backupInfo_backups_BackupLocation_DELEGATED, _backupInfo_backups;
841
+ var _backupInfo_backups_BackupLocation_DELEGATED_length;
842
+ return ((_backupInfo_backups_BackupLocation_DELEGATED_length = backupInfo == null ? void 0 : (_backupInfo_backups = backupInfo.backups) == null ? void 0 : (_backupInfo_backups_BackupLocation_DELEGATED = _backupInfo_backups[core.BackupLocation.DELEGATED]) == null ? void 0 : _backupInfo_backups_BackupLocation_DELEGATED.length) != null ? _backupInfo_backups_BackupLocation_DELEGATED_length : 0) > 0;
843
+ };
844
+ /**
845
+ * Distribution for adding Google Drive backup to an existing delegation.
846
+ * Client's shares go to both Dynamic and Google Drive.
847
+ * delegatedShare is undefined - we don't re-publish, but preserve the location.
848
+ */ const createAddGoogleDriveToExistingDelegationDistribution = ({ clientShares })=>({
849
+ dynamicBackendShares: clientShares,
850
+ googleDriveShares: clientShares
851
+ });
852
+
853
+ class DynamicWalletClient {
854
+ async initializeForwardMPCClient() {
623
855
  try {
624
- await this.loadIframe();
625
- this.initializeMessageTransport();
626
- this.initializeIframeStorage();
856
+ await this.apiClient.forwardMPCClient.connect();
857
+ this.logger.info('Connected to ForwardMPC enclave websocket. Instance: ' + this.instanceId);
858
+ try {
859
+ await this.apiClient.forwardMPCClient.handshake();
860
+ this.logger.debug('Handshaked with ForwardMPC enclave websocket. Instance: ' + this.instanceId);
861
+ } catch (error) {
862
+ this.logger.error('Error handshaking with ForwardMPC enclave websocket. Instance: ' + this.instanceId, error);
863
+ }
627
864
  } catch (error) {
628
- this.logger.error('Error initializing iframe:', error);
629
- throw error;
865
+ this.logger.error('Error connecting to ForwardMPC enclave websocket. Instance: ' + this.instanceId, {
866
+ error,
867
+ environmentId: this.environmentId
868
+ });
630
869
  }
631
870
  }
632
- /**
633
- * create a promise to load an iframe
634
- * @returns {Promise<void>} that resolves when the iframe is loaded
635
- */ loadIframe() {
636
- return new Promise((resolve, reject)=>{
637
- const iframe = document.createElement('iframe');
638
- const iframeTimeoutId = setTimeout(()=>{
639
- reject(new Error('Iframe load timeout'));
640
- }, 10000);
641
- iframe.style.display = 'none';
642
- iframe.setAttribute('title', 'Dynamic Wallet Iframe');
643
- iframe.setAttribute('referrerpolicy', 'origin');
644
- iframe.style.position = 'fixed';
645
- iframe.style.top = '0';
646
- iframe.style.left = '0';
647
- iframe.style.width = '0';
648
- iframe.style.height = '0';
649
- iframe.style.border = 'none';
650
- iframe.style.pointerEvents = 'none';
651
- const params = new URLSearchParams({
652
- instanceId: this.instanceId,
653
- hostOrigin: window.location.origin
654
- });
655
- iframe.src = `${this.iframeDomain}/waas/${this.environmentId}?${params.toString()}`;
656
- this.logger.debug('Creating iframe with src:', iframe.src);
657
- document.body.appendChild(iframe);
658
- iframe.onload = ()=>{
659
- clearTimeout(iframeTimeoutId);
660
- this.logger.debug('Iframe loaded successfully');
661
- this.iframe = iframe;
662
- resolve();
663
- };
664
- iframe.onerror = (error)=>{
665
- clearTimeout(iframeTimeoutId);
666
- this.logger.error('Iframe failed to load:', error);
667
- reject(new Error('Failed to load iframe'));
668
- };
669
- });
670
- }
671
- /**
672
- * Load an iframe for a specific container
673
- * @param {HTMLElement} container - The container to which the iframe will be attached
674
- * @returns {Promise<HTMLIFrameElement>} that resolves when the iframe is loaded
675
- */ loadIframeForContainer(container) {
676
- return new Promise((resolve, reject)=>{
677
- const iframe = document.createElement('iframe');
678
- const iframeTimeoutId = setTimeout(()=>{
679
- reject(new Error('Iframe load timeout'));
680
- }, 10000);
681
- iframe.style.display = 'block';
682
- iframe.style.width = '100%';
683
- iframe.style.height = '100%';
684
- iframe.setAttribute('title', 'Dynamic Wallet Storage');
685
- iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin');
686
- iframe.setAttribute('referrerpolicy', 'origin');
687
- const params = new URLSearchParams({
688
- instanceId: this.instanceId,
689
- hostOrigin: window.location.origin
690
- });
691
- iframe.src = `${this.iframeDomain}/waas/${this.environmentId}?${params.toString()}`;
692
- this.logger.debug('Creating iframe with src:', iframe.src);
693
- // Add iframe to the provided container
694
- container.appendChild(iframe);
695
- iframe.onload = ()=>{
696
- clearTimeout(iframeTimeoutId);
697
- this.logger.debug('Iframe loaded successfully');
698
- this.iframe = iframe;
699
- resolve(iframe);
700
- };
701
- iframe.onerror = (error)=>{
702
- clearTimeout(iframeTimeoutId);
703
- this.logger.error('Iframe failed to load:', error);
704
- reject(new Error('Failed to load iframe'));
705
- };
706
- });
871
+ getAuthMode() {
872
+ return this.authMode;
707
873
  }
708
874
  /**
709
- * initialize the message transport after iframe is successfully loaded
710
- */ initializeMessageTransport() {
711
- const transport = messageTransport.applyDefaultMessageOrigin({
712
- defaultOrigin: 'host',
713
- messageTransport: messageTransport.createMessageTransport()
714
- });
715
- this.messageTransport = transport;
716
- if (!this.iframe) {
717
- throw new Error('Iframe not available');
875
+ * Check if the SDK version meets the requirement for signed session ID
876
+ * Uses namespace-specific version requirements when available
877
+ * @returns boolean indicating if requireSignedSessionId should be set to true
878
+ */ requiresSignedSessionId() {
879
+ if (!this.sdkVersion) {
880
+ return false;
718
881
  }
719
- setupMessageTransportBridge(this.messageTransport, this.iframe, this.iframeDomain);
720
- }
721
- /**
722
- * initialize the iframe storage after iframe is successfully loaded
723
- */ initializeIframeStorage() {
724
- if (!this.messageTransport) {
725
- throw new Error('Message transport not initialized');
882
+ try {
883
+ const parsedVersion = core.parseNamespacedVersion(this.sdkVersion);
884
+ if (!parsedVersion) {
885
+ return false;
886
+ }
887
+ const { namespace, version } = parsedVersion;
888
+ // Check if we have a namespace-specific version requirement
889
+ const namespaceMinVersion = SIGNED_SESSION_ID_MIN_VERSION_BY_NAMESPACE[namespace];
890
+ if (namespaceMinVersion) {
891
+ return semver.gte(version, namespaceMinVersion);
892
+ }
893
+ // Fall back to default version requirement
894
+ return semver.gte(version, SIGNED_SESSION_ID_MIN_VERSION);
895
+ } catch (error) {
896
+ logger.warn(`[DynamicWaasWalletClient] Error checking if requiresSignedSessionId should be set to true for version ${this.sdkVersion}`, error);
897
+ return false;
726
898
  }
727
- this.iframeStorage = new StorageRequestChannelAdapter(this.messageTransport);
728
899
  }
729
- /**
730
- * Gets the initialized iframe instance. This method ensures the iframe is properly loaded and configured.
731
- * The first call will initialize and await the iframe loading process.
732
- * Subsequent calls will return the same iframe instance immediately.
733
- *
734
- * @throws {Error} If iframe initialization fails
735
- * @throws {Error} If message transport initialization fails
736
- * @throws {Error} If iframe storage initialization fails
737
- * @returns {Promise<HTMLIFrameElement>} The initialized iframe element
738
- */ async getIframe() {
739
- await this.initializeIframeCommunication();
740
- if (!this.iframe) {
741
- throw new Error('Failed to initialize iframe');
742
- }
743
- if (!this.messageTransport) {
744
- throw new Error('Failed to initialize message transport');
900
+ async initLoggerContext(authToken) {
901
+ // only decode jwt token in header auth mode
902
+ if (this.authMode === 'cookie') {
903
+ setLoggerContext({
904
+ environmentId: this.environmentId,
905
+ authMode: this.authMode
906
+ });
907
+ return;
745
908
  }
746
- if (!this.iframeStorage) {
747
- throw new Error('Failed to initialize iframe storage');
909
+ try {
910
+ // Split the JWT token into its parts (header.payload.signature)
911
+ const parts = authToken.split('.');
912
+ if (parts.length !== 3) {
913
+ logger.debug('[DynamicWaasWalletClient] Invalid JWT token when initializing logger context');
914
+ return;
915
+ }
916
+ // Decode the payload (second part)
917
+ const base64Payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
918
+ const jsonPayload = decodeURIComponent(Buffer.from(base64Payload, 'base64').toString('utf-8'));
919
+ const payload = JSON.parse(jsonPayload);
920
+ if (!payload || typeof payload !== 'object') {
921
+ logger.debug('[DynamicWaasWalletClient] Invalid JWT payload when initializing logger context');
922
+ return;
923
+ }
924
+ const userId = payload['sub'] || 'unknown';
925
+ const sessionId = payload['sid'] || 'unknown';
926
+ setLoggerContext({
927
+ environmentId: this.environmentId,
928
+ authMode: this.authMode,
929
+ sessionId,
930
+ userId
931
+ });
932
+ this.sessionId = sessionId;
933
+ } catch (error) {
934
+ logError({
935
+ message: 'Error initializing logger context',
936
+ error: error,
937
+ context: {}
938
+ });
939
+ throw error;
748
940
  }
749
- return this.iframe;
750
941
  }
751
- /**
752
- * Gets the initialized iframe storage instance. This method ensures the iframe storage is properly configured.
753
- * The first call will initialize and await the iframe communication process.
754
- * Subsequent calls will return the same storage instance immediately.
755
- *
756
- * @throws {Error} If iframe storage initialization fails
757
- * @returns {Promise<SupportedStorage>} The initialized iframe storage instance
758
- */ async getIframeStorage() {
759
- await this.initializeIframeCommunication();
760
- if (!this.iframeStorage) {
761
- throw new Error('Failed to initialize iframe storage');
942
+ async initialize(traceContext) {
943
+ if (this.initializePromise) {
944
+ return await this.initializePromise;
762
945
  }
763
- return this.iframeStorage;
946
+ this.logger.debug('[DynamicWaasWalletClient] Initializing Dynamic Waas Wallet SDK');
947
+ this.initializePromise = this._initialize(traceContext);
948
+ const result = await this.initializePromise;
949
+ this.logger.debug('[DynamicWaasWalletClient] Dynamic Waas Wallet SDK initialized');
950
+ return result;
764
951
  }
765
952
  /**
766
953
  * Client initialization logic
767
- */ async _initialize() {
954
+ */ async _initialize(traceContext) {
768
955
  try {
769
956
  const initializePromises = [
770
- this.restoreWallets(),
771
- this.initializeIframeCommunication()
957
+ this.restoreWallets()
772
958
  ];
773
959
  await Promise.all(initializePromises);
774
960
  return {
775
- error: null
961
+ error: null,
962
+ traceContext
776
963
  };
777
964
  } catch (error) {
778
965
  return {
779
- error
966
+ error,
967
+ traceContext
780
968
  };
781
969
  }
782
970
  }
783
- async serverInitializeKeyGen({ chainName, clientKeygenIds, thresholdSignatureScheme, onError, onCeremonyComplete }) {
971
+ async serverInitializeKeyGen({ chainName, clientKeygenIds, dynamicRequestId, thresholdSignatureScheme, onError, onCeremonyComplete }) {
784
972
  // Initialize keygen, create room, and create the wallet account on the server
785
973
  const data = await this.apiClient.createWalletAccount({
786
974
  chainName,
787
975
  clientKeygenIds,
976
+ dynamicRequestId,
788
977
  thresholdSignatureScheme,
789
978
  onError,
790
979
  onCeremonyComplete
791
980
  });
981
+ this.logger.debug(`[DynamicWaasWalletClient] Initialized client key generation with IDs: ${clientKeygenIds.join(', ')} for chain: ${chainName} using scheme: ${thresholdSignatureScheme}`);
792
982
  return data;
793
983
  }
794
984
  async clientInitializeKeyGen({ chainName, thresholdSignatureScheme }) {
@@ -809,8 +999,8 @@ class DynamicWalletClient {
809
999
  let publicKey;
810
1000
  if (mpcSigner instanceof web.Ecdsa) {
811
1001
  publicKey = await mpcSigner.derivePubkey(keyShare, derivationPath);
812
- } else if (mpcSigner instanceof web.Ed25519) {
813
- publicKey = await mpcSigner.derivePubkey(keyShare, derivationPath);
1002
+ } else if (mpcSigner instanceof web.ExportableEd25519) {
1003
+ publicKey = await mpcSigner.getPubkey(keyShare);
814
1004
  }
815
1005
  return publicKey;
816
1006
  }
@@ -831,7 +1021,13 @@ class DynamicWalletClient {
831
1021
  ...serverKeygenIds,
832
1022
  ...otherClientKeygenIds
833
1023
  ];
834
- return mpcSigner.keygen(roomId, mpcConfig.numberOfParties, mpcConfig.threshold, currentInit, allOtherKeygenIds);
1024
+ if (!(mpcSigner instanceof web.ExportableEd25519)) {
1025
+ return mpcSigner.keygen(roomId, mpcConfig.numberOfParties, mpcConfig.threshold, currentInit, allOtherKeygenIds);
1026
+ } else {
1027
+ // One party joins the keygen room using acting as the sampler: (wallet-service)
1028
+ // The remaining parties join the key sampling ceremony using: (browser)
1029
+ return mpcSigner.receiveKey(roomId, mpcConfig.numberOfParties, mpcConfig.threshold, currentInit, allOtherKeygenIds);
1030
+ }
835
1031
  }));
836
1032
  // only need one client keygen result to derive the public key
837
1033
  const [clientKeygenResult] = clientKeygenResults;
@@ -847,82 +1043,157 @@ class DynamicWalletClient {
847
1043
  clientKeygenResults
848
1044
  };
849
1045
  }
850
- async keyGen({ chainName, thresholdSignatureScheme, onError, onCeremonyComplete }) {
1046
+ async keyGen({ chainName, thresholdSignatureScheme, onError, onCeremonyComplete, traceContext }) {
1047
+ const dynamicRequestId = uuid.v4();
1048
+ try {
1049
+ const clientKeygenInitResults = await this.clientInitializeKeyGen({
1050
+ chainName,
1051
+ thresholdSignatureScheme
1052
+ });
1053
+ const clientKeygenIds = clientKeygenInitResults.map((result)=>result.keygenId);
1054
+ this.instrument('[DynamicWaasWalletClient] Initialized client key generation', _extends({
1055
+ clientKeygenIds: clientKeygenIds.join(', '),
1056
+ chainName,
1057
+ thresholdSignatureScheme,
1058
+ key: 'keyGen'
1059
+ }, this.getTraceContext(traceContext)));
1060
+ const { roomId, serverKeygenIds } = await this.serverInitializeKeyGen({
1061
+ chainName,
1062
+ clientKeygenIds,
1063
+ dynamicRequestId,
1064
+ thresholdSignatureScheme,
1065
+ onCeremonyComplete
1066
+ });
1067
+ this.instrument('[DynamicWaasWalletClient] Server key generation initialized', _extends({
1068
+ roomId,
1069
+ clientKeygenIds: clientKeygenIds.join(', '),
1070
+ serverKeygenIds: serverKeygenIds.join(', '),
1071
+ chainName,
1072
+ key: 'keyGen',
1073
+ operation: 'serverKeyGen'
1074
+ }, this.getTraceContext(traceContext)));
1075
+ const { rawPublicKey, clientKeygenResults: clientKeyShares } = await this.clientKeyGen({
1076
+ chainName,
1077
+ roomId,
1078
+ serverKeygenIds,
1079
+ clientKeygenInitResults,
1080
+ thresholdSignatureScheme
1081
+ });
1082
+ this.instrument('[DynamicWaasWalletClient] Client key generation completed', _extends({
1083
+ roomId,
1084
+ serverKeygenIds: serverKeygenIds.join(', '),
1085
+ clientKeygenIds: clientKeygenIds.join(', '),
1086
+ chainName,
1087
+ thresholdSignatureScheme,
1088
+ rawPublicKey,
1089
+ clientKeySharesCount: clientKeyShares.length,
1090
+ key: 'keyGen',
1091
+ operation: 'clientKeyGen'
1092
+ }, this.getTraceContext(traceContext)));
1093
+ return {
1094
+ rawPublicKey,
1095
+ clientKeyShares
1096
+ };
1097
+ } catch (error) {
1098
+ logError({
1099
+ message: 'Error in keyGen',
1100
+ error: error,
1101
+ context: _extends({
1102
+ chainName,
1103
+ thresholdSignatureScheme,
1104
+ dynamicRequestId
1105
+ }, this.getTraceContext(traceContext))
1106
+ });
1107
+ throw error;
1108
+ }
1109
+ }
1110
+ async importRawPrivateKey({ chainName, privateKey, thresholdSignatureScheme, onError, onCeremonyComplete, traceContext }) {
1111
+ const dynamicRequestId = uuid.v4();
851
1112
  try {
1113
+ const mpcSigner = getMPCSigner({
1114
+ chainName,
1115
+ baseRelayUrl: this.baseMPCRelayApiUrl
1116
+ });
852
1117
  const clientKeygenInitResults = await this.clientInitializeKeyGen({
853
1118
  chainName,
854
1119
  thresholdSignatureScheme
855
1120
  });
856
1121
  const clientKeygenIds = clientKeygenInitResults.map((result)=>result.keygenId);
857
- const { roomId, serverKeygenIds } = await this.serverInitializeKeyGen({
1122
+ this.instrument('[DynamicWaasWalletClient] Client key generation initialized', _extends({
1123
+ clientKeygenIds: clientKeygenIds.join(', '),
1124
+ chainName,
1125
+ thresholdSignatureScheme,
1126
+ key: 'importRawPrivateKey',
1127
+ operation: 'clientKeyGen'
1128
+ }, this.getTraceContext(traceContext)));
1129
+ const { roomId, serverKeygenIds } = await this.apiClient.importPrivateKey({
858
1130
  chainName,
859
1131
  clientKeygenIds,
1132
+ dynamicRequestId,
860
1133
  thresholdSignatureScheme,
1134
+ onError,
861
1135
  onCeremonyComplete
862
1136
  });
863
- const { rawPublicKey, clientKeygenResults: clientKeyShares } = await this.clientKeyGen({
864
- chainName,
1137
+ this.instrument('[DynamicWaasWalletClient] Server key generation initialized', _extends({
865
1138
  roomId,
866
- serverKeygenIds,
867
- clientKeygenInitResults,
868
- thresholdSignatureScheme
1139
+ clientKeygenIds: clientKeygenIds.join(', '),
1140
+ serverKeygenIds: serverKeygenIds.join(', '),
1141
+ chainName,
1142
+ key: 'importRawPrivateKey',
1143
+ operation: 'serverImportPrivateKey'
1144
+ }, this.getTraceContext(traceContext)));
1145
+ const { threshold } = core.getTSSConfig(thresholdSignatureScheme);
1146
+ const clientKeygenResults = await Promise.all(clientKeygenInitResults.map(async (currentInit, index)=>{
1147
+ const otherClientKeygenIds = clientKeygenInitResults.filter((init)=>init.keygenId !== currentInit.keygenId).map((init)=>init.keygenId);
1148
+ if (index === 0) {
1149
+ const otherKeyGenIds = [
1150
+ ...serverKeygenIds,
1151
+ ...otherClientKeygenIds
1152
+ ];
1153
+ const importerKeygenResult = await mpcSigner.importPrivateKeyImporter(roomId, threshold, privateKey, currentInit, otherKeyGenIds);
1154
+ return importerKeygenResult;
1155
+ } else {
1156
+ const recipientKeygenResult = await mpcSigner.importPrivateKeyRecipient(roomId, threshold, currentInit, [
1157
+ ...serverKeygenIds,
1158
+ ...otherClientKeygenIds
1159
+ ]);
1160
+ return recipientKeygenResult;
1161
+ }
1162
+ }));
1163
+ const [clientKeygenResult] = clientKeygenResults;
1164
+ const rawPublicKey = await this.derivePublicKey({
1165
+ chainName,
1166
+ keyShare: clientKeygenResult,
1167
+ derivationPath: undefined
869
1168
  });
1169
+ this.instrument('[DynamicWaasWalletClient] Completed import of raw private key', _extends({
1170
+ rawPublicKey,
1171
+ chainName,
1172
+ thresholdSignatureScheme,
1173
+ roomId,
1174
+ serverKeygenIds: serverKeygenIds.join(', '),
1175
+ clientKeygenIds: clientKeygenIds.join(', '),
1176
+ key: 'importRawPrivateKey',
1177
+ operation: 'importRawPrivateKey'
1178
+ }, this.getTraceContext(traceContext)));
870
1179
  return {
871
1180
  rawPublicKey,
872
- clientKeyShares
1181
+ clientKeyShares: clientKeygenResults
873
1182
  };
874
1183
  } catch (error) {
875
- this.logger.error('Error creating wallet account', error);
876
- throw new Error('Error creating wallet account');
1184
+ logError({
1185
+ message: 'Error in importRawPrivateKey',
1186
+ error: error,
1187
+ context: _extends({
1188
+ chainName,
1189
+ thresholdSignatureScheme,
1190
+ dynamicRequestId
1191
+ }, this.getTraceContext(traceContext))
1192
+ });
1193
+ throw error;
877
1194
  }
878
1195
  }
879
- async importRawPrivateKey({ chainName, privateKey, thresholdSignatureScheme, onError, onCeremonyComplete }) {
880
- const mpcSigner = getMPCSigner({
881
- chainName,
882
- baseRelayUrl: this.baseMPCRelayApiUrl
883
- });
884
- const clientKeygenInitResults = await this.clientInitializeKeyGen({
885
- chainName,
886
- thresholdSignatureScheme
887
- });
888
- const clientKeygenIds = clientKeygenInitResults.map((result)=>result.keygenId);
889
- const { roomId, serverKeygenIds } = await this.apiClient.importPrivateKey({
890
- chainName,
891
- clientKeygenIds,
892
- thresholdSignatureScheme,
893
- onError,
894
- onCeremonyComplete
895
- });
896
- const { threshold } = core.getTSSConfig(thresholdSignatureScheme);
897
- const clientKeygenResults = await Promise.all(clientKeygenInitResults.map(async (currentInit, index)=>{
898
- const otherClientKeygenIds = clientKeygenInitResults.filter((init)=>init.keygenId !== currentInit.keygenId).map((init)=>init.keygenId);
899
- if (index === 0) {
900
- const otherKeyGenIds = [
901
- ...serverKeygenIds,
902
- ...otherClientKeygenIds
903
- ];
904
- const importerKeygenResult = await mpcSigner.importPrivateKeyImporter(roomId, threshold, privateKey, currentInit, otherKeyGenIds);
905
- return importerKeygenResult;
906
- } else {
907
- const recipientKeygenResult = await mpcSigner.importPrivateKeyRecipient(roomId, threshold, currentInit, [
908
- ...serverKeygenIds,
909
- ...otherClientKeygenIds
910
- ]);
911
- return recipientKeygenResult;
912
- }
913
- }));
914
- const [clientKeygenResult] = clientKeygenResults;
915
- const rawPublicKey = await this.derivePublicKey({
916
- chainName,
917
- keyShare: clientKeygenResult,
918
- derivationPath: undefined
919
- });
920
- return {
921
- rawPublicKey,
922
- clientKeyShares: clientKeygenResults
923
- };
924
- }
925
- async serverSign({ walletId, message, isFormatted }) {
1196
+ async serverSign({ walletId, message, isFormatted, mfaToken, context, onError, dynamicRequestId, traceContext }) {
926
1197
  // Create the room and sign the message
927
1198
  if (typeof message !== 'string') {
928
1199
  message = `0x${Buffer.from(message).toString('hex')}`;
@@ -930,94 +1201,229 @@ class DynamicWalletClient {
930
1201
  const data = await this.apiClient.signMessage({
931
1202
  walletId,
932
1203
  message,
933
- isFormatted
1204
+ isFormatted,
1205
+ dynamicRequestId,
1206
+ mfaToken,
1207
+ context: context ? JSON.parse(JSON.stringify(context, (_key, value)=>typeof value === 'bigint' ? value.toString() : value)) : undefined,
1208
+ onError,
1209
+ forwardMPCClientEnabled: this.forwardMPCEnabled,
1210
+ traceContext
934
1211
  });
935
1212
  return data;
936
1213
  }
937
- async clientSign({ chainName, message, roomId, keyShare, derivationPath, isFormatted }) {
1214
+ async forwardMPCClientSign({ chainName, message, roomId, keyShare, derivationPath, formattedMessage, dynamicRequestId, isFormatted, traceContext }) {
1215
+ try {
1216
+ if (!this.apiClient.forwardMPCClient.connected) {
1217
+ await this.initializeForwardMPCClient();
1218
+ }
1219
+ const messageForForwardMPC = core.serializeMessageForForwardMPC({
1220
+ message,
1221
+ isFormatted,
1222
+ chainName
1223
+ });
1224
+ this.logger.info('Forward MPC enabled, signing message with forward MPC', this.getTraceContext(traceContext));
1225
+ const signature = await this.apiClient.forwardMPCClient.signMessage({
1226
+ keyshare: keyShare,
1227
+ message: chainName === 'SVM' ? formattedMessage : messageForForwardMPC,
1228
+ relayDomain: this.baseMPCRelayApiUrl || '',
1229
+ signingAlgo: chainName === 'EVM' ? 'ECDSA' : 'ED25519',
1230
+ hashAlgo: chainName === 'EVM' && !isFormatted ? 'keccak256' : undefined,
1231
+ derivationPath: derivationPath,
1232
+ roomUuid: roomId
1233
+ });
1234
+ const signatureBytes = signature.data.signature;
1235
+ if (!(signatureBytes instanceof Uint8Array)) {
1236
+ throw new TypeError(`Invalid signature format: expected Uint8Array, got ${typeof signatureBytes}`);
1237
+ }
1238
+ // Convert to EcdsaSignature
1239
+ if (chainName === 'EVM') {
1240
+ const ecdsaSignature = web.EcdsaSignature.fromBuffer(signatureBytes);
1241
+ return ecdsaSignature;
1242
+ } else {
1243
+ return signatureBytes;
1244
+ }
1245
+ } catch (error) {
1246
+ this.logger.error('Error signing message with forward MPC client', {
1247
+ error,
1248
+ environmentId: this.environmentId,
1249
+ userId: this.userId,
1250
+ dynamicRequestId
1251
+ });
1252
+ throw error;
1253
+ }
1254
+ }
1255
+ async clientSign({ chainName, message, roomId, keyShare, derivationPath, isFormatted, dynamicRequestId, traceContext }) {
938
1256
  try {
939
1257
  const mpcSigner = getMPCSigner({
940
1258
  chainName,
941
1259
  baseRelayUrl: this.baseMPCRelayApiUrl
942
1260
  });
943
1261
  const formattedMessage = isFormatted ? new web.MessageHash(message) : formatMessage(chainName, message);
1262
+ this.logger.debug('[DynamicWaasWalletClient] Starting client sign', _extends({
1263
+ chainName,
1264
+ message,
1265
+ roomId,
1266
+ derivationPath,
1267
+ isFormatted
1268
+ }, this.getTraceContext(traceContext)));
1269
+ if (this.forwardMPCEnabled) {
1270
+ return this.forwardMPCClientSign({
1271
+ chainName,
1272
+ message,
1273
+ roomId,
1274
+ keyShare,
1275
+ derivationPath,
1276
+ formattedMessage,
1277
+ dynamicRequestId,
1278
+ isFormatted,
1279
+ traceContext
1280
+ });
1281
+ }
944
1282
  const signature = await mpcSigner.sign(roomId, keyShare, formattedMessage, derivationPath);
945
1283
  return signature;
946
1284
  } catch (error) {
947
- this.logger.error('Error in clientSign:', error);
1285
+ logError({
1286
+ message: 'Error in clientSign',
1287
+ error: error,
1288
+ context: _extends({
1289
+ chainName,
1290
+ roomId,
1291
+ derivationPath,
1292
+ isFormatted,
1293
+ dynamicRequestId
1294
+ }, this.getTraceContext(traceContext))
1295
+ });
948
1296
  throw error;
949
1297
  }
950
1298
  }
951
1299
  //todo: need to modify with imported flag
952
- async sign({ accountAddress, message, chainName, password = undefined, isFormatted = false }) {
953
- await this.verifyPassword({
954
- accountAddress,
955
- password,
956
- walletOperation: core.WalletOperation.SIGN_MESSAGE
957
- });
958
- const wallet = await this.getWallet({
959
- accountAddress,
960
- password,
961
- walletOperation: core.WalletOperation.SIGN_MESSAGE
962
- });
963
- // Perform the server sign
964
- const data = await this.serverSign({
965
- walletId: wallet.walletId,
966
- message,
967
- isFormatted
968
- });
969
- const derivationPath = wallet.derivationPath && wallet.derivationPath != '' ? new Uint32Array(Object.values(JSON.parse(wallet.derivationPath))) : undefined;
970
- // Perform the client sign and return the signature
971
- const clientKeyShares = await this.getClientKeySharesFromLocalStorage({
972
- accountAddress
973
- });
974
- const signature = await this.clientSign({
975
- chainName,
976
- message,
977
- roomId: data.roomId,
978
- keyShare: clientKeyShares[0],
979
- derivationPath,
980
- isFormatted
981
- });
982
- return signature;
1300
+ async sign({ accountAddress, message, chainName, password = undefined, isFormatted = false, signedSessionId, mfaToken, context, onError, traceContext }) {
1301
+ const dynamicRequestId = uuid.v4();
1302
+ try {
1303
+ await this.verifyPassword({
1304
+ accountAddress,
1305
+ password,
1306
+ walletOperation: core.WalletOperation.SIGN_MESSAGE,
1307
+ signedSessionId
1308
+ });
1309
+ const wallet = await this.getWallet({
1310
+ accountAddress,
1311
+ password,
1312
+ walletOperation: core.WalletOperation.SIGN_MESSAGE,
1313
+ signedSessionId
1314
+ });
1315
+ // Perform the server sign
1316
+ const data = await this.serverSign({
1317
+ walletId: wallet.walletId,
1318
+ message,
1319
+ isFormatted,
1320
+ mfaToken,
1321
+ context,
1322
+ onError,
1323
+ dynamicRequestId,
1324
+ traceContext
1325
+ });
1326
+ this.instrument('[DynamicWaasWalletClient] Server sign completed', _extends({
1327
+ message,
1328
+ accountAddress,
1329
+ walletId: wallet.walletId,
1330
+ roomId: data.roomId,
1331
+ dynamicRequestId,
1332
+ key: 'sign',
1333
+ operation: 'serverSign'
1334
+ }, this.getTraceContext(traceContext)));
1335
+ const derivationPath = wallet.derivationPath && wallet.derivationPath != '' ? new Uint32Array(Object.values(JSON.parse(wallet.derivationPath))) : undefined;
1336
+ // Perform the client sign and return the signature
1337
+ const clientKeyShares = await this.getClientKeySharesFromLocalStorage({
1338
+ accountAddress
1339
+ });
1340
+ const signature = await this.clientSign({
1341
+ chainName,
1342
+ message,
1343
+ roomId: data.roomId,
1344
+ keyShare: clientKeyShares[0],
1345
+ derivationPath,
1346
+ isFormatted,
1347
+ dynamicRequestId,
1348
+ traceContext
1349
+ });
1350
+ this.instrument('[DynamicWaasWalletClient] Client sign completed', _extends({
1351
+ accountAddress,
1352
+ chainName,
1353
+ message,
1354
+ roomId: data.roomId,
1355
+ derivationPath,
1356
+ isFormatted,
1357
+ key: 'sign',
1358
+ operation: 'clientSign'
1359
+ }, this.getTraceContext(traceContext)));
1360
+ return signature;
1361
+ } catch (error) {
1362
+ logError({
1363
+ message: 'Error in sign',
1364
+ error: error,
1365
+ context: _extends({
1366
+ accountAddress,
1367
+ chainName,
1368
+ isFormatted: isFormatted ? 'true' : 'false',
1369
+ dynamicRequestId
1370
+ }, this.getTraceContext(traceContext))
1371
+ });
1372
+ throw error;
1373
+ }
983
1374
  }
984
- async refreshWalletAccountShares({ accountAddress, chainName, password = undefined }) {
985
- await this.verifyPassword({
986
- accountAddress,
987
- password,
988
- walletOperation: core.WalletOperation.REFRESH
989
- });
990
- const wallet = await this.getWallet({
991
- accountAddress,
992
- walletOperation: core.WalletOperation.NO_OPERATION,
993
- password
994
- });
995
- const mpcSigner = getMPCSigner({
996
- chainName,
997
- baseRelayUrl: this.baseMPCRelayApiUrl
998
- });
999
- // Create the room and refresh the shares
1000
- const data = await this.apiClient.refreshWalletAccountShares({
1001
- walletId: wallet.walletId
1002
- });
1003
- const roomId = data.roomId;
1004
- const clientKeyShares = await this.getClientKeySharesFromLocalStorage({
1005
- accountAddress
1006
- });
1007
- const refreshResults = await Promise.all(clientKeyShares.map((clientKeyShare)=>mpcSigner.refresh(roomId, clientKeyShare)));
1008
- this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
1009
- clientKeySharesBackupInfo: getClientKeyShareBackupInfo()
1010
- });
1011
- await this.setClientKeySharesToLocalStorage({
1012
- accountAddress,
1013
- clientKeyShares: refreshResults,
1014
- overwriteOrMerge: 'overwrite'
1015
- });
1016
- await this.storeEncryptedBackupByWallet({
1017
- accountAddress,
1018
- password: password != null ? password : this.environmentId
1019
- });
1020
- return refreshResults;
1375
+ async refreshWalletAccountShares({ accountAddress, chainName, password = undefined, signedSessionId, mfaToken, traceContext }) {
1376
+ const dynamicRequestId = uuid.v4();
1377
+ try {
1378
+ await this.verifyPassword({
1379
+ accountAddress,
1380
+ password,
1381
+ walletOperation: core.WalletOperation.REFRESH,
1382
+ signedSessionId
1383
+ });
1384
+ const wallet = await this.getWallet({
1385
+ accountAddress,
1386
+ walletOperation: core.WalletOperation.NO_OPERATION,
1387
+ password,
1388
+ signedSessionId
1389
+ });
1390
+ const mpcSigner = getMPCSigner({
1391
+ chainName,
1392
+ baseRelayUrl: this.baseMPCRelayApiUrl
1393
+ });
1394
+ // Create the room and refresh the shares
1395
+ const data = await this.apiClient.refreshWalletAccountShares({
1396
+ dynamicRequestId,
1397
+ walletId: wallet.walletId,
1398
+ mfaToken
1399
+ });
1400
+ const roomId = data.roomId;
1401
+ const clientKeyShares = await this.getClientKeySharesFromLocalStorage({
1402
+ accountAddress
1403
+ });
1404
+ const refreshResults = await Promise.all(clientKeyShares.map((clientKeyShare)=>mpcSigner.refresh(roomId, clientKeyShare)));
1405
+ await this.setClientKeySharesToLocalStorage({
1406
+ accountAddress,
1407
+ clientKeyShares: refreshResults,
1408
+ overwriteOrMerge: 'overwrite'
1409
+ });
1410
+ await this.storeEncryptedBackupByWallet({
1411
+ accountAddress,
1412
+ password: password != null ? password : this.environmentId,
1413
+ signedSessionId
1414
+ });
1415
+ } catch (error) {
1416
+ logError({
1417
+ message: 'Error in refreshWalletAccountShares',
1418
+ error: error,
1419
+ context: _extends({
1420
+ accountAddress,
1421
+ chainName,
1422
+ dynamicRequestId
1423
+ }, this.getTraceContext(traceContext))
1424
+ });
1425
+ throw error;
1426
+ }
1021
1427
  }
1022
1428
  async getExportId({ chainName, clientKeyShare }) {
1023
1429
  const mpcSigner = getMPCSigner({
@@ -1070,105 +1476,277 @@ class DynamicWalletClient {
1070
1476
  existingClientKeyShares
1071
1477
  };
1072
1478
  }
1073
- async reshare({ chainName, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password = undefined }) {
1074
- await this.verifyPassword({
1479
+ async reshare({ chainName, accountAddress, oldThresholdSignatureScheme, newThresholdSignatureScheme, password = undefined, signedSessionId, backupToGoogleDrive = false, delegateToProjectEnvironment = false, mfaToken, revokeDelegation = false }) {
1480
+ const dynamicRequestId = uuid.v4();
1481
+ try {
1482
+ await this.verifyPassword({
1483
+ accountAddress,
1484
+ password,
1485
+ walletOperation: core.WalletOperation.RESHARE,
1486
+ signedSessionId
1487
+ });
1488
+ const { existingClientShareCount } = core.getReshareConfig({
1489
+ oldThresholdSignatureScheme,
1490
+ newThresholdSignatureScheme
1491
+ });
1492
+ const wallet = await this.getWallet({
1493
+ accountAddress,
1494
+ walletOperation: core.WalletOperation.NO_OPERATION,
1495
+ shareCount: existingClientShareCount,
1496
+ password,
1497
+ signedSessionId
1498
+ });
1499
+ const { newClientInitKeygenResults, newClientKeygenIds, existingClientKeygenIds, existingClientKeyShares } = await this.reshareStrategy({
1500
+ chainName,
1501
+ accountAddress,
1502
+ wallet,
1503
+ oldThresholdSignatureScheme,
1504
+ newThresholdSignatureScheme
1505
+ });
1506
+ const clientKeygenIds = [
1507
+ ...newClientKeygenIds,
1508
+ ...existingClientKeygenIds
1509
+ ];
1510
+ // Server to create the room and complete the server reshare logics
1511
+ const data = await this.apiClient.reshare({
1512
+ walletId: wallet.walletId,
1513
+ clientKeygenIds: clientKeygenIds,
1514
+ oldThresholdSignatureScheme,
1515
+ newThresholdSignatureScheme,
1516
+ dynamicRequestId,
1517
+ delegateToProjectEnvironment,
1518
+ mfaToken,
1519
+ revokeDelegation
1520
+ });
1521
+ const { roomId, serverKeygenIds, newServerKeygenIds = [] } = data;
1522
+ // Get the MPC config for the threshold signature scheme
1523
+ const oldMpcConfig = core.MPC_CONFIG[oldThresholdSignatureScheme];
1524
+ const newMpcConfig = core.MPC_CONFIG[newThresholdSignatureScheme];
1525
+ const allPartyKeygenIds = [
1526
+ ...clientKeygenIds,
1527
+ ...serverKeygenIds,
1528
+ ...newServerKeygenIds
1529
+ ];
1530
+ const mpcSigner = getMPCSigner({
1531
+ chainName,
1532
+ baseRelayUrl: this.baseMPCRelayApiUrl
1533
+ });
1534
+ const existingResharePromises = existingClientKeyShares.map((keyShare)=>mpcSigner.reshareRemainingParty(roomId, newMpcConfig.threshold, keyShare, allPartyKeygenIds));
1535
+ const newResharePromises = newClientInitKeygenResults.map((keygenResult)=>mpcSigner.reshareNewParty(roomId, oldMpcConfig.threshold, newMpcConfig.threshold, keygenResult, allPartyKeygenIds));
1536
+ // Run both share parties in parallel by group
1537
+ const [existingReshareResults, newReshareResults] = await Promise.all([
1538
+ Promise.all(existingResharePromises),
1539
+ Promise.all(newResharePromises)
1540
+ ]);
1541
+ const clientKeysharesToLocalStorage = delegateToProjectEnvironment ? [
1542
+ ...existingReshareResults
1543
+ ] : [
1544
+ ...existingReshareResults,
1545
+ ...newReshareResults
1546
+ ];
1547
+ this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
1548
+ thresholdSignatureScheme: newThresholdSignatureScheme
1549
+ });
1550
+ // store client key shares to localStorage
1551
+ await this.setClientKeySharesToLocalStorage({
1552
+ accountAddress,
1553
+ clientKeyShares: clientKeysharesToLocalStorage,
1554
+ overwriteOrMerge: 'overwrite'
1555
+ });
1556
+ const allClientShares = [
1557
+ ...existingReshareResults,
1558
+ ...newReshareResults
1559
+ ];
1560
+ let distribution;
1561
+ if (delegateToProjectEnvironment && backupToGoogleDrive) {
1562
+ // Delegation + Google Drive: Client's existing share backs up to both Dynamic and Google Drive.
1563
+ // The new share goes to the webhook for delegation.
1564
+ distribution = createDelegationWithGoogleDriveDistribution({
1565
+ existingShares: existingReshareResults,
1566
+ delegatedShare: newReshareResults[0]
1567
+ });
1568
+ } else if (delegateToProjectEnvironment) {
1569
+ // Delegation only: Client's existing share backs up to Dynamic.
1570
+ // The new share goes to the webhook for delegation. No Google Drive backup.
1571
+ distribution = createDelegationOnlyDistribution({
1572
+ existingShares: existingReshareResults,
1573
+ delegatedShare: newReshareResults[0]
1574
+ });
1575
+ } else if (backupToGoogleDrive) {
1576
+ // Google Drive only: Split shares between Dynamic (N-1) and Google Drive (1).
1577
+ // The last share (new share) goes to Google Drive.
1578
+ distribution = createGoogleDriveOnlyDistribution({
1579
+ allShares: allClientShares
1580
+ });
1581
+ } else {
1582
+ // No delegation, no Google Drive: All shares go to Dynamic backend only.
1583
+ distribution = createDynamicOnlyDistribution({
1584
+ allShares: allClientShares
1585
+ });
1586
+ }
1587
+ await this.backupSharesWithDistribution({
1588
+ accountAddress,
1589
+ password,
1590
+ signedSessionId,
1591
+ distribution
1592
+ });
1593
+ } catch (error) {
1594
+ logError({
1595
+ message: 'Error in reshare, resetting wallet to previous state',
1596
+ error: error,
1597
+ context: {
1598
+ accountAddress,
1599
+ chainName,
1600
+ oldThresholdSignatureScheme,
1601
+ newThresholdSignatureScheme,
1602
+ backupToGoogleDrive,
1603
+ dynamicRequestId
1604
+ }
1605
+ });
1606
+ // reset user wallet when reshare fails, this would allow the client to recover wallets from an active state
1607
+ this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
1608
+ thresholdSignatureScheme: oldThresholdSignatureScheme
1609
+ });
1610
+ await this.setClientKeySharesToLocalStorage({
1611
+ accountAddress,
1612
+ clientKeyShares: [],
1613
+ overwriteOrMerge: 'overwrite'
1614
+ });
1615
+ throw error;
1616
+ }
1617
+ }
1618
+ async performDelegationOperation({ accountAddress, password, signedSessionId, mfaToken, newThresholdSignatureScheme, revokeDelegation = false, operationName }) {
1619
+ try {
1620
+ var _this_walletMap_accountAddress;
1621
+ const delegateToProjectEnvironment = this.featureFlags && this.featureFlags[core.FEATURE_FLAGS.ENABLE_DELEGATED_KEY_SHARES_FLAG] === true;
1622
+ if (!delegateToProjectEnvironment) {
1623
+ throw new Error('Delegation is not allowed for this project environment');
1624
+ }
1625
+ const wallet = await this.getWallet({
1626
+ accountAddress,
1627
+ walletOperation: core.WalletOperation.REACH_ALL_PARTIES,
1628
+ password,
1629
+ signedSessionId
1630
+ });
1631
+ if (wallet.chainName === 'SUI') {
1632
+ throw new Error('Delegation is not allowed for SUI');
1633
+ }
1634
+ const currentThresholdSignatureScheme = this.walletMap[accountAddress].thresholdSignatureScheme;
1635
+ await this.reshare({
1636
+ chainName: this.walletMap[accountAddress].chainName,
1637
+ accountAddress,
1638
+ oldThresholdSignatureScheme: currentThresholdSignatureScheme,
1639
+ newThresholdSignatureScheme,
1640
+ password,
1641
+ signedSessionId,
1642
+ backupToGoogleDrive: hasGoogleDriveBackup((_this_walletMap_accountAddress = this.walletMap[accountAddress]) == null ? void 0 : _this_walletMap_accountAddress.clientKeySharesBackupInfo),
1643
+ delegateToProjectEnvironment: true,
1644
+ mfaToken,
1645
+ revokeDelegation
1646
+ });
1647
+ } catch (error) {
1648
+ logError({
1649
+ message: `Error in ${operationName}`,
1650
+ error: error,
1651
+ context: {
1652
+ accountAddress
1653
+ }
1654
+ });
1655
+ throw error;
1656
+ }
1657
+ }
1658
+ async delegateKeyShares({ accountAddress, password = undefined, signedSessionId, mfaToken }) {
1659
+ await this.performDelegationOperation({
1075
1660
  accountAddress,
1076
1661
  password,
1077
- walletOperation: core.WalletOperation.RESHARE
1078
- });
1079
- const { existingClientShareCount } = core.getReshareConfig({
1080
- oldThresholdSignatureScheme,
1081
- newThresholdSignatureScheme
1082
- });
1083
- const wallet = await this.getWallet({
1084
- accountAddress,
1085
- walletOperation: core.WalletOperation.NO_OPERATION,
1086
- shareCount: existingClientShareCount,
1087
- password
1662
+ signedSessionId,
1663
+ mfaToken,
1664
+ newThresholdSignatureScheme: core.ThresholdSignatureScheme.TWO_OF_THREE,
1665
+ operationName: 'delegateKeyShares'
1088
1666
  });
1089
- const { newClientInitKeygenResults, newClientKeygenIds, existingClientKeygenIds, existingClientKeyShares } = await this.reshareStrategy({
1090
- chainName,
1091
- accountAddress,
1092
- wallet,
1093
- oldThresholdSignatureScheme,
1094
- newThresholdSignatureScheme
1095
- });
1096
- const clientKeygenIds = [
1097
- ...newClientKeygenIds,
1098
- ...existingClientKeygenIds
1099
- ];
1100
- // Server to create the room and complete the server reshare logics
1101
- const data = await this.apiClient.reshare({
1102
- walletId: wallet.walletId,
1103
- clientKeygenIds: clientKeygenIds,
1104
- oldThresholdSignatureScheme,
1105
- newThresholdSignatureScheme
1106
- });
1107
- const { roomId, serverKeygenIds, newServerKeygenIds = [] } = data;
1108
- // Get the MPC config for the threshold signature scheme
1109
- const oldMpcConfig = core.MPC_CONFIG[oldThresholdSignatureScheme];
1110
- const newMpcConfig = core.MPC_CONFIG[newThresholdSignatureScheme];
1111
- const allPartyKeygenIds = [
1112
- ...clientKeygenIds,
1113
- ...serverKeygenIds,
1114
- ...newServerKeygenIds
1115
- ];
1116
- const mpcSigner = getMPCSigner({
1117
- chainName,
1118
- baseRelayUrl: this.baseMPCRelayApiUrl
1119
- });
1120
- const reshareResults = await Promise.all([
1121
- ...newClientInitKeygenResults.map((keygenResult)=>mpcSigner.reshareNewParty(roomId, oldMpcConfig.threshold, newMpcConfig.threshold, keygenResult, allPartyKeygenIds)),
1122
- ...existingClientKeyShares.map((keyShare)=>mpcSigner.reshareRemainingParty(roomId, newMpcConfig.threshold, keyShare, allPartyKeygenIds))
1123
- ]);
1124
- await this.setClientKeySharesToLocalStorage({
1125
- accountAddress,
1126
- clientKeyShares: reshareResults,
1127
- overwriteOrMerge: 'overwrite'
1128
- });
1129
- await this.storeEncryptedBackupByWallet({
1130
- accountAddress,
1131
- password
1132
- });
1133
- return reshareResults;
1667
+ const backupInfo = this.walletMap[accountAddress].clientKeySharesBackupInfo;
1668
+ const delegatedKeyShares = backupInfo.backups[core.BackupLocation.DELEGATED] || [];
1669
+ return delegatedKeyShares;
1134
1670
  }
1135
- async exportKey({ accountAddress, chainName, password = undefined }) {
1136
- const wallet = await this.getWallet({
1671
+ async revokeDelegation({ accountAddress, password = undefined, signedSessionId, mfaToken }) {
1672
+ await this.performDelegationOperation({
1137
1673
  accountAddress,
1138
1674
  password,
1139
- walletOperation: core.WalletOperation.EXPORT_PRIVATE_KEY
1140
- });
1141
- const mpcSigner = getMPCSigner({
1142
- chainName,
1143
- baseRelayUrl: this.baseMPCRelayApiUrl
1144
- });
1145
- const clientKeyShares = await this.getClientKeySharesFromLocalStorage({
1146
- accountAddress
1147
- });
1148
- const exportId = await this.getExportId({
1149
- chainName,
1150
- clientKeyShare: clientKeyShares[0]
1151
- });
1152
- const data = await this.apiClient.exportKey({
1153
- walletId: wallet.walletId,
1154
- exportId
1155
- });
1156
- const keyExportRaw = await mpcSigner.exportFullPrivateKey(data.roomId, clientKeyShares[0], exportId);
1157
- if (!keyExportRaw) {
1158
- throw new Error('Error exporting private key');
1159
- }
1160
- const derivationPath = wallet.derivationPath && wallet.derivationPath != '' ? new Uint32Array(Object.values(JSON.parse(wallet.derivationPath))) : undefined;
1161
- let derivedPrivateKey;
1162
- if (mpcSigner instanceof web.Ecdsa) {
1163
- derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, derivationPath);
1164
- } else if (mpcSigner instanceof web.Ed25519) {
1165
- derivedPrivateKey = keyExportRaw;
1166
- } else if (mpcSigner instanceof web.BIP340) {
1167
- derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, derivationPath);
1675
+ signedSessionId,
1676
+ mfaToken,
1677
+ newThresholdSignatureScheme: core.ThresholdSignatureScheme.TWO_OF_TWO,
1678
+ revokeDelegation: true,
1679
+ operationName: 'revokeDelegation'
1680
+ });
1681
+ }
1682
+ async exportKey({ accountAddress, chainName, password = undefined, signedSessionId, mfaToken, traceContext }) {
1683
+ const dynamicRequestId = uuid.v4();
1684
+ try {
1685
+ const wallet = await this.getWallet({
1686
+ accountAddress,
1687
+ password,
1688
+ walletOperation: core.WalletOperation.EXPORT_PRIVATE_KEY,
1689
+ signedSessionId
1690
+ });
1691
+ const mpcSigner = getMPCSigner({
1692
+ chainName,
1693
+ baseRelayUrl: this.baseMPCRelayApiUrl
1694
+ });
1695
+ const clientKeyShares = await this.getClientKeySharesFromLocalStorage({
1696
+ accountAddress
1697
+ });
1698
+ const exportId = await this.getExportId({
1699
+ chainName,
1700
+ clientKeyShare: clientKeyShares[0]
1701
+ });
1702
+ const data = await this.apiClient.exportKey({
1703
+ walletId: wallet.walletId,
1704
+ exportId,
1705
+ dynamicRequestId,
1706
+ mfaToken
1707
+ });
1708
+ this.logger.debug('[DynamicWaasWalletClient] Starting export of private key', _extends({
1709
+ accountAddress,
1710
+ chainName,
1711
+ walletId: wallet.walletId,
1712
+ exportId,
1713
+ roomId: data.roomId
1714
+ }, this.getTraceContext(traceContext)));
1715
+ const keyExportRaw = await mpcSigner.exportFullPrivateKey(data.roomId, clientKeyShares[0], exportId);
1716
+ if (!keyExportRaw) {
1717
+ throw new Error('Error exporting private key');
1718
+ }
1719
+ this.logger.debug('[DynamicWaasWalletClient] Completed export of private key', _extends({
1720
+ accountAddress,
1721
+ chainName,
1722
+ walletId: wallet.walletId,
1723
+ exportId,
1724
+ roomId: data.roomId
1725
+ }, this.getTraceContext(traceContext)));
1726
+ const derivationPath = wallet.derivationPath && wallet.derivationPath != '' ? new Uint32Array(Object.values(JSON.parse(wallet.derivationPath))) : undefined;
1727
+ let derivedPrivateKey;
1728
+ if (mpcSigner instanceof web.Ecdsa) {
1729
+ derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, derivationPath);
1730
+ } else if (mpcSigner instanceof web.ExportableEd25519) {
1731
+ derivedPrivateKey = keyExportRaw;
1732
+ } else if (mpcSigner instanceof web.BIP340) {
1733
+ derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, derivationPath);
1734
+ }
1735
+ return {
1736
+ derivedPrivateKey
1737
+ };
1738
+ } catch (error) {
1739
+ logError({
1740
+ message: 'Error in exportKey',
1741
+ error: error,
1742
+ context: _extends({
1743
+ accountAddress,
1744
+ chainName,
1745
+ dynamicRequestId
1746
+ }, this.getTraceContext(traceContext))
1747
+ });
1748
+ throw error;
1168
1749
  }
1169
- return {
1170
- derivedPrivateKey
1171
- };
1172
1750
  }
1173
1751
  async offlineExportKey({ chainName, keyShares, derivationPath }) {
1174
1752
  try {
@@ -1180,7 +1758,7 @@ class DynamicWalletClient {
1180
1758
  baseRelayUrl: this.baseMPCRelayApiUrl
1181
1759
  });
1182
1760
  const walletKeyShares = keyShares.map((keyShare)=>{
1183
- return mpcSigner instanceof web.Ecdsa ? new web.EcdsaKeygenResult(keyShare.pubkey, keyShare.secretShare) : mpcSigner instanceof web.Ed25519 ? new web.Ed25519KeygenResult(keyShare.pubkey, keyShare.secretShare) : new web.BIP340KeygenResult(keyShare.pubkey, keyShare.secretShare);
1761
+ return mpcSigner instanceof web.Ecdsa ? new web.EcdsaKeygenResult(keyShare.pubkey, keyShare.secretShare) : mpcSigner instanceof web.ExportableEd25519 ? new web.ExportableEd25519KeygenResult(keyShare.pubkey, keyShare.secretShare) : new web.BIP340KeygenResult(keyShare.pubkey, keyShare.secretShare);
1184
1762
  });
1185
1763
  const keyExportRaw = await mpcSigner.offlineExportFullPrivateKey(walletKeyShares);
1186
1764
  if (!keyExportRaw) {
@@ -1191,7 +1769,7 @@ class DynamicWalletClient {
1191
1769
  let derivedPrivateKey;
1192
1770
  if (mpcSigner instanceof web.Ecdsa) {
1193
1771
  derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, walletDerivationPath);
1194
- } else if (mpcSigner instanceof web.Ed25519) {
1772
+ } else if (mpcSigner instanceof web.ExportableEd25519) {
1195
1773
  derivedPrivateKey = keyExportRaw;
1196
1774
  } else if (mpcSigner instanceof web.BIP340) {
1197
1775
  derivedPrivateKey = await mpcSigner.derivePrivateKeyFromXpriv(keyExportRaw, walletDerivationPath);
@@ -1206,7 +1784,13 @@ class DynamicWalletClient {
1206
1784
  rawPublicKey
1207
1785
  };
1208
1786
  } catch (error) {
1209
- this.logger.error('Error in offlineExportKey:', error);
1787
+ logError({
1788
+ message: 'Error in offlineExportKey',
1789
+ error: error,
1790
+ context: {
1791
+ chainName
1792
+ }
1793
+ });
1210
1794
  throw error;
1211
1795
  }
1212
1796
  }
@@ -1223,113 +1807,265 @@ class DynamicWalletClient {
1223
1807
  /**
1224
1808
  * helper function to store encrypted backup by wallet from iframe local storage
1225
1809
  */ async getClientKeySharesFromLocalStorage({ accountAddress }) {
1226
- var _this_iframeStorage;
1227
- await this.initializeIframeCommunication();
1228
- const walletObject = await ((_this_iframeStorage = this.iframeStorage) == null ? void 0 : _this_iframeStorage.getItem(accountAddress));
1810
+ var _this_storage;
1811
+ const walletObject = await ((_this_storage = this.storage) == null ? void 0 : _this_storage.getItem(accountAddress));
1229
1812
  if (!walletObject) {
1230
- this.logger.debug(`No item found in iframe local storage for accountAddress: ${accountAddress}`);
1813
+ this.logger.debug(`[DynamicWaasWalletClient] No item found in iframe local storage for accountAddress: ${accountAddress}`);
1231
1814
  return [];
1232
1815
  }
1233
1816
  try {
1234
- return (walletObject == null ? void 0 : walletObject.clientKeyShares) || [];
1817
+ let parsedWalletObject;
1818
+ if (typeof walletObject === 'string') {
1819
+ parsedWalletObject = JSON.parse(walletObject);
1820
+ } else {
1821
+ parsedWalletObject = walletObject;
1822
+ }
1823
+ return (parsedWalletObject == null ? void 0 : parsedWalletObject.clientKeyShares) || [];
1235
1824
  } catch (error) {
1236
- this.logger.error(`Error parsing clientKeyShares: ${error} for accountAddress: ${accountAddress}`);
1825
+ logError({
1826
+ message: `Error parsing clientKeyShares: Error for accountAddress:`,
1827
+ error: error,
1828
+ context: {
1829
+ accountAddress
1830
+ }
1831
+ });
1237
1832
  return [];
1238
1833
  }
1239
1834
  }
1240
1835
  /**
1241
1836
  * helper function to store encrypted backup by wallet from iframe local storage
1242
1837
  */ async setClientKeySharesToLocalStorage({ accountAddress, clientKeyShares, overwriteOrMerge = 'merge' }) {
1243
- var _this_iframeStorage;
1244
- await this.initializeIframeCommunication();
1245
- await ((_this_iframeStorage = this.iframeStorage) == null ? void 0 : _this_iframeStorage.setItem(accountAddress, {
1838
+ var _this_storage;
1839
+ const stringifiedClientKeyShares = JSON.stringify({
1246
1840
  clientKeyShares: overwriteOrMerge === 'overwrite' ? clientKeyShares : mergeUniqueKeyShares(await this.getClientKeySharesFromLocalStorage({
1247
1841
  accountAddress
1248
1842
  }), clientKeyShares)
1249
- }));
1843
+ });
1844
+ await ((_this_storage = this.storage) == null ? void 0 : _this_storage.setItem(accountAddress, stringifiedClientKeyShares));
1845
+ }
1846
+ async backupSharesWithDistribution({ accountAddress, password, signedSessionId, distribution, preserveDelegatedLocation = false }) {
1847
+ const dynamicRequestId = uuid.v4();
1848
+ try {
1849
+ var _this_walletMap_accountAddress;
1850
+ if (!((_this_walletMap_accountAddress = this.walletMap[accountAddress]) == null ? void 0 : _this_walletMap_accountAddress.walletId)) {
1851
+ const error = new Error(`WalletId not found for accountAddress ${accountAddress}`);
1852
+ logError({
1853
+ message: 'Error in backupSharesWithDistribution, wallet or walletId not found from the wallet map',
1854
+ error,
1855
+ context: {
1856
+ accountAddress,
1857
+ walletMap: this.walletMap
1858
+ }
1859
+ });
1860
+ throw error;
1861
+ }
1862
+ const locations = [];
1863
+ if (distribution.dynamicBackendShares.length > 0) {
1864
+ const encryptedDynamicShares = await Promise.all(distribution.dynamicBackendShares.map((keyShare)=>this.encryptKeyShare({
1865
+ keyShare,
1866
+ password
1867
+ })));
1868
+ const data = await this.apiClient.storeEncryptedBackupByWallet({
1869
+ walletId: this.walletMap[accountAddress].walletId,
1870
+ encryptedKeyShares: encryptedDynamicShares,
1871
+ passwordEncrypted: Boolean(password) && password !== this.environmentId,
1872
+ encryptionVersion: ENCRYPTION_VERSION_CURRENT,
1873
+ signedSessionId,
1874
+ authMode: this.authMode,
1875
+ requiresSignedSessionId: this.requiresSignedSessionId(),
1876
+ dynamicRequestId
1877
+ });
1878
+ if (data.keyShareIds.length === 0) {
1879
+ throw new Error('No key shares were backed up to Dynamic backend');
1880
+ }
1881
+ locations.push({
1882
+ location: core.BackupLocation.DYNAMIC,
1883
+ externalKeyShareId: data.keyShareIds[0]
1884
+ });
1885
+ }
1886
+ if (distribution.googleDriveShares.length > 0) {
1887
+ const encryptedGoogleDriveShares = await Promise.all(distribution.googleDriveShares.map((keyShare)=>this.encryptKeyShare({
1888
+ keyShare,
1889
+ password
1890
+ })));
1891
+ await this.uploadKeySharesToGoogleDrive({
1892
+ accountAddress,
1893
+ encryptedKeyShares: encryptedGoogleDriveShares
1894
+ });
1895
+ locations.push({
1896
+ location: core.BackupLocation.GOOGLE_DRIVE
1897
+ });
1898
+ }
1899
+ if (distribution.delegatedShare) {
1900
+ var _publicKey_key, _publicKey_key1, _publicKey_key2;
1901
+ const publicKey = await this.apiClient.getDelegatedEncryptionKey({
1902
+ environmentId: this.environmentId
1903
+ });
1904
+ if (!(publicKey == null ? void 0 : (_publicKey_key = publicKey.key) == null ? void 0 : _publicKey_key.publicKeyPemB64)) {
1905
+ throw new Error('Public key not found');
1906
+ }
1907
+ var _publicKey_key_keyId;
1908
+ const encryptedDelegatedKeyShareEnvelope = await encryptDelegatedKeyShare(JSON.stringify(distribution.delegatedShare), publicKey == null ? void 0 : (_publicKey_key1 = publicKey.key) == null ? void 0 : _publicKey_key1.publicKeyPemB64, (_publicKey_key_keyId = publicKey == null ? void 0 : (_publicKey_key2 = publicKey.key) == null ? void 0 : _publicKey_key2.keyId) != null ? _publicKey_key_keyId : publicKey == null ? void 0 : publicKey.keyId);
1909
+ const { status } = await this.apiClient.publishDelegatedKeyShare({
1910
+ walletId: this.walletMap[accountAddress].walletId,
1911
+ encryptedKeyShare: encryptedDelegatedKeyShareEnvelope,
1912
+ signedSessionId,
1913
+ requiresSignedSessionId: this.requiresSignedSessionId(),
1914
+ dynamicRequestId
1915
+ });
1916
+ if (status !== 200) {
1917
+ throw new Error('Failed to publish delegated key share');
1918
+ }
1919
+ locations.push({
1920
+ location: core.BackupLocation.DELEGATED
1921
+ });
1922
+ }
1923
+ // Preserve existing delegated location without re-publishing
1924
+ if (preserveDelegatedLocation && !distribution.delegatedShare) {
1925
+ locations.push({
1926
+ location: core.BackupLocation.DELEGATED
1927
+ });
1928
+ }
1929
+ const backupData = await this.apiClient.markKeySharesAsBackedUp({
1930
+ walletId: this.walletMap[accountAddress].walletId,
1931
+ locations,
1932
+ dynamicRequestId
1933
+ });
1934
+ const updatedBackupInfo = getClientKeyShareBackupInfo({
1935
+ walletProperties: {
1936
+ derivationPath: this.walletMap[accountAddress].derivationPath,
1937
+ keyShares: backupData.locationsWithKeyShares.map((ks)=>({
1938
+ id: ks.keyShareId,
1939
+ backupLocation: ks.location,
1940
+ externalKeyShareId: ks.externalKeyShareId,
1941
+ passwordEncrypted: Boolean(password) && password !== this.environmentId
1942
+ })),
1943
+ thresholdSignatureScheme: this.walletMap[accountAddress].thresholdSignatureScheme
1944
+ }
1945
+ });
1946
+ this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
1947
+ clientKeySharesBackupInfo: updatedBackupInfo
1948
+ });
1949
+ await this.storage.setItem(this.storageKey, JSON.stringify(this.walletMap));
1950
+ return backupData;
1951
+ } catch (error) {
1952
+ logError({
1953
+ message: 'Error in backupSharesWithDistribution',
1954
+ error: error,
1955
+ context: {
1956
+ accountAddress,
1957
+ dynamicRequestId
1958
+ }
1959
+ });
1960
+ throw error;
1961
+ }
1250
1962
  }
1251
1963
  /**
1252
- * Encrypts and stores wallet key shares as backups.
1964
+ * Central backup orchestrator that encrypts and stores wallet key shares.
1253
1965
  *
1254
- * This method encrypts all client key shares for a specific wallet and stores them
1255
- * in Dynamic's backend. If Google Drive backup is already configured for this wallet,
1256
- * it will also update the backup in Google Drive.
1966
+ * This method serves as the main backup coordinator, handling the distribution of encrypted
1967
+ * key shares between Dynamic's backend and Google Drive based on the wallet's threshold scheme.
1968
+ * It is used by multiple operations including reshare, refresh, and manual backup requests.
1257
1969
  *
1258
- * The method performs the following steps:
1970
+ * **Backup Distribution Strategy:**
1971
+ * - **Single share wallets**: All shares stored on Dynamic's backend only
1972
+ * - **Multi-share wallets (2+)**: When backing up to Google Drive, N-1 shares on Dynamic's backend, 1 share on Google Drive
1973
+ * - **Multi-share wallets (2+)**: When not backing up to Google Drive, all shares on Dynamic's backend
1974
+ *
1975
+ * **Process Flow:**
1259
1976
  * 1. Encrypts all client key shares with the provided password (or environment ID if no password)
1260
- * 2. Stores the encrypted key shares in Dynamic's backend
1261
- * 3. If Google Drive backup exists, updates the backup there as well
1262
- * 4. Updates the local wallet map with the new backup information
1263
- * 5. Persists the updated wallet map to storage
1977
+ * 2. For multi-share wallets (2+): conditionally distributes N-1 to backend, 1 to Google Drive
1978
+ * 3. For other configurations: stores all shares on Dynamic's backend
1979
+ * 4. Updates backup metadata and synchronizes wallet state
1980
+ * 5. Persists the updated wallet map to local storage
1981
+ *
1982
+ * **Delegated Key Shares:**
1983
+ * - When delegatedKeyshare is provided, the method will not store the delegated key share but it will mark the delegated share as backed up on Dynamic's backend
1984
+ * - and encrypt the delegated key share to publish it to the webhook
1264
1985
  *
1265
- * @param {Object} params - The parameters for the backup operation
1266
- * @param {string} params.accountAddress - The account address of the wallet to backup
1267
- * @param {string} [params.password] - Optional password for encrypting the key shares
1268
- */ async storeEncryptedBackupByWallet({ accountAddress, clientKeyShares = undefined, password = undefined }) {
1986
+ * @param params - The backup operation parameters
1987
+ * @param params.accountAddress - The account address of the wallet to backup
1988
+ * @param params.clientKeyShares - Optional specific key shares to backup (uses localStorage if not provided)
1989
+ * @param params.password - Optional password for encryption (uses environment ID if not provided)
1990
+ * @param params.signedSessionId - Optional signed session ID for authentication
1991
+ * @param params.backupToGoogleDrive - Whether to backup to Google Drive (defaults to false)
1992
+ * @returns Promise with backup metadata including share locations and IDs
1993
+ */ async storeEncryptedBackupByWallet({ accountAddress, clientKeyShares = undefined, password = undefined, signedSessionId, backupToGoogleDrive = false, delegatedKeyshare = undefined }) {
1994
+ var _this_walletMap_accountAddress, _this_walletMap_accountAddress1;
1269
1995
  const keySharesToBackup = clientKeyShares != null ? clientKeyShares : await this.getClientKeySharesFromLocalStorage({
1270
1996
  accountAddress
1271
1997
  });
1272
- const encryptedKeyShares = await Promise.all(keySharesToBackup.map((keyShare)=>this.encryptKeyShare({
1273
- keyShare,
1274
- password
1275
- })));
1276
- if (!this.walletMap[accountAddress].walletId) {
1277
- throw new Error(`WalletId not found for accountAddress: ${accountAddress}`);
1278
- }
1279
- const data = await this.apiClient.storeEncryptedBackupByWallet({
1280
- walletId: this.walletMap[accountAddress].walletId,
1281
- encryptedKeyShares,
1282
- passwordEncrypted: Boolean(password) && password !== this.environmentId
1283
- });
1284
- const hasGoogleDriveBackup = this.walletMap[accountAddress].clientKeySharesBackupInfo.backups[core.BackupLocation.GOOGLE_DRIVE].length > 0;
1285
- if (hasGoogleDriveBackup) {
1286
- const googleDriveKeyShareIds = await this.backupKeySharesToGoogleDrive({
1287
- accountAddress,
1288
- password
1998
+ const shouldBackupToGoogleDrive = backupToGoogleDrive || hasGoogleDriveBackup((_this_walletMap_accountAddress = this.walletMap[accountAddress]) == null ? void 0 : _this_walletMap_accountAddress.clientKeySharesBackupInfo);
1999
+ const hasExistingDelegation = hasDelegatedBackup((_this_walletMap_accountAddress1 = this.walletMap[accountAddress]) == null ? void 0 : _this_walletMap_accountAddress1.clientKeySharesBackupInfo);
2000
+ let distribution;
2001
+ let preserveDelegatedLocation = false;
2002
+ if (delegatedKeyshare && shouldBackupToGoogleDrive) {
2003
+ // NEW delegation + Google Drive: Client's shares back up to both Dynamic and Google Drive.
2004
+ // The delegated share goes to the webhook.
2005
+ distribution = createDelegationWithGoogleDriveDistribution({
2006
+ existingShares: keySharesToBackup,
2007
+ delegatedShare: delegatedKeyshare
1289
2008
  });
1290
- data.keyShares.push({
1291
- backupLocation: core.BackupLocation.GOOGLE_DRIVE,
1292
- id: googleDriveKeyShareIds
2009
+ } else if (delegatedKeyshare) {
2010
+ // NEW delegation only: Client's shares back up to Dynamic.
2011
+ // The delegated share goes to the webhook. No Google Drive backup.
2012
+ distribution = createDelegationOnlyDistribution({
2013
+ existingShares: keySharesToBackup,
2014
+ delegatedShare: delegatedKeyshare
2015
+ });
2016
+ } else if (hasExistingDelegation && shouldBackupToGoogleDrive) {
2017
+ // ADD Google Drive to EXISTING delegation: Client's share backs up to both Dynamic and GD.
2018
+ // Don't re-publish delegated share, just preserve the location.
2019
+ distribution = createAddGoogleDriveToExistingDelegationDistribution({
2020
+ clientShares: keySharesToBackup
2021
+ });
2022
+ preserveDelegatedLocation = true;
2023
+ } else if (shouldBackupToGoogleDrive && keySharesToBackup.length >= 2) {
2024
+ // Google Drive only (no delegation): Split shares between Dynamic (N-1) and Google Drive (1).
2025
+ distribution = createGoogleDriveOnlyDistribution({
2026
+ allShares: keySharesToBackup
2027
+ });
2028
+ } else {
2029
+ // No delegation, no Google Drive: All shares go to Dynamic backend only.
2030
+ distribution = createDynamicOnlyDistribution({
2031
+ allShares: keySharesToBackup
1293
2032
  });
1294
2033
  }
1295
- const updatedBackupInfo = getClientKeyShareBackupInfo({
1296
- walletProperties: {
1297
- derivationPath: this.walletMap[accountAddress].derivationPath,
1298
- keyShares: data.keyShares,
1299
- thresholdSignatureScheme: this.walletMap[accountAddress].thresholdSignatureScheme
1300
- }
2034
+ const backupData = await this.backupSharesWithDistribution({
2035
+ accountAddress,
2036
+ password,
2037
+ signedSessionId,
2038
+ distribution,
2039
+ preserveDelegatedLocation
1301
2040
  });
1302
- this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
1303
- clientKeySharesBackupInfo: updatedBackupInfo
2041
+ return _extends({}, backupData, {
2042
+ keyShareIds: backupData.locationsWithKeyShares.map((ks)=>ks.keyShareId)
1304
2043
  });
1305
- await this.storage.setItem(this.storageKey, JSON.stringify(this.walletMap));
1306
- return data;
1307
2044
  }
1308
- async storeEncryptedBackupByWalletWithRetry({ accountAddress, clientKeyShares, password }) {
2045
+ async storeEncryptedBackupByWalletWithRetry({ accountAddress, clientKeyShares, password, signedSessionId }) {
1309
2046
  await retryPromise(()=>this.storeEncryptedBackupByWallet({
1310
2047
  accountAddress,
1311
2048
  clientKeyShares,
1312
- password
2049
+ password,
2050
+ signedSessionId
1313
2051
  }), {
1314
2052
  operationName: 'store encrypted backup',
1315
2053
  logContext: {
1316
- walletAddress: accountAddress,
1317
- keyShares: clientKeyShares == null ? void 0 : clientKeyShares.map((keyShare)=>this.encryptKeyShare({
1318
- keyShare,
1319
- password
1320
- }))
2054
+ walletAddress: accountAddress
1321
2055
  }
1322
2056
  });
1323
2057
  }
1324
- async updatePassword({ accountAddress, existingPassword, newPassword }) {
2058
+ async updatePassword({ accountAddress, existingPassword, newPassword, signedSessionId }) {
1325
2059
  await this.getWallet({
1326
2060
  accountAddress,
1327
2061
  password: existingPassword,
1328
- walletOperation: core.WalletOperation.REACH_ALL_PARTIES
2062
+ walletOperation: core.WalletOperation.REACH_ALL_PARTIES,
2063
+ signedSessionId
1329
2064
  });
1330
2065
  await this.storeEncryptedBackupByWallet({
1331
2066
  accountAddress,
1332
- password: newPassword
2067
+ password: newPassword,
2068
+ signedSessionId
1333
2069
  });
1334
2070
  }
1335
2071
  async decryptKeyShare({ keyShare, password }) {
@@ -1347,16 +2083,34 @@ class DynamicWalletClient {
1347
2083
  * @returns The Google OAuth Account ID
1348
2084
  * @throws Error if no Google OAuth account ID is found
1349
2085
  */ async getGoogleOauthAccountIdOrThrow(accountAddress) {
1350
- const user = await this.apiClient.getUser();
1351
- const oauthAccountId = getGoogleOAuthAccountId(user == null ? void 0 : user.verifiedCredentials);
1352
- if (!oauthAccountId) {
1353
- this.logger.error('No Google OAuth account ID found', {
1354
- user,
1355
- accountAddress
2086
+ const dynamicRequestId = uuid.v4();
2087
+ try {
2088
+ const user = await this.apiClient.getUser(dynamicRequestId);
2089
+ const oauthAccountId = getGoogleOAuthAccountId(user == null ? void 0 : user.verifiedCredentials);
2090
+ if (!oauthAccountId) {
2091
+ const error = new Error('No Google OAuth account ID found');
2092
+ logError({
2093
+ message: 'No Google OAuth account ID found',
2094
+ error,
2095
+ context: {
2096
+ user,
2097
+ accountAddress
2098
+ }
2099
+ });
2100
+ throw error;
2101
+ }
2102
+ return oauthAccountId;
2103
+ } catch (error) {
2104
+ logError({
2105
+ message: 'Error in getGoogleOauthAccountIdOrThrow',
2106
+ error: error,
2107
+ context: {
2108
+ accountAddress,
2109
+ dynamicRequestId
2110
+ }
1356
2111
  });
1357
- throw new Error('No Google OAuth account ID found');
2112
+ throw error;
1358
2113
  }
1359
- return oauthAccountId;
1360
2114
  }
1361
2115
  /**
1362
2116
  * Helper function to determine keyshare recovery strategy for dynamic shares.
@@ -1380,39 +2134,58 @@ class DynamicWalletClient {
1380
2134
  const dynamicShares = backups[core.BackupLocation.DYNAMIC].slice(0, requiredShareCount);
1381
2135
  return {
1382
2136
  shares: {
1383
- [core.BackupLocation.DYNAMIC]: dynamicShares
2137
+ [core.BackupLocation.DYNAMIC]: dynamicShares.map((ks)=>{
2138
+ var _ks_externalKeyShareId, _ref;
2139
+ return (_ref = (_ks_externalKeyShareId = ks.externalKeyShareId) != null ? _ks_externalKeyShareId : ks.keyShareId) != null ? _ref : '';
2140
+ })
1384
2141
  },
1385
2142
  requiredShareCount
1386
2143
  };
1387
2144
  }
1388
- async recoverEncryptedBackupByWallet({ accountAddress, password, walletOperation, shareCount = undefined, storeRecoveredShares = true }) {
1389
- const wallet = this.walletMap[accountAddress];
1390
- this.logger.debug(`recoverEncryptedBackupByWallet wallet: ${walletOperation}`, wallet);
1391
- const { shares } = this.recoverStrategy({
1392
- clientKeyShareBackupInfo: wallet.clientKeySharesBackupInfo,
1393
- thresholdSignatureScheme: wallet.thresholdSignatureScheme,
1394
- walletOperation,
1395
- shareCount
1396
- });
1397
- const { dynamic: dynamicKeyShareIds } = shares;
1398
- const data = await this.apiClient.recoverEncryptedBackupByWallet({
1399
- walletId: wallet.walletId,
1400
- keyShareIds: dynamicKeyShareIds
1401
- });
1402
- const dynamicKeyShares = data.keyShares.filter((keyShare)=>keyShare.encryptedAccountCredential !== null && keyShare.backupLocation === core.BackupLocation.DYNAMIC);
1403
- const decryptedKeyShares = await Promise.all(dynamicKeyShares.map((keyShare)=>this.decryptKeyShare({
1404
- keyShare: keyShare.encryptedAccountCredential,
1405
- password: password != null ? password : this.environmentId
1406
- })));
1407
- if (storeRecoveredShares) {
1408
- await this.setClientKeySharesToLocalStorage({
1409
- accountAddress,
1410
- clientKeyShares: decryptedKeyShares,
1411
- overwriteOrMerge: 'merge'
2145
+ async recoverEncryptedBackupByWallet({ accountAddress, password, walletOperation, signedSessionId, shareCount = undefined, storeRecoveredShares = true, mfaToken }) {
2146
+ try {
2147
+ const wallet = this.walletMap[accountAddress];
2148
+ this.logger.debug(`recoverEncryptedBackupByWallet wallet: ${walletOperation}`, wallet);
2149
+ const { shares } = this.recoverStrategy({
2150
+ clientKeyShareBackupInfo: wallet.clientKeySharesBackupInfo,
2151
+ thresholdSignatureScheme: wallet.thresholdSignatureScheme,
2152
+ walletOperation,
2153
+ shareCount
1412
2154
  });
1413
- await this.storage.setItem(this.storageKey, JSON.stringify(this.walletMap));
2155
+ const { dynamic: dynamicKeyShareIds } = shares;
2156
+ const data = await this.apiClient.recoverEncryptedBackupByWallet({
2157
+ walletId: wallet.walletId,
2158
+ keyShareIds: dynamicKeyShareIds,
2159
+ signedSessionId,
2160
+ mfaToken,
2161
+ requiresSignedSessionId: this.requiresSignedSessionId()
2162
+ });
2163
+ const dynamicKeyShares = data.keyShares.filter((keyShare)=>keyShare.encryptedAccountCredential !== null && keyShare.backupLocation === core.BackupLocation.DYNAMIC);
2164
+ const decryptedKeyShares = await Promise.all(dynamicKeyShares.map((keyShare)=>this.decryptKeyShare({
2165
+ keyShare: keyShare.encryptedAccountCredential,
2166
+ password: password != null ? password : this.environmentId
2167
+ })));
2168
+ if (storeRecoveredShares) {
2169
+ await this.setClientKeySharesToLocalStorage({
2170
+ accountAddress,
2171
+ clientKeyShares: decryptedKeyShares,
2172
+ overwriteOrMerge: 'merge'
2173
+ });
2174
+ await this.storage.setItem(this.storageKey, JSON.stringify(this.walletMap));
2175
+ }
2176
+ return decryptedKeyShares;
2177
+ } catch (error) {
2178
+ logError({
2179
+ message: 'Error in recoverEncryptedBackupByWallet',
2180
+ error: error,
2181
+ context: {
2182
+ accountAddress,
2183
+ walletOperation,
2184
+ shareCount
2185
+ }
2186
+ });
2187
+ throw error;
1414
2188
  }
1415
- return decryptedKeyShares;
1416
2189
  }
1417
2190
  async restoreWallets() {
1418
2191
  const wallets = await this.storage.getItem(this.storageKey);
@@ -1421,117 +2194,207 @@ class DynamicWalletClient {
1421
2194
  }
1422
2195
  this.walletMap = JSON.parse(wallets);
1423
2196
  }
1424
- async backupKeySharesToGoogleDrive({ accountAddress, password }) {
1425
- await this.getWallet({
1426
- accountAddress,
1427
- walletOperation: core.WalletOperation.REACH_ALL_PARTIES,
1428
- password
1429
- });
1430
- const clientKeyShares = await this.getClientKeySharesFromLocalStorage({
1431
- accountAddress
1432
- });
1433
- if (clientKeyShares.length === 0) {
1434
- throw new Error('No key shares found');
2197
+ /**
2198
+ * This method handles the complete flow for ensuring wallet key shares are backed up to Google Drive:
2199
+ * - For 2-of-2 wallets: Automatically reshares to 2-of-3 threshold, then distributes shares (1 to backend, 1 to Google Drive)
2200
+ * - For 2-of-3 wallets: Call storeEncryptedBackupByWallet to backup for backend and Google Drive
2201
+ *
2202
+ * @param params - The backup parameters
2203
+ * @param params.accountAddress - The wallet account address to backup
2204
+ * @param params.password - Optional password for encryption (uses environment ID if not provided)
2205
+ * @param params.signedSessionId - Optional signed session ID for authentication
2206
+ * @returns Promise<string[]> - Array of Google Drive key share IDs that were backed up
2207
+ */ async backupKeySharesToGoogleDrive({ accountAddress, password, signedSessionId }) {
2208
+ try {
2209
+ await this.getWallet({
2210
+ accountAddress,
2211
+ walletOperation: core.WalletOperation.REACH_ALL_PARTIES,
2212
+ password,
2213
+ signedSessionId
2214
+ });
2215
+ const currentThresholdSignatureScheme = this.walletMap[accountAddress].thresholdSignatureScheme;
2216
+ if (currentThresholdSignatureScheme === core.ThresholdSignatureScheme.TWO_OF_TWO) {
2217
+ // Reshare to 2-of-3, which will automatically handle the backup distribution
2218
+ await this.reshare({
2219
+ chainName: this.walletMap[accountAddress].chainName,
2220
+ accountAddress,
2221
+ oldThresholdSignatureScheme: currentThresholdSignatureScheme,
2222
+ newThresholdSignatureScheme: core.ThresholdSignatureScheme.TWO_OF_THREE,
2223
+ password,
2224
+ signedSessionId,
2225
+ backupToGoogleDrive: true
2226
+ });
2227
+ const backupInfo = this.walletMap[accountAddress].clientKeySharesBackupInfo;
2228
+ const googleDriveShares = backupInfo.backups[core.BackupLocation.GOOGLE_DRIVE] || [];
2229
+ return googleDriveShares.map((ks)=>{
2230
+ var _ks_externalKeyShareId;
2231
+ return (_ks_externalKeyShareId = ks.externalKeyShareId) != null ? _ks_externalKeyShareId : '';
2232
+ });
2233
+ } else {
2234
+ await this.storeEncryptedBackupByWallet({
2235
+ accountAddress,
2236
+ password,
2237
+ signedSessionId,
2238
+ backupToGoogleDrive: true
2239
+ });
2240
+ const backupInfo = this.walletMap[accountAddress].clientKeySharesBackupInfo;
2241
+ const googleDriveShares = backupInfo.backups[core.BackupLocation.GOOGLE_DRIVE] || [];
2242
+ return googleDriveShares.map((ks)=>{
2243
+ var _ks_externalKeyShareId;
2244
+ return (_ks_externalKeyShareId = ks.externalKeyShareId) != null ? _ks_externalKeyShareId : '';
2245
+ });
2246
+ }
2247
+ } catch (error) {
2248
+ logError({
2249
+ message: 'Error in backupKeySharesToGoogleDrive',
2250
+ error: error,
2251
+ context: {
2252
+ accountAddress
2253
+ }
2254
+ });
2255
+ throw error;
1435
2256
  }
1436
- const encryptedKeyShares = await Promise.all(clientKeyShares.map((keyShare)=>this.encryptKeyShare({
1437
- keyShare,
1438
- password
1439
- })));
1440
- const oauthAccountId = await this.getGoogleOauthAccountIdOrThrow(accountAddress);
1441
- const accessToken = await this.apiClient.getAccessToken({
1442
- oauthAccountId
1443
- });
1444
- const thresholdSignatureScheme = this.walletMap[accountAddress].thresholdSignatureScheme;
1445
- const fileName = getClientKeyShareExportFileName({
1446
- thresholdSignatureScheme,
1447
- accountAddress
1448
- });
1449
- const backupData = createBackupData({
1450
- encryptedKeyShares,
1451
- accountAddress,
1452
- thresholdSignatureScheme
1453
- });
1454
- await uploadBackupToGoogleDrive({
1455
- accessToken,
1456
- fileName,
1457
- backupData,
1458
- accountAddress
1459
- });
1460
- const data = await this.apiClient.markKeySharesAsBackedUpGoogleDrive({
1461
- walletId: this.walletMap[accountAddress].walletId
1462
- });
1463
- await updateWalletMapWithBackupInfo({
1464
- data,
1465
- walletMap: this.walletMap,
1466
- accountAddress,
1467
- storage: this.storage,
1468
- storageKey: this.storageKey
1469
- });
1470
2257
  }
1471
- async restoreBackupFromGoogleDrive({ accountAddress, displayContainer, password }) {
1472
- await this.getWallet({
1473
- accountAddress
1474
- });
1475
- const oauthAccountId = await this.getGoogleOauthAccountIdOrThrow(accountAddress);
1476
- const accessToken = await this.apiClient.getAccessToken({
1477
- oauthAccountId
1478
- });
1479
- const thresholdSignatureScheme = this.walletMap[accountAddress].thresholdSignatureScheme;
1480
- const fileName = getClientKeyShareExportFileName({
1481
- thresholdSignatureScheme,
1482
- accountAddress
1483
- });
1484
- let backupData = null;
2258
+ /**
2259
+ * This method handles only the Google Drive upload mechanics without any reshare logic.
2260
+ * It encrypts the provided key shares, uploads them to Google Drive, and updates the
2261
+ * backup metadata. This method is intended for internal use by storeEncryptedBackupByWallet
2262
+ * and should not be called directly from external code.
2263
+ *
2264
+ * @param params - The upload parameters
2265
+ * @param params.accountAddress - The wallet account address
2266
+ * @param params.password - Optional password for encryption (uses environment ID if not provided)
2267
+ * @param params.encryptedKeyShares - The specific key shares to upload to Google Drive
2268
+ * @returns Promise<string[]> - Array of Google Drive key share IDs that were uploaded
2269
+ */ async uploadKeySharesToGoogleDrive({ accountAddress, encryptedKeyShares }) {
1485
2270
  try {
1486
- backupData = await retryPromise(()=>downloadFileFromGoogleDrive({
1487
- accessToken,
1488
- fileName
1489
- }));
1490
- } catch (error) {
1491
- this.logger.error('Failed to download backup from Google Drive', {
2271
+ if (encryptedKeyShares.length === 0) {
2272
+ throw new Error('No key shares found');
2273
+ }
2274
+ const oauthAccountId = await this.getGoogleOauthAccountIdOrThrow(accountAddress);
2275
+ const accessToken = await this.apiClient.getAccessToken({
2276
+ oauthAccountId
2277
+ });
2278
+ const thresholdSignatureScheme = this.walletMap[accountAddress].thresholdSignatureScheme;
2279
+ const fileName = getClientKeyShareExportFileName({
2280
+ thresholdSignatureScheme,
2281
+ accountAddress,
2282
+ isGoogleDrive: true
2283
+ });
2284
+ const backupData = createBackupData({
2285
+ encryptedKeyShares,
1492
2286
  accountAddress,
2287
+ thresholdSignatureScheme
2288
+ });
2289
+ await uploadBackupToGoogleDrive({
2290
+ accessToken,
1493
2291
  fileName,
1494
- error
2292
+ backupData,
2293
+ accountAddress
2294
+ });
2295
+ return;
2296
+ } catch (error) {
2297
+ logError({
2298
+ message: 'Error in backupKeySharesToGoogleDrive',
2299
+ error: error,
2300
+ context: {
2301
+ accountAddress
2302
+ }
1495
2303
  });
1496
- throw new Error('Failed to restore backup from Google Drive');
2304
+ throw error;
1497
2305
  }
1498
- if (!backupData) {
1499
- this.logger.error('No backup file found', {
2306
+ }
2307
+ async exportClientKeysharesFromGoogleDrive({ accountAddress, password, signedSessionId }) {
2308
+ try {
2309
+ await this.getWallet({
1500
2310
  accountAddress,
1501
- fileName
2311
+ signedSessionId
1502
2312
  });
1503
- throw new Error('No backup file found');
1504
- }
1505
- // Validate the backup data structure
1506
- if (!backupData.keyShares || !backupData.metadata) {
1507
- this.logger.error('Invalid backup format: missing keyShares or metadata', {
2313
+ const oauthAccountId = await this.getGoogleOauthAccountIdOrThrow(accountAddress);
2314
+ const accessToken = await this.apiClient.getAccessToken({
2315
+ oauthAccountId
2316
+ });
2317
+ const thresholdSignatureScheme = this.walletMap[accountAddress].thresholdSignatureScheme;
2318
+ const backupFileName = getClientKeyShareExportFileName({
2319
+ thresholdSignatureScheme,
2320
+ accountAddress,
2321
+ isGoogleDrive: true
2322
+ });
2323
+ let backupData = null;
2324
+ try {
2325
+ backupData = await retryPromise(()=>downloadFileFromGoogleDrive({
2326
+ accessToken,
2327
+ fileName: backupFileName
2328
+ }));
2329
+ } catch (error) {
2330
+ logError({
2331
+ message: 'Failed to download backup from Google Drive',
2332
+ error: error,
2333
+ context: {
2334
+ accountAddress,
2335
+ fileName: backupFileName
2336
+ }
2337
+ });
2338
+ throw error;
2339
+ }
2340
+ if (!backupData) {
2341
+ const error = new Error('No backup file found');
2342
+ logError({
2343
+ message: 'No backup file found',
2344
+ error: new Error('No backup file found'),
2345
+ context: {
2346
+ accountAddress,
2347
+ fileName: backupFileName
2348
+ }
2349
+ });
2350
+ throw error;
2351
+ }
2352
+ // Validate the backup data structure
2353
+ if (!backupData.keyShares || !backupData.metadata) {
2354
+ const error = new Error('Invalid backup format: missing keyShares or metadata');
2355
+ logError({
2356
+ message: 'Invalid backup format: missing keyShares or metadata',
2357
+ error,
2358
+ context: {
2359
+ accountAddress,
2360
+ fileName: backupFileName
2361
+ }
2362
+ });
2363
+ throw error;
2364
+ }
2365
+ const { keyShares } = backupData;
2366
+ const decryptedKeyShares = await Promise.all(keyShares.map((keyShare)=>this.decryptKeyShare({
2367
+ keyShare,
2368
+ password
2369
+ })));
2370
+ const text = JSON.stringify(decryptedKeyShares, null, 2);
2371
+ const exportFileName = getClientKeyShareExportFileName({
2372
+ thresholdSignatureScheme,
1508
2373
  accountAddress,
1509
- fileName
2374
+ isGoogleDrive: true
2375
+ });
2376
+ downloadStringAsFile({
2377
+ filename: exportFileName,
2378
+ content: text,
2379
+ mimeType: 'application/json'
1510
2380
  });
1511
- throw new Error('Invalid backup format: missing keyShares or metadata');
2381
+ } catch (error) {
2382
+ logError({
2383
+ message: 'Error in exportClientKeysharesFromGoogleDrive',
2384
+ error: error,
2385
+ context: {
2386
+ accountAddress
2387
+ }
2388
+ });
2389
+ throw error;
1512
2390
  }
1513
- const { keyShares } = backupData;
1514
- const decryptedKeyShares = await Promise.all(keyShares.map((keyShare)=>this.decryptKeyShare({
1515
- keyShare,
1516
- password
1517
- })));
1518
- await this.setClientKeySharesToLocalStorage({
1519
- accountAddress,
1520
- clientKeyShares: decryptedKeyShares,
1521
- overwriteOrMerge: 'merge'
1522
- });
1523
- // Display the client shares in the container via iframe
1524
- const { iframeDisplay } = await this.initializeIframeDisplayForContainer({
1525
- container: displayContainer
1526
- });
1527
- iframeDisplay.displayClientShares(keyShares);
1528
- return decryptedKeyShares;
1529
2391
  }
1530
- async exportClientKeyshares({ accountAddress, password }) {
2392
+ async exportClientKeyshares({ accountAddress, password, signedSessionId }) {
1531
2393
  await this.verifyPassword({
1532
2394
  accountAddress,
1533
2395
  password,
1534
- walletOperation: core.WalletOperation.REACH_ALL_PARTIES
2396
+ walletOperation: core.WalletOperation.REACH_ALL_PARTIES,
2397
+ signedSessionId
1535
2398
  });
1536
2399
  const clientKeyShares = await this.getClientKeySharesFromLocalStorage({
1537
2400
  accountAddress
@@ -1544,22 +2407,18 @@ class DynamicWalletClient {
1544
2407
  keyShares: clientKeyShares,
1545
2408
  derivationPath
1546
2409
  });
1547
- const blob = new Blob([
1548
- text
1549
- ], {
1550
- type: 'text/plain'
2410
+ downloadStringAsFile({
2411
+ filename: `${CLIENT_KEYSHARE_EXPORT_FILENAME_PREFIX}-${accountAddress}.txt`,
2412
+ content: text,
2413
+ mimeType: 'text/plain'
1551
2414
  });
1552
- const url = URL.createObjectURL(blob);
1553
- const a = document.createElement('a');
1554
- a.href = url;
1555
- a.download = `${CLIENT_KEYSHARE_EXPORT_FILENAME_PREFIX}-${accountAddress}.txt`;
1556
- a.click();
1557
2415
  }
1558
- async getClientKeyShares({ accountAddress, password }) {
2416
+ async getClientKeyShares({ accountAddress, password, signedSessionId }) {
1559
2417
  await this.getWallet({
1560
2418
  accountAddress,
1561
2419
  password,
1562
- walletOperation: core.WalletOperation.REACH_THRESHOLD
2420
+ walletOperation: core.WalletOperation.REACH_THRESHOLD,
2421
+ signedSessionId
1563
2422
  });
1564
2423
  return this.getClientKeySharesFromLocalStorage({
1565
2424
  accountAddress
@@ -1612,11 +2471,12 @@ class DynamicWalletClient {
1612
2471
  * verifyPassword attempts to recover and decrypt a single client key share using the provided password.
1613
2472
  * If successful, the key share is encrypted with the new password. This method solely performs the recovery
1614
2473
  * and decryption without storing the restored key shares. If unsuccessful, it throws an error.
1615
- */ async verifyPassword({ accountAddress, password = undefined, walletOperation = core.WalletOperation.NO_OPERATION }) {
2474
+ */ async verifyPassword({ accountAddress, password = undefined, walletOperation = core.WalletOperation.NO_OPERATION, signedSessionId }) {
1616
2475
  await this.getWallet({
1617
2476
  accountAddress,
1618
2477
  password,
1619
- walletOperation
2478
+ walletOperation,
2479
+ signedSessionId
1620
2480
  });
1621
2481
  if (await this.requiresPasswordForOperation({
1622
2482
  accountAddress,
@@ -1636,16 +2496,24 @@ class DynamicWalletClient {
1636
2496
  throw new Error('No dynamic key shares found');
1637
2497
  }
1638
2498
  try {
2499
+ // TODO(zfaizal2): throw error if signedSessionId is not provided after service deploy
1639
2500
  await this.recoverEncryptedBackupByWallet({
1640
2501
  accountAddress,
1641
2502
  password,
1642
2503
  walletOperation,
1643
2504
  shareCount: 1,
1644
- storeRecoveredShares: false
2505
+ storeRecoveredShares: false,
2506
+ signedSessionId
1645
2507
  });
1646
2508
  } catch (error) {
1647
- this.logger.error('Error in verifying password', error);
1648
- throw new Error('Incorrect password');
2509
+ logError({
2510
+ message: 'Error in verifyPassword',
2511
+ error: error,
2512
+ context: {
2513
+ accountAddress
2514
+ }
2515
+ });
2516
+ throw error;
1649
2517
  }
1650
2518
  }
1651
2519
  async isPasswordEncrypted({ accountAddress }) {
@@ -1691,127 +2559,204 @@ class DynamicWalletClient {
1691
2559
  return true;
1692
2560
  }
1693
2561
  async getWalletClientKeyShareBackupInfo({ accountAddress }) {
1694
- var _this_walletMap_accountAddress_clientKeySharesBackupInfo_backups_BackupLocation_DYNAMIC, _this_walletMap_accountAddress_clientKeySharesBackupInfo_backups, _this_walletMap_accountAddress_clientKeySharesBackupInfo, _this_walletMap_accountAddress, _user_verifiedCredentials;
1695
- // Return existing backup info if it exists
1696
- if (((_this_walletMap_accountAddress = this.walletMap[accountAddress]) == null ? void 0 : (_this_walletMap_accountAddress_clientKeySharesBackupInfo = _this_walletMap_accountAddress.clientKeySharesBackupInfo) == null ? void 0 : (_this_walletMap_accountAddress_clientKeySharesBackupInfo_backups = _this_walletMap_accountAddress_clientKeySharesBackupInfo.backups) == null ? void 0 : (_this_walletMap_accountAddress_clientKeySharesBackupInfo_backups_BackupLocation_DYNAMIC = _this_walletMap_accountAddress_clientKeySharesBackupInfo_backups[core.BackupLocation.DYNAMIC]) == null ? void 0 : _this_walletMap_accountAddress_clientKeySharesBackupInfo_backups_BackupLocation_DYNAMIC.length) > 0) {
1697
- return this.walletMap[accountAddress].clientKeySharesBackupInfo;
2562
+ const dynamicRequestId = uuid.v4();
2563
+ try {
2564
+ var _this_walletMap_accountAddress_clientKeySharesBackupInfo_backups_BackupLocation_DYNAMIC, _this_walletMap_accountAddress_clientKeySharesBackupInfo_backups, _this_walletMap_accountAddress_clientKeySharesBackupInfo, _this_walletMap_accountAddress, _user_verifiedCredentials;
2565
+ // Return existing backup info if it exists
2566
+ if (((_this_walletMap_accountAddress = this.walletMap[accountAddress]) == null ? void 0 : (_this_walletMap_accountAddress_clientKeySharesBackupInfo = _this_walletMap_accountAddress.clientKeySharesBackupInfo) == null ? void 0 : (_this_walletMap_accountAddress_clientKeySharesBackupInfo_backups = _this_walletMap_accountAddress_clientKeySharesBackupInfo.backups) == null ? void 0 : (_this_walletMap_accountAddress_clientKeySharesBackupInfo_backups_BackupLocation_DYNAMIC = _this_walletMap_accountAddress_clientKeySharesBackupInfo_backups[core.BackupLocation.DYNAMIC]) == null ? void 0 : _this_walletMap_accountAddress_clientKeySharesBackupInfo_backups_BackupLocation_DYNAMIC.length) > 0) {
2567
+ return this.walletMap[accountAddress].clientKeySharesBackupInfo;
2568
+ }
2569
+ // Get backup info from server
2570
+ const user = await this.apiClient.getUser(dynamicRequestId);
2571
+ const wallet = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.find((vc)=>vc.address.toLowerCase() === accountAddress.toLowerCase());
2572
+ return getClientKeyShareBackupInfo({
2573
+ walletProperties: wallet == null ? void 0 : wallet.walletProperties
2574
+ });
2575
+ } catch (error) {
2576
+ logError({
2577
+ message: 'Error in getWalletClientKeyShareBackupInfo',
2578
+ error: error,
2579
+ context: {
2580
+ accountAddress,
2581
+ dynamicRequestId
2582
+ }
2583
+ });
2584
+ throw error;
1698
2585
  }
1699
- // Get backup info from server
1700
- const user = await this.apiClient.getUser();
1701
- const wallet = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.find((vc)=>vc.address.toLowerCase() === accountAddress.toLowerCase());
1702
- return getClientKeyShareBackupInfo({
1703
- walletProperties: wallet == null ? void 0 : wallet.walletProperties
1704
- });
1705
2586
  }
1706
- async getWallet({ accountAddress, walletOperation = core.WalletOperation.NO_OPERATION, shareCount = undefined, password = undefined }) {
1707
- var _user_verifiedCredentials;
1708
- const existingWalletCheck = await this.checkWalletFields({
1709
- accountAddress,
1710
- walletOperation,
1711
- shareCount
1712
- });
1713
- if (existingWalletCheck) {
1714
- this.logger.debug(`Wallet ${accountAddress} already exists`);
1715
- return this.walletMap[accountAddress];
1716
- }
1717
- // Fetch and restore wallet from server
1718
- const user = await this.apiClient.getUser();
1719
- const wallet = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.find((vc)=>vc.address.toLowerCase() === accountAddress.toLowerCase());
1720
- this.logger.debug('Restoring wallet', wallet);
1721
- const walletProperties = wallet.walletProperties;
1722
- this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
1723
- walletId: wallet.id,
1724
- chainName: wallet.chainName,
1725
- accountAddress,
1726
- thresholdSignatureScheme: walletProperties.thresholdSignatureScheme,
1727
- derivationPath: walletProperties.derivationPath,
1728
- clientKeySharesBackupInfo: getClientKeyShareBackupInfo({
1729
- walletProperties
1730
- })
1731
- });
1732
- if (walletOperation !== core.WalletOperation.NO_OPERATION && await this.requiresRestoreBackupSharesForOperation({
1733
- accountAddress,
1734
- walletOperation
1735
- })) {
1736
- const decryptedKeyShares = await this.recoverEncryptedBackupByWallet({
2587
+ async getWallet({ accountAddress, walletOperation = core.WalletOperation.NO_OPERATION, shareCount = undefined, password = undefined, signedSessionId }) {
2588
+ const dynamicRequestId = uuid.v4();
2589
+ try {
2590
+ var _user_verifiedCredentials;
2591
+ const existingWalletCheck = await this.checkWalletFields({
1737
2592
  accountAddress,
1738
- password: password != null ? password : this.environmentId,
1739
- walletOperation: walletOperation,
2593
+ walletOperation,
1740
2594
  shareCount
1741
2595
  });
1742
- const existingKeyShares = await this.getClientKeySharesFromLocalStorage({
1743
- accountAddress
2596
+ if (existingWalletCheck) {
2597
+ this.logger.debug(`[DynamicWaasWalletClient] Wallet ${accountAddress} already exists`);
2598
+ return this.walletMap[accountAddress];
2599
+ }
2600
+ // Fetch and restore wallet from server
2601
+ const user = await this.apiClient.getUser(dynamicRequestId);
2602
+ const wallet = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.find((vc)=>vc.address.toLowerCase() === accountAddress.toLowerCase());
2603
+ this.logger.debug('[DynamicWaasWalletClient] Restoring wallet', wallet);
2604
+ const walletProperties = wallet.walletProperties;
2605
+ this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress], {
2606
+ walletId: wallet.id,
2607
+ chainName: core.verifiedCredentialNameToChainEnum[wallet.chain],
2608
+ accountAddress,
2609
+ thresholdSignatureScheme: walletProperties.thresholdSignatureScheme,
2610
+ derivationPath: walletProperties.derivationPath,
2611
+ clientKeySharesBackupInfo: getClientKeyShareBackupInfo({
2612
+ walletProperties
2613
+ })
1744
2614
  });
1745
- await this.setClientKeySharesToLocalStorage({
2615
+ if (walletOperation !== core.WalletOperation.NO_OPERATION && await this.requiresRestoreBackupSharesForOperation({
1746
2616
  accountAddress,
1747
- clientKeyShares: mergeUniqueKeyShares(existingKeyShares, decryptedKeyShares)
2617
+ walletOperation
2618
+ })) {
2619
+ // TODO(zfaizal2): throw error if signedSessionId is not provided after service deploy
2620
+ const decryptedKeyShares = await this.recoverEncryptedBackupByWallet({
2621
+ accountAddress,
2622
+ password: password != null ? password : this.environmentId,
2623
+ walletOperation: walletOperation,
2624
+ signedSessionId,
2625
+ shareCount
2626
+ });
2627
+ const existingKeyShares = await this.getClientKeySharesFromLocalStorage({
2628
+ accountAddress
2629
+ });
2630
+ await this.setClientKeySharesToLocalStorage({
2631
+ accountAddress,
2632
+ clientKeyShares: mergeUniqueKeyShares(existingKeyShares, decryptedKeyShares)
2633
+ });
2634
+ this.logger.debug('[DynamicWaasWalletClient] Recovered backup', decryptedKeyShares);
2635
+ }
2636
+ const walletCount = Object.keys(this.walletMap).length;
2637
+ if (walletCount === 0) {
2638
+ throw new Error('No wallets found');
2639
+ }
2640
+ // Return the only wallet if there's just one
2641
+ if (walletCount === 1) {
2642
+ return Object.values(this.walletMap)[0];
2643
+ }
2644
+ return this.walletMap[accountAddress];
2645
+ } catch (error) {
2646
+ logError({
2647
+ message: 'Error in getWallet',
2648
+ error: error,
2649
+ context: {
2650
+ accountAddress,
2651
+ walletOperation,
2652
+ shareCount,
2653
+ dynamicRequestId
2654
+ }
1748
2655
  });
1749
- this.logger.debug('Recovered backup', decryptedKeyShares);
1750
- }
1751
- const walletCount = Object.keys(this.walletMap).length;
1752
- if (walletCount === 0) {
1753
- throw new Error('No wallets found');
1754
- }
1755
- // Return the only wallet if there's just one
1756
- if (walletCount === 1) {
1757
- return Object.values(this.walletMap)[0];
2656
+ throw error;
1758
2657
  }
1759
- return this.walletMap[accountAddress];
1760
2658
  }
1761
2659
  async getWallets() {
1762
- var _user_verifiedCredentials;
1763
- const user = await this.apiClient.getUser();
1764
- const waasWallets = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.filter((vc)=>vc.walletName === 'dynamicwaas');
1765
- const wallets = waasWallets.map((vc)=>{
1766
- var _this_walletMap_vc_address, _vc_walletProperties;
1767
- var _this_walletMap_vc_address_derivationPath;
1768
- return {
1769
- walletId: vc.id,
1770
- chainName: vc.chain,
1771
- accountAddress: vc.address,
1772
- clientKeySharesBackupInfo: getClientKeyShareBackupInfo({
1773
- walletProperties: vc.walletProperties || {}
1774
- }),
1775
- derivationPath: (_this_walletMap_vc_address_derivationPath = (_this_walletMap_vc_address = this.walletMap[vc.address]) == null ? void 0 : _this_walletMap_vc_address.derivationPath) != null ? _this_walletMap_vc_address_derivationPath : undefined,
1776
- thresholdSignatureScheme: (_vc_walletProperties = vc.walletProperties) == null ? void 0 : _vc_walletProperties.thresholdSignatureScheme
1777
- };
1778
- });
1779
- this.walletMap = wallets.reduce((acc, wallet)=>{
1780
- var _acc_accountAddress;
1781
- const accountAddress = wallet.accountAddress;
1782
- acc[wallet.accountAddress] = {
1783
- walletId: wallet.walletId,
1784
- chainName: wallet.chainName,
1785
- accountAddress: wallet.accountAddress,
1786
- clientKeySharesBackupInfo: wallet.clientKeySharesBackupInfo,
1787
- derivationPath: ((_acc_accountAddress = acc[accountAddress]) == null ? void 0 : _acc_accountAddress.derivationPath) || undefined,
1788
- thresholdSignatureScheme: wallet.thresholdSignatureScheme
1789
- };
1790
- return acc;
1791
- }, {});
1792
- return wallets;
2660
+ const dynamicRequestId = uuid.v4();
2661
+ try {
2662
+ var _user_verifiedCredentials;
2663
+ const user = await this.apiClient.getUser(dynamicRequestId);
2664
+ this.userId = user.id;
2665
+ const waasWallets = (_user_verifiedCredentials = user.verifiedCredentials) == null ? void 0 : _user_verifiedCredentials.filter((vc)=>vc.walletName === 'dynamicwaas');
2666
+ const wallets = waasWallets.map((vc)=>{
2667
+ var _this_walletMap_vc_address, _vc_walletProperties;
2668
+ var _this_walletMap_vc_address_derivationPath;
2669
+ return {
2670
+ walletId: vc.id,
2671
+ chainName: vc.chain,
2672
+ accountAddress: vc.address,
2673
+ clientKeySharesBackupInfo: getClientKeyShareBackupInfo({
2674
+ walletProperties: vc.walletProperties || {}
2675
+ }),
2676
+ derivationPath: (_this_walletMap_vc_address_derivationPath = (_this_walletMap_vc_address = this.walletMap[vc.address]) == null ? void 0 : _this_walletMap_vc_address.derivationPath) != null ? _this_walletMap_vc_address_derivationPath : undefined,
2677
+ thresholdSignatureScheme: (_vc_walletProperties = vc.walletProperties) == null ? void 0 : _vc_walletProperties.thresholdSignatureScheme
2678
+ };
2679
+ });
2680
+ this.walletMap = wallets.reduce((acc, wallet)=>{
2681
+ var _acc_accountAddress;
2682
+ const accountAddress = wallet.accountAddress;
2683
+ acc[wallet.accountAddress] = {
2684
+ walletId: wallet.walletId,
2685
+ chainName: wallet.chainName,
2686
+ accountAddress: wallet.accountAddress,
2687
+ clientKeySharesBackupInfo: wallet.clientKeySharesBackupInfo,
2688
+ derivationPath: ((_acc_accountAddress = acc[accountAddress]) == null ? void 0 : _acc_accountAddress.derivationPath) || undefined,
2689
+ thresholdSignatureScheme: wallet.thresholdSignatureScheme
2690
+ };
2691
+ return acc;
2692
+ }, {});
2693
+ return wallets;
2694
+ } catch (error) {
2695
+ logError({
2696
+ message: 'Error in getWallets',
2697
+ error: error,
2698
+ context: {
2699
+ dynamicRequestId
2700
+ }
2701
+ });
2702
+ throw error;
2703
+ }
2704
+ }
2705
+ /**
2706
+ * sync auth token with api client
2707
+ * @param authToken - auth token to sync
2708
+ */ syncAuthToken(authToken) {
2709
+ if (this.authMode === core.AuthMode.COOKIE) {
2710
+ return;
2711
+ }
2712
+ this.apiClient.syncAuthToken(authToken);
1793
2713
  }
1794
- constructor({ environmentId, authToken, baseApiUrl, baseMPCRelayApiUrl, storageKey, debug }){
2714
+ /**
2715
+ * Helper method to instrument with automatic properties inclusion
2716
+ */ instrument(message, context) {
2717
+ const defaultContext = {
2718
+ environmentId: context.environmentId || this.environmentId
2719
+ };
2720
+ this.logger.debug(message, _extends({}, defaultContext, context));
2721
+ this.logger.instrument(message, _extends({}, defaultContext, context));
2722
+ }
2723
+ getTraceContext(traceContext) {
2724
+ const now = Date.now();
2725
+ return _extends({
2726
+ now,
2727
+ time: (traceContext == null ? void 0 : traceContext.startTime) ? now - traceContext.startTime : 0
2728
+ }, traceContext);
2729
+ }
2730
+ constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, storageKey, debug, featureFlags, authMode = core.AuthMode.HEADER, authToken = undefined, // Represents the version of the client SDK used by developer
2731
+ sdkVersion, forwardMPCClient, baseClientKeysharesRelayApiUrl }){
2732
+ this.userId = undefined;
2733
+ this.sessionId = undefined;
1795
2734
  this.initializePromise = null;
1796
2735
  this.logger = logger;
1797
2736
  this.walletMap = {} // todo: store in session storage
1798
2737
  ;
1799
- this.iframeStorage = null;
1800
- this.iframeDisplay = null;
1801
2738
  this.memoryStorage = null;
1802
- this.messageTransport = null;
1803
2739
  this.iframe = null;
1804
- this.iframeLoadPromise = null;
2740
+ this.forwardMPCEnabled = false;
2741
+ this.featureFlags = {};
1805
2742
  this.environmentId = environmentId;
1806
2743
  this.storageKey = `${STORAGE_KEY}-${storageKey != null ? storageKey : environmentId}`;
1807
2744
  this.baseMPCRelayApiUrl = baseMPCRelayApiUrl;
2745
+ this.authMode = authMode;
2746
+ this.sdkVersion = sdkVersion;
2747
+ this.baseClientKeysharesRelayApiUrl = baseClientKeysharesRelayApiUrl;
1808
2748
  this.apiClient = new core.DynamicApiClient({
1809
2749
  environmentId,
1810
2750
  authToken,
1811
- baseApiUrl
2751
+ baseApiUrl,
2752
+ authMode,
2753
+ sdkVersion,
2754
+ forwardMPCClient,
2755
+ baseClientKeysharesRelayApiUrl
1812
2756
  });
1813
2757
  this.debug = Boolean(debug);
1814
- this.logger.setLogLevel(this.debug ? 'DEBUG' : DEFAULT_LOG_LEVEL);
2758
+ this.logger.setLogLevel(this.debug ? logger$1.LogLevel.DEBUG : DEFAULT_LOG_LEVEL);
2759
+ this.featureFlags = featureFlags || {};
1815
2760
  // setup storage
1816
2761
  if (supportsLocalStorage()) {
1817
2762
  this.storage = localStorageAdapter;
@@ -1822,12 +2767,29 @@ class DynamicWalletClient {
1822
2767
  const environment = core.getEnvironmentFromUrl(baseApiUrl);
1823
2768
  this.iframeDomain = core.IFRAME_DOMAIN_MAP[environment];
1824
2769
  // Generate unique instanceId when client is created
1825
- this.instanceId = crypto.randomUUID();
1826
- // initialize the client
1827
- this.initialize();
2770
+ this.instanceId = uuid.v4();
2771
+ // initialize logger context
2772
+ if (authMode === core.AuthMode.HEADER && authToken) {
2773
+ this.initLoggerContext(authToken);
2774
+ }
2775
+ this.forwardMPCEnabled = this.featureFlags && this.featureFlags[core.FEATURE_FLAGS.ENABLE_FORWARD_MPC_CLIENT_FLAG] === true;
2776
+ // if forwardMPCEnabled is true and forwardMPCClient is not provided, initialize the forwardMPCClient
2777
+ if (this.forwardMPCEnabled && !forwardMPCClient) {
2778
+ this.initializeForwardMPCClient();
2779
+ }
1828
2780
  }
1829
2781
  }
1830
2782
 
2783
+ const ERROR_KEYGEN_FAILED = '[DynamicWaasWalletClient]: Error with keygen';
2784
+ const ERROR_CREATE_WALLET_ACCOUNT = '[DynamicWaasWalletClient]: Error creating wallet account';
2785
+ const ERROR_SIGN_MESSAGE = '[DynamicWaasWalletClient]: Error signing message';
2786
+ const ERROR_SIGN_TYPED_DATA = '[DynamicWaasWalletClient]: Error signing typed data';
2787
+ const ERROR_ACCOUNT_ADDRESS_REQUIRED = '[DynamicWaasWalletClient]: Account address is required';
2788
+ const ERROR_VERIFY_MESSAGE_SIGNATURE = '[DynamicWaasWalletClient]: Error verifying message signature';
2789
+ const ERROR_VERIFY_TRANSACTION_SIGNATURE = '[DynamicWaasWalletClient]: Error verifying transaction signature';
2790
+ const ERROR_EXPORT_PRIVATE_KEY = '[DynamicWaasWalletClient]: Error exporting private key';
2791
+ const ERROR_IMPORT_PRIVATE_KEY = '[DynamicWaasWalletClient]: Error importing private key';
2792
+
1831
2793
  Object.defineProperty(exports, "BIP340", {
1832
2794
  enumerable: true,
1833
2795
  get: function () { return web.BIP340; }
@@ -1876,11 +2838,27 @@ Object.defineProperty(exports, "MessageHash", {
1876
2838
  enumerable: true,
1877
2839
  get: function () { return web.MessageHash; }
1878
2840
  });
2841
+ Object.defineProperty(exports, "Logger", {
2842
+ enumerable: true,
2843
+ get: function () { return logger$1.Logger; }
2844
+ });
1879
2845
  exports.DynamicWalletClient = DynamicWalletClient;
1880
- exports.base64ToBytes = base64ToBytes;
1881
- exports.bytesToBase64 = bytesToBase64;
2846
+ exports.ERROR_ACCOUNT_ADDRESS_REQUIRED = ERROR_ACCOUNT_ADDRESS_REQUIRED;
2847
+ exports.ERROR_CREATE_WALLET_ACCOUNT = ERROR_CREATE_WALLET_ACCOUNT;
2848
+ exports.ERROR_EXPORT_PRIVATE_KEY = ERROR_EXPORT_PRIVATE_KEY;
2849
+ exports.ERROR_IMPORT_PRIVATE_KEY = ERROR_IMPORT_PRIVATE_KEY;
2850
+ exports.ERROR_KEYGEN_FAILED = ERROR_KEYGEN_FAILED;
2851
+ exports.ERROR_SIGN_MESSAGE = ERROR_SIGN_MESSAGE;
2852
+ exports.ERROR_SIGN_TYPED_DATA = ERROR_SIGN_TYPED_DATA;
2853
+ exports.ERROR_VERIFY_MESSAGE_SIGNATURE = ERROR_VERIFY_MESSAGE_SIGNATURE;
2854
+ exports.ERROR_VERIFY_TRANSACTION_SIGNATURE = ERROR_VERIFY_TRANSACTION_SIGNATURE;
2855
+ exports.createAddGoogleDriveToExistingDelegationDistribution = createAddGoogleDriveToExistingDelegationDistribution;
1882
2856
  exports.createBackupData = createBackupData;
1883
- exports.ensureBase64Padding = ensureBase64Padding;
2857
+ exports.createDelegationOnlyDistribution = createDelegationOnlyDistribution;
2858
+ exports.createDelegationWithGoogleDriveDistribution = createDelegationWithGoogleDriveDistribution;
2859
+ exports.createDynamicOnlyDistribution = createDynamicOnlyDistribution;
2860
+ exports.createGoogleDriveOnlyDistribution = createGoogleDriveOnlyDistribution;
2861
+ exports.downloadStringAsFile = downloadStringAsFile;
1884
2862
  exports.formatEvmMessage = formatEvmMessage;
1885
2863
  exports.formatMessage = formatMessage;
1886
2864
  exports.getClientKeyShareBackupInfo = getClientKeyShareBackupInfo;
@@ -1888,11 +2866,12 @@ exports.getClientKeyShareExportFileName = getClientKeyShareExportFileName;
1888
2866
  exports.getGoogleOAuthAccountId = getGoogleOAuthAccountId;
1889
2867
  exports.getMPCSignatureScheme = getMPCSignatureScheme;
1890
2868
  exports.getMPCSigner = getMPCSigner;
2869
+ exports.hasDelegatedBackup = hasDelegatedBackup;
2870
+ exports.hasGoogleDriveBackup = hasGoogleDriveBackup;
1891
2871
  exports.isBrowser = isBrowser;
1892
2872
  exports.isHexString = isHexString;
1893
2873
  exports.mergeUniqueKeyShares = mergeUniqueKeyShares;
1894
2874
  exports.retryPromise = retryPromise;
1895
- exports.stringToBytes = stringToBytes;
1896
2875
  exports.timeoutPromise = timeoutPromise;
1897
2876
  Object.keys(core).forEach(function (k) {
1898
2877
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {