@dynamic-labs-wallet/core 0.0.354 → 0.1.0-request-signing

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 (82) hide show
  1. package/index.cjs +2632 -367
  2. package/index.esm.js +2550 -332
  3. package/package.json +21 -8
  4. package/src/api/api.d.ts +550 -121
  5. package/src/api/api.d.ts.map +1 -1
  6. package/src/api/client.d.ts +33 -1
  7. package/src/api/client.d.ts.map +1 -1
  8. package/src/api/index.d.ts +3 -0
  9. package/src/api/index.d.ts.map +1 -1
  10. package/src/api/requestSigner.d.ts +19 -0
  11. package/src/api/requestSigner.d.ts.map +1 -0
  12. package/src/api/signAndBroadcastRequestTooLargeError.d.ts +8 -0
  13. package/src/api/signAndBroadcastRequestTooLargeError.d.ts.map +1 -0
  14. package/src/api/types.d.ts +26 -0
  15. package/src/api/types.d.ts.map +1 -0
  16. package/src/businessAccounts/businessAccountClient.d.ts +128 -0
  17. package/src/businessAccounts/businessAccountClient.d.ts.map +1 -0
  18. package/src/businessAccounts/index.d.ts +3 -0
  19. package/src/businessAccounts/index.d.ts.map +1 -0
  20. package/src/businessAccounts/types.d.ts +121 -0
  21. package/src/businessAccounts/types.d.ts.map +1 -0
  22. package/src/constants.d.ts +29 -15
  23. package/src/constants.d.ts.map +1 -1
  24. package/src/earn/earnClient.d.ts +79 -0
  25. package/src/earn/earnClient.d.ts.map +1 -0
  26. package/src/earn/index.d.ts +3 -0
  27. package/src/earn/index.d.ts.map +1 -0
  28. package/src/earn/types.d.ts +23 -0
  29. package/src/earn/types.d.ts.map +1 -0
  30. package/src/eventStream/signingConsentRequiredError.d.ts +33 -0
  31. package/src/eventStream/signingConsentRequiredError.d.ts.map +1 -0
  32. package/src/eventStream/utils.d.ts +89 -5
  33. package/src/eventStream/utils.d.ts.map +1 -1
  34. package/src/exportIntent.d.ts +13 -0
  35. package/src/exportIntent.d.ts.map +1 -0
  36. package/src/index.d.ts +8 -0
  37. package/src/index.d.ts.map +1 -1
  38. package/src/internal/sdk-api-core/index.d.ts +2 -0
  39. package/src/internal/sdk-api-core/index.d.ts.map +1 -0
  40. package/src/mpc/constants.d.ts +17 -0
  41. package/src/mpc/constants.d.ts.map +1 -1
  42. package/src/mpc/index.d.ts +1 -0
  43. package/src/mpc/index.d.ts.map +1 -1
  44. package/src/mpc/privateKey.d.ts +20 -0
  45. package/src/mpc/privateKey.d.ts.map +1 -0
  46. package/src/mpc/utils.d.ts +1 -0
  47. package/src/mpc/utils.d.ts.map +1 -1
  48. package/src/reshareIntent.d.ts +14 -0
  49. package/src/reshareIntent.d.ts.map +1 -0
  50. package/src/services/axiosErrorResponse.d.ts +18 -3
  51. package/src/services/axiosErrorResponse.d.ts.map +1 -1
  52. package/src/signingIntent.d.ts +28 -0
  53. package/src/signingIntent.d.ts.map +1 -0
  54. package/src/types.d.ts +960 -91
  55. package/src/types.d.ts.map +1 -1
  56. package/src/utils/attachRequestIds.d.ts +8 -0
  57. package/src/utils/attachRequestIds.d.ts.map +1 -0
  58. package/src/utils/forwardMpcEnclaveUrl.d.ts +9 -0
  59. package/src/utils/forwardMpcEnclaveUrl.d.ts.map +1 -0
  60. package/src/utils/forwardMpcErrorHandling.d.ts +44 -1
  61. package/src/utils/forwardMpcErrorHandling.d.ts.map +1 -1
  62. package/src/utils/forwardMpcFallback.d.ts +33 -0
  63. package/src/utils/forwardMpcFallback.d.ts.map +1 -0
  64. package/src/utils/index.d.ts +9 -0
  65. package/src/utils/index.d.ts.map +1 -1
  66. package/src/utils/isEvmCompatibleChain/index.d.ts +2 -0
  67. package/src/utils/isEvmCompatibleChain/index.d.ts.map +1 -0
  68. package/src/utils/isEvmCompatibleChain/isEvmCompatibleChain.d.ts +28 -0
  69. package/src/utils/isEvmCompatibleChain/isEvmCompatibleChain.d.ts.map +1 -0
  70. package/src/utils/keyShare.d.ts +8 -0
  71. package/src/utils/keyShare.d.ts.map +1 -1
  72. package/src/utils/messageSerialization.d.ts.map +1 -1
  73. package/src/utils/rawMessage.d.ts +4 -0
  74. package/src/utils/rawMessage.d.ts.map +1 -0
  75. package/src/utils/serializeError.d.ts +16 -0
  76. package/src/utils/serializeError.d.ts.map +1 -0
  77. package/src/utils/toJsonSafeContext.d.ts +4 -0
  78. package/src/utils/toJsonSafeContext.d.ts.map +1 -0
  79. package/src/utils/uuid.d.ts +2 -0
  80. package/src/utils/uuid.d.ts.map +1 -0
  81. package/src/utils/withTraceId.d.ts +7 -0
  82. package/src/utils/withTraceId.d.ts.map +1 -0
package/index.esm.js CHANGED
@@ -1,9 +1,14 @@
1
1
  import { SigningAlgorithm } from '@dynamic-labs-wallet/primitives';
2
2
  export { SigningAlgorithm } from '@dynamic-labs-wallet/primitives';
3
3
  import { v4 } from 'uuid';
4
- import axios from 'axios';
4
+ import { WaasChainEnum } from '@dynamic-labs/sdk-api-core/models/WaasChainEnum';
5
+ export { WaasChainEnum } from '@dynamic-labs/sdk-api-core/models/WaasChainEnum';
6
+ export { WaasPolicyConstraintCondition } from '@dynamic-labs/sdk-api-core/models/WaasPolicyConstraintCondition';
7
+ export { WaasPolicyRuleType } from '@dynamic-labs/sdk-api-core/models/WaasPolicyRuleType';
8
+ import axios, { isAxiosError } from 'axios';
5
9
  export { isAxiosError } from 'axios';
6
- export { classifyForwardMpcError, isAttestationError, isForwardMpcError } from '@dynamic-labs-wallet/forward-mpc-client/utils';
10
+ import { classifyForwardMpcError as classifyForwardMpcError$1 } from '@dynamic-labs-wallet/forward-mpc-client/utils';
11
+ export { isAttestationError, isForwardMpcError } from '@dynamic-labs-wallet/forward-mpc-client/utils';
7
12
 
8
13
  var ENVIRONMENT_ENUM = /*#__PURE__*/ function(ENVIRONMENT_ENUM) {
9
14
  ENVIRONMENT_ENUM["development"] = "development";
@@ -13,6 +18,9 @@ var ENVIRONMENT_ENUM = /*#__PURE__*/ function(ENVIRONMENT_ENUM) {
13
18
  }({});
14
19
  const DynamicRequestIdHeader = 'x-dyn-request-id';
15
20
  const DynamicClientSessionSignature = 'x-dyn-client-session-signature';
21
+ // Session public key the client signed with; lets the keyshare service log
22
+ // which key was used to sign vs which key it expected on a signature failure.
23
+ const DynamicSessionPublicKeyHeader = 'x-dyn-session-public-key';
16
24
  const DynamicMfaTokenHeader = 'x-mfa-auth-token';
17
25
  const DynamicElevatedAccessTokenHeader = 'x-dyn-elevated-access-token';
18
26
  const DynamicForwardMPCHeader = 'x-forward-mpc-client';
@@ -37,7 +45,7 @@ const DYNAMIC_KEYSHARES_RELAY_PREPROD_BASE_API_URL = 'https://waas-keyshares-rel
37
45
  const DYNAMIC_KEYSHARES_RELAY_MAP = {
38
46
  ["production"]: DYNAMIC_KEYSHARES_RELAY_PROD_BASE_API_URL,
39
47
  ["preprod"]: DYNAMIC_KEYSHARES_RELAY_PREPROD_BASE_API_URL,
40
- ["development"]: DYNAMIC_KEYSHARES_RELAY_PREPROD_BASE_API_URL
48
+ ["development"]: 'http://localhost:3001'
41
49
  };
42
50
  /**
43
51
  * Dymamic MPC relay where the MPC operations are performed (NOT keyshare relay in Evervault)
@@ -66,6 +74,12 @@ const DYNAMIC_CLIENT_RELAY_REDCOAST_API_KEY_MAP = {
66
74
  ["preprod"]: PREPROD_RELAY_API_KEY,
67
75
  ["development"]: undefined
68
76
  };
77
+ /**
78
+ * Route prefixes for SDK vs server SDK traffic.
79
+ * Server SDK routes authenticate via API key directly (no JWT exchange).
80
+ * @see DYNT-537
81
+ */ const BROWSER_SDK_ROUTE_PREFIX = '/api/v0/sdk';
82
+ const SERVER_SDK_ROUTE_PREFIX = '/api/v0/server';
69
83
  const SOLANA_RPC_URL = 'https://api.devnet.solana.com';
70
84
  const chain = {
71
85
  EVM: 'EVM',
@@ -74,7 +88,12 @@ const chain = {
74
88
  BTC: 'BTC',
75
89
  FLOW: 'FLOW',
76
90
  SUI: 'SUI',
77
- TON: 'TON'
91
+ TON: 'TON',
92
+ STELLAR: 'STELLAR',
93
+ TEMPO: 'TEMPO',
94
+ TRON: 'TRON',
95
+ ALEO: 'ALEO',
96
+ MIDNIGHT: 'MIDNIGHT'
78
97
  };
79
98
  var WalletOperation = /*#__PURE__*/ function(WalletOperation) {
80
99
  WalletOperation["REACH_THRESHOLD"] = "REACH_THRESHOLD";
@@ -96,6 +115,7 @@ var BackupLocation = /*#__PURE__*/ function(BackupLocation) {
96
115
  BackupLocation["USER"] = "user";
97
116
  BackupLocation["EXTERNAL"] = "external";
98
117
  BackupLocation["DELEGATED"] = "delegated";
118
+ BackupLocation["OFFLINE_RECOVERY"] = "offlineRecovery";
99
119
  return BackupLocation;
100
120
  }({});
101
121
  const IFRAME_DOMAIN_MAP = {
@@ -110,21 +130,36 @@ const chainEnumToVerifiedCredentialName = {
110
130
  SVM: 'solana',
111
131
  TEMPO: 'tempo'
112
132
  };
133
+ // Must cover every chain with a wallet client: getWallets() resolves each
134
+ // verified credential's chainName through this map, and wallets that resolve
135
+ // to undefined are silently skipped by eager key-share recovery (the share
136
+ // then never reaches a new device even though the backup is recoverable).
113
137
  const verifiedCredentialNameToChainEnum = {
138
+ aleo: 'ALEO',
114
139
  bip122: 'BTC',
115
140
  eip155: 'EVM',
141
+ midnight: 'MIDNIGHT',
116
142
  solana: 'SVM',
117
143
  stellar: 'STELLAR',
118
144
  sui: 'SUI',
119
145
  tempo: 'TEMPO',
120
- ton: 'TON'
146
+ ton: 'TON',
147
+ tron: 'TRON'
121
148
  };
122
149
  const DELEGATED_SHARE_COUNT = 1;
123
150
  const FEATURE_FLAGS = {
151
+ ENABLE_ARGON2ID_REBACKUP_TARGETS_FLAG: 'enable-argon2id-rebackup-targets',
152
+ ENABLE_CKS_REPORTS_LOCATION_FLAG: 'enable-cks-reports-location',
124
153
  ENABLE_DELEGATED_KEY_SHARES_FLAG: 'enable-delegated-key-shares',
125
154
  ENABLE_FORWARD_MPC_CLIENT_FLAG: 'enable-forward-mpc-client',
155
+ ENABLE_HTTP_WAAS_TRANSPORT: 'enable-http-waas-transport',
156
+ ENABLE_HTTP_WAAS_TRANSPORT_SIGNMESSAGE: 'enable-http-waas-transport-signmessage',
157
+ ENABLE_HTTP_WAAS_TRANSPORT_EXPORT: 'enable-http-waas-transport-export',
126
158
  ENABLE_ROOM_CACHE_FLAG: 'enable-mpc-room-cache',
127
- ENABLE_SHARE_SET_RESHARE: 'enable-share-set-reshare'
159
+ ENABLE_SHARE_SET_RESHARE: 'enable-share-set-reshare',
160
+ ENABLE_TRON_MPC_FLAG: 'enable-tron-mpc',
161
+ VERIFY_BACKUP_RECOVERABILITY_FLAG: 'enable-verify-backup-recoverability',
162
+ WASM_WARM_STRATEGY_FLAG: 'enable-wasm-warm-strategy'
128
163
  };
129
164
  const DYNAMIC_FORWARD_MPC_PROD_ENCLAVE_URL = 'wss://mpc-client.dynamicauth.com/ws';
130
165
  const DYNAMIC_FORWARD_MPC_PREPROD_ENCLAVE_URL = 'wss://mpc-client.dynamic-preprod.xyz/ws';
@@ -134,21 +169,28 @@ const DYNAMIC_FORWARD_MPC_ENCLAVE_URL_MAP = {
134
169
  ["preprod"]: DYNAMIC_FORWARD_MPC_PREPROD_ENCLAVE_URL,
135
170
  ["development"]: DYNAMIC_FORWARD_MPC_PREPROD_ENCLAVE_URL
136
171
  };
172
+ const PREPROD_FORWARD_MPC_ATTESTATION_CONFIG = {
173
+ expectedPcr8: [
174
+ 'acc59ec98dbf7ecb43f9a6b9890866141868c079aa879e05e3675e1a10e187259a64951e72cc531541b02dbdcd780770',
175
+ '3b64661db625663481e4eb85a96214fb2356600ad4b4ba8a5951c3384ecc6150c03a411243f0390c744e33cc57516dc6'
176
+ ],
177
+ strictCertValidation: true
178
+ };
179
+ // expectedPcr8 is a list so a signing-cert rotation can add the new PCR8
180
+ // alongside the old one; remove the old entry once the rollout completes.
137
181
  const DYNAMIC_FORWARD_MPC_ENCLAVE_ATTESTATION_CONFIG_MAP = {
138
182
  ["production"]: {
139
- expectedPcr8: '484fd412249304fe7659b2a9a4869504f0e4502d8abb4f88183e65416b4f62354e4eda60e80a5b2e9d730ab0d804f83e',
140
- strictCertValidation: true
141
- },
142
- ["preprod"]: {
143
- expectedPcr8: 'acc59ec98dbf7ecb43f9a6b9890866141868c079aa879e05e3675e1a10e187259a64951e72cc531541b02dbdcd780770',
183
+ expectedPcr8: [
184
+ 'd35c62ae0076882804c61aab5075e77cdfde68fc4755fbb13527fc29d9d9f01d208ecb303d7d0c46740d52feab20a6cb'
185
+ ],
144
186
  strictCertValidation: true
145
187
  },
146
- ["development"]: {
147
- expectedPcr8: 'acc59ec98dbf7ecb43f9a6b9890866141868c079aa879e05e3675e1a10e187259a64951e72cc531541b02dbdcd780770',
148
- strictCertValidation: true
149
- }
188
+ // development mirrors preprod: same enclave, same rotation set.
189
+ ["preprod"]: PREPROD_FORWARD_MPC_ATTESTATION_CONFIG,
190
+ ["development"]: PREPROD_FORWARD_MPC_ATTESTATION_CONFIG
150
191
  };
151
192
 
193
+ const DEFAULT_ED25519_VARIANT = 'ed25519Exportable';
152
194
  const BITCOIN_DERIVATION_PATHS = {
153
195
  NATIVE_SEGWIT: [
154
196
  84,
@@ -295,6 +337,17 @@ const MPC_CHAIN_CONFIG = {
295
337
  ],
296
338
  signingAlgorithm: SigningAlgorithm.ECDSA
297
339
  },
340
+ TRON: {
341
+ // Uses secp256k1 ECDSA
342
+ derivationPath: [
343
+ 44,
344
+ 195,
345
+ 0,
346
+ 0,
347
+ 0
348
+ ],
349
+ signingAlgorithm: SigningAlgorithm.ECDSA
350
+ },
298
351
  ALEO: {
299
352
  // Uses Edwards-BLS12-377 Schnorr (EdBls12377) — no BIP32/BIP44 derivation
300
353
  // Path is a placeholder for config-shape uniformity; Sodot EdBls12377 keygen
@@ -405,20 +458,20 @@ const getDynamicServerThreshold = (thresholdSignatureScheme)=>{
405
458
  * }} The number of existing and new client and server shares needed
406
459
  */ const getReshareConfig = ({ oldThresholdSignatureScheme, newThresholdSignatureScheme })=>{
407
460
  switch(true){
408
- // 2-of-2 -> 2-of-2:
409
- // -- dynamic server shares: 1 existing, 0 new
410
- // -- client shares: 1 existing, 0 new
411
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO:
461
+ // 2-of-2 -> 2-of-2: same-parties refresh — server + rootUser-client both
462
+ // call `reshareRemainingParty`. Share-set delegation lands here too; the
463
+ // delegated share is delivered out-of-band, not via the MPC ceremony.
464
+ case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO || oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO:
412
465
  return {
413
466
  existingClientShareCount: 1,
414
467
  newClientShareCount: 0,
415
468
  existingServerShareCount: 1,
416
469
  newServerShareCount: 0
417
470
  };
418
- // 2-of-3 -> 2-of-3:
471
+ // 2-of-3 -> 2-of-3 and 2-of-2 -> 2-of-3:
419
472
  // -- dynamic server shares: 1 existing, 0 new
420
473
  // -- client shares: 1 existing, 1 new
421
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE:
474
+ case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE || oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE:
422
475
  return {
423
476
  existingClientShareCount: 1,
424
477
  newClientShareCount: 1,
@@ -435,46 +488,16 @@ const getDynamicServerThreshold = (thresholdSignatureScheme)=>{
435
488
  existingServerShareCount: 2,
436
489
  newServerShareCount: 0
437
490
  };
438
- // 2-of-2 -> 2-of-3:
439
- // -- dynamic server shares: 1 existing, 0 new
440
- // -- client shares: 1 existing, 1 new
441
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE:
442
- return {
443
- existingClientShareCount: 1,
444
- newClientShareCount: 1,
445
- existingServerShareCount: 1,
446
- newServerShareCount: 0
447
- };
448
- // 2-of-2 -> 3-of-5:
449
- // -- dynamic server shares: 1 existing, 1 new
450
- // -- client shares: 1 existing, 2 new
451
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE:
452
- return {
453
- existingClientShareCount: 1,
454
- newClientShareCount: 2,
455
- existingServerShareCount: 1,
456
- newServerShareCount: 1
457
- };
458
- // 2-of-3 -> 3-of-5:
491
+ // 2-of-2 -> 3-of-5 and 2-of-3 -> 3-of-5:
459
492
  // -- dynamic server shares: 1 existing, 1 new
460
493
  // -- client shares: 1 existing, 2 new
461
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE:
494
+ case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE || oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE:
462
495
  return {
463
496
  existingClientShareCount: 1,
464
497
  newClientShareCount: 2,
465
498
  existingServerShareCount: 1,
466
499
  newServerShareCount: 1
467
500
  };
468
- // 2-of-3 -> 2-of-2:
469
- // -- dynamic server shares: 1 existing, 0 new
470
- // -- client shares: 1 existing, 0 new
471
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO:
472
- return {
473
- existingClientShareCount: 1,
474
- newClientShareCount: 0,
475
- existingServerShareCount: 1,
476
- newServerShareCount: 0
477
- };
478
501
  // 3-of-5 -> 2-of-3:
479
502
  // -- dynamic server shares: 1 existing, 0 new
480
503
  // -- client shares: 2 existing, 0 new
@@ -501,20 +524,20 @@ const getDynamicServerThreshold = (thresholdSignatureScheme)=>{
501
524
  * }} The number of existing and new client and server shares needed
502
525
  */ const getServerWalletReshareConfig = ({ oldThresholdSignatureScheme, newThresholdSignatureScheme })=>{
503
526
  switch(true){
504
- // 2-of-2 -> 2-of-2:
505
- // -- dyanmic server shares: 1 existing, 0 new
527
+ // 2-of-2 -> 2-of-2 and 2-of-3 -> 2-of-2:
528
+ // -- dynamic server shares: 1 existing, 0 new
506
529
  // -- external server shares: 1 existing, 0 new
507
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO:
530
+ case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO || oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO:
508
531
  return {
509
532
  existingExternalServerShareCount: 1,
510
533
  newExternalServerShareCount: 0,
511
534
  existingDynamicServerShareCount: 1,
512
535
  newDynamicServerShareCount: 0
513
536
  };
514
- // 2-of-3 -> 2-of-3:
515
- // -- dyanmic server shares: 1 existing, 0 new
537
+ // 2-of-3 -> 2-of-3 and 2-of-2 -> 2-of-3:
538
+ // -- dynamic server shares: 1 existing, 0 new
516
539
  // -- external server shares: 1 existing, 1 new
517
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE:
540
+ case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE || oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE:
518
541
  return {
519
542
  existingExternalServerShareCount: 1,
520
543
  newExternalServerShareCount: 1,
@@ -522,7 +545,7 @@ const getDynamicServerThreshold = (thresholdSignatureScheme)=>{
522
545
  newDynamicServerShareCount: 0
523
546
  };
524
547
  // 3-of-5 -> 3-of-5:
525
- // -- dyanmic server shares: 2 existing, 0 new
548
+ // -- dynamic server shares: 2 existing, 0 new
526
549
  // -- external server shares: 1 existing, 2 new
527
550
  case oldThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE && newThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE:
528
551
  return {
@@ -531,46 +554,16 @@ const getDynamicServerThreshold = (thresholdSignatureScheme)=>{
531
554
  existingDynamicServerShareCount: 2,
532
555
  newDynamicServerShareCount: 0
533
556
  };
534
- // 2-of-2 -> 2-of-3:
535
- // -- dyanmic server shares: 1 existing, 0 new
536
- // -- external server shares: 1 existing, 1 new
537
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE:
538
- return {
539
- existingExternalServerShareCount: 1,
540
- newExternalServerShareCount: 1,
541
- existingDynamicServerShareCount: 1,
542
- newDynamicServerShareCount: 0
543
- };
544
- // 2-of-2 -> 3-of-5:
545
- // -- dyanmic server shares: 1 existing, 1 new
546
- // -- external server shares: 1 existing, 2 new
547
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE:
548
- return {
549
- existingExternalServerShareCount: 1,
550
- newExternalServerShareCount: 2,
551
- existingDynamicServerShareCount: 1,
552
- newDynamicServerShareCount: 1
553
- };
554
- // 2-of-3 -> 3-of-5:
555
- // -- dyanmic server shares: 1 existing, 1 new
557
+ // 2-of-2 -> 3-of-5 and 2-of-3 -> 3-of-5:
558
+ // -- dynamic server shares: 1 existing, 1 new
556
559
  // -- external server shares: 1 existing, 2 new
557
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE:
560
+ case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO && newThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE || oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.THREE_OF_FIVE:
558
561
  return {
559
562
  existingExternalServerShareCount: 1,
560
563
  newExternalServerShareCount: 2,
561
564
  existingDynamicServerShareCount: 1,
562
565
  newDynamicServerShareCount: 1
563
566
  };
564
- // 2-of-3 -> 2-of-2:
565
- // -- dyanmic server shares: 1 existing, 0 new
566
- // -- external server shares: 1 existing, 0 new
567
- case oldThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_THREE && newThresholdSignatureScheme === ThresholdSignatureScheme.TWO_OF_TWO:
568
- return {
569
- existingExternalServerShareCount: 1,
570
- newExternalServerShareCount: 0,
571
- existingDynamicServerShareCount: 1,
572
- newDynamicServerShareCount: 0
573
- };
574
567
  // 3-of-5 -> 2-of-3:
575
568
  // -- dyanmic server shares: 1 existing, 0 new
576
569
  // -- external server shares: 2 existing, 0 new
@@ -603,6 +596,57 @@ function getEnvironmentFromUrl(url) {
603
596
  return ENVIRONMENT_ENUM.production;
604
597
  }
605
598
 
599
+ // secp256k1 group order n; ECDSA and BIP340 private keys must be in [1, n).
600
+ const SECP256K1_ORDER = BigInt('0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141');
601
+ const PRIVATE_KEY_HEX_LENGTH = 64;
602
+ // A malformed key fails every ceremony attempt identically, so flag it
603
+ // non-retryable for callers wrapped in retryPromise (browser client).
604
+ const invalidPrivateKeyError = (message)=>{
605
+ const error = new Error(message);
606
+ error.isRetryable = false;
607
+ return error;
608
+ };
609
+ /**
610
+ * Validates a private key for `importPrivateKey` before any API call or MPC
611
+ * ceremony starts, and returns it normalized for the MPC importer (surrounding
612
+ * whitespace trimmed, optional `0x` prefix stripped).
613
+ *
614
+ * Every chain expects a 32-byte hex key at this layer — chain-specific input
615
+ * formats (WIF, base58, bech32, Stellar seed) are converted to hex by the chain
616
+ * clients beforehand. For secp256k1 chains (ECDSA, BIP340) the key is also
617
+ * range-checked against the curve order.
618
+ *
619
+ * Error messages report only the key's length and character class — never the
620
+ * key material itself.
621
+ */ const normalizeAndValidatePrivateKey = ({ privateKey, chainName, bitcoinConfig })=>{
622
+ const chainLabel = chainName ? ` for chain ${chainName}` : '';
623
+ if (typeof privateKey !== 'string') {
624
+ throw invalidPrivateKeyError(`Invalid private key${chainLabel}: expected a hex string, got ${typeof privateKey}`);
625
+ }
626
+ let normalized = privateKey.trim();
627
+ if (normalized.startsWith('0x') || normalized.startsWith('0X')) {
628
+ normalized = normalized.slice(2);
629
+ }
630
+ if (normalized.length !== PRIVATE_KEY_HEX_LENGTH) {
631
+ throw invalidPrivateKeyError(`Invalid private key${chainLabel}: expected ${PRIVATE_KEY_HEX_LENGTH} hex characters ` + `(32 bytes), got ${normalized.length}`);
632
+ }
633
+ if (!/^[0-9a-fA-F]+$/.test(normalized)) {
634
+ throw invalidPrivateKeyError(`Invalid private key${chainLabel}: expected ${PRIVATE_KEY_HEX_LENGTH} hex characters ` + `(32 bytes), got non-hex characters`);
635
+ }
636
+ const { signingAlgorithm } = getMPCChainConfig(chainName, bitcoinConfig);
637
+ const isSecp256k1Chain = signingAlgorithm === SigningAlgorithm.ECDSA || signingAlgorithm === SigningAlgorithm.BIP340;
638
+ if (isSecp256k1Chain) {
639
+ const keyValue = BigInt(`0x${normalized}`);
640
+ if (keyValue === 0n) {
641
+ throw invalidPrivateKeyError(`Invalid private key${chainLabel}: key cannot be zero`);
642
+ }
643
+ if (keyValue >= SECP256K1_ORDER) {
644
+ throw invalidPrivateKeyError(`Invalid private key${chainLabel}: key exceeds the secp256k1 curve order`);
645
+ }
646
+ }
647
+ return normalized;
648
+ };
649
+
606
650
  function _extends() {
607
651
  _extends = Object.assign || function assign(target) {
608
652
  for(var i = 1; i < arguments.length; i++){
@@ -614,6 +658,43 @@ function _extends() {
614
658
  return _extends.apply(this, arguments);
615
659
  }
616
660
 
661
+ var BusinessAccountMemberRole = /*#__PURE__*/ function(BusinessAccountMemberRole) {
662
+ BusinessAccountMemberRole["Owner"] = "owner";
663
+ BusinessAccountMemberRole["Admin"] = "admin";
664
+ BusinessAccountMemberRole["Viewer"] = "viewer";
665
+ return BusinessAccountMemberRole;
666
+ }({});
667
+ var BusinessAccountSignerType = /*#__PURE__*/ function(BusinessAccountSignerType) {
668
+ BusinessAccountSignerType["EndUser"] = "endUser";
669
+ BusinessAccountSignerType["Server"] = "server";
670
+ return BusinessAccountSignerType;
671
+ }({});
672
+ /** Re-passes the pair together; destructuring a request splits the union and the compiler cannot rejoin it. */ const pickSignerTarget = ({ signerType, targetSignerIdentity })=>({
673
+ signerType,
674
+ targetSignerIdentity
675
+ });
676
+ class BusinessAccountIntentRequiredError extends Error {
677
+ constructor(intent){
678
+ super('Business account action requires a signed intent');
679
+ this.name = 'BusinessAccountIntentRequiredError';
680
+ this.intent = intent;
681
+ }
682
+ }
683
+ const isBusinessAccountActionRequired = (value)=>typeof value === 'object' && value !== null && (value.reason === 'INTENT_REQUIRED' || value.reason === 'APPROVALS_REQUIRED');
684
+ /** Strips a `BusinessAccountSignedIntent` (and its nested `intent`) down to known fields before it's spread into a request body. */ const sanitizeBusinessAccountSignedIntent = (signedIntent)=>signedIntent && {
685
+ autoExecute: signedIntent.autoExecute,
686
+ intent: signedIntent.intent && {
687
+ actionType: signedIntent.intent.actionType,
688
+ autoExecute: signedIntent.intent.autoExecute,
689
+ businessAccountId: signedIntent.intent.businessAccountId,
690
+ createdAt: signedIntent.intent.createdAt,
691
+ initiatorUserId: signedIntent.intent.initiatorUserId,
692
+ intentId: signedIntent.intent.intentId,
693
+ payload: signedIntent.intent.payload
694
+ },
695
+ intentSignature: signedIntent.intentSignature
696
+ };
697
+
617
698
  var AuthMode = /*#__PURE__*/ function(AuthMode) {
618
699
  AuthMode["HEADER"] = "header";
619
700
  AuthMode["COOKIE"] = "cookie";
@@ -638,6 +719,7 @@ var SuccessEventType = /*#__PURE__*/ function(SuccessEventType) {
638
719
  SuccessEventType["KeygenComplete"] = "keygen_complete";
639
720
  SuccessEventType["RoomCreated"] = "room_created";
640
721
  SuccessEventType["CeremonyComplete"] = "ceremony_complete";
722
+ SuccessEventType["ConsentRequired"] = "consent_required";
641
723
  return SuccessEventType;
642
724
  }({});
643
725
  class NoopLogger {
@@ -655,9 +737,388 @@ class NoopLogger {
655
737
  }
656
738
  }
657
739
 
740
+ var _Logger;
741
+ /**
742
+ * Global static logger for SDK-internal use.
743
+ *
744
+ * Call `Logger.configure(impl)` once at startup to wire in your logger.
745
+ * Call `Logger.setContext(ctx)` to attach metadata merged into every log call.
746
+ *
747
+ * Parses variadic args: any Error instance is extracted and passed as the
748
+ * third argument; all plain objects are merged into a single context object.
749
+ * This matches Datadog's (message, context?, error?) calling convention.
750
+ */ const Logger = (_Logger = class Logger {
751
+ static configure(logger) {
752
+ this._instance = logger;
753
+ }
754
+ static setContext(context) {
755
+ this._context = _extends({}, this._context, context);
756
+ }
757
+ static resetContext() {
758
+ this._context = {};
759
+ }
760
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
761
+ static debug(message, ...args) {
762
+ const { context } = this._parse(args);
763
+ if (context) {
764
+ this._instance.debug(message, context);
765
+ } else {
766
+ this._instance.debug(message);
767
+ }
768
+ }
769
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
770
+ static info(message, ...args) {
771
+ const { context } = this._parse(args);
772
+ if (context) {
773
+ this._instance.info(message, context);
774
+ } else {
775
+ this._instance.info(message);
776
+ }
777
+ }
778
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
779
+ static warn(message, ...args) {
780
+ const { context } = this._parse(args);
781
+ if (context) {
782
+ this._instance.warn(message, context);
783
+ } else {
784
+ this._instance.warn(message);
785
+ }
786
+ }
787
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
788
+ static error(message, ...args) {
789
+ const { error, context } = this._parse(args);
790
+ if (error) {
791
+ this._instance.error(message, context != null ? context : {}, error);
792
+ } else if (context) {
793
+ this._instance.error(message, context);
794
+ } else {
795
+ this._instance.error(message);
796
+ }
797
+ }
798
+ /**
799
+ * Separates variadic args into a merged context object and an optional Error.
800
+ * All plain objects are merged (later args win). Error instances are extracted.
801
+ * Handles unknown/primitive args by wrapping them in a context object.
802
+ */ // eslint-disable-next-line @typescript-eslint/no-explicit-any
803
+ static _parse(args) {
804
+ let error;
805
+ let merged = _extends({}, this._context);
806
+ let hasData = Object.keys(this._context).length > 0;
807
+ for (const arg of args){
808
+ if (arg instanceof Error) {
809
+ error = arg;
810
+ } else if (arg !== null && typeof arg === 'object') {
811
+ merged = _extends({}, merged, arg);
812
+ hasData = true;
813
+ } else if (arg !== undefined && arg !== null) {
814
+ merged = _extends({}, merged, {
815
+ value: arg
816
+ });
817
+ hasData = true;
818
+ }
819
+ }
820
+ return {
821
+ context: hasData ? merged : undefined,
822
+ error
823
+ };
824
+ }
825
+ }, _Logger._instance = new NoopLogger(), _Logger._context = {}, _Logger);
826
+
827
+ class WalletApiError extends Error {
828
+ constructor(status, message, code){
829
+ super(message);
830
+ this.name = 'WalletApiError';
831
+ this.status = status;
832
+ this.code = code;
833
+ }
834
+ }
835
+ const getResponseRecord = (error)=>{
836
+ var _error_response;
837
+ const data = (_error_response = error.response) == null ? void 0 : _error_response.data;
838
+ return data && typeof data === 'object' ? data : undefined;
839
+ };
840
+ // The Key Share Service returns its machine-readable cause under `error_code`; other
841
+ // backends use `code` or a bare `error`. Exported for callers that must skip handleAxiosError's own logging.
842
+ const extractServerErrorCode = (error)=>{
843
+ const record = getResponseRecord(error);
844
+ const candidates = [
845
+ record == null ? void 0 : record['code'],
846
+ record == null ? void 0 : record['error_code'],
847
+ record == null ? void 0 : record['error']
848
+ ];
849
+ return candidates.find((value)=>typeof value === 'string');
850
+ };
851
+ const INTERNAL_SERVER_ERROR_MESSAGE = 'Internal server error';
852
+ /**
853
+ * `status` for a request that never received an HTTP response at all — the
854
+ * client lost connectivity, the request was aborted, DNS/TLS failed, or CORS
855
+ * blocked it. 0 matches the XHR/`fetch` convention for "no response".
856
+ *
857
+ * This used to be reported as `500 Internal server error`, which made a
858
+ * client-side network failure indistinguishable from a backend fault: the
859
+ * "Backend 500s" monitor counted 1,395 events on a day when the API returned
860
+ * only 33 real 5xx responses.
861
+ */ const NETWORK_ERROR_STATUS = 0;
862
+ const NETWORK_ERROR_CODE = 'NETWORK_ERROR';
863
+ const NETWORK_ERROR_MESSAGE = 'Network error - no response received';
864
+ const STATUS_MESSAGES = {
865
+ 400: 'Invalid request',
866
+ 403: 'Forbidden',
867
+ 422: 'Unprocessable content',
868
+ 429: 'Rate limited',
869
+ 500: INTERNAL_SERVER_ERROR_MESSAGE
870
+ };
871
+ const MISSING_AUTH_MESSAGE = 'Authorization header or cookie missing';
872
+ // A 401 can mean the request carried no credentials, or carried credentials the
873
+ // backend rejected — the two need different messages. The Authorization header
874
+ // is readable so we can confirm its presence; the auth cookie is httpOnly, so we
875
+ // can only report whether cookie mode was enabled (`withCredentials`), not that a
876
+ // cookie was actually attached.
877
+ const getRequestCredentials = (error)=>{
878
+ var _error_config, _error_config1;
879
+ const requestHeaders = (_error_config = error.config) == null ? void 0 : _error_config.headers;
880
+ var _requestHeaders_Authorization;
881
+ const hasAuthorizationHeader = Boolean((_requestHeaders_Authorization = requestHeaders == null ? void 0 : requestHeaders['Authorization']) != null ? _requestHeaders_Authorization : requestHeaders == null ? void 0 : requestHeaders['authorization']);
882
+ const usesCookieAuth = Boolean((_error_config1 = error.config) == null ? void 0 : _error_config1.withCredentials);
883
+ return {
884
+ hasAuthorizationHeader,
885
+ usesCookieAuth
886
+ };
887
+ };
888
+ const resolveUnauthorizedMessage = (error)=>{
889
+ const { hasAuthorizationHeader, usesCookieAuth } = getRequestCredentials(error);
890
+ if (!hasAuthorizationHeader && !usesCookieAuth) {
891
+ return MISSING_AUTH_MESSAGE;
892
+ }
893
+ const credentialDescriptions = [];
894
+ if (hasAuthorizationHeader) {
895
+ credentialDescriptions.push('Authorization header present');
896
+ }
897
+ if (usesCookieAuth) {
898
+ credentialDescriptions.push('withCredentials enabled (cookie auth)');
899
+ }
900
+ return `Unauthorized (${credentialDescriptions.join(', ')})`;
901
+ };
902
+ const resolveStatusMessage = (status, error)=>{
903
+ if (status === 401) {
904
+ return resolveUnauthorizedMessage(error);
905
+ }
906
+ if (status && STATUS_MESSAGES[status]) {
907
+ return STATUS_MESSAGES[status];
908
+ }
909
+ return undefined;
910
+ };
911
+ const handleAxiosError = (error, message, context, /**
912
+ * Optional severity hint from the caller, for failures the caller knows are
913
+ * expected (e.g. a business-rule rejection). It can only *lower* severity to
914
+ * `warn` — a caller must not be able to escalate, and a genuine 5xx has to
915
+ * stay at `error` regardless of what the call site believes.
916
+ *
917
+ * Without this the hint that `logError` accepts was silently discarded for
918
+ * every AxiosError, which is the most common error type in the SDK.
919
+ */ options)=>{
920
+ var _error_config, _error_config1, _error_response, _error_response1, _error_response2;
921
+ const requestUrl = (_error_config = error.config) == null ? void 0 : _error_config.url;
922
+ const requestBaseUrl = (_error_config1 = error.config) == null ? void 0 : _error_config1.baseURL;
923
+ // The HTTP status MUST NOT be logged as a top-level `status` field: Datadog
924
+ // reserves `status` for the log level and its remapper turns a numeric value
925
+ // into `info`, silently burying every 4xx/5xx we emit here. `http.status_code`
926
+ // is Datadog's standard attribute, so the level survives and these logs join
927
+ // against edge/CDN logs on the same field.
928
+ const logPayload = _extends({
929
+ message,
930
+ error: (_error_response = error.response) == null ? void 0 : _error_response.data,
931
+ http: {
932
+ status_code: (_error_response1 = error.response) == null ? void 0 : _error_response1.status
933
+ }
934
+ }, requestBaseUrl && {
935
+ requestBaseUrl
936
+ }, requestUrl && {
937
+ requestUrl
938
+ }, {
939
+ context
940
+ });
941
+ const status = (_error_response2 = error.response) == null ? void 0 : _error_response2.status;
942
+ // A 429 (Too Many Requests) is a transient rate-limit signal, not a code or
943
+ // logic failure — and a request that never got a response is a client-side
944
+ // connectivity problem, not a server fault. Both are logged at `warn` so they
945
+ // don't pollute error dashboards or trigger PagerDuty. The 429 case covers
946
+ // both Cloudflare WAF blocks and application-level rate limiting.
947
+ const inferredLevel = status === 429 || status === undefined ? 'warn' : 'error';
948
+ // A 5xx is a server fault: no call site is entitled to downgrade it, however
949
+ // expected it believes the failure to be. The hint only applies below 500.
950
+ const isServerFault = status !== undefined && status >= 500;
951
+ const logLevel = (options == null ? void 0 : options.level) === 'warn' && !isServerFault ? 'warn' : inferredLevel;
952
+ Logger[logLevel]('[DynamicWaasWalletClient] Axios error: ', logPayload);
953
+ // No response at all: report it as such rather than laundering it into a 500.
954
+ if (status === undefined) {
955
+ throw new WalletApiError(NETWORK_ERROR_STATUS, NETWORK_ERROR_MESSAGE, NETWORK_ERROR_CODE);
956
+ }
957
+ var _resolveStatusMessage;
958
+ // Preserve the real status. Collapsing every unmapped code to 500 made a 404
959
+ // (backup not found) and a 504 (gateway timeout) both surface as
960
+ // "Internal server error", so neither the caller nor a monitor could tell a
961
+ // missing resource from an outage.
962
+ const resolvedMessage = (_resolveStatusMessage = resolveStatusMessage(status, error)) != null ? _resolveStatusMessage : `Request failed with status ${status}`;
963
+ throw new WalletApiError(status, resolvedMessage, extractServerErrorCode(error));
964
+ };
965
+
966
+ /**
967
+ * Thrown when a signMessage/signTransaction SSE stream ends with `consent_required` instead of
968
+ * completing — the wallet belongs to a business account with an unmet signing-quorum requirement.
969
+ * Mirrors `BusinessAccountActionRequired`: `reason` tells the caller whether to sign `intent`
970
+ * (`INTENT_REQUIRED`) or wait for approvals on `proposalId` (`APPROVALS_REQUIRED`).
971
+ *
972
+ * A governed offline-recovery reshare's `INTENT_REQUIRED` also carries
973
+ * `offlineRecoveryEncryptionKey`, the key the server will encrypt the recovery
974
+ * share to; the reshare Intent must echo it.
975
+ */ class SigningConsentRequiredError extends Error {
976
+ constructor(actionRequired){
977
+ super(`Signing requires consent: ${actionRequired.reason}`);
978
+ this.name = 'SigningConsentRequiredError';
979
+ this.reason = actionRequired.reason;
980
+ this.intent = actionRequired.intent;
981
+ this.proposalId = actionRequired.proposalId;
982
+ this.approvalRequirements = actionRequired.approvalRequirements;
983
+ if (actionRequired.offlineRecoveryEncryptionKey) {
984
+ this.offlineRecoveryEncryptionKey = actionRequired.offlineRecoveryEncryptionKey;
985
+ }
986
+ }
987
+ }
988
+ /**
989
+ * The consent error for a server's action-required payload, also handed to the caller's `onError`.
990
+ * Every transport reports it this way: the browser's cached-room sign ignores the request's
991
+ * rejection and only reacts to `onError`, so skipping it leaves the sign waiting for a timeout.
992
+ */ const reportConsentRequired = (actionRequired, onError)=>{
993
+ const error = new SigningConsentRequiredError(actionRequired);
994
+ onError == null ? void 0 : onError(error);
995
+ return error;
996
+ };
997
+ /**
998
+ * The `202 { code: 'consent_required', reason, ... }` body the HTTP ceremony transport answers with
999
+ * where the SSE stream would send a `consent_required` event. `undefined` for any other body.
1000
+ */ const asConsentRequiredFrom202Body = (body)=>(body == null ? void 0 : body.code) === SuccessEventType.ConsentRequired && isBusinessAccountActionRequired(body) ? body : undefined;
1001
+
658
1002
  const getElapsedTime = (startTime)=>{
659
1003
  return startTime ? (Date.now() - startTime).toString() : undefined;
660
1004
  };
1005
+ /**
1006
+ * Reports a request that failed before any response (e.g. a dropped
1007
+ * connection) to `onError` and returns the error to reject with. Axios errors
1008
+ * carry request config (incl. auth headers) on the error itself, so onError
1009
+ * only gets a fresh error with the message, HTTP status and backend code (the
1010
+ * 409 recovery predicates key off `code`), never the raw error object.
1011
+ */ const reportRequestFailure = (err, onError)=>{
1012
+ var _err_response, _err_response_data, _err_response1;
1013
+ const error = err instanceof Error ? err : new Error(String(err));
1014
+ const status = err == null ? void 0 : (_err_response = err.response) == null ? void 0 : _err_response.status;
1015
+ const code = extractServerErrorCode(err);
1016
+ // The server's reason (e.g. a policy denial on a held HTTP response) beats axios's generic "status code 400".
1017
+ const serverMessage = err == null ? void 0 : (_err_response1 = err.response) == null ? void 0 : (_err_response_data = _err_response1.data) == null ? void 0 : _err_response_data.error;
1018
+ const message = typeof serverMessage === 'string' && serverMessage ? serverMessage : error.message;
1019
+ try {
1020
+ onError == null ? void 0 : onError(Object.assign(new Error(message), _extends({}, status !== undefined && {
1021
+ status
1022
+ }, code && {
1023
+ code
1024
+ })));
1025
+ } catch (observerError) {
1026
+ Logger.warn('Event stream error observer threw', {
1027
+ observerErrorType: observerError instanceof Error ? observerError.name : typeof observerError
1028
+ });
1029
+ }
1030
+ return error;
1031
+ };
1032
+ /**
1033
+ * A promise that can be rejected from outside. Paired with the SSE stream's
1034
+ * onError callback it lets a caller race a ceremony (relay join, MPC
1035
+ * operation) against server-side failures that arrive AFTER the success event
1036
+ * (e.g. room_created) already resolved the handshake — a policy denial
1037
+ * otherwise only surfaces as the ceremony's own timeout.
1038
+ * The internal catch swallows a rejection that never wins a race so it can't
1039
+ * surface as an unhandled rejection.
1040
+ */ const createRejectablePromise = ()=>{
1041
+ let reject;
1042
+ const promise = new Promise((_, rej)=>{
1043
+ reject = rej;
1044
+ });
1045
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
1046
+ promise.catch(()=>{});
1047
+ return {
1048
+ promise,
1049
+ reject
1050
+ };
1051
+ };
1052
+ /**
1053
+ * Redcoast's 422 intent_required envelope (`{ code, payload: { intent } }`),
1054
+ * normalized to the same `{ reason, intent }` shape a 202 consent-pending
1055
+ * body already carries. `undefined` for any other 422 body.
1056
+ */ const asIntentRequiredFrom422Body = (parsed)=>{
1057
+ var _body_payload;
1058
+ if (typeof parsed !== 'object' || parsed === null) return undefined;
1059
+ const body = parsed;
1060
+ return body.code === 'intent_required' && ((_body_payload = body.payload) == null ? void 0 : _body_payload.intent) ? {
1061
+ intent: body.payload.intent,
1062
+ reason: 'INTENT_REQUIRED'
1063
+ } : undefined;
1064
+ };
1065
+ /** Drains a fetch-adapter stream body into its full text. */ const readStreamToText = async (reader)=>{
1066
+ const decoder = new TextDecoder();
1067
+ let text = '';
1068
+ const pump = async ()=>{
1069
+ const chunk = await reader.read();
1070
+ if (chunk.value) {
1071
+ text += decoder.decode(chunk.value, {
1072
+ stream: true
1073
+ });
1074
+ }
1075
+ if (chunk.done) {
1076
+ return text + decoder.decode();
1077
+ }
1078
+ return pump();
1079
+ };
1080
+ return pump();
1081
+ };
1082
+ const parseJsonOrText = (text)=>{
1083
+ try {
1084
+ return JSON.parse(text);
1085
+ } catch (e) {
1086
+ return text;
1087
+ }
1088
+ };
1089
+ const SERVER_ERROR_CODE_KEYS = [
1090
+ 'code',
1091
+ 'error_code',
1092
+ 'error'
1093
+ ];
1094
+ // handleAxiosError logs `response.data` verbatim, so only the machine-readable code fields may survive.
1095
+ const pickServerErrorCodes = (body)=>{
1096
+ if (typeof body !== 'object' || body === null) return undefined;
1097
+ const record = body;
1098
+ return Object.fromEntries(SERVER_ERROR_CODE_KEYS.flatMap((key)=>typeof record[key] === 'string' ? [
1099
+ [
1100
+ key,
1101
+ record[key]
1102
+ ]
1103
+ ] : []));
1104
+ };
1105
+ /**
1106
+ * With `responseType: 'stream'` an error response's body is an unread stream, so the backend's
1107
+ * `code` never reaches `handleAxiosError`. Replaces it in place with its code fields only.
1108
+ */ const drainStreamErrorBody = async (err)=>{
1109
+ var _response_data;
1110
+ const response = err == null ? void 0 : err.response;
1111
+ if (!(response == null ? void 0 : (_response_data = response.data) == null ? void 0 : _response_data.getReader)) return;
1112
+ try {
1113
+ Object.assign(response, {
1114
+ data: pickServerErrorCodes(parseJsonOrText(await readStreamToText(response.data.getReader())))
1115
+ });
1116
+ } catch (readError) {
1117
+ Logger.warn('Could not read the error response body', {
1118
+ readError
1119
+ });
1120
+ }
1121
+ };
661
1122
  /**
662
1123
  * Creates a promise that resolves when a specific event is received from an event stream.
663
1124
  * Adds a timeout to prevent hanging and races the two promises.
@@ -666,7 +1127,10 @@ const getElapsedTime = (startTime)=>{
666
1127
  * @param apiClient The axios instance to use for API calls
667
1128
  * @param options The configuration options
668
1129
  * @returns A promise that resolves with the event data or rejects on timeout
669
- */ const createEventStreamPromise = ({ apiClient, dynamicRequestId, endpoint, body, successEventType, timeoutMs = 30000, timeoutMessage, onError, onCeremonyComplete, mfaToken, elevatedAccessToken, forwardMPCClientEnabled, traceContext })=>{
1130
+ */ const createEventStreamPromise = ({ apiClient, dynamicRequestId, endpoint, body, successEventType, timeoutMs = 30000, timeoutMessage, onError, onCeremonyComplete, onSlowDelivery, slowDeliveryWatchdogMs = 4000, mfaToken, elevatedAccessToken, forwardMPCClientEnabled, traceContext })=>{
1131
+ // At runtime this can also resolve with a BusinessAccountActionRequired body
1132
+ // (see the 202 handling below) — callers that can reach a governed 202 must
1133
+ // declare their own wider `Promise<T | BusinessAccountActionRequired>` return type.
670
1134
  const headers = _extends({
671
1135
  Accept: 'text/event-stream',
672
1136
  'Cache-Control': 'no-cache',
@@ -681,31 +1145,74 @@ const getElapsedTime = (startTime)=>{
681
1145
  [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
682
1146
  [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
683
1147
  });
684
- // Create a promise that will resolve when the success event is received
1148
+ // Watchdog: warn (via onSlowDelivery) when the success event is late. The
1149
+ // delivery lag this surfaces is otherwise invisible — buffering proxies hold
1150
+ // the stream's bytes until the connection closes (see the create-wallet
1151
+ // "user created without a wallet" App Review failures).
1152
+ const requestStartedAt = Date.now();
1153
+ let headersReceived = false;
1154
+ let eventsSeen = 0;
1155
+ let successOrErrorSeen = false;
1156
+ let watchdogId;
1157
+ if (onSlowDelivery) {
1158
+ watchdogId = setTimeout(()=>{
1159
+ if (!successOrErrorSeen) {
1160
+ onSlowDelivery({
1161
+ elapsedMs: Date.now() - requestStartedAt,
1162
+ endpoint,
1163
+ eventsSeen,
1164
+ headersReceived,
1165
+ watchdogMs: slowDeliveryWatchdogMs
1166
+ });
1167
+ }
1168
+ }, slowDeliveryWatchdogMs);
1169
+ }
1170
+ // Create a promise that will resolve when the success event is received
685
1171
  const eventPromise = new Promise((resolve, reject)=>{
686
1172
  apiClient.post(endpoint, body, {
687
1173
  responseType: 'stream',
688
1174
  headers: _extends({}, headers),
689
- adapter: 'fetch'
690
- }).then(createSuccessErrorEventStreamHandler({
691
- onError,
692
- reject,
693
- resolve,
694
- successEventType,
695
- onCeremonyComplete
696
- })).catch(reject);
1175
+ adapter: 'fetch',
1176
+ // Axios's default validateStatus treats any non-2xx as an error,
1177
+ // rejecting before the intent_required body below is ever read. 422
1178
+ // is added to the accepted range so it resolves the same way 202
1179
+ // already does (202 is 2xx, so it needed no override).
1180
+ validateStatus: (status)=>status >= 200 && status < 300 || status === 422
1181
+ }).then((response)=>{
1182
+ headersReceived = true;
1183
+ return createSuccessErrorEventStreamHandler({
1184
+ onError,
1185
+ reject,
1186
+ resolve,
1187
+ successEventType,
1188
+ onCeremonyComplete,
1189
+ onEvent: (eventType)=>{
1190
+ eventsSeen += 1;
1191
+ if (eventType === successEventType || eventType === 'error') {
1192
+ successOrErrorSeen = true;
1193
+ clearTimeout(watchdogId);
1194
+ }
1195
+ }
1196
+ })(response);
1197
+ })// Without onError, a caller that races the ceremony against it (the cached-room
1198
+ // sign path never awaits this promise) waits out its queue timeout instead.
1199
+ .catch(async (err)=>{
1200
+ await drainStreamErrorBody(err);
1201
+ reject(reportRequestFailure(err, onError));
1202
+ });
697
1203
  });
698
1204
  // Add a timeout to prevent hanging
699
1205
  let timeoutId;
700
1206
  const timeoutPromise = new Promise((_, reject)=>{
701
1207
  timeoutId = setTimeout(()=>reject(new Error(timeoutMessage)), timeoutMs);
702
1208
  });
703
- // Return the event data as soon as it's available, clearing the timeout either way
1209
+ // Return the event data as soon as it's available, clearing the timers either way
704
1210
  return Promise.race([
705
1211
  eventPromise,
706
1212
  timeoutPromise
707
1213
  ]).finally(()=>{
708
1214
  clearTimeout(timeoutId);
1215
+ clearTimeout(watchdogId);
709
1216
  });
710
1217
  };
711
1218
  /**
@@ -719,31 +1226,101 @@ const getElapsedTime = (startTime)=>{
719
1226
  * @param {string} successEventType - The event type string that indicates a successful operation
720
1227
  * @param {function} [onError] - Optional callback for error handling, allowing custom error processing
721
1228
  * @returns {function} A response handler function that processes the event stream
722
- */ const createSuccessErrorEventStreamHandler = ({ resolve, reject, successEventType, onError, onCeremonyComplete })=>{
1229
+ */ const createSuccessErrorEventStreamHandler = ({ resolve, reject, successEventType, onError, onCeremonyComplete, onEvent })=>{
723
1230
  return (response)=>{
1231
+ const rejectWithStatusError = ()=>{
1232
+ const error = new Error(`Request failed with status ${response.status}`);
1233
+ reject(error);
1234
+ onError == null ? void 0 : onError(error);
1235
+ };
724
1236
  // Reject immediately for non-2xx HTTP responses (e.g. 429 rate limit).
725
1237
  // With axios fetch adapter + responseType: 'stream', non-2xx responses
726
1238
  // may not be rejected automatically and arrive here as a stream of
727
1239
  // non-SSE content that would never parse into success/error events.
728
1240
  if (response.status && (response.status < 200 || response.status >= 300)) {
729
- const error = new Error(`Request failed with status ${response.status}`);
730
- reject(error);
731
- onError == null ? void 0 : onError(error);
1241
+ // A governed ceremony with nothing signed yet answers 422
1242
+ // intent_required — read its body for the intent to sign instead of
1243
+ // reporting a generic failure.
1244
+ if (response.status !== 422) {
1245
+ rejectWithStatusError();
1246
+ return;
1247
+ }
1248
+ readStreamToText(response.data.getReader()).then((text)=>{
1249
+ let parsed;
1250
+ try {
1251
+ parsed = JSON.parse(text);
1252
+ } catch (parseError) {
1253
+ Logger.warn('Unparsable 422 body — reporting a generic failure', {
1254
+ parseError
1255
+ });
1256
+ rejectWithStatusError();
1257
+ return;
1258
+ }
1259
+ const intentRequired = asIntentRequiredFrom422Body(parsed);
1260
+ if (intentRequired) {
1261
+ resolve(intentRequired);
1262
+ } else {
1263
+ rejectWithStatusError();
1264
+ }
1265
+ }).catch((err)=>{
1266
+ const error = err instanceof Error ? err : new Error(String(err));
1267
+ reject(error);
1268
+ onError == null ? void 0 : onError(error);
1269
+ });
1270
+ return;
1271
+ }
1272
+ // A governed business-account mutation answers 202 with a single JSON
1273
+ // object instead of opening the ceremony's SSE stream — read it as plain
1274
+ // text, not as events. An unrecognized 202 body falls through to the SSE
1275
+ // parser below (which finds no events and times out) rather than
1276
+ // resolving with something the caller can't act on.
1277
+ if (response.status === 202) {
1278
+ readStreamToText(response.data.getReader()).then((text)=>{
1279
+ let parsed;
1280
+ try {
1281
+ parsed = JSON.parse(text);
1282
+ } catch (parseError) {
1283
+ Logger.warn('Unparsable 202 body — falling through to the SSE parser, which will time out', {
1284
+ parseError
1285
+ });
1286
+ return;
1287
+ }
1288
+ if (isBusinessAccountActionRequired(parsed)) {
1289
+ resolve(parsed);
1290
+ } else {
1291
+ Logger.warn('202 response is not a recognized action-required body — falling through to the SSE parser, which will time out', {
1292
+ parsed
1293
+ });
1294
+ }
1295
+ }).catch((err)=>{
1296
+ const error = err instanceof Error ? err : new Error(String(err));
1297
+ reject(error);
1298
+ onError == null ? void 0 : onError(error);
1299
+ });
732
1300
  return;
733
1301
  }
734
1302
  const reader = response.data.getReader();
735
1303
  const decoder = new TextDecoder();
736
1304
  let buffer = '';
737
1305
  let settled = false;
1306
+ let ceremonyCompleteSeen = false;
738
1307
  const processEvents = (events)=>{
739
1308
  for (const event of events){
1309
+ onEvent == null ? void 0 : onEvent(event.type);
740
1310
  if (event.type === successEventType) {
741
1311
  settled = true;
742
1312
  resolve(event.data);
743
1313
  }
744
1314
  if (event.type === SuccessEventType.CeremonyComplete) {
745
- const { accountAddress, walletId, shareSetId, shareSetType } = event.data;
746
- onCeremonyComplete == null ? void 0 : onCeremonyComplete(accountAddress, walletId, shareSetId, shareSetType);
1315
+ ceremonyCompleteSeen = true;
1316
+ onCeremonyComplete == null ? void 0 : onCeremonyComplete(event.data);
1317
+ }
1318
+ // Sent instead of the success event when an unmet signing quorum blocks the sign;
1319
+ // treated as terminal, since the caller must act on `reason` rather than retry.
1320
+ if (event.type === SuccessEventType.ConsentRequired) {
1321
+ settled = true;
1322
+ reject(reportConsentRequired(event.data, onError));
1323
+ return true;
747
1324
  }
748
1325
  if (event.type === 'error') {
749
1326
  settled = true;
@@ -773,6 +1350,12 @@ const getElapsedTime = (startTime)=>{
773
1350
  const error = new Error('SSE stream ended without a success or error event');
774
1351
  reject(error);
775
1352
  onError == null ? void 0 : onError(error);
1353
+ } else if (onCeremonyComplete && !ceremonyCompleteSeen) {
1354
+ // A ceremony op resolved early on its room-created event, but the
1355
+ // stream closed before ceremony_complete — the server-side ceremony
1356
+ // did not finish (or the event was dropped). Surface via onError so
1357
+ // callers gating backup on completion abort instead of hanging.
1358
+ onError == null ? void 0 : onError(new Error('SSE stream ended before ceremony_complete'));
776
1359
  }
777
1360
  return;
778
1361
  }
@@ -788,12 +1371,17 @@ const getElapsedTime = (startTime)=>{
788
1371
  if (hadError) {
789
1372
  return;
790
1373
  }
791
- processStream();
1374
+ void processStream();
792
1375
  } catch (err) {
793
- reject(err instanceof Error ? err : new Error(String(err)));
1376
+ const error = err instanceof Error ? err : new Error(String(err));
1377
+ reject(error);
1378
+ // A transport drop after the API promise already resolved (on
1379
+ // room_created) would otherwise leave a ceremony backer hanging — surface
1380
+ // it so onError-gated callers abort.
1381
+ onError == null ? void 0 : onError(error);
794
1382
  }
795
1383
  };
796
- processStream();
1384
+ void processStream();
797
1385
  };
798
1386
  };
799
1387
  /**
@@ -808,6 +1396,37 @@ const getElapsedTime = (startTime)=>{
808
1396
  }
809
1397
  return error;
810
1398
  };
1399
+ /**
1400
+ * Sends a plain JSON POST and resolves with the parsed response body.
1401
+ * A lightweight alternative to createEventStreamPromise for endpoints that
1402
+ * return a single JSON object instead of an SSE stream.
1403
+ */ const requestJson = ({ apiClient, dynamicRequestId, endpoint, body, idempotencyKey, timeoutMs = 5000, timeoutMessage, mfaToken, elevatedAccessToken, forwardMPCClientEnabled, onError, traceContext })=>{
1404
+ const headers = _extends({}, body !== undefined && {
1405
+ 'Content-Type': 'application/json'
1406
+ }, idempotencyKey && {
1407
+ 'x-idempotency-key': idempotencyKey
1408
+ }, {
1409
+ [DynamicRequestIdHeader]: dynamicRequestId,
1410
+ [DynamicMfaTokenHeader]: mfaToken,
1411
+ [DynamicElevatedAccessTokenHeader]: elevatedAccessToken,
1412
+ [DynamicForwardMPCHeader]: forwardMPCClientEnabled,
1413
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
1414
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
1415
+ });
1416
+ let timeoutId;
1417
+ const timeoutPromise = new Promise((_, reject)=>{
1418
+ timeoutId = setTimeout(()=>reject(new Error(timeoutMessage)), timeoutMs);
1419
+ });
1420
+ const requestPromise = apiClient.post(endpoint, body, {
1421
+ headers
1422
+ }).then((response)=>response.data).catch((err)=>{
1423
+ throw reportRequestFailure(err, onError);
1424
+ });
1425
+ return Promise.race([
1426
+ requestPromise,
1427
+ timeoutPromise
1428
+ ]).finally(()=>clearTimeout(timeoutId));
1429
+ };
811
1430
  /**
812
1431
  * Parses a Server-Sent Events (SSE) stream into structured event objects.
813
1432
  * Returns both the parsed events and any remaining unparsed data (incomplete events)
@@ -864,9 +1483,139 @@ const getElapsedTime = (startTime)=>{
864
1483
  };
865
1484
  };
866
1485
 
867
- var version = "0.0.354";
1486
+ /**
1487
+ * Thrown when sign-and-broadcast answers 413: the request body is over the server's 640kb limit,
1488
+ * which large calldata can reach.
1489
+ */ class SignAndBroadcastRequestTooLargeError extends Error {
1490
+ constructor(){
1491
+ super('The sign-and-broadcast request is too large. Send less calldata.');
1492
+ this.name = 'SignAndBroadcastRequestTooLargeError';
1493
+ }
1494
+ }
1495
+
1496
+ const getRequiredExternalKeyShareId = (ks)=>{
1497
+ if (!ks.externalKeyShareId) {
1498
+ throw new Error(`Missing externalKeyShareId for key share (id: ${ks.id}, keygenId: ${ks.keygenId})`);
1499
+ }
1500
+ return ks.externalKeyShareId;
1501
+ };
1502
+ /**
1503
+ * A `dynamic` key share is retrievable only via its `externalKeyShareId`, so
1504
+ * recording one without that reference persists an unrecoverable share that
1505
+ * locks the user out at recovery time (where `getRequiredExternalKeyShareId`
1506
+ * throws). Throw the same error here so the bad backup location is rejected
1507
+ * before it is posted and surfaces in Datadog exactly as the recovery path does.
1508
+ */ const assertDynamicLocationsHaveExternalKeyShareId = (locations)=>locations.filter((location)=>location.location === BackupLocation.DYNAMIC).forEach((location)=>getRequiredExternalKeyShareId(location));
1509
+
1510
+ var version = "0.1.0-request-signing";
1511
+
1512
+ const EMPTY_BODY = new Uint8Array(0);
1513
+ // Built per call: a module-scope encoder throws on import in runtimes without TextEncoder (jsdom).
1514
+ const encodeUtf8 = (text)=>new TextEncoder().encode(text);
1515
+ /** Serializes a request body once so the signed bytes are the sent bytes. */ const serializeBody = (config)=>{
1516
+ const { data } = config;
1517
+ if (data === undefined || data === null) return EMPTY_BODY;
1518
+ if (typeof data === 'string') return encodeUtf8(data);
1519
+ if (data instanceof Uint8Array) return data;
1520
+ if (typeof data !== 'object' || data instanceof ArrayBuffer || typeof data.pipe === 'function') {
1521
+ throw new Error('Cannot sign a request body that is not a string, bytes or JSON object');
1522
+ }
1523
+ const json = JSON.stringify(data);
1524
+ config.data = json;
1525
+ config.headers.set('Content-Type', 'application/json');
1526
+ return encodeUtf8(json);
1527
+ };
1528
+ const toRequestTarget = (client, config)=>{
1529
+ const { pathname, search } = new URL(client.getUri(config), 'http://localhost');
1530
+ return `${pathname}${search}`;
1531
+ };
1532
+ /**
1533
+ * Runs `sign` on every request this client sends, retries included, so each
1534
+ * attempt carries its own proof.
1535
+ */ const installRequestSigner = (client, sign)=>{
1536
+ client.interceptors.request.use(async (config)=>{
1537
+ const authorization = config.headers.get('Authorization');
1538
+ var _config_method;
1539
+ const headers = await sign({
1540
+ method: ((_config_method = config.method) != null ? _config_method : 'get').toUpperCase(),
1541
+ path: toRequestTarget(client, config),
1542
+ body: serializeBody(config),
1543
+ authorization: typeof authorization === 'string' ? authorization : undefined
1544
+ });
1545
+ Object.entries(headers).forEach(([name, value])=>config.headers.set(name, value));
1546
+ return config;
1547
+ });
1548
+ };
868
1549
 
1550
+ /**
1551
+ * Reads the Authorization header off an axios request config, which stores
1552
+ * headers either as a plain object or as an `AxiosHeaders` instance.
1553
+ */ const readAuthorizationHeader = (requestHeaders)=>{
1554
+ if (typeof requestHeaders !== 'object' || requestHeaders === null) {
1555
+ return undefined;
1556
+ }
1557
+ const headers = requestHeaders;
1558
+ var _headers_Authorization;
1559
+ const authorization = (_headers_Authorization = headers['Authorization']) != null ? _headers_Authorization : headers['authorization'];
1560
+ if (typeof authorization !== 'string') {
1561
+ return undefined;
1562
+ }
1563
+ return authorization;
1564
+ };
869
1565
  class BaseClient {
1566
+ /**
1567
+ * Fire {@link onUnauthorized} whenever a request on this axios instance sees a
1568
+ * 401, so the iframe can tell the host to log the user out.
1569
+ *
1570
+ * Both branches are needed: ordinary requests reject on 401 (onRejected),
1571
+ * but the SSE sign/keygen path uses the fetch adapter with
1572
+ * `responseType: 'stream'`, where a non-2xx response can arrive *resolved*
1573
+ * (see createSuccessErrorEventStreamHandler) — so the fulfilled branch must
1574
+ * inspect `response.status` too. The interceptor never alters the
1575
+ * response/error; it only signals out-of-band, leaving existing error
1576
+ * handling unchanged.
1577
+ */ installUnauthorizedInterceptor(client) {
1578
+ const fireIfUnauthorized = (status, requestHeaders)=>{
1579
+ if (status !== 401) {
1580
+ return;
1581
+ }
1582
+ if (this.isSupersededAuthHeader(requestHeaders)) {
1583
+ this.logger.info('[BaseClient] ignoring 401 for a request that carried a superseded auth token');
1584
+ return;
1585
+ }
1586
+ try {
1587
+ this.onUnauthorized == null ? void 0 : this.onUnauthorized.call(this);
1588
+ } catch (error) {
1589
+ this.logger.error('[BaseClient] onUnauthorized handler threw', {
1590
+ error
1591
+ });
1592
+ }
1593
+ };
1594
+ client.interceptors.response.use((response)=>{
1595
+ var _response_config;
1596
+ fireIfUnauthorized(response == null ? void 0 : response.status, response == null ? void 0 : (_response_config = response.config) == null ? void 0 : _response_config.headers);
1597
+ return response;
1598
+ }, (error)=>{
1599
+ var _error_response, _error_config;
1600
+ var _error_response_status;
1601
+ fireIfUnauthorized((_error_response_status = error == null ? void 0 : (_error_response = error.response) == null ? void 0 : _error_response.status) != null ? _error_response_status : error == null ? void 0 : error.status, error == null ? void 0 : (_error_config = error.config) == null ? void 0 : _error_config.headers);
1602
+ return Promise.reject(error);
1603
+ });
1604
+ }
1605
+ /**
1606
+ * Whether a request was sent with an auth token that {@link syncAuthToken} has
1607
+ * since replaced. Its 401 says nothing about the token the client holds now,
1608
+ * so it must not reach {@link onUnauthorized} and log the user out.
1609
+ */ isSupersededAuthHeader(requestHeaders) {
1610
+ if (this.authMode !== AuthMode.HEADER || !this.currentAuthHeader) {
1611
+ return false;
1612
+ }
1613
+ const requestAuthHeader = readAuthorizationHeader(requestHeaders);
1614
+ if (!requestAuthHeader) {
1615
+ return false;
1616
+ }
1617
+ return requestAuthHeader !== this.currentAuthHeader;
1618
+ }
870
1619
  get forwardMPCClient() {
871
1620
  if (!this._forwardMpcClient) {
872
1621
  throw new Error('Forward MPC client is not initialized');
@@ -884,6 +1633,7 @@ class BaseClient {
884
1633
  throw new Error('Auth token is required for header authentication');
885
1634
  }
886
1635
  const authHeader = `Bearer ${authToken}`;
1636
+ this.currentAuthHeader = authHeader;
887
1637
  this.apiClient.defaults.headers['Authorization'] = authHeader;
888
1638
  this.clientRelayApiClient.defaults.headers['Authorization'] = authHeader;
889
1639
  this.apiClient.defaults.headers.common['Authorization'] = authHeader;
@@ -903,12 +1653,14 @@ class BaseClient {
903
1653
  this.clientRelayApiClient.defaults.headers['Authorization'] = `Bearer ${backupServiceAuthToken}`;
904
1654
  }
905
1655
  constructor({ environmentId, baseApiUrl, authToken, backupServiceAuthToken, baseClientKeysharesRelayApiUrl, authMode = AuthMode.HEADER, // Represents the version of the client SDK used by developer
906
- sdkVersion, forwardMPCClient, logger }){
1656
+ sdkVersion, forwardMPCClient, logger, onUnauthorized, requestSigner }){
907
1657
  this.logger = logger != null ? logger : new NoopLogger();
1658
+ this.onUnauthorized = onUnauthorized;
908
1659
  const headers = {};
909
1660
  // Only set Authorization header if using header auth mode and token is provided
910
1661
  if (authMode === AuthMode.HEADER && authToken) {
911
1662
  headers['Authorization'] = `Bearer ${authToken}`;
1663
+ this.currentAuthHeader = headers['Authorization'];
912
1664
  }
913
1665
  headers['x-dyn-wallet-sdk-version'] = version;
914
1666
  headers['x-dyn-version'] = sdkVersion;
@@ -929,6 +1681,7 @@ class BaseClient {
929
1681
  // so we need to pass the backupServiceAuthToken to the clientRelayApiClient
930
1682
  // This was requested from the backend during initWaasWalletClient
931
1683
  if (authMode === AuthMode.COOKIE && backupServiceAuthToken && !authToken) {
1684
+ this.backupServiceAuthToken = backupServiceAuthToken;
932
1685
  headers['Authorization'] = `Bearer ${backupServiceAuthToken}`;
933
1686
  }
934
1687
  this.clientRelayApiClient = axios.create({
@@ -938,13 +1691,150 @@ class BaseClient {
938
1691
  [RELAY_APP_ID_HEADER]: DYNAMIC_CLIENT_RELAY_REDCOAST_APP_ID_MAP[environment]
939
1692
  })
940
1693
  });
1694
+ this.installUnauthorizedInterceptor(this.apiClient);
1695
+ this.installUnauthorizedInterceptor(this.clientRelayApiClient);
1696
+ // CKS accepts a server signer's recover only with its proof, so the relay client signs too.
1697
+ if (requestSigner) {
1698
+ installRequestSigner(this.apiClient, requestSigner);
1699
+ installRequestSigner(this.clientRelayApiClient, requestSigner);
1700
+ }
941
1701
  this.forwardMPCClient = forwardMPCClient;
942
1702
  }
943
1703
  }
944
1704
 
1705
+ const createWalletAccountRequestBody = ({ chainName, clientKeygenIds, thresholdSignatureScheme, skipLock, bitcoinConfig, businessAccountId, returnEncryptedWalletApiKey })=>{
1706
+ const { addressType } = bitcoinConfig || {};
1707
+ return _extends({
1708
+ chain: chainName,
1709
+ clientKeygenIds,
1710
+ thresholdSignatureScheme
1711
+ }, skipLock ? {
1712
+ skipLock
1713
+ } : {}, addressType ? {
1714
+ addressType
1715
+ } : {}, businessAccountId ? {
1716
+ businessAccountId
1717
+ } : {}, returnEncryptedWalletApiKey ? {
1718
+ delegateToProjectEnvironment: true
1719
+ } : {});
1720
+ };
1721
+ const MAX_SERVER_MESSAGE_LENGTH = 200;
1722
+ /**
1723
+ * A rejected sign-and-broadcast as a `WalletApiError` that names the server's reason and code, since the generic status text says nothing about which check failed. A failure with no response (timeout, no connection) passes through.
1724
+ *
1725
+ * @param error - What the request threw.
1726
+ */ const toSignAndBroadcastApiError = (error)=>{
1727
+ if (!isAxiosError(error) || !error.response) {
1728
+ return error;
1729
+ }
1730
+ const { status, data } = error.response;
1731
+ const code = extractServerErrorCode(error);
1732
+ const record = data && typeof data === 'object' ? data : undefined;
1733
+ const serverMessage = [
1734
+ record == null ? void 0 : record['error'],
1735
+ record == null ? void 0 : record['message']
1736
+ ].find((candidate)=>typeof candidate === 'string' && candidate.length > 0 && candidate !== code);
1737
+ const detail = [
1738
+ serverMessage == null ? void 0 : serverMessage.slice(0, MAX_SERVER_MESSAGE_LENGTH),
1739
+ code && `code: ${code}`
1740
+ ].filter(Boolean).join(', ');
1741
+ const suffix = detail ? ` (${detail})` : '';
1742
+ return new WalletApiError(status, `Sign and broadcast failed with status ${status}${suffix}`, code);
1743
+ };
1744
+ /** The governed-mutation body fields; the flag the intent was signed over wins, then the wrapper's, then the option. */ const toGovernedBody = ({ autoExecute, signedIntent })=>{
1745
+ var _signed_intent;
1746
+ const signed = sanitizeBusinessAccountSignedIntent(signedIntent);
1747
+ var _signed_intent_autoExecute, _ref;
1748
+ const effectiveAutoExecute = (_ref = (_signed_intent_autoExecute = signed == null ? void 0 : (_signed_intent = signed.intent) == null ? void 0 : _signed_intent.autoExecute) != null ? _signed_intent_autoExecute : signed == null ? void 0 : signed.autoExecute) != null ? _ref : autoExecute;
1749
+ return _extends({}, signed, effectiveAutoExecute === undefined ? {} : {
1750
+ autoExecute: effectiveAutoExecute
1751
+ });
1752
+ };
945
1753
  class DynamicApiClient extends BaseClient {
1754
+ // --- Earn / yield vaults (SDK routes, gated by the environment's Earn feature flag) ---
1755
+ /** List the yield vaults enabled for the environment. */ async listYieldVaults({ traceContext } = {}) {
1756
+ const { data } = await this.apiClient.get(`${this.sdkYieldRoutePrefix}/vaults`, {
1757
+ headers: this.buildTraceHeaders(traceContext)
1758
+ });
1759
+ return data;
1760
+ }
1761
+ /** Full detail for a single vault, including the asset and contract metadata needed to deposit. */ async getYieldVaultDetails({ vaultId, traceContext }) {
1762
+ const { data } = await this.apiClient.get(`${this.sdkYieldRoutePrefix}/vaults/${vaultId}`, {
1763
+ headers: this.buildTraceHeaders(traceContext)
1764
+ });
1765
+ return data;
1766
+ }
1767
+ /** An owner's shares and underlying assets in a vault. */ async getYieldVaultPosition({ vaultId, ownerAddress, traceContext }) {
1768
+ const { data } = await this.apiClient.get(`${this.sdkYieldRoutePrefix}/vaults/${vaultId}/position`, {
1769
+ params: {
1770
+ ownerAddress
1771
+ },
1772
+ headers: this.buildTraceHeaders(traceContext)
1773
+ });
1774
+ return data;
1775
+ }
1776
+ /** Rewards accrued by an owner in a vault. */ async getYieldVaultRewards({ vaultId, ownerAddress, traceContext }) {
1777
+ const { data } = await this.apiClient.get(`${this.sdkYieldRoutePrefix}/vaults/${vaultId}/rewards`, {
1778
+ params: {
1779
+ ownerAddress
1780
+ },
1781
+ headers: this.buildTraceHeaders(traceContext)
1782
+ });
1783
+ return data;
1784
+ }
1785
+ /** Indexed performance of an owner's position in a vault (trails the chain head). */ async getYieldVaultPositionPerformance({ vaultId, ownerAddress, traceContext }) {
1786
+ const { data } = await this.apiClient.get(`${this.sdkYieldRoutePrefix}/vaults/${vaultId}/position/performance`, {
1787
+ params: {
1788
+ ownerAddress
1789
+ },
1790
+ headers: this.buildTraceHeaders(traceContext)
1791
+ });
1792
+ return data;
1793
+ }
1794
+ /** An owner's earnings across every vault on a chain, with USD totals and a per-vault breakdown. */ async getYieldEarnings({ ownerAddress, chainId, chainName, traceContext }) {
1795
+ const { data } = await this.apiClient.get(`${this.sdkYieldRoutePrefix}/earnings`, {
1796
+ params: _extends({
1797
+ ownerAddress,
1798
+ chainId
1799
+ }, chainName ? {
1800
+ chainName
1801
+ } : {}),
1802
+ headers: this.buildTraceHeaders(traceContext)
1803
+ });
1804
+ return data;
1805
+ }
1806
+ /** Build the unsigned deposit transaction (plus ERC-20 approval when the allowance is short). */ async yieldVaultDeposit({ vaultId, ownerAddress, amount, receiverAddress, traceContext }) {
1807
+ const { data } = await this.apiClient.post(`${this.sdkYieldRoutePrefix}/vaults/${vaultId}/deposit`, _extends({
1808
+ ownerAddress,
1809
+ amount
1810
+ }, receiverAddress ? {
1811
+ receiverAddress
1812
+ } : {}), {
1813
+ headers: this.buildTraceHeaders(traceContext)
1814
+ });
1815
+ return data;
1816
+ }
1817
+ /** Build the unsigned withdrawal transaction. */ async yieldVaultWithdraw({ vaultId, ownerAddress, amount, receiverAddress, traceContext }) {
1818
+ const { data } = await this.apiClient.post(`${this.sdkYieldRoutePrefix}/vaults/${vaultId}/withdraw`, _extends({
1819
+ ownerAddress,
1820
+ amount
1821
+ }, receiverAddress ? {
1822
+ receiverAddress
1823
+ } : {}), {
1824
+ headers: this.buildTraceHeaders(traceContext)
1825
+ });
1826
+ return data;
1827
+ }
1828
+ /** Build the unsigned reward-claim transaction. */ async yieldVaultClaim({ vaultId, ownerAddress, traceContext }) {
1829
+ const { data } = await this.apiClient.post(`${this.sdkYieldRoutePrefix}/vaults/${vaultId}/claim`, {
1830
+ ownerAddress
1831
+ }, {
1832
+ headers: this.buildTraceHeaders(traceContext)
1833
+ });
1834
+ return data;
1835
+ }
946
1836
  async getBackupRelayToken({ traceContext }) {
947
- const { data } = await this.apiClient.get(`/api/v0/sdk/${this.environmentId}/waas/keyShares/backup/token`, {
1837
+ const { data } = await this.apiClient.get(`${this.waasRoutePrefix}/keyShares/backup/token`, {
948
1838
  headers: {
949
1839
  [DynamicRequestIdHeader]: v4().replace('-', ''),
950
1840
  [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
@@ -953,47 +1843,124 @@ class DynamicApiClient extends BaseClient {
953
1843
  });
954
1844
  return data.token;
955
1845
  }
956
- async authenticateApiToken({ environmentId }) {
1846
+ /**
1847
+ * In cookie mode the relay token is fetched once at iframe boot and never
1848
+ * refreshed, so session rotation or token expiry leaves it stale (DYNT-2309).
1849
+ * Wraps each relay call: re-mint only when the pinned token is missing or
1850
+ * expiring, and retry once with a fresh token when the relay rejects the call
1851
+ * with 403 (revoked session after rotation). The API client authenticates via
1852
+ * cookie, so the new token always carries the live session. A 401 is left to
1853
+ * the existing onUnauthorized handling — session genuinely invalid.
1854
+ */ async withBackupTokenRefresh(call) {
1855
+ if (this.authMode !== AuthMode.COOKIE) {
1856
+ return call();
1857
+ }
1858
+ if (this.isBackupTokenExpiringSoon()) {
1859
+ await this.mintBackupRelayToken();
1860
+ }
1861
+ try {
1862
+ return await call();
1863
+ } catch (error) {
1864
+ var _error_response;
1865
+ const status = isAxiosError(error) ? (_error_response = error.response) == null ? void 0 : _error_response.status : undefined;
1866
+ if (status !== 403) {
1867
+ throw error;
1868
+ }
1869
+ }
1870
+ await this.mintBackupRelayToken();
1871
+ return call();
1872
+ }
1873
+ isBackupTokenExpiringSoon() {
1874
+ if (!this.backupServiceAuthToken) {
1875
+ return true;
1876
+ }
1877
+ try {
1878
+ const payload = JSON.parse(Buffer.from(this.backupServiceAuthToken.split('.')[1], 'base64').toString('utf-8'));
1879
+ return typeof payload.exp !== 'number' || payload.exp * 1000 < Date.now() + 30000;
1880
+ } catch (e) {
1881
+ return true;
1882
+ }
1883
+ }
1884
+ async mintBackupRelayToken() {
1885
+ var _this_backupRelayTokenRefresh;
1886
+ (_this_backupRelayTokenRefresh = this.backupRelayTokenRefresh) != null ? _this_backupRelayTokenRefresh : this.backupRelayTokenRefresh = this.getBackupRelayToken({}).then((token)=>this.syncBackupServiceAuthToken(token)).finally(()=>{
1887
+ this.backupRelayTokenRefresh = undefined;
1888
+ });
1889
+ await this.backupRelayTokenRefresh;
1890
+ }
1891
+ async authenticateApiToken({ environmentId, signingPublicKey }) {
957
1892
  return this.apiClient.post(`/api/v0/environments/${environmentId}/waas/authenticate`, undefined, {
958
- headers: {
1893
+ headers: _extends({
959
1894
  [DynamicRequestIdHeader]: v4().replace('-', '')
960
- }
1895
+ }, signingPublicKey ? {
1896
+ [DynamicSessionPublicKeyHeader]: signingPublicKey
1897
+ } : {})
961
1898
  });
962
1899
  }
963
- async createWalletAccount({ chainName, clientKeygenIds, dynamicRequestId, thresholdSignatureScheme, skipLock, bitcoinConfig, onError, onCeremonyComplete, traceContext }) {
964
- const { addressType } = bitcoinConfig || {};
965
- const requestBody = _extends({
966
- chain: chainName,
1900
+ async createWalletAccount({ chainName, clientKeygenIds, dynamicRequestId, thresholdSignatureScheme, skipLock, bitcoinConfig, businessAccountId, returnEncryptedWalletApiKey, onError, onCeremonyComplete, onSlowDelivery, traceContext }) {
1901
+ const requestBody = createWalletAccountRequestBody({
1902
+ chainName,
967
1903
  clientKeygenIds,
968
- thresholdSignatureScheme
969
- }, skipLock ? {
970
- skipLock
971
- } : {}, addressType ? {
972
- addressType
973
- } : {});
1904
+ thresholdSignatureScheme,
1905
+ skipLock,
1906
+ bitcoinConfig,
1907
+ businessAccountId,
1908
+ returnEncryptedWalletApiKey});
974
1909
  return createEventStreamPromise({
975
1910
  apiClient: this.apiClient,
976
1911
  dynamicRequestId,
977
- endpoint: `/api/v0/sdk/${this.environmentId}/waas/create`,
1912
+ endpoint: `${this.waasRoutePrefix}/create`,
978
1913
  body: requestBody,
979
1914
  successEventType: SuccessEventType.KeygenComplete,
980
1915
  timeoutMessage: 'Wallet creation timed out',
981
1916
  onError,
982
1917
  onCeremonyComplete,
1918
+ onSlowDelivery,
1919
+ traceContext
1920
+ });
1921
+ }
1922
+ /**
1923
+ * Plain-JSON (non-SSE) request to the `/create` endpoint. Does NOT synchronously
1924
+ * create the wallet: it initiates the server keygen ceremony (mints the MPC room,
1925
+ * enqueues the async worker that builds the wallet) and returns `{ roomId,
1926
+ * serverKeygenIds }`. With `poll: true` it instead reads the in-flight ceremony,
1927
+ * returning the wallet identity (`walletId`/`accountAddress`/`shareSetId`) once the
1928
+ * worker has finished. The wallet is the product of the full ceremony, not this call.
1929
+ */ async requestWalletCreationJson({ chainName, clientKeygenIds, dynamicRequestId, thresholdSignatureScheme, skipLock, bitcoinConfig, businessAccountId, returnEncryptedWalletApiKey, idempotencyKey, timeoutMs, traceContext, poll }) {
1930
+ const requestBody = _extends({}, createWalletAccountRequestBody({
1931
+ chainName,
1932
+ clientKeygenIds,
1933
+ thresholdSignatureScheme,
1934
+ skipLock,
1935
+ bitcoinConfig,
1936
+ businessAccountId,
1937
+ returnEncryptedWalletApiKey}), poll ? {
1938
+ poll: true
1939
+ } : {});
1940
+ return requestJson({
1941
+ apiClient: this.apiClient,
1942
+ dynamicRequestId,
1943
+ idempotencyKey,
1944
+ endpoint: `${this.waasRoutePrefix}/create`,
1945
+ body: requestBody,
1946
+ timeoutMs,
1947
+ timeoutMessage: 'Wallet creation timed out',
983
1948
  traceContext
984
1949
  });
985
1950
  }
986
- async signMessage({ dynamicRequestId, walletId, shareSetId, message, onError, isFormatted, mfaToken, elevatedAccessToken, roomId, context, forwardMPCClientEnabled, traceContext, bitcoinConfig }) {
1951
+ async signMessage({ dynamicRequestId, walletId, shareSetId, message, onError, isFormatted, mfaToken, elevatedAccessToken, roomId, context, approvalQuorum, forwardMPCClientEnabled, traceContext, bitcoinConfig }) {
987
1952
  return createEventStreamPromise({
988
1953
  apiClient: this.apiClient,
989
1954
  dynamicRequestId,
990
- endpoint: `/api/v0/sdk/${this.environmentId}/waas/${walletId}/signMessage`,
1955
+ endpoint: `${this.waasRoutePrefix}/${walletId}/signMessage`,
991
1956
  body: _extends({
992
1957
  message,
993
1958
  isFormatted,
994
1959
  context,
995
1960
  roomId
996
- }, bitcoinConfig ? {
1961
+ }, approvalQuorum ? {
1962
+ approvalQuorum
1963
+ } : {}, bitcoinConfig ? {
997
1964
  bitcoinConfig
998
1965
  } : {}, shareSetId ? {
999
1966
  shareSetId
@@ -1007,11 +1974,120 @@ class DynamicApiClient extends BaseClient {
1007
1974
  traceContext
1008
1975
  });
1009
1976
  }
1977
+ /**
1978
+ * Plain-JSON (non-SSE) variant of `signMessage`. Hits the same
1979
+ * `/signMessage` endpoint; the `x-idempotency-key` header tells the backend
1980
+ * (when `enable-http-waas-transport-signmessage` is on) to respond with the
1981
+ * OpenRoomResponse synchronously instead of streaming `room_created` over SSE.
1982
+ * Unlike wallet creation, no completion polling is needed — the response is final.
1983
+ *
1984
+ * @throws SigningConsentRequiredError when a governed wallet needs approvers' consent first
1985
+ * (the backend answers 202 `consent_required` instead of a room).
1986
+ */ async requestSignMessageJson({ dynamicRequestId, walletId, shareSetId, message, onError, isFormatted, mfaToken, elevatedAccessToken, roomId, context, approvalQuorum, idempotencyKey, forwardMPCClientEnabled, traceContext, bitcoinConfig }) {
1987
+ const response = await requestJson({
1988
+ apiClient: this.apiClient,
1989
+ dynamicRequestId,
1990
+ idempotencyKey,
1991
+ endpoint: `${this.waasRoutePrefix}/${walletId}/signMessage`,
1992
+ body: _extends({
1993
+ message,
1994
+ isFormatted,
1995
+ context,
1996
+ roomId
1997
+ }, approvalQuorum ? {
1998
+ approvalQuorum
1999
+ } : {}, bitcoinConfig ? {
2000
+ bitcoinConfig
2001
+ } : {}, shareSetId ? {
2002
+ shareSetId
2003
+ } : {}),
2004
+ timeoutMs: 20000,
2005
+ timeoutMessage: 'Message signing timed out',
2006
+ onError,
2007
+ mfaToken,
2008
+ elevatedAccessToken,
2009
+ forwardMPCClientEnabled,
2010
+ traceContext
2011
+ });
2012
+ const consentRequired = asConsentRequiredFrom202Body(response);
2013
+ if (consentRequired) {
2014
+ throw reportConsentRequired(consentRequired, onError);
2015
+ }
2016
+ return response;
2017
+ }
2018
+ /**
2019
+ * Starts a sign-and-broadcast: Dynamic opens a signing room, you sign in it, and Dynamic then sends the transaction. The signature never comes back.
2020
+ *
2021
+ * @param params.walletId - The wallet that signs.
2022
+ * @param params.shareSetId - Which of the wallet's key sets to use. Defaults to its active one.
2023
+ * @param params.message - The transaction as the bytes to sign (RLP hex on EVM, message bytes on Solana). Not hashed.
2024
+ * @param params.context - What the message does in readable form (chain, recipient, amount). Dynamic checks it against the wallet and its policies.
2025
+ * @param params.broadcastOptions - Solana send settings: other required signers' signatures, and skipping the pre-send dry run.
2026
+ * @param params.isFormatted - `true` if the message is already a hash. `false` for a serialized transaction.
2027
+ * @param params.requestedCertainty - How sure to be before calling it confirmed: `fast`, `safe` or `final`, or `chain:` plus a chain-specific value. Defaults to `safe`.
2028
+ * @param params.externalReference - Your own label, returned on every event. Not unique.
2029
+ * @param params.roomId - A signing room you already opened; Dynamic opens one when omitted.
2030
+ * @param params.approvalQuorum - Approvers' consent for a governed wallet, sent on the retry after `intent_required`.
2031
+ * @param params.idempotencyKey - Makes a retry safe: the same key replays the stored answer instead of sending twice.
2032
+ * @param params.dynamicRequestId - Id of this one request, to match client and server logs.
2033
+ * @param params.traceContext - Ties this call's logs to the server's, across retries. Created when omitted.
2034
+ * @param params.mfaToken - Proof of the user's multi-factor check, when the wallet needs one.
2035
+ * @param params.elevatedAccessToken - Proof of a recent re-login, when the wallet needs one.
2036
+ * @param params.onError - Called with the failure's message, never the raw error.
2037
+ * @returns The transaction record: its id, its status, and the signing room while signing is pending.
2038
+ * @throws SignAndBroadcastRequestTooLargeError when the body is over the server limit.
2039
+ * @throws SigningConsentRequiredError when a governed wallet needs approvers' consent first.
2040
+ * @throws WalletApiError when the server rejects it, with its reason and code.
2041
+ */ async signAndBroadcast({ dynamicRequestId, walletId, shareSetId, context, broadcastOptions, message, isFormatted, requestedCertainty, externalReference, roomId, approvalQuorum, idempotencyKey, onError, mfaToken, elevatedAccessToken, traceContext }) {
2042
+ try {
2043
+ return await requestJson({
2044
+ apiClient: this.apiClient,
2045
+ dynamicRequestId,
2046
+ idempotencyKey,
2047
+ endpoint: `${this.waasRoutePrefix}/${walletId}/signAndBroadcast`,
2048
+ body: _extends({
2049
+ message,
2050
+ context
2051
+ }, broadcastOptions ? {
2052
+ broadcastOptions
2053
+ } : {}, {
2054
+ isFormatted
2055
+ }, requestedCertainty ? {
2056
+ requestedCertainty
2057
+ } : {}, externalReference ? {
2058
+ externalReference
2059
+ } : {}, roomId ? {
2060
+ roomId
2061
+ } : {}, approvalQuorum ? {
2062
+ approvalQuorum
2063
+ } : {}, shareSetId ? {
2064
+ shareSetId
2065
+ } : {}),
2066
+ timeoutMs: 20000,
2067
+ timeoutMessage: 'Sign and broadcast timed out',
2068
+ onError,
2069
+ mfaToken,
2070
+ elevatedAccessToken,
2071
+ traceContext
2072
+ });
2073
+ } catch (error) {
2074
+ const response = error.response;
2075
+ if ((response == null ? void 0 : response.status) === 413) {
2076
+ throw new SignAndBroadcastRequestTooLargeError();
2077
+ }
2078
+ // A governed wallet with nothing signed yet answers 422 intent_required, as plain signing's stream does.
2079
+ const intentRequired = (response == null ? void 0 : response.status) === 422 ? asIntentRequiredFrom422Body(response.data) : undefined;
2080
+ if (intentRequired) {
2081
+ throw new SigningConsentRequiredError(intentRequired);
2082
+ }
2083
+ throw toSignAndBroadcastApiError(error);
2084
+ }
2085
+ }
1010
2086
  async refreshWalletAccountShares({ dynamicRequestId, walletId, shareSetId, onError, onCeremonyComplete, mfaToken, elevatedAccessToken, traceContext }) {
1011
2087
  return createEventStreamPromise({
1012
2088
  apiClient: this.apiClient,
1013
2089
  dynamicRequestId,
1014
- endpoint: `/api/v0/sdk/${this.environmentId}/waas/${walletId}/refresh`,
2090
+ endpoint: `${this.waasRoutePrefix}/${walletId}/refresh`,
1015
2091
  body: shareSetId ? {
1016
2092
  shareSetId
1017
2093
  } : undefined,
@@ -1024,11 +2100,11 @@ class DynamicApiClient extends BaseClient {
1024
2100
  traceContext
1025
2101
  });
1026
2102
  }
1027
- async reshare({ walletId, shareSetId, dynamicRequestId, clientKeygenIds, oldThresholdSignatureScheme, newThresholdSignatureScheme, delegateToProjectEnvironment, revokeDelegation, mfaToken, elevatedAccessToken, onError, onCeremonyComplete, traceContext }) {
2103
+ async reshare({ walletId, shareSetId, dynamicRequestId, clientKeygenIds, oldThresholdSignatureScheme, newThresholdSignatureScheme, delegateToProjectEnvironment, revokeDelegation, mfaToken, elevatedAccessToken, onError, onCeremonyComplete, traceContext, initialSignerRules, reshareKind, offlineRecoveryEncryptionKey, approvalQuorum, proposalId }) {
1028
2104
  return createEventStreamPromise({
1029
2105
  apiClient: this.apiClient,
1030
2106
  dynamicRequestId,
1031
- endpoint: `/api/v0/sdk/${this.environmentId}/waas/${walletId}/reshare`,
2107
+ endpoint: `${this.waasRoutePrefix}/${walletId}/reshare`,
1032
2108
  body: _extends({
1033
2109
  clientKeygenIds,
1034
2110
  delegateToProjectEnvironment,
@@ -1037,6 +2113,16 @@ class DynamicApiClient extends BaseClient {
1037
2113
  revokeDelegation
1038
2114
  }, shareSetId ? {
1039
2115
  shareSetId
2116
+ } : {}, initialSignerRules ? {
2117
+ initialSignerRules
2118
+ } : {}, reshareKind ? {
2119
+ reshareKind
2120
+ } : {}, offlineRecoveryEncryptionKey ? {
2121
+ offlineRecoveryEncryptionKey
2122
+ } : {}, approvalQuorum ? {
2123
+ approvalQuorum
2124
+ } : {}, proposalId ? {
2125
+ proposalId
1040
2126
  } : {}),
1041
2127
  successEventType: SuccessEventType.RoomCreated,
1042
2128
  timeoutMessage: 'Reshare timed out',
@@ -1047,7 +2133,7 @@ class DynamicApiClient extends BaseClient {
1047
2133
  traceContext
1048
2134
  });
1049
2135
  }
1050
- async exportKey({ mfaToken, elevatedAccessToken, dynamicRequestId, walletId, shareSetId, exportId, bitcoinConfig, onError, traceContext }) {
2136
+ async exportKey({ mfaToken, elevatedAccessToken, dynamicRequestId, walletId, shareSetId, exportId, bitcoinConfig, approvalQuorum, proposalId, onError, traceContext }) {
1051
2137
  const { addressType } = bitcoinConfig || {};
1052
2138
  const requestBody = _extends({
1053
2139
  exportId
@@ -1055,11 +2141,15 @@ class DynamicApiClient extends BaseClient {
1055
2141
  addressType
1056
2142
  } : {}, shareSetId ? {
1057
2143
  shareSetId
2144
+ } : {}, approvalQuorum ? {
2145
+ approvalQuorum
2146
+ } : {}, proposalId ? {
2147
+ proposalId
1058
2148
  } : {});
1059
2149
  return createEventStreamPromise({
1060
2150
  apiClient: this.apiClient,
1061
2151
  dynamicRequestId,
1062
- endpoint: `/api/v0/sdk/${this.environmentId}/waas/${walletId}/privateKey/export`,
2152
+ endpoint: `${this.waasRoutePrefix}/${walletId}/privateKey/export`,
1063
2153
  body: requestBody,
1064
2154
  successEventType: SuccessEventType.RoomCreated,
1065
2155
  timeoutMessage: 'Key export timed out',
@@ -1070,6 +2160,35 @@ class DynamicApiClient extends BaseClient {
1070
2160
  });
1071
2161
  }
1072
2162
  /**
2163
+ * Plain-JSON (non-SSE) variant of `exportKey`. Hits the same
2164
+ * `/privateKey/export` endpoint; the `x-idempotency-key` header tells the
2165
+ * backend (when `enable-http-waas-transport-export` is on) to respond with
2166
+ * the OpenRoomResponse synchronously instead of streaming `room_created`
2167
+ * over SSE.
2168
+ */ async requestExportKeyJson({ mfaToken, elevatedAccessToken, dynamicRequestId, walletId, shareSetId, exportId, bitcoinConfig, onError, traceContext, idempotencyKey, timeoutMs }) {
2169
+ const { addressType } = bitcoinConfig || {};
2170
+ const requestBody = _extends({
2171
+ exportId
2172
+ }, addressType ? {
2173
+ addressType
2174
+ } : {}, shareSetId ? {
2175
+ shareSetId
2176
+ } : {});
2177
+ return requestJson({
2178
+ apiClient: this.apiClient,
2179
+ dynamicRequestId,
2180
+ idempotencyKey,
2181
+ endpoint: `${this.waasRoutePrefix}/${walletId}/privateKey/export`,
2182
+ body: requestBody,
2183
+ timeoutMs: timeoutMs != null ? timeoutMs : 20000,
2184
+ timeoutMessage: 'Key export timed out',
2185
+ onError,
2186
+ mfaToken,
2187
+ elevatedAccessToken,
2188
+ traceContext
2189
+ });
2190
+ }
2191
+ /**
1073
2192
  * Kick off the Aleo view-key export MPC ceremony. Returns the MPC room once
1074
2193
  * redcoast + wallet-service have joined; the client then joins the same
1075
2194
  * room via Sodot's `exportViewKey` to receive the view key.
@@ -1232,7 +2351,7 @@ class DynamicApiClient extends BaseClient {
1232
2351
  return data;
1233
2352
  }
1234
2353
  async getDelegatedEncryptionKey({ environmentId, traceContext }) {
1235
- const { data } = await this.apiClient.get(`/api/v0/sdk/${environmentId}/waas/delegatedAccess/encryptionPublicKey`, {
2354
+ const { data } = await this.apiClient.get(`${this.sdkRoutePrefix}/${environmentId}/waas/delegatedAccess/encryptionPublicKey`, {
1236
2355
  headers: {
1237
2356
  [DynamicRequestIdHeader]: v4().replace('-', ''),
1238
2357
  [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
@@ -1246,7 +2365,7 @@ class DynamicApiClient extends BaseClient {
1246
2365
  throw new Error('Signed session ID is required');
1247
2366
  }
1248
2367
  const apiClient = this.apiClient;
1249
- const { data, status } = await apiClient.post(`/api/v0/sdk/${this.environmentId}/waas/${walletId}/delegatedAccess/delivery`, _extends({
2368
+ const { data, status } = await apiClient.post(`${this.waasRoutePrefix}/${walletId}/delegatedAccess/delivery`, _extends({
1250
2369
  encryptedDelegatedShare: encryptedKeyShare
1251
2370
  }, shareSetId ? {
1252
2371
  shareSetId
@@ -1263,20 +2382,11 @@ class DynamicApiClient extends BaseClient {
1263
2382
  status
1264
2383
  };
1265
2384
  }
1266
- // shareSetId is accepted in the param shape so callers can thread their
1267
- // wallet-map state through, but is intentionally NOT destructured or
1268
- // forwarded — CKS is a share-set-agnostic storage service keyed by
1269
- // externalKeyShareId.
1270
- async storeEncryptedBackupByWallet({ walletId, encryptedKeyShares, passwordEncrypted, signedSessionId, encryptionVersion, requiresSignedSessionId = false, dynamicRequestId, traceContext }) {
2385
+ async revokeDelegation({ walletId, shareSetId, signedSessionId, requiresSignedSessionId = false, dynamicRequestId, traceContext }) {
1271
2386
  if (requiresSignedSessionId && !signedSessionId) {
1272
2387
  throw new Error('Signed session ID is required');
1273
2388
  }
1274
- const { data } = await this.clientRelayApiClient.post(`/api/v0/sdk/${this.environmentId}/waas/${walletId}/keyShares/backup`, {
1275
- // TODO: decide on whether to store encryptedAccountCredentials or encryptedKeyShares as backup
1276
- encryptedAccountCredentials: encryptedKeyShares,
1277
- passwordEncrypted,
1278
- encryptionVersion
1279
- }, {
2389
+ const { data } = await this.apiClient.delete(`/api/v0/sdk/${this.environmentId}/waas/${walletId}/delegatedAccess/${shareSetId}`, {
1280
2390
  headers: {
1281
2391
  [DynamicRequestIdHeader]: dynamicRequestId,
1282
2392
  [DynamicClientSessionSignature]: signedSessionId,
@@ -1286,13 +2396,58 @@ class DynamicApiClient extends BaseClient {
1286
2396
  });
1287
2397
  return data;
1288
2398
  }
1289
- async markKeySharesAsBackedUp({ walletId, shareSetId, locations, dynamicRequestId, traceContext, passwordUpdateBatchId }) {
1290
- const { data } = await this.apiClient.post(`/api/v0/sdk/${this.environmentId}/waas/${walletId}/keyShares/backup/locations`, _extends({
2399
+ // shareSetId is forwarded only when `sendLocation` is also true —
2400
+ // that's the signal that CKS should call redcoast's backup/locations
2401
+ // itself once the share is stored. Redcoast needs shareSetId to resolve
2402
+ // which share set to activate when a wallet has more than one (e.g. mid
2403
+ // refresh/reshare, where an old active set and a new pending set coexist);
2404
+ // without it CKS would have nothing to forward and activation could target
2405
+ // the wrong set.
2406
+ async storeEncryptedBackupByWallet({ walletId, encryptedKeyShares, passwordEncrypted, passwordSetByBA, signedSessionId, sessionPublicKey, encryptionVersion, requiresSignedSessionId = false, dynamicRequestId, traceContext, sendLocation, shareSetId, businessAccountId, passwordUpdateBatchId }) {
2407
+ if (requiresSignedSessionId && !signedSessionId) {
2408
+ throw new Error('Signed session ID is required');
2409
+ }
2410
+ return this.withBackupTokenRefresh(async ()=>{
2411
+ const { data } = await this.clientRelayApiClient.post(`${this.waasRoutePrefix}/${walletId}/keyShares/backup`, _extends({
2412
+ // TODO: decide on whether to store encryptedAccountCredentials or encryptedKeyShares as backup
2413
+ encryptedAccountCredentials: encryptedKeyShares,
2414
+ passwordEncrypted
2415
+ }, passwordSetByBA !== undefined ? {
2416
+ passwordSetByBA
2417
+ } : {}, {
2418
+ encryptionVersion
2419
+ }, sendLocation ? _extends({
2420
+ sendLocation
2421
+ }, shareSetId ? {
2422
+ shareSetId
2423
+ } : {}, businessAccountId ? {
2424
+ businessAccountId
2425
+ } : {}, passwordUpdateBatchId ? {
2426
+ passwordUpdateBatchId
2427
+ } : {}) : {}), {
2428
+ headers: _extends({
2429
+ [DynamicRequestIdHeader]: dynamicRequestId,
2430
+ [DynamicClientSessionSignature]: signedSessionId
2431
+ }, sessionPublicKey ? {
2432
+ [DynamicSessionPublicKeyHeader]: sessionPublicKey
2433
+ } : {}, {
2434
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2435
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
2436
+ })
2437
+ });
2438
+ return data;
2439
+ });
2440
+ }
2441
+ async markKeySharesAsBackedUp({ walletId, shareSetId, locations, dynamicRequestId, traceContext, passwordUpdateBatchId, businessAccountId }) {
2442
+ assertDynamicLocationsHaveExternalKeyShareId(locations);
2443
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/keyShares/backup/locations`, _extends({
1291
2444
  locations
1292
2445
  }, passwordUpdateBatchId && {
1293
2446
  passwordUpdateBatchId
1294
2447
  }, shareSetId ? {
1295
2448
  shareSetId
2449
+ } : {}, businessAccountId ? {
2450
+ businessAccountId
1296
2451
  } : {}), {
1297
2452
  headers: {
1298
2453
  [DynamicRequestIdHeader]: dynamicRequestId,
@@ -1324,30 +2479,32 @@ class DynamicApiClient extends BaseClient {
1324
2479
  const recoverBody = externalKeyShareIds ? {
1325
2480
  keyShareIds: externalKeyShareIds
1326
2481
  } : undefined;
1327
- const { data } = await this.clientRelayApiClient.post(`/api/v0/sdk/${this.environmentId}/waas/${walletId}/keyShares/recover`, recoverBody, {
1328
- headers: {
1329
- [DynamicRequestIdHeader]: dynamicRequestId,
1330
- [DynamicClientSessionSignature]: signedSessionId,
1331
- [DynamicMfaTokenHeader]: mfaToken,
1332
- [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
1333
- [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
1334
- }
1335
- });
1336
- if (data.keyShares && data.keyShares.length > 1) {
1337
- this.logger.warn('Recover encrypted backup by wallet returning more than 1 share', {
1338
- context: {
1339
- dynamicRequestId,
1340
- environmentId: this.environmentId,
1341
- keyShareCount: data.keyShares.length,
1342
- walletId,
1343
- userId
2482
+ return this.withBackupTokenRefresh(async ()=>{
2483
+ const { data } = await this.clientRelayApiClient.post(`${this.waasRoutePrefix}/${walletId}/keyShares/recover`, recoverBody, {
2484
+ headers: {
2485
+ [DynamicRequestIdHeader]: dynamicRequestId,
2486
+ [DynamicClientSessionSignature]: signedSessionId,
2487
+ [DynamicMfaTokenHeader]: mfaToken,
2488
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2489
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
1344
2490
  }
1345
2491
  });
1346
- }
1347
- return data;
2492
+ if (data.keyShares && data.keyShares.length > 1) {
2493
+ this.logger.warn('Recover encrypted backup by wallet returning more than 1 share', {
2494
+ context: {
2495
+ dynamicRequestId,
2496
+ environmentId: this.environmentId,
2497
+ keyShareCount: data.keyShares.length,
2498
+ walletId,
2499
+ userId
2500
+ }
2501
+ });
2502
+ }
2503
+ return data;
2504
+ });
1348
2505
  }
1349
2506
  async getAccessToken({ oauthAccountId, traceContext }) {
1350
- const { data } = await this.apiClient.get(`/api/v0/sdk/${this.environmentId}/oauthAccounts/${oauthAccountId}/accessToken`, {
2507
+ const { data } = await this.apiClient.get(`${this.sdkRoutePrefix}/${this.environmentId}/oauthAccounts/${oauthAccountId}/accessToken`, {
1351
2508
  headers: {
1352
2509
  [DynamicRequestIdHeader]: v4().replace('-', ''),
1353
2510
  [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
@@ -1357,12 +2514,12 @@ class DynamicApiClient extends BaseClient {
1357
2514
  return data.accessToken;
1358
2515
  }
1359
2516
  // TODO: return array instead considering cases where server has multiple parties
1360
- async importPrivateKey({ chainName, dynamicRequestId, clientKeygenIds, thresholdSignatureScheme, bitcoinConfig, onError, onCeremonyComplete, traceContext, legacyWalletId }) {
2517
+ async importPrivateKey({ chainName, dynamicRequestId, clientKeygenIds, thresholdSignatureScheme, bitcoinConfig, onError, onCeremonyComplete, traceContext, legacyWalletId, variant }) {
1361
2518
  const { addressType } = bitcoinConfig || {};
1362
2519
  return createEventStreamPromise({
1363
2520
  apiClient: this.apiClient,
1364
2521
  dynamicRequestId,
1365
- endpoint: `/api/v0/sdk/${this.environmentId}/waas/privateKey/import`,
2522
+ endpoint: `${this.waasRoutePrefix}/privateKey/import`,
1366
2523
  body: _extends({
1367
2524
  chain: chainName,
1368
2525
  clientKeygenIds,
@@ -1371,6 +2528,8 @@ class DynamicApiClient extends BaseClient {
1371
2528
  addressType
1372
2529
  } : {}, legacyWalletId ? {
1373
2530
  legacyWalletId
2531
+ } : {}, variant ? {
2532
+ variant
1374
2533
  } : {}),
1375
2534
  successEventType: SuccessEventType.KeygenComplete,
1376
2535
  timeoutMessage: 'Key import timed out',
@@ -1380,7 +2539,7 @@ class DynamicApiClient extends BaseClient {
1380
2539
  });
1381
2540
  }
1382
2541
  async getUser(dynamicRequestId, traceContext) {
1383
- const { data } = await this.apiClient.get(`/api/v0/sdk/${this.environmentId}/users`, {
2542
+ const { data } = await this.apiClient.get(`${this.sdkRoutePrefix}/${this.environmentId}/users`, {
1384
2543
  headers: {
1385
2544
  [DynamicRequestIdHeader]: dynamicRequestId,
1386
2545
  [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
@@ -1390,7 +2549,7 @@ class DynamicApiClient extends BaseClient {
1390
2549
  return data;
1391
2550
  }
1392
2551
  async refreshUser(traceContext) {
1393
- const { data } = await this.apiClient.post(`/api/v0/sdk/${this.environmentId}/refresh`, undefined, {
2552
+ const { data } = await this.apiClient.post(`${this.sdkRoutePrefix}/${this.environmentId}/refresh`, undefined, {
1394
2553
  headers: {
1395
2554
  [DynamicRequestIdHeader]: v4().replace('-', ''),
1396
2555
  [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
@@ -1400,7 +2559,7 @@ class DynamicApiClient extends BaseClient {
1400
2559
  return data;
1401
2560
  }
1402
2561
  async getEnvironmentSettings(traceContext) {
1403
- const { data } = await this.apiClient.get(`/api/v0/sdk/${this.environmentId}/settings`, {
2562
+ const { data } = await this.apiClient.get(`${this.sdkRoutePrefix}/${this.environmentId}/settings`, {
1404
2563
  headers: {
1405
2564
  [DynamicRequestIdHeader]: v4().replace('-', ''),
1406
2565
  [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
@@ -1423,7 +2582,7 @@ class DynamicApiClient extends BaseClient {
1423
2582
  * Fetch a single WaaS wallet by ID using the /sdk/{environmentId}/waas/{walletId} endpoint.
1424
2583
  * This endpoint returns user information with verified credentials filtered to only include the specified WaaS wallet.
1425
2584
  */ async getWaasWalletByAddress({ walletAddress, traceContext }) {
1426
- const { data } = await this.apiClient.get(`/api/v0/sdk/${this.environmentId}/waas/byWalletAddress/${walletAddress}`, {
2585
+ const { data } = await this.apiClient.get(`${this.waasRoutePrefix}/byWalletAddress/${walletAddress}`, {
1427
2586
  headers: {
1428
2587
  [DynamicRequestIdHeader]: v4().replace('-', ''),
1429
2588
  [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
@@ -1432,25 +2591,281 @@ class DynamicApiClient extends BaseClient {
1432
2591
  });
1433
2592
  return data;
1434
2593
  }
1435
- async delegatedSignMessage({ walletId, message, isFormatted, dynamicRequestId, onError, context, traceContext }) {
1436
- return createEventStreamPromise({
1437
- apiClient: this.apiClient,
1438
- dynamicRequestId,
1439
- endpoint: `/api/v0/environments/${this.environmentId}/waas/${walletId}/delegatedAccess/signMessage`,
1440
- body: {
1441
- message,
1442
- isFormatted,
1443
- context
1444
- },
1445
- successEventType: SuccessEventType.RoomCreated,
1446
- timeoutMessage: 'Delegated sign message timed out',
1447
- onError,
1448
- traceContext
1449
- });
1450
- }
1451
- async createRooms({ walletId, roomType, roomCount = 5, traceContext }) {
1452
- const { data } = await this.apiClient.post(`/api/v0/sdk/${this.environmentId}/waas/${walletId}/createRooms`, {
1453
- roomCount,
2594
+ // --- Business accounts (SDK routes, JWT-authed, membership-scoped) ---
2595
+ /** Create a business account; the caller's JWT user is seeded as the first owner. */ async createBusinessAccount({ request, traceContext }) {
2596
+ const { data } = await this.apiClient.post(this.businessAccountsRoutePrefix, request, {
2597
+ headers: {
2598
+ [DynamicRequestIdHeader]: v4().replace('-', ''),
2599
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2600
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
2601
+ }
2602
+ });
2603
+ return data;
2604
+ }
2605
+ /** List business accounts the caller is a member of. */ async listBusinessAccounts({ traceContext } = {}) {
2606
+ const { data } = await this.apiClient.get(this.businessAccountsRoutePrefix, {
2607
+ headers: {
2608
+ [DynamicRequestIdHeader]: v4().replace('-', ''),
2609
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2610
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
2611
+ }
2612
+ });
2613
+ return data;
2614
+ }
2615
+ /** Get a business account with embedded members + signers. 404 if the caller is not a member. */ async getBusinessAccountById({ businessAccountId, traceContext }) {
2616
+ const { data } = await this.apiClient.get(`${this.businessAccountsRoutePrefix}/${businessAccountId}`, {
2617
+ headers: {
2618
+ [DynamicRequestIdHeader]: v4().replace('-', ''),
2619
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2620
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
2621
+ }
2622
+ });
2623
+ return data;
2624
+ }
2625
+ async listBusinessAccountProposals({ businessAccountId, status, traceContext }) {
2626
+ const { data } = await this.apiClient.get(`${this.businessAccountsRoutePrefix}/${encodeURIComponent(businessAccountId)}/proposals`, _extends({}, status ? {
2627
+ params: {
2628
+ status
2629
+ }
2630
+ } : {}, {
2631
+ headers: this.buildTraceHeaders(traceContext)
2632
+ }));
2633
+ return data;
2634
+ }
2635
+ async getBusinessAccountProposal({ businessAccountId, proposalId, traceContext }) {
2636
+ const { data } = await this.apiClient.get(`${this.businessAccountsRoutePrefix}/${encodeURIComponent(businessAccountId)}/proposals/${encodeURIComponent(proposalId)}`, {
2637
+ headers: this.buildTraceHeaders(traceContext)
2638
+ });
2639
+ return data;
2640
+ }
2641
+ async recordBusinessAccountProposalApproval({ businessAccountId, proposalId, approvedAt, signature, traceContext }) {
2642
+ const { data } = await this.apiClient.post(`${this.businessAccountsRoutePrefix}/${encodeURIComponent(businessAccountId)}/proposals/${encodeURIComponent(proposalId)}/approvals`, {
2643
+ approvedAt,
2644
+ signature
2645
+ }, {
2646
+ headers: this.buildTraceHeaders(traceContext)
2647
+ });
2648
+ return data;
2649
+ }
2650
+ async executeBusinessAccountProposal({ businessAccountId, proposalId, traceContext }) {
2651
+ const { data } = await this.apiClient.post(`${this.businessAccountsRoutePrefix}/${encodeURIComponent(businessAccountId)}/proposals/${encodeURIComponent(proposalId)}/execute`, {}, {
2652
+ headers: this.buildTraceHeaders(traceContext)
2653
+ });
2654
+ return data;
2655
+ }
2656
+ /**
2657
+ * Sends a governed mutation. A 202 consent-pending body resolves as-is; the
2658
+ * 422 `intent_required` refusal is rejected by axios before its body is read,
2659
+ * so it is re-raised as `BusinessAccountIntentRequiredError` for the caller to sign.
2660
+ */ async submitBusinessAccountMutation(send) {
2661
+ try {
2662
+ const { data } = await send();
2663
+ return data;
2664
+ } catch (error) {
2665
+ var _asIntentRequiredFrom422Body;
2666
+ const response = isAxiosError(error) ? error.response : undefined;
2667
+ const intent = (response == null ? void 0 : response.status) === 422 ? (_asIntentRequiredFrom422Body = asIntentRequiredFrom422Body(response.data)) == null ? void 0 : _asIntentRequiredFrom422Body.intent : undefined;
2668
+ if (intent) {
2669
+ throw new BusinessAccountIntentRequiredError(intent);
2670
+ }
2671
+ throw error;
2672
+ }
2673
+ }
2674
+ async updateBusinessAccountMemberRole({ businessAccountId, userId, role, autoExecute, signedIntent, traceContext }) {
2675
+ return this.submitBusinessAccountMutation(()=>this.apiClient.patch(`${this.businessAccountsRoutePrefix}/${encodeURIComponent(businessAccountId)}/members/${encodeURIComponent(userId)}`, _extends({
2676
+ role
2677
+ }, toGovernedBody({
2678
+ autoExecute,
2679
+ signedIntent
2680
+ })), {
2681
+ headers: this.buildTraceHeaders(traceContext)
2682
+ }));
2683
+ }
2684
+ async getBusinessAccountGovernance({ businessAccountId, traceContext }) {
2685
+ const { data } = await this.apiClient.get(`${this.businessAccountsRoutePrefix}/${encodeURIComponent(businessAccountId)}/governance`, {
2686
+ headers: this.buildTraceHeaders(traceContext)
2687
+ });
2688
+ return data;
2689
+ }
2690
+ /** Replaces the whole governance section. Itself governed, so it can answer with the same refusals. */ async setBusinessAccountGovernance({ businessAccountId, governance, autoExecute, signedIntent, traceContext }) {
2691
+ return this.submitBusinessAccountMutation(()=>this.apiClient.put(`${this.businessAccountsRoutePrefix}/${encodeURIComponent(businessAccountId)}/governance`, _extends({
2692
+ governance
2693
+ }, toGovernedBody({
2694
+ autoExecute,
2695
+ signedIntent
2696
+ })), {
2697
+ headers: this.buildTraceHeaders(traceContext)
2698
+ }));
2699
+ }
2700
+ /**
2701
+ * Add an existing wallet to a business account. No ceremony — the server
2702
+ * transfers ownership and registers the caller as owner + signer bound to
2703
+ * their existing share set. Omit `businessAccountId` to find-or-create the
2704
+ * per-wallet business account. Returns the business-account detail. Idempotent.
2705
+ */ async linkWalletToBusinessAccount({ walletId, businessAccountId, traceContext }) {
2706
+ const { data } = await this.apiClient.post(`${this.businessAccountsRoutePrefix}/linkWallet`, _extends({
2707
+ walletId
2708
+ }, businessAccountId ? {
2709
+ businessAccountId
2710
+ } : {}), {
2711
+ headers: {
2712
+ [DynamicRequestIdHeader]: v4().replace('-', ''),
2713
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2714
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
2715
+ }
2716
+ });
2717
+ return data;
2718
+ }
2719
+ /**
2720
+ * Add a member to a business account. Resolve the target by `userId`, or by
2721
+ * `identifier` + `identifierType` (e.g. an email) — the user is created if
2722
+ * absent, mirroring addBusinessAccountSigner.
2723
+ */ async addBusinessAccountMember({ businessAccountId, userId, identifier, identifierType, smsCountryCode, socialProvider, role, autoExecute, signedIntent, traceContext }) {
2724
+ return this.submitBusinessAccountMutation(()=>this.apiClient.post(`${this.businessAccountsRoutePrefix}/${businessAccountId}/members`, _extends({}, userId ? {
2725
+ userId
2726
+ } : {}, identifier ? {
2727
+ identifier
2728
+ } : {}, identifierType ? {
2729
+ type: identifierType
2730
+ } : {}, smsCountryCode ? {
2731
+ smsCountryCode
2732
+ } : {}, socialProvider ? {
2733
+ socialProvider
2734
+ } : {}, role ? {
2735
+ role
2736
+ } : {}, toGovernedBody({
2737
+ autoExecute,
2738
+ signedIntent
2739
+ })), {
2740
+ headers: {
2741
+ [DynamicRequestIdHeader]: v4().replace('-', ''),
2742
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2743
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
2744
+ }
2745
+ }));
2746
+ }
2747
+ /**
2748
+ * Add a signer to a business-account wallet. Resolve the target by `userId`, or by
2749
+ * `identifier` + `identifierType` (e.g. an email). Returns a PENDING signer
2750
+ * (HTTP 202, `shareSetId: null`) — the reshare ceremony that mints the share
2751
+ * is a follow-up and not yet performed server-side.
2752
+ */ async addBusinessAccountSigner({ businessAccountId, walletId, signerType, userId, identifier, identifierType, serverIdentifier, smsCountryCode, socialProvider, traceContext }) {
2753
+ const { data } = await this.apiClient.post(`${this.businessAccountsRoutePrefix}/${businessAccountId}/wallets/${walletId}/signers`, _extends({
2754
+ signerType
2755
+ }, serverIdentifier ? {
2756
+ serverIdentifier
2757
+ } : {}, userId ? {
2758
+ userId
2759
+ } : {}, identifier ? {
2760
+ identifier
2761
+ } : {}, identifierType ? {
2762
+ type: identifierType
2763
+ } : {}, smsCountryCode ? {
2764
+ smsCountryCode
2765
+ } : {}, socialProvider ? {
2766
+ socialProvider
2767
+ } : {}), {
2768
+ headers: {
2769
+ [DynamicRequestIdHeader]: v4().replace('-', ''),
2770
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2771
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
2772
+ }
2773
+ });
2774
+ return data;
2775
+ }
2776
+ /**
2777
+ * SSE ceremony for addSigner. Same-parties 2/2 -> 2/2 reshare on the signers
2778
+ * endpoint: the caller's existing client share participates as the remaining
2779
+ * party (clientKeygenIds = [existing], no new party). The server runs the
2780
+ * reshare with `newServerKeygenIds=[]` and persists the result as a NEW
2781
+ * isolated share set for the target signer — it does not refresh the
2782
+ * caller's set in place.
2783
+ *
2784
+ * Returns the room (createEventStreamPromise) + the new `shareSetId` via
2785
+ * onCeremonyComplete. The resulting client share is reshared locally and
2786
+ * seeded to the client-keyshare-service on the target's behalf (see
2787
+ * `seedBusinessAccountSignerShare`).
2788
+ */ async addBusinessAccountSignerCeremony({ businessAccountId, walletId, clientKeygenIds, oldThresholdSignatureScheme, signerType, userId, identifier, identifierType, serverIdentifier, signedIntent, initialSignerRules, dynamicRequestId, elevatedAccessToken, onError, onCeremonyComplete, traceContext }) {
2789
+ return createEventStreamPromise({
2790
+ apiClient: this.apiClient,
2791
+ dynamicRequestId,
2792
+ elevatedAccessToken,
2793
+ endpoint: `${this.businessAccountsRoutePrefix}/${encodeURIComponent(businessAccountId)}/wallets/${encodeURIComponent(walletId)}/signers`,
2794
+ body: _extends({
2795
+ signerType,
2796
+ clientKeygenIds,
2797
+ oldThresholdSignatureScheme,
2798
+ // FF-on share-set semantics: always reshare to a NEW 2/2 share set.
2799
+ newThresholdSignatureScheme: ThresholdSignatureScheme.TWO_OF_TWO
2800
+ }, serverIdentifier ? {
2801
+ serverIdentifier
2802
+ } : {}, userId ? {
2803
+ userId
2804
+ } : {}, identifier ? {
2805
+ identifier
2806
+ } : {}, identifierType ? {
2807
+ type: identifierType
2808
+ } : {}, sanitizeBusinessAccountSignedIntent(signedIntent), initialSignerRules ? {
2809
+ initialSignerRules
2810
+ } : {}),
2811
+ successEventType: SuccessEventType.RoomCreated,
2812
+ timeoutMessage: 'Add signer reshare timed out',
2813
+ onError,
2814
+ onCeremonyComplete,
2815
+ traceContext
2816
+ });
2817
+ }
2818
+ /**
2819
+ * On-behalf KSS write for addSigner: store the added signer's freshly-reshared
2820
+ * client share in the client-keyshare-service keyed to the ADDED signer's
2821
+ * partition via `targetUserId` in the body. Uses the caller's relay auth (the
2822
+ * business-account-membership gate is FF-bypassed for now; the client-keyshare-service
2823
+ * reads `targetUserId` and inserts-if-empty). Returns the stored keyShareId(s)
2824
+ * to thread as `externalKeyShareId` into `markKeySharesAsBackedUp`.
2825
+ * Hardened auth (scoped grant token) is the follow-up — DYNT-1071/1072.
2826
+ */ async backupOnBehalfOfAddedSigner({ walletId, targetUserId, encryptedAccountCredentials, passwordEncrypted, encryptionVersion, clientKeyshareBackupGrant, signedSessionId, dynamicRequestId, traceContext }) {
2827
+ return this.withBackupTokenRefresh(async ()=>{
2828
+ const { data } = await this.clientRelayApiClient.post(`${this.waasRoutePrefix}/${walletId}/keyShares/backup`, {
2829
+ encryptedAccountCredentials,
2830
+ passwordEncrypted,
2831
+ passwordSetByBA: true,
2832
+ encryptionVersion,
2833
+ targetUserId
2834
+ }, {
2835
+ headers: _extends({
2836
+ [DynamicRequestIdHeader]: dynamicRequestId,
2837
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2838
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
2839
+ }, signedSessionId && {
2840
+ [DynamicClientSessionSignature]: signedSessionId
2841
+ }, clientKeyshareBackupGrant && {
2842
+ Authorization: `Bearer ${clientKeyshareBackupGrant}`
2843
+ })
2844
+ });
2845
+ return data;
2846
+ });
2847
+ }
2848
+ async delegatedSignMessage({ walletId, shareSetId, message, isFormatted, dynamicRequestId, onError, context, traceContext }) {
2849
+ return createEventStreamPromise({
2850
+ apiClient: this.apiClient,
2851
+ dynamicRequestId,
2852
+ endpoint: `/api/v0/environments/${this.environmentId}/waas/${walletId}/delegatedAccess/signMessage`,
2853
+ body: _extends({
2854
+ message,
2855
+ isFormatted,
2856
+ context
2857
+ }, shareSetId ? {
2858
+ shareSetId
2859
+ } : {}),
2860
+ successEventType: SuccessEventType.RoomCreated,
2861
+ timeoutMessage: 'Delegated sign message timed out',
2862
+ onError,
2863
+ traceContext
2864
+ });
2865
+ }
2866
+ async createRooms({ walletId, roomType, roomCount = 5, traceContext }) {
2867
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/createRooms`, {
2868
+ roomCount,
1454
2869
  roomType
1455
2870
  }, {
1456
2871
  headers: {
@@ -1462,7 +2877,7 @@ class DynamicApiClient extends BaseClient {
1462
2877
  return data;
1463
2878
  }
1464
2879
  async createRoomsWithoutWalletId({ roomType, thresholdSignatureScheme, roomCount = 5, traceContext }) {
1465
- const { data } = await this.apiClient.post(`/api/v0/sdk/${this.environmentId}/waas/createRooms`, {
2880
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/createRooms`, {
1466
2881
  roomCount,
1467
2882
  roomType,
1468
2883
  thresholdSignatureScheme
@@ -1475,11 +2890,13 @@ class DynamicApiClient extends BaseClient {
1475
2890
  });
1476
2891
  return data;
1477
2892
  }
1478
- async requestSvmSponsoredTransaction({ transaction, traceContext }) {
2893
+ async requestSvmSponsoredTransaction({ transaction, userId, traceContext }) {
1479
2894
  try {
1480
- const { data } = await this.apiClient.post(`/api/v0/sdk/${this.environmentId}/solana/sponsorTransaction`, {
2895
+ const { data } = await this.apiClient.post(`${this.sdkRoutePrefix}/${this.environmentId}/solana/sponsorTransaction`, _extends({
1481
2896
  transaction
1482
- }, {
2897
+ }, userId ? {
2898
+ userId
2899
+ } : {}), {
1483
2900
  headers: {
1484
2901
  [DynamicRequestIdHeader]: v4().replace('-', ''),
1485
2902
  [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
@@ -1488,15 +2905,109 @@ class DynamicApiClient extends BaseClient {
1488
2905
  });
1489
2906
  return data;
1490
2907
  } catch (error) {
1491
- var _error_response, _error_response1;
1492
- const status = error == null ? void 0 : (_error_response = error.response) == null ? void 0 : _error_response.status;
1493
- const rawData = error == null ? void 0 : (_error_response1 = error.response) == null ? void 0 : _error_response1.data;
1494
- var _rawData_error, _ref;
1495
- const detail = (_ref = (_rawData_error = rawData == null ? void 0 : rawData.error) != null ? _rawData_error : typeof rawData === 'string' ? rawData : JSON.stringify(rawData)) != null ? _ref : error == null ? void 0 : error.message;
1496
- const statusStr = status ? ` (${status})` : '';
1497
- throw new Error(`SVM sponsorship failed${statusStr}: ${detail}`);
2908
+ this.throwGaslessApiError('SVM sponsorship failed', error);
2909
+ }
2910
+ }
2911
+ async getSvmSponsorAddress({ traceContext } = {}) {
2912
+ try {
2913
+ const { data } = await this.apiClient.get(`${this.sdkRoutePrefix}/${this.environmentId}/solana/sponsorAddress`, {
2914
+ headers: this.buildTraceHeaders(traceContext)
2915
+ });
2916
+ return data;
2917
+ } catch (error) {
2918
+ this.throwGaslessApiError('SVM sponsor address lookup failed', error);
2919
+ }
2920
+ }
2921
+ buildTraceHeaders(traceContext) {
2922
+ return {
2923
+ [DynamicRequestIdHeader]: v4().replace('-', ''),
2924
+ [DynamicTraceIdHeader]: traceContext == null ? void 0 : traceContext.traceId,
2925
+ [DynamicTraceElapsedTimeHeader]: getElapsedTime(traceContext == null ? void 0 : traceContext.startTime)
2926
+ };
2927
+ }
2928
+ throwGaslessApiError(label, error) {
2929
+ var _error_response, _error_response1;
2930
+ const status = error == null ? void 0 : (_error_response = error.response) == null ? void 0 : _error_response.status;
2931
+ const rawData = error == null ? void 0 : (_error_response1 = error.response) == null ? void 0 : _error_response1.data;
2932
+ var _rawData_error, _ref;
2933
+ const detail = (_ref = (_rawData_error = rawData == null ? void 0 : rawData.error) != null ? _rawData_error : typeof rawData === 'string' ? rawData : JSON.stringify(rawData)) != null ? _ref : error == null ? void 0 : error.message;
2934
+ const statusStr = status ? ` (${status})` : '';
2935
+ // Callers that branch on the HTTP status (e.g. re-authenticating on a 401)
2936
+ // need it as data, not prose. The axios error is not re-thrown or attached
2937
+ // as a cause because its config carries the request's bearer token.
2938
+ throw Object.assign(new Error(`${label}${statusStr}: ${detail}`), {
2939
+ status
2940
+ });
2941
+ }
2942
+ async sponsorEVMTransaction({ request, traceContext }) {
2943
+ try {
2944
+ const { data } = await this.apiClient.post(`${this.sdkRoutePrefix}/${this.environmentId}/evm/sponsorTransaction`, request, {
2945
+ headers: this.buildTraceHeaders(traceContext)
2946
+ });
2947
+ return data;
2948
+ } catch (error) {
2949
+ this.throwGaslessApiError('EVM sponsorship failed', error);
2950
+ }
2951
+ }
2952
+ async getEVMSponsoredTransactionStatus({ requestId, traceContext }) {
2953
+ try {
2954
+ const { data } = await this.apiClient.get(`${this.sdkRoutePrefix}/${this.environmentId}/evm/sponsorTransaction/${requestId}`, {
2955
+ headers: this.buildTraceHeaders(traceContext)
2956
+ });
2957
+ return data;
2958
+ } catch (error) {
2959
+ this.throwGaslessApiError('EVM sponsorship status check failed', error);
2960
+ }
2961
+ }
2962
+ async getAvailableEVMGaslessRelayer({ chainId, traceContext }) {
2963
+ try {
2964
+ const { data } = await this.apiClient.get(`${this.sdkEvmRoutePrefix}/availableGaslessRelayer`, {
2965
+ params: {
2966
+ chainId
2967
+ },
2968
+ headers: this.buildTraceHeaders(traceContext)
2969
+ });
2970
+ return data;
2971
+ } catch (error) {
2972
+ this.throwGaslessApiError('EVM gasless relayer lookup failed', error);
1498
2973
  }
1499
2974
  }
2975
+ async getNonces({ count = 1 } = {}) {
2976
+ return this.fetchNonces(this.sdkRoutePrefix, count);
2977
+ }
2978
+ /**
2979
+ * Nonces from the public `/api/v0/sdk` route regardless of client type, so no token is sent: safe to call
2980
+ * from a request signer, whose own calls would otherwise each need a nonce first.
2981
+ */ async getAuthServiceNonces({ count = 1 } = {}) {
2982
+ return this.fetchNonces(BROWSER_SDK_ROUTE_PREFIX, count);
2983
+ }
2984
+ async fetchNonces(routePrefix, count) {
2985
+ if (!Number.isInteger(count) || count < 1) {
2986
+ throw new Error('getNonces: count must be a positive integer');
2987
+ }
2988
+ const { data } = await this.apiClient.get(`${routePrefix}/${this.environmentId}/nonces?count=${count}`, {
2989
+ headers: {
2990
+ [DynamicRequestIdHeader]: v4().replace('-', '')
2991
+ }
2992
+ });
2993
+ return data;
2994
+ }
2995
+ /**
2996
+ * Resolves this environment's server identity — a real userId the server
2997
+ * itself is authenticated as, but with no discoverable email/externalUserId
2998
+ * of its own. Feed the returned userId into `businessAccounts.addMember`
2999
+ * to add the server as a business-account member. Server-only — always
3000
+ * uses `/api/v0/server`, regardless of `isServerSdk`, since this client is
3001
+ * shared with the browser SDK (via `BusinessAccountClient`) and the route
3002
+ * doesn't exist under `/api/v0/sdk`.
3003
+ */ async getServerIdentity() {
3004
+ const { data } = await this.apiClient.get(`${SERVER_SDK_ROUTE_PREFIX}/${this.environmentId}/serverIdentity`, {
3005
+ headers: {
3006
+ [DynamicRequestIdHeader]: v4().replace('-', '')
3007
+ }
3008
+ });
3009
+ return data;
3010
+ }
1500
3011
  async updateAdditionalAddresses({ walletId, additionalAddresses, dynamicRequestId, traceContext }) {
1501
3012
  const { data } = await this.apiClient.put(`/api/v0/sdk/${this.environmentId}/waas/${walletId}/additionalAddresses`, {
1502
3013
  additionalAddresses
@@ -1509,8 +3020,49 @@ class DynamicApiClient extends BaseClient {
1509
3020
  });
1510
3021
  return data;
1511
3022
  }
3023
+ /**
3024
+ * Generates a Token-2022 confidential-transfer seed inside the enclave and
3025
+ * stores the sealed result in CKS. Returns the public ElGamal key.
3026
+ */ async createConfidentialSeed({ walletId, request, traceContext }) {
3027
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/confidentialSeed`, request, {
3028
+ headers: this.buildTraceHeaders(traceContext)
3029
+ });
3030
+ return data;
3031
+ }
3032
+ /**
3033
+ * Builds Token-2022 confidential-transfer transactions in the enclave.
3034
+ * Returns base64 unsigned transactions in broadcast order plus a binding
3035
+ * tag; sign them through `signConfidentialTransactions`.
3036
+ */ async signConfidentialTransfer({ walletId, request, traceContext }) {
3037
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/buildConfidentialTransaction`, request, {
3038
+ headers: this.buildTraceHeaders(traceContext)
3039
+ });
3040
+ return data;
3041
+ }
3042
+ /**
3043
+ * Second half of the confidential-transfer ceremony: provisions one MPC
3044
+ * room per transaction and dispatches the enclave co-sign. Returns the
3045
+ * room ids for the client share to join.
3046
+ */ async signConfidentialTransactions({ walletId, request, mfaToken, elevatedAccessToken, traceContext }) {
3047
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/signConfidentialTransaction`, request, {
3048
+ headers: _extends({}, this.buildTraceHeaders(traceContext), {
3049
+ [DynamicMfaTokenHeader]: mfaToken,
3050
+ [DynamicElevatedAccessTokenHeader]: elevatedAccessToken
3051
+ })
3052
+ });
3053
+ return data;
3054
+ }
3055
+ /**
3056
+ * Decrypts a confidential token account's available and pending balances
3057
+ * inside the enclave, using the wallet's stored confidential seed.
3058
+ */ async getSvmConfidentialBalance({ walletId, request, traceContext }) {
3059
+ const { data } = await this.apiClient.post(`${this.waasRoutePrefix}/${walletId}/svmConfidentialBalance`, request, {
3060
+ headers: this.buildTraceHeaders(traceContext)
3061
+ });
3062
+ return data;
3063
+ }
1512
3064
  constructor({ environmentId, authToken, backupServiceAuthToken, baseApiUrl, authMode = AuthMode.HEADER, // Represents the version of the client SDK used by developer
1513
- sdkVersion, forwardMPCClient, baseClientKeysharesRelayApiUrl, logger }){
3065
+ sdkVersion, forwardMPCClient, baseClientKeysharesRelayApiUrl, logger, isServerSdk = false, onUnauthorized, requestSigner }){
1514
3066
  super({
1515
3067
  environmentId,
1516
3068
  authToken: authToken || '',
@@ -1520,11 +3072,573 @@ class DynamicApiClient extends BaseClient {
1520
3072
  sdkVersion,
1521
3073
  forwardMPCClient,
1522
3074
  baseClientKeysharesRelayApiUrl,
1523
- logger
3075
+ logger,
3076
+ onUnauthorized,
3077
+ requestSigner
1524
3078
  });
3079
+ this.sdkRoutePrefix = isServerSdk ? SERVER_SDK_ROUTE_PREFIX : BROWSER_SDK_ROUTE_PREFIX;
3080
+ this.waasRoutePrefix = `${this.sdkRoutePrefix}/${this.environmentId}/waas`;
3081
+ this.sdkEvmRoutePrefix = `${BROWSER_SDK_ROUTE_PREFIX}/${this.environmentId}/evm`;
3082
+ this.businessAccountsRoutePrefix = `${this.sdkRoutePrefix}/${this.environmentId}/businessAccounts`;
3083
+ this.sdkYieldRoutePrefix = `${BROWSER_SDK_ROUTE_PREFIX}/${this.environmentId}/yield`;
1525
3084
  }
1526
3085
  }
1527
3086
 
3087
+ const SUPPORTED_IDENTIFIER_TYPES = new Set([
3088
+ 'email',
3089
+ 'externalUserId',
3090
+ 'id',
3091
+ 'phoneNumber',
3092
+ 'socialAccountId',
3093
+ 'socialUsername'
3094
+ ]);
3095
+ /**
3096
+ * Business-account orchestration. Lives in core (not on the monolithic wallet
3097
+ * client) so both browser and node clients can compose it. Pure REST today.
3098
+ */ class BusinessAccountClient {
3099
+ get apiClient() {
3100
+ return this.getApiClient();
3101
+ }
3102
+ /** Create a business account; the authenticated caller is seeded as the first owner member. */ async createBusinessAccount(request = {}, options) {
3103
+ return this.apiClient.createBusinessAccount({
3104
+ request,
3105
+ traceContext: options == null ? void 0 : options.traceContext
3106
+ });
3107
+ }
3108
+ /** List business accounts the caller is a member of. */ async listBusinessAccounts(options) {
3109
+ return this.apiClient.listBusinessAccounts({
3110
+ traceContext: options == null ? void 0 : options.traceContext
3111
+ });
3112
+ }
3113
+ /**
3114
+ * Resolves this environment's server identity — feed the returned userId
3115
+ * into `addMember({ targetIdentity: { userId } })` to add the server as a
3116
+ * business-account member. Server-only.
3117
+ */ async getServerIdentity() {
3118
+ return this.apiClient.getServerIdentity();
3119
+ }
3120
+ /** Full account detail (members + signers). 404 if the caller is not a member. */ async getBusinessAccount(businessAccountId, options) {
3121
+ return this.apiClient.getBusinessAccountById({
3122
+ businessAccountId,
3123
+ traceContext: options == null ? void 0 : options.traceContext
3124
+ });
3125
+ }
3126
+ async listProposals(businessAccountId, options) {
3127
+ return this.apiClient.listBusinessAccountProposals({
3128
+ businessAccountId,
3129
+ status: options == null ? void 0 : options.status,
3130
+ traceContext: options == null ? void 0 : options.traceContext
3131
+ });
3132
+ }
3133
+ async getProposal(businessAccountId, proposalId, options) {
3134
+ return this.apiClient.getBusinessAccountProposal({
3135
+ businessAccountId,
3136
+ proposalId,
3137
+ traceContext: options == null ? void 0 : options.traceContext
3138
+ });
3139
+ }
3140
+ async recordProposalApproval({ businessAccountId, proposalId, approvedAt, signature, traceContext }) {
3141
+ return this.apiClient.recordBusinessAccountProposalApproval({
3142
+ businessAccountId,
3143
+ proposalId,
3144
+ approvedAt,
3145
+ signature,
3146
+ traceContext
3147
+ });
3148
+ }
3149
+ async executeProposal(businessAccountId, proposalId, options) {
3150
+ return this.apiClient.executeBusinessAccountProposal({
3151
+ businessAccountId,
3152
+ proposalId,
3153
+ traceContext: options == null ? void 0 : options.traceContext
3154
+ });
3155
+ }
3156
+ async updateMemberRole({ businessAccountId, userId, role, autoExecute, signedIntent, traceContext }) {
3157
+ if (role === BusinessAccountMemberRole.Owner) {
3158
+ throw new Error('Use transferOwnership to assign the owner role');
3159
+ }
3160
+ return this.apiClient.updateBusinessAccountMemberRole({
3161
+ businessAccountId,
3162
+ userId,
3163
+ role,
3164
+ autoExecute,
3165
+ signedIntent,
3166
+ traceContext
3167
+ });
3168
+ }
3169
+ /** The approval requirements in force, readable by any member. `{}` when nothing is governed. */ async getGovernance(businessAccountId, options) {
3170
+ return this.apiClient.getBusinessAccountGovernance({
3171
+ businessAccountId,
3172
+ traceContext: options == null ? void 0 : options.traceContext
3173
+ });
3174
+ }
3175
+ /**
3176
+ * Replaces the whole governance section — merge against `getGovernance` first, or the
3177
+ * rules of any action you omit are dropped. Owner-only, and itself governed.
3178
+ */ async setGovernance({ businessAccountId, governance, autoExecute, signedIntent, traceContext }) {
3179
+ return this.apiClient.setBusinessAccountGovernance({
3180
+ businessAccountId,
3181
+ governance,
3182
+ autoExecute,
3183
+ signedIntent,
3184
+ traceContext
3185
+ });
3186
+ }
3187
+ /**
3188
+ * Bring an existing wallet under a business account so signers can be added to it.
3189
+ * Pure REST, no ceremony — the owner already holds a valid share set, so the
3190
+ * server just transfers ownership and registers the caller as owner + signer.
3191
+ * Omit `businessAccountId` to find-or-create the per-wallet business account.
3192
+ * Idempotent.
3193
+ */ async addWalletToBusinessAccount({ walletId, businessAccountId, traceContext }) {
3194
+ return this.apiClient.linkWalletToBusinessAccount({
3195
+ walletId,
3196
+ businessAccountId,
3197
+ traceContext
3198
+ });
3199
+ }
3200
+ /**
3201
+ * Add a member to a business account, resolved by `email` (or explicit
3202
+ * `userId`), mirroring addSigner. The server creates the user if absent.
3203
+ * Caller must be an owner/admin.
3204
+ */ async addMember({ businessAccountId, targetIdentity, role, autoExecute, signedIntent, traceContext }) {
3205
+ const { userId, identifier, identifierType, smsCountryCode, socialProvider } = targetIdentity;
3206
+ if (!userId && !(identifier && identifierType)) {
3207
+ throw new Error('BusinessAccountClient.addMember requires targetIdentity.userId, or identifier + identifierType');
3208
+ }
3209
+ if (identifierType && !SUPPORTED_IDENTIFIER_TYPES.has(identifierType)) {
3210
+ throw new Error(`BusinessAccountClient.addMember: identifierType '${identifierType}' is not supported. Use one of: ${[
3211
+ ...SUPPORTED_IDENTIFIER_TYPES
3212
+ ].join(', ')}.`);
3213
+ }
3214
+ return this.apiClient.addBusinessAccountMember({
3215
+ businessAccountId,
3216
+ userId,
3217
+ identifier,
3218
+ identifierType,
3219
+ smsCountryCode,
3220
+ socialProvider,
3221
+ role,
3222
+ autoExecute,
3223
+ signedIntent,
3224
+ traceContext
3225
+ });
3226
+ }
3227
+ /**
3228
+ * Add a signer to a business-account wallet, resolved by `email` (or explicit
3229
+ * `userId`). Server creates the user if absent, auto-adds them as a member,
3230
+ * and writes a PENDING signer row. Returns the pending signer — the reshare
3231
+ * ceremony that mints the share lives in the browser SDK.
3232
+ *
3233
+ * Omit `businessAccountId` to add a signer to a wallet that isn't in a
3234
+ * business account yet: we first find-or-create the per-wallet account via
3235
+ * `addWalletToBusinessAccount` (idempotent — returns the existing account if
3236
+ * the wallet is already linked, or converts the personal wallet by minting
3237
+ * the account and seating its owner as the first signer), then add the new
3238
+ * signer to it.
3239
+ */ async addSigner({ businessAccountId, walletId, targetSignerIdentity, signerType = BusinessAccountSignerType.EndUser, traceContext }) {
3240
+ const identity = targetSignerIdentity;
3241
+ const { userId, identifier, identifierType, serverIdentifier, smsCountryCode, socialProvider } = identity;
3242
+ if (!userId && !serverIdentifier && !(identifier && identifierType)) {
3243
+ throw new Error('BusinessAccountClient.addSigner requires targetSignerIdentity.userId, serverIdentifier, or identifier + identifierType');
3244
+ }
3245
+ // Reject before the link below, which converts a personal wallet and has no rollback.
3246
+ if (serverIdentifier && signerType !== BusinessAccountSignerType.Server) {
3247
+ throw new Error("BusinessAccountClient.addSigner: serverIdentifier is only valid with signerType 'server'");
3248
+ }
3249
+ if (identifierType && !SUPPORTED_IDENTIFIER_TYPES.has(identifierType)) {
3250
+ throw new Error(`BusinessAccountClient.addSigner: identifierType '${identifierType}' is not supported. Use one of: ${[
3251
+ ...SUPPORTED_IDENTIFIER_TYPES
3252
+ ].join(', ')}.`);
3253
+ }
3254
+ let resolvedBusinessAccountId = businessAccountId;
3255
+ if (!resolvedBusinessAccountId) {
3256
+ this.logger.info('BusinessAccountClient.addSigner: no businessAccountId — find-or-creating the per-wallet account before adding the signer');
3257
+ const account = await this.addWalletToBusinessAccount({
3258
+ walletId,
3259
+ traceContext
3260
+ });
3261
+ resolvedBusinessAccountId = account.id;
3262
+ }
3263
+ this.logger.info('BusinessAccountClient.addSigner creating pending signer (reshare pending)');
3264
+ return this.apiClient.addBusinessAccountSigner({
3265
+ businessAccountId: resolvedBusinessAccountId,
3266
+ walletId,
3267
+ signerType,
3268
+ userId,
3269
+ identifier,
3270
+ identifierType,
3271
+ serverIdentifier,
3272
+ smsCountryCode,
3273
+ socialProvider,
3274
+ traceContext
3275
+ });
3276
+ }
3277
+ constructor(deps){
3278
+ this.getApiClient = 'getApiClient' in deps ? deps.getApiClient : ()=>deps.apiClient;
3279
+ this.logger = deps.logger;
3280
+ }
3281
+ }
3282
+
3283
+ /**
3284
+ * Earn (yield vault) reads and unsigned-transaction builders. Lives in core so
3285
+ * the browser and node clients can compose it. The `prepare*` methods only ask
3286
+ * the API for a payload — executing it on-chain is the chain client's job.
3287
+ */ class EarnClient {
3288
+ /** Vaults enabled for the environment. */ async listVaults(options) {
3289
+ const { vaults } = await this.getApiClient().listYieldVaults({
3290
+ traceContext: options == null ? void 0 : options.traceContext
3291
+ });
3292
+ return vaults;
3293
+ }
3294
+ /** Full detail for a single vault, including the addresses needed to deposit. */ async getVaultDetails(vaultId, options) {
3295
+ return this.getApiClient().getYieldVaultDetails({
3296
+ vaultId,
3297
+ traceContext: options == null ? void 0 : options.traceContext
3298
+ });
3299
+ }
3300
+ /** An owner's shares and underlying assets in a vault. */ async getPosition({ vaultId, ownerAddress, traceContext }) {
3301
+ return this.getApiClient().getYieldVaultPosition({
3302
+ vaultId,
3303
+ ownerAddress,
3304
+ traceContext
3305
+ });
3306
+ }
3307
+ /** Indexed performance of an owner's position in a vault (trails the chain head). */ async getPerformance({ vaultId, ownerAddress, traceContext }) {
3308
+ return this.getApiClient().getYieldVaultPositionPerformance({
3309
+ vaultId,
3310
+ ownerAddress,
3311
+ traceContext
3312
+ });
3313
+ }
3314
+ /** An owner's earnings across every vault on a chain, with USD totals and a per-vault breakdown. */ async getEarnings({ ownerAddress, chainId, chainName, traceContext }) {
3315
+ return this.getApiClient().getYieldEarnings({
3316
+ ownerAddress,
3317
+ chainId,
3318
+ chainName,
3319
+ traceContext
3320
+ });
3321
+ }
3322
+ /** Rewards accrued by an owner in a vault. */ async getRewards({ vaultId, ownerAddress, traceContext }) {
3323
+ const { rewards } = await this.getApiClient().getYieldVaultRewards({
3324
+ vaultId,
3325
+ ownerAddress,
3326
+ traceContext
3327
+ });
3328
+ return rewards;
3329
+ }
3330
+ /**
3331
+ * Unsigned deposit transaction, plus an ERC-20 approval when the vault's
3332
+ * allowance is short. Shares are credited to `receiverAddress` when given,
3333
+ * otherwise to `ownerAddress`.
3334
+ */ async prepareDeposit({ vaultId, ownerAddress, amount, receiverAddress, traceContext }) {
3335
+ const { signingPayload } = await this.getApiClient().yieldVaultDeposit({
3336
+ vaultId,
3337
+ ownerAddress,
3338
+ amount,
3339
+ receiverAddress,
3340
+ traceContext
3341
+ });
3342
+ return signingPayload;
3343
+ }
3344
+ /** Unsigned withdrawal transaction. `amount` is in the vault asset's raw units. */ async prepareWithdrawal({ vaultId, ownerAddress, amount, receiverAddress, traceContext }) {
3345
+ const { signingPayload } = await this.getApiClient().yieldVaultWithdraw({
3346
+ vaultId,
3347
+ ownerAddress,
3348
+ amount,
3349
+ receiverAddress,
3350
+ traceContext
3351
+ });
3352
+ return signingPayload;
3353
+ }
3354
+ /** Unsigned transaction that claims every reward accrued by `ownerAddress`. */ async prepareClaimRewards({ vaultId, ownerAddress, traceContext }) {
3355
+ const { signingPayload } = await this.getApiClient().yieldVaultClaim({
3356
+ vaultId,
3357
+ ownerAddress,
3358
+ traceContext
3359
+ });
3360
+ return signingPayload;
3361
+ }
3362
+ constructor({ getApiClient }){
3363
+ this.getApiClient = getApiClient;
3364
+ }
3365
+ }
3366
+
3367
+ // crypto.randomUUID is unavailable on older webviews (< Chrome 92) and in
3368
+ // non-secure contexts; fall back to a getRandomValues-based v4 UUID there.
3369
+ const generateUUID = ()=>{
3370
+ const cryptoProvider = globalThis.crypto;
3371
+ if (typeof (cryptoProvider == null ? void 0 : cryptoProvider.randomUUID) === 'function') {
3372
+ return cryptoProvider.randomUUID();
3373
+ }
3374
+ if (typeof (cryptoProvider == null ? void 0 : cryptoProvider.getRandomValues) !== 'function') {
3375
+ throw new TypeError('Secure UUID generation is unavailable');
3376
+ }
3377
+ const bytes = cryptoProvider.getRandomValues(new Uint8Array(16));
3378
+ bytes[6] = bytes[6] & 0x0f | 0x40;
3379
+ bytes[8] = bytes[8] & 0x3f | 0x80;
3380
+ const hex = Array.from(bytes, (b)=>b.toString(16).padStart(2, '0')).join('');
3381
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
3382
+ };
3383
+
3384
+ const isPreparedTransaction = (prepared)=>prepared.operation.kind === 'transaction';
3385
+ const isPreparedSvmTransaction = (prepared)=>prepared.operation.chainName === 'SVM';
3386
+ const isPreparedTronTransaction = (prepared)=>prepared.operation.chainName === 'TRON';
3387
+ const isPreparedStellarTransaction = (prepared)=>prepared.operation.chainName === 'STELLAR';
3388
+ const isPreparedBtcTransaction = (prepared)=>prepared.operation.chainName === 'BTC';
3389
+ const validateRequest = (request, prepared, now)=>{
3390
+ if (Number.isNaN(now.getTime())) throw new Error('Invalid signing intent creation time');
3391
+ if (!request.accountAddress || !request.businessAccountId || !request.initiatorUserId || !request.walletId) {
3392
+ throw new Error('Signing intent identity is required');
3393
+ }
3394
+ if (!Object.values(WaasChainEnum).includes(request.chainName)) {
3395
+ throw new Error('Signing intent requires a canonical chain name');
3396
+ }
3397
+ if (request.chainName !== prepared.operation.chainName || request.kind !== prepared.operation.kind) {
3398
+ throw new Error('Signing intent operation does not match request');
3399
+ }
3400
+ };
3401
+ const validateCompleteBy = (completeBy, now)=>{
3402
+ if (!completeBy) return;
3403
+ const timestamp = Date.parse(completeBy);
3404
+ const isCanonicalFutureTimestamp = Number.isFinite(timestamp) && new Date(timestamp).toISOString() === completeBy && timestamp > now.getTime();
3405
+ if (!isCanonicalFutureTimestamp) {
3406
+ throw new Error('Signing intent completion time must be a future ISO timestamp');
3407
+ }
3408
+ };
3409
+ const createEnvelope = (request, now, providedIntentId)=>{
3410
+ const intentId = providedIntentId != null ? providedIntentId : generateUUID();
3411
+ return _extends({
3412
+ actionType: 'waasSigningQuorumApprove',
3413
+ accountAddress: request.accountAddress,
3414
+ businessAccountId: request.businessAccountId,
3415
+ initiatorUserId: request.initiatorUserId,
3416
+ intentId,
3417
+ createdAt: now.toISOString(),
3418
+ // validateRequest has already refused a missing walletId.
3419
+ walletId: request.walletId
3420
+ }, request.completeBy ? {
3421
+ completeBy: request.completeBy
3422
+ } : {});
3423
+ };
3424
+ const addEvmTransactionMetadata = (envelope, { operation, limits, lifetime })=>{
3425
+ if (!limits) throw new Error('Transaction signing limits are required');
3426
+ if (!lifetime) return _extends({}, envelope, {
3427
+ operation,
3428
+ limits
3429
+ });
3430
+ if (lifetime.refreshable !== 'nonce') throw new Error('EVM signing intent lifetime must be nonce');
3431
+ return _extends({}, envelope, {
3432
+ operation,
3433
+ limits,
3434
+ lifetime: {
3435
+ refreshable: 'nonce'
3436
+ }
3437
+ });
3438
+ };
3439
+ const addSvmTransactionMetadata = (envelope, { operation, lifetime })=>{
3440
+ if ((lifetime == null ? void 0 : lifetime.refreshable) !== 'blockhash') throw new Error('SVM signing intent requires a lifetime');
3441
+ return _extends({}, envelope, {
3442
+ operation,
3443
+ lifetime: {
3444
+ refreshable: 'blockhash'
3445
+ }
3446
+ });
3447
+ };
3448
+ const addTronTransactionMetadata = (envelope, { operation, lifetime })=>{
3449
+ if ((lifetime == null ? void 0 : lifetime.refreshable) !== 'expiration') throw new Error('TRON signing intent requires a lifetime');
3450
+ return _extends({}, envelope, {
3451
+ operation,
3452
+ lifetime: {
3453
+ refreshable: 'expiration'
3454
+ }
3455
+ });
3456
+ };
3457
+ const addStellarTransactionMetadata = (envelope, { operation, lifetime })=>{
3458
+ if ((lifetime == null ? void 0 : lifetime.refreshable) !== 'expiration') throw new Error('Stellar signing intent requires a lifetime');
3459
+ return _extends({}, envelope, {
3460
+ operation,
3461
+ lifetime: {
3462
+ refreshable: 'expiration'
3463
+ }
3464
+ });
3465
+ };
3466
+ const addBtcTransactionMetadata = (envelope, { operation, limits, lifetime })=>{
3467
+ if (limits || lifetime) throw new Error('BTC signing intent has no limits or lifetime');
3468
+ return _extends({}, envelope, {
3469
+ operation
3470
+ });
3471
+ };
3472
+ const addTransactionMetadata = (envelope, prepared)=>{
3473
+ if (isPreparedSvmTransaction(prepared)) return addSvmTransactionMetadata(envelope, prepared);
3474
+ if (isPreparedTronTransaction(prepared)) return addTronTransactionMetadata(envelope, prepared);
3475
+ if (isPreparedStellarTransaction(prepared)) return addStellarTransactionMetadata(envelope, prepared);
3476
+ if (isPreparedBtcTransaction(prepared)) return addBtcTransactionMetadata(envelope, prepared);
3477
+ return addEvmTransactionMetadata(envelope, prepared);
3478
+ };
3479
+ const addMessageMetadata = (envelope, request, operation)=>{
3480
+ if (request.kind !== 'message' || typeof request.message !== 'string') {
3481
+ throw new Error('Signing intent message is required');
3482
+ }
3483
+ return _extends({}, envelope, {
3484
+ operation: _extends({}, operation, {
3485
+ message: request.message
3486
+ })
3487
+ });
3488
+ };
3489
+ const addTypedDataMetadata = (envelope, request, operation)=>{
3490
+ if (request.kind !== 'typedData' || request.chainName !== 'EVM' || !request.typedData) {
3491
+ throw new Error('EVM signing intent typed data is required');
3492
+ }
3493
+ return _extends({}, envelope, {
3494
+ operation: _extends({}, operation, {
3495
+ chainName: 'EVM',
3496
+ typedData: request.typedData
3497
+ })
3498
+ });
3499
+ };
3500
+ const addRawMetadata = (envelope, request, operation)=>{
3501
+ var _request_rawSign;
3502
+ if (request.kind !== 'raw' || !((_request_rawSign = request.rawSign) == null ? void 0 : _request_rawSign.payload) || !request.rawSign.hashFunction) {
3503
+ throw new Error('Raw signing intent requires a preimage and hash function');
3504
+ }
3505
+ return _extends({}, envelope, {
3506
+ operation: _extends({}, operation, {
3507
+ rawSign: request.rawSign
3508
+ })
3509
+ });
3510
+ };
3511
+ const addEip7702AuthMetadata = (envelope, request, operation)=>{
3512
+ if (request.kind !== 'eip7702Auth') throw new Error('EIP-7702 signing intent authorization is required');
3513
+ return _extends({}, envelope, {
3514
+ operation
3515
+ });
3516
+ };
3517
+ const addRequestMetadata = (envelope, request, prepared)=>{
3518
+ if (isPreparedTransaction(prepared)) return addTransactionMetadata(envelope, prepared);
3519
+ switch(prepared.operation.kind){
3520
+ case 'message':
3521
+ return addMessageMetadata(envelope, request, prepared.operation);
3522
+ case 'typedData':
3523
+ return addTypedDataMetadata(envelope, request, prepared.operation);
3524
+ case 'raw':
3525
+ return addRawMetadata(envelope, request, prepared.operation);
3526
+ case 'eip7702Auth':
3527
+ return addEip7702AuthMetadata(envelope, request, prepared.operation);
3528
+ }
3529
+ };
3530
+ const createSigningIntent = (request, prepared, options = {})=>{
3531
+ var _options_now;
3532
+ const now = (_options_now = options.now) != null ? _options_now : new Date();
3533
+ validateRequest(request, prepared, now);
3534
+ validateCompleteBy(request.completeBy, now);
3535
+ return addRequestMetadata(createEnvelope(request, now, options.intentId), request, prepared);
3536
+ };
3537
+
3538
+ /** Must match redcoast's and wallet-service's `WAAS_EXPORT_INTENT_ACTION`. */ const WAAS_EXPORT_INTENT_ACTION = 'waasExportQuorumApprove';
3539
+ /** How long approvers have when the caller doesn't ask for a shorter window. */ const DEFAULT_COMPLETE_WITHIN_MS$1 = 24 * 60 * 60 * 1000;
3540
+ const assertIdentity$1 = (request)=>{
3541
+ if (!request.accountAddress || !request.businessAccountId || !request.initiatorUserId || !request.exportId || !request.walletId) {
3542
+ throw new Error('Export intent identity is required');
3543
+ }
3544
+ };
3545
+ const assertValidNow$1 = (now)=>{
3546
+ if (Number.isNaN(now.getTime())) throw new Error('Invalid export intent creation time');
3547
+ };
3548
+ /** The caller's `completeBy`, or the default window, once it is known to be a canonical future ISO timestamp. */ const resolveCompleteBy$1 = (requested, now)=>{
3549
+ const completeBy = requested != null ? requested : new Date(now.getTime() + DEFAULT_COMPLETE_WITHIN_MS$1).toISOString();
3550
+ const timestamp = Date.parse(completeBy);
3551
+ const isCanonicalFutureTimestamp = Number.isFinite(timestamp) && new Date(timestamp).toISOString() === completeBy && timestamp > now.getTime();
3552
+ if (!isCanonicalFutureTimestamp) {
3553
+ throw new Error('Export intent completion time must be a future ISO timestamp');
3554
+ }
3555
+ return completeBy;
3556
+ };
3557
+ /**
3558
+ * Builds the export Intent the initiator signs. It binds one `exportId`, so a
3559
+ * set of approvals can't be replayed onto a different export. The server
3560
+ * clamps `completeBy` to the policy rule's own window; it can only tighten it.
3561
+ */ const createExportIntent = (request, options = {})=>{
3562
+ var _globalThis_crypto_randomUUID, _globalThis_crypto;
3563
+ var _options_now;
3564
+ const now = (_options_now = options.now) != null ? _options_now : new Date();
3565
+ assertValidNow$1(now);
3566
+ assertIdentity$1(request);
3567
+ const completeBy = resolveCompleteBy$1(request.completeBy, now);
3568
+ var _options_intentId;
3569
+ const intentId = (_options_intentId = options.intentId) != null ? _options_intentId : (_globalThis_crypto = globalThis.crypto) == null ? void 0 : (_globalThis_crypto_randomUUID = _globalThis_crypto.randomUUID) == null ? void 0 : _globalThis_crypto_randomUUID.call(_globalThis_crypto);
3570
+ if (!intentId) throw new Error('Secure UUID generation is unavailable');
3571
+ return {
3572
+ accountAddress: request.accountAddress,
3573
+ actionType: WAAS_EXPORT_INTENT_ACTION,
3574
+ businessAccountId: request.businessAccountId,
3575
+ completeBy,
3576
+ createdAt: now.toISOString(),
3577
+ initiatorUserId: request.initiatorUserId,
3578
+ intentId,
3579
+ operation: {
3580
+ exportId: request.exportId,
3581
+ kind: 'export',
3582
+ restriction: 'blockExport'
3583
+ },
3584
+ walletId: request.walletId
3585
+ };
3586
+ };
3587
+
3588
+ /** Must match redcoast's and wallet-service's `WAAS_RESHARE_INTENT_ACTION`. */ const WAAS_RESHARE_INTENT_ACTION = 'waasReshareQuorumApprove';
3589
+ /** How long approvers have when the caller doesn't ask for a shorter window. */ const DEFAULT_COMPLETE_WITHIN_MS = 24 * 60 * 60 * 1000;
3590
+ const assertIdentity = (request)=>{
3591
+ if (!request.accountAddress || !request.businessAccountId || !request.initiatorUserId || !request.walletId) {
3592
+ throw new Error('Reshare intent identity is required');
3593
+ }
3594
+ };
3595
+ const assertValidNow = (now)=>{
3596
+ if (Number.isNaN(now.getTime())) throw new Error('Invalid reshare intent creation time');
3597
+ };
3598
+ /** The caller's `completeBy`, or the default window, once it is known to be a canonical future ISO timestamp. */ const resolveCompleteBy = (requested, now)=>{
3599
+ const completeBy = requested != null ? requested : new Date(now.getTime() + DEFAULT_COMPLETE_WITHIN_MS).toISOString();
3600
+ const timestamp = Date.parse(completeBy);
3601
+ const isCanonicalFutureTimestamp = Number.isFinite(timestamp) && new Date(timestamp).toISOString() === completeBy && timestamp > now.getTime();
3602
+ if (!isCanonicalFutureTimestamp) {
3603
+ throw new Error('Reshare intent completion time must be a future ISO timestamp');
3604
+ }
3605
+ return completeBy;
3606
+ };
3607
+ /**
3608
+ * Builds the reshare Intent the initiator signs. Its `operation` names the
3609
+ * reshare and the fields that define it, so a set of approvals can't be
3610
+ * replayed onto a different reshare. The server clamps `completeBy` to the policy rule's own
3611
+ * window; it can only tighten it.
3612
+ */ const createReshareIntent = (request, options = {})=>{
3613
+ var _globalThis_crypto_randomUUID, _globalThis_crypto;
3614
+ var _options_now;
3615
+ const now = (_options_now = options.now) != null ? _options_now : new Date();
3616
+ assertValidNow(now);
3617
+ assertIdentity(request);
3618
+ const completeBy = resolveCompleteBy(request.completeBy, now);
3619
+ var _options_intentId;
3620
+ const intentId = (_options_intentId = options.intentId) != null ? _options_intentId : (_globalThis_crypto = globalThis.crypto) == null ? void 0 : (_globalThis_crypto_randomUUID = _globalThis_crypto.randomUUID) == null ? void 0 : _globalThis_crypto_randomUUID.call(_globalThis_crypto);
3621
+ if (!intentId) throw new Error('Secure UUID generation is unavailable');
3622
+ return {
3623
+ accountAddress: request.accountAddress,
3624
+ actionType: WAAS_RESHARE_INTENT_ACTION,
3625
+ businessAccountId: request.businessAccountId,
3626
+ completeBy,
3627
+ createdAt: now.toISOString(),
3628
+ initiatorUserId: request.initiatorUserId,
3629
+ intentId,
3630
+ operation: _extends({
3631
+ kind: 'reshare',
3632
+ newThresholdSignatureScheme: request.newThresholdSignatureScheme
3633
+ }, request.offlineRecoveryEncryptionKey ? {
3634
+ offlineRecoveryEncryptionKey: request.offlineRecoveryEncryptionKey
3635
+ } : {}, {
3636
+ reshareType: request.reshareType
3637
+ }),
3638
+ walletId: request.walletId
3639
+ };
3640
+ };
3641
+
1528
3642
  const SDK_NAMESPACE = {
1529
3643
  REACT: 'WalletKit',
1530
3644
  CLIENT: 'ClientSDK'
@@ -1590,10 +3704,38 @@ const SDK_NAMESPACE = {
1590
3704
  return parsed ? parsed.namespace : null;
1591
3705
  }
1592
3706
 
3707
+ /**
3708
+ * Chain names whose forward-MPC payload is treated as EVM-compatible:
3709
+ * they use secp256k1 ECDSA signing and serialize a pre-hashed
3710
+ * (`isFormatted=true`) payload over the wire as a hex string.
3711
+ *
3712
+ * Add new EVM-compatible chains here.
3713
+ */ const EVM_COMPATIBLE_CHAINS = [
3714
+ 'EVM',
3715
+ 'TEMPO',
3716
+ 'TRON'
3717
+ ];
3718
+ /**
3719
+ * Returns `true` if `chainName` is an EVM-compatible chain — i.e. signs with
3720
+ * secp256k1 ECDSA and serializes pre-hashed messages over the forward-MPC
3721
+ * wire as a hex string.
3722
+ *
3723
+ * The check is case-sensitive: pass the canonical uppercase chain identifier
3724
+ * (e.g. `'EVM'`, `'TEMPO'`, `'TRON'`).
3725
+ *
3726
+ * @param chainName - Canonical chain name to test.
3727
+ * @returns `true` if the chain is EVM-compatible, `false` otherwise.
3728
+ *
3729
+ * @example
3730
+ * isEvmCompatibleChain('EVM'); // => true
3731
+ * isEvmCompatibleChain('TRON'); // => true
3732
+ * isEvmCompatibleChain('SUI'); // => false
3733
+ * isEvmCompatibleChain('tron'); // => false (case-sensitive)
3734
+ */ const isEvmCompatibleChain = (chainName)=>EVM_COMPATIBLE_CHAINS.includes(chainName);
3735
+
1593
3736
  const serializeMessageForForwardMPC = ({ message, isFormatted = false, chainName })=>{
1594
3737
  let serializedMessage = message;
1595
- const isEvmCompatible = chainName === 'EVM' || chainName === 'TEMPO';
1596
- if (isFormatted && isEvmCompatible) {
3738
+ if (isFormatted && isEvmCompatibleChain(chainName)) {
1597
3739
  if (typeof message === 'string') {
1598
3740
  // Handle hex string (with or without 0x prefix)
1599
3741
  const cleanHex = message.startsWith('0x') ? message.slice(2) : message;
@@ -1609,140 +3751,216 @@ const serializeMessageForForwardMPC = ({ message, isFormatted = false, chainName
1609
3751
  return serializedMessage;
1610
3752
  };
1611
3753
 
1612
- const getRequiredExternalKeyShareId = (ks)=>{
1613
- if (!ks.externalKeyShareId) {
1614
- throw new Error(`Missing externalKeyShareId for key share (id: ${ks.id}, keygenId: ${ks.keygenId})`);
1615
- }
1616
- return ks.externalKeyShareId;
3754
+ // Mirrors forward-mpc-client's ErrorCode values (the /utils subpath does not
3755
+ // export the ErrorCode const, so the codes are inlined here).
3756
+ const NOT_CONNECTED = 'NOT_CONNECTED';
3757
+ const RECOVERED_CONNECTION_CHURN_CODES = new Set([
3758
+ 'CONNECTION_FAILED',
3759
+ 'CONNECTION_TIMEOUT',
3760
+ NOT_CONNECTED,
3761
+ 'TRANSPORT_CLOSED',
3762
+ 'HANDSHAKE_FAILED'
3763
+ ]);
3764
+ // WebSocket.send() throws InvalidStateError only while the socket is still CONNECTING,
3765
+ // before any bytes go out, so the enclave never saw the room. Matched by name: a DOMException
3766
+ // is not always `instanceof Error` (other realms, jsdom).
3767
+ const isSendBeforeOpenError = (error)=>(error == null ? void 0 : error.name) === 'InvalidStateError';
3768
+ /**
3769
+ * The library's classifier, plus: a send on a still-connecting socket is the library's own
3770
+ * NOT_CONNECTED. Left unclassified it reads as "may have joined" and burns the room.
3771
+ */ const classifyForwardMpcError = (error)=>{
3772
+ const classification = classifyForwardMpcError$1(error);
3773
+ return classification.errorCode === undefined && isSendBeforeOpenError(error) ? _extends({}, classification, {
3774
+ errorCode: NOT_CONNECTED
3775
+ }) : classification;
1617
3776
  };
1618
-
1619
- var _Logger;
1620
3777
  /**
1621
- * Global static logger for SDK-internal use.
3778
+ * Returns true when a classified Forward MPC error is recovered connection
3779
+ * churn that should be logged at `warn` rather than `error`.
1622
3780
  *
1623
- * Call `Logger.configure(impl)` once at startup to wire in your logger.
1624
- * Call `Logger.setContext(ctx)` to attach metadata merged into every log call.
3781
+ * The Forward MPC enclave is an optimization side-channel: the client retries
3782
+ * connections internally, and `shouldFallback` is true for every Forward MPC
3783
+ * failure mode — relay-based MPC is a fully functional safety net, so a
3784
+ * connection-lifecycle failure never blocks a user operation on its own.
3785
+ * Terminal failures (both paths failing) are logged at the operation sites.
1625
3786
  *
1626
- * Parses variadic args: any Error instance is extracted and passed as the
1627
- * third argument; all plain objects are merged into a single context object.
1628
- * This matches Datadog's (message, context?, error?) calling convention.
1629
- */ const Logger = (_Logger = class Logger {
1630
- static configure(logger) {
1631
- this._instance = logger;
1632
- }
1633
- static setContext(context) {
1634
- this._context = _extends({}, this._context, context);
1635
- }
1636
- static resetContext() {
1637
- this._context = {};
1638
- }
1639
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1640
- static debug(message, ...args) {
1641
- const { context } = this._parse(args);
1642
- if (context) {
1643
- this._instance.debug(message, context);
1644
- } else {
1645
- this._instance.debug(message);
1646
- }
3787
+ * Churn covers rate-limited upgrades and the transport-lifecycle error codes
3788
+ * (connect/reconnect failures, timeouts, socket closes, and handshake-request
3789
+ * timeouts — production evidence shows these concentrate on hostile/flaky
3790
+ * networks). Attestation failures, HANDSHAKE_INVALID_RESPONSE, SERVER_ERROR,
3791
+ * and unclassified errors are NOT churn: they indicate enclave tampering or
3792
+ * protocol breakage and must stay at `error` so monitors can page on them.
3793
+ */ const isRecoveredForwardMpcConnectionChurn = (classification)=>classification.errorType === 'RATE_LIMITED' || classification.errorCode !== undefined && RECOVERED_CONNECTION_CHURN_CODES.has(classification.errorCode);
3794
+ // Missing WebAssembly global (e.g. iOS WKWebView under Lockdown Mode):
3795
+ // JSC reports "Can't find variable: WebAssembly", V8 "WebAssembly is not defined".
3796
+ const WASM_UNAVAILABLE_MESSAGE = /can't find variable: webassembly|webassembly is not defined/i;
3797
+ /**
3798
+ * True when an error indicates the client's JS runtime lacks the WebAssembly
3799
+ * global — a client environment issue, so it logs at `warn`, not `error`.
3800
+ */ const isWasmUnavailableErrorMessage = (message)=>message !== undefined && WASM_UNAVAILABLE_MESSAGE.test(message);
3801
+ /**
3802
+ * Thrown by `assertWebAssemblyAvailable` before any MPC work starts when the
3803
+ * runtime has no WebAssembly global. The message intentionally matches
3804
+ * WASM_UNAVAILABLE_MESSAGE so log classification stays `warn`.
3805
+ */ class WasmUnavailableError extends Error {
3806
+ constructor(){
3807
+ super('WebAssembly is not defined: this runtime cannot run MPC operations (e.g. iOS Lockdown Mode disables WebAssembly)');
3808
+ this.name = 'WasmUnavailableError';
1647
3809
  }
1648
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1649
- static info(message, ...args) {
1650
- const { context } = this._parse(args);
1651
- if (context) {
1652
- this._instance.info(message, context);
1653
- } else {
1654
- this._instance.info(message);
1655
- }
3810
+ }
3811
+ /**
3812
+ * Fails fast when the client's JS runtime lacks the WebAssembly global — every
3813
+ * MPC path needs WASM, so keygen/sign/export would throw a raw ReferenceError
3814
+ * deeper in anyway.
3815
+ */ const assertWebAssemblyAvailable = ()=>{
3816
+ if (typeof WebAssembly === 'undefined') throw new WasmUnavailableError();
3817
+ };
3818
+
3819
+ /**
3820
+ * True when the forward enclave may already be in the room. The enclave gets
3821
+ * the room only inside a request sent over an established session, so only a
3822
+ * failure after the session, or an unrecognised error (no code), can follow a join.
3823
+ */ const forwardMpcMayHaveJoinedRoom = ({ sessionEstablished, errorCode })=>sessionEstablished || errorCode === undefined;
3824
+ const throwIfAborted = (signal)=>{
3825
+ if (signal == null ? void 0 : signal.aborted) {
3826
+ throw signal.reason instanceof Error ? signal.reason : new Error('Operation aborted');
1656
3827
  }
1657
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1658
- static warn(message, ...args) {
1659
- const { context } = this._parse(args);
1660
- if (context) {
1661
- this._instance.warn(message, context);
1662
- } else {
1663
- this._instance.warn(message);
1664
- }
3828
+ };
3829
+ // Observers are telemetry only; their failures must not change the fallback.
3830
+ const notify = (observer, value)=>{
3831
+ try {
3832
+ observer == null ? void 0 : observer(value);
3833
+ } catch (e) {
3834
+ // Ignored on purpose.
1665
3835
  }
1666
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1667
- static error(message, ...args) {
1668
- const { error, context } = this._parse(args);
1669
- if (error) {
1670
- this._instance.error(message, context != null ? context : {}, error);
1671
- } else if (context) {
1672
- this._instance.error(message, context);
1673
- } else {
1674
- this._instance.error(message);
3836
+ };
3837
+ /**
3838
+ * Runs an MPC ceremony over forward MPC, falling back to relay MPC on a
3839
+ * fallback-eligible failure.
3840
+ *
3841
+ * Invariant: relay never runs in a room the forward enclave may have joined.
3842
+ * That would put the same party in the room twice and fail with
3843
+ * "Mismatch between the public keys of the server and the ones provided".
3844
+ * When the enclave may have joined, relay runs in a room from `refreshRoom`;
3845
+ * without `refreshRoom`, the forward error is rethrown.
3846
+ *
3847
+ * `signal` stops the fallback when the operation already failed elsewhere
3848
+ * (for example, a server policy denial). A forward ceremony already in flight
3849
+ * cannot be cancelled.
3850
+ */ const runWithForwardMpcFallback = async ({ room, forward, relay, refreshRoom, signal, onForwardFailure, onRoomRefreshed })=>{
3851
+ throwIfAborted(signal);
3852
+ if (!forward) {
3853
+ return relay(room);
3854
+ }
3855
+ let relayRoom = room;
3856
+ try {
3857
+ return await forward(room);
3858
+ } catch (error) {
3859
+ const errorInfo = classifyForwardMpcError(error);
3860
+ notify(onForwardFailure, errorInfo);
3861
+ if (!errorInfo.shouldFallback) {
3862
+ throw error;
1675
3863
  }
1676
- }
1677
- /**
1678
- * Separates variadic args into a merged context object and an optional Error.
1679
- * All plain objects are merged (later args win). Error instances are extracted.
1680
- * Handles unknown/primitive args by wrapping them in a context object.
1681
- */ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1682
- static _parse(args) {
1683
- let error;
1684
- let merged = _extends({}, this._context);
1685
- let hasData = Object.keys(this._context).length > 0;
1686
- for (const arg of args){
1687
- if (arg instanceof Error) {
1688
- error = arg;
1689
- } else if (arg !== null && typeof arg === 'object') {
1690
- merged = _extends({}, merged, arg);
1691
- hasData = true;
1692
- } else if (arg !== undefined && arg !== null) {
1693
- merged = _extends({}, merged, {
1694
- value: arg
1695
- });
1696
- hasData = true;
3864
+ throwIfAborted(signal);
3865
+ if (forwardMpcMayHaveJoinedRoom(errorInfo)) {
3866
+ if (!refreshRoom) {
3867
+ throw error;
1697
3868
  }
3869
+ relayRoom = await refreshRoom();
3870
+ throwIfAborted(signal);
3871
+ notify(onRoomRefreshed, relayRoom);
1698
3872
  }
1699
- return {
1700
- context: hasData ? merged : undefined,
1701
- error
1702
- };
1703
3873
  }
1704
- }, _Logger._instance = new NoopLogger(), _Logger._context = {}, _Logger);
3874
+ return relay(relayRoom);
3875
+ };
1705
3876
 
1706
- class WalletApiError extends Error {
1707
- constructor(status, message){
1708
- super(message);
1709
- this.name = 'WalletApiError';
1710
- this.status = status;
3877
+ /**
3878
+ * Appends `envId` to the ForwardMPC enclave WebSocket URL.
3879
+ *
3880
+ * The enclave binds the value to its session logger at the WS upgrade, and the
3881
+ * Cloudflare WAF rules on `mpc-client.*` match `envId=<uuid>` in the query
3882
+ * string to exempt approved environments from the per-IP /ws rate limits.
3883
+ */ const buildForwardMpcEnclaveUrl = (baseEnclaveUrl, environmentId)=>{
3884
+ if (!environmentId) {
3885
+ return baseEnclaveUrl;
3886
+ }
3887
+ const separator = baseEnclaveUrl.includes('?') ? '&' : '?';
3888
+ return `${baseEnclaveUrl}${separator}envId=${encodeURIComponent(environmentId)}`;
3889
+ };
3890
+
3891
+ /**
3892
+ * Normalizes an unknown thrown value into flat, log-friendly fields.
3893
+ *
3894
+ * Error objects don't survive serialization into log context (their `name`,
3895
+ * `message`, and `stack` are non-enumerable, so they serialize to `{}`), which
3896
+ * is why the underlying cause of signing failures was invisible in Datadog.
3897
+ * This extracts the useful detail — including a wrapped `cause` — into plain
3898
+ * strings that loggers will actually emit and that can be grouped/filtered on.
3899
+ */ const serializeError = (error)=>{
3900
+ const err = error instanceof Error ? error : new Error(String(error));
3901
+ const cause = err.cause;
3902
+ return _extends({
3903
+ errorName: err.name,
3904
+ errorMessage: err.message
3905
+ }, cause instanceof Error ? {
3906
+ causeMessage: cause.message
3907
+ } : {});
3908
+ };
3909
+
3910
+ const formatRawMessageForSigning = (chainName, message)=>{
3911
+ if (typeof message !== 'string') return message;
3912
+ const hex = message.startsWith('0x') ? message.slice(2) : message;
3913
+ if (/^[0-9A-Fa-f]+$/.test(hex)) {
3914
+ return new Uint8Array(Buffer.from(hex, 'hex'));
1711
3915
  }
1712
- }
1713
- const STATUS_MESSAGES = {
1714
- 400: 'Invalid request',
1715
- 401: 'Authorization header or cookie is required',
1716
- 403: 'Forbidden',
1717
- 422: 'Unprocessable content',
1718
- 429: 'Rate limited',
1719
- 500: 'Internal server error'
3916
+ return chainName === 'ALEO' ? new Uint8Array(Buffer.from(message, 'utf-8')) : Buffer.from(message).toString('hex');
1720
3917
  };
1721
- const isCloudflareRateLimitError = (error)=>{
1722
- var _error_response, _error_response1;
1723
- const data = (_error_response = error.response) == null ? void 0 : _error_response.data;
1724
- return ((_error_response1 = error.response) == null ? void 0 : _error_response1.status) === 429 && (data == null ? void 0 : data['cloudflare_error']) === true;
3918
+ const prepareRawMessageSigningPayload = (chainName, message)=>{
3919
+ const formatted = formatRawMessageForSigning(chainName, message);
3920
+ return typeof formatted === 'string' ? formatted : Buffer.from(formatted).toString('hex');
1725
3921
  };
1726
- const handleAxiosError = (error, message, context, _logger)=>{
1727
- var _error_config, _error_config1, _error_response, _error_response1, _error_response2;
1728
- const requestUrl = (_error_config = error.config) == null ? void 0 : _error_config.url;
1729
- const requestBaseUrl = (_error_config1 = error.config) == null ? void 0 : _error_config1.baseURL;
1730
- const logPayload = _extends({
1731
- message,
1732
- error: (_error_response = error.response) == null ? void 0 : _error_response.data,
1733
- status: (_error_response1 = error.response) == null ? void 0 : _error_response1.status
1734
- }, requestBaseUrl && {
1735
- requestBaseUrl
1736
- }, requestUrl && {
1737
- requestUrl
1738
- }, {
1739
- context
3922
+
3923
+ /** Returns the context as plain JSON, with each bigint (which `JSON.stringify` throws on) turned into a string. */ const toJsonSafeContext = (context)=>{
3924
+ try {
3925
+ var _serialized_evmTypedData_domain, _serialized_evmTypedData;
3926
+ const serialized = JSON.parse(JSON.stringify(context, (_key, value)=>typeof value === 'bigint' ? String(value) : value));
3927
+ // Eip712Domain.chainId must reach the API as a number, but a bigint chain
3928
+ // id comes out of the JSON round-trip as a string; restore it when the
3929
+ // value is a safe integer.
3930
+ const chainId = serialized == null ? void 0 : (_serialized_evmTypedData = serialized.evmTypedData) == null ? void 0 : (_serialized_evmTypedData_domain = _serialized_evmTypedData.domain) == null ? void 0 : _serialized_evmTypedData_domain.chainId;
3931
+ const chainIdAsNumber = typeof chainId === 'string' ? Number(chainId) : undefined;
3932
+ if (chainIdAsNumber !== undefined && Number.isSafeInteger(chainIdAsNumber) && String(chainIdAsNumber) === chainId) {
3933
+ serialized.evmTypedData.domain.chainId = chainIdAsNumber;
3934
+ }
3935
+ return serialized;
3936
+ } catch (error) {
3937
+ throw new Error(`Could not serialize the signing context: ${error instanceof Error ? error.message : String(error)}`, {
3938
+ cause: error
3939
+ });
3940
+ }
3941
+ };
3942
+
3943
+ /**
3944
+ * Returns a trace context that always has an id, so a retrying operation can hand the same one to each attempt.
3945
+ * The id is 32 lowercase hex characters, a valid W3C trace id the server can continue.
3946
+ */ const withTraceId = (traceContext)=>{
3947
+ var _traceContext_traceId, _traceContext_startTime;
3948
+ return _extends({}, traceContext, {
3949
+ traceId: (_traceContext_traceId = traceContext == null ? void 0 : traceContext.traceId) != null ? _traceContext_traceId : v4().replaceAll('-', ''),
3950
+ startTime: (_traceContext_startTime = traceContext == null ? void 0 : traceContext.startTime) != null ? _traceContext_startTime : Date.now()
1740
3951
  });
1741
- const logLevel = isCloudflareRateLimitError(error) ? 'warn' : 'error';
1742
- Logger[logLevel]('[DynamicWaasWalletClient] Axios error: ', logPayload);
1743
- const status = (_error_response2 = error.response) == null ? void 0 : _error_response2.status;
1744
- const resolvedStatus = status && STATUS_MESSAGES[status] ? status : 500;
1745
- throw new WalletApiError(resolvedStatus, STATUS_MESSAGES[resolvedStatus]);
1746
3952
  };
1747
3953
 
1748
- export { AuthMode, BITCOIN_ADDRESS_TYPE_CONFIG, BITCOIN_DERIVATION_PATHS, BackupLocation, BitcoinAddressType, BitcoinNetwork, CreateRoomPartiesOptions, DELEGATED_SHARE_COUNT, DYNAMIC_AUTH_BASE_API_URL_MAP, DYNAMIC_AUTH_DEV_BASE_API_URL, DYNAMIC_AUTH_PREPROD_BASE_API_URL, DYNAMIC_AUTH_PROD_BASE_API_URL, DYNAMIC_CLIENT_RELAY_REDCOAST_API_KEY_MAP, DYNAMIC_CLIENT_RELAY_REDCOAST_APP_ID_MAP, DYNAMIC_FORWARD_MPC_DEV_ENCLAVE_URL, DYNAMIC_FORWARD_MPC_ENCLAVE_ATTESTATION_CONFIG_MAP, DYNAMIC_FORWARD_MPC_ENCLAVE_URL_MAP, DYNAMIC_FORWARD_MPC_PREPROD_ENCLAVE_URL, DYNAMIC_FORWARD_MPC_PROD_ENCLAVE_URL, DYNAMIC_KEYSHARES_RELAY_MAP, DYNAMIC_KEYSHARES_RELAY_PREPROD_BASE_API_URL, DYNAMIC_KEYSHARES_RELAY_PROD_BASE_API_URL, DynamicApiClient, DynamicClientSessionSignature, DynamicElevatedAccessTokenHeader, DynamicForwardMPCHeader, DynamicMfaTokenHeader, DynamicRequestIdHeader, DynamicTraceElapsedTimeHeader, DynamicTraceIdHeader, ENCRYPTED_SHARES_STORAGE_SUFFIX, ENVIRONMENT_ENUM, FEATURE_FLAGS, IFRAME_DOMAIN_MAP, Logger, MIDNIGHT_DERIVATION_PATHS, MPC_CHAIN_CONFIG, MPC_CONFIG, MPC_RELAY_DEV_API_URL, MPC_RELAY_PREPROD_API_URL, MPC_RELAY_PROD_API_URL, MPC_RELAY_URL_MAP, NoopLogger, PREPROD_RELAY_API_KEY, PREPROD_RELAY_APP_ID, PROD_RELAY_API_KEY, PROD_RELAY_APP_ID, RELAY_API_KEY_HEADER, RELAY_APP_ID_HEADER, SDK_NAMESPACE, SOLANA_RPC_URL, SuccessEventType, ThresholdSignatureScheme, URL_PATTERNS, WalletApiError, WalletOperation, WalletReadyState, chain, chainEnumToVerifiedCredentialName, formatNamespacedVersion, getBitcoinChainConfig, getClientThreshold, getDynamicServerThreshold, getEnvironmentFromUrl, getMPCChainConfig, getRequiredExternalKeyShareId, getReshareConfig, getServerWalletReshareConfig, getTSSConfig, getVersionNamespace, getVersionWithoutNamespace, handleAxiosError, isCloudflareRateLimitError, parseNamespacedVersion, serializeMessageForForwardMPC, verifiedCredentialNameToChainEnum };
3954
+ /** The ids a caller can quote to support so one failed attempt can be found in client and server logs. */ /** Sets `traceId` and `requestId` on a thrown error so apps can quote them, keeping any id already set. */ const attachRequestIds = (error, { traceId, requestId })=>{
3955
+ var _target, _target1;
3956
+ if (!error || typeof error !== 'object' || !Object.isExtensible(error)) {
3957
+ return;
3958
+ }
3959
+ const target = error;
3960
+ var _traceId;
3961
+ (_traceId = (_target = target).traceId) != null ? _traceId : _target.traceId = traceId;
3962
+ var _requestId;
3963
+ (_requestId = (_target1 = target).requestId) != null ? _requestId : _target1.requestId = requestId;
3964
+ };
3965
+
3966
+ export { AuthMode, BITCOIN_ADDRESS_TYPE_CONFIG, BITCOIN_DERIVATION_PATHS, BROWSER_SDK_ROUTE_PREFIX, BackupLocation, BitcoinAddressType, BitcoinNetwork, BusinessAccountClient, BusinessAccountIntentRequiredError, BusinessAccountMemberRole, BusinessAccountSignerType, CreateRoomPartiesOptions, DEFAULT_ED25519_VARIANT, DELEGATED_SHARE_COUNT, DYNAMIC_AUTH_BASE_API_URL_MAP, DYNAMIC_AUTH_DEV_BASE_API_URL, DYNAMIC_AUTH_PREPROD_BASE_API_URL, DYNAMIC_AUTH_PROD_BASE_API_URL, DYNAMIC_CLIENT_RELAY_REDCOAST_API_KEY_MAP, DYNAMIC_CLIENT_RELAY_REDCOAST_APP_ID_MAP, DYNAMIC_FORWARD_MPC_DEV_ENCLAVE_URL, DYNAMIC_FORWARD_MPC_ENCLAVE_ATTESTATION_CONFIG_MAP, DYNAMIC_FORWARD_MPC_ENCLAVE_URL_MAP, DYNAMIC_FORWARD_MPC_PREPROD_ENCLAVE_URL, DYNAMIC_FORWARD_MPC_PROD_ENCLAVE_URL, DYNAMIC_KEYSHARES_RELAY_MAP, DYNAMIC_KEYSHARES_RELAY_PREPROD_BASE_API_URL, DYNAMIC_KEYSHARES_RELAY_PROD_BASE_API_URL, DynamicApiClient, DynamicClientSessionSignature, DynamicElevatedAccessTokenHeader, DynamicForwardMPCHeader, DynamicMfaTokenHeader, DynamicRequestIdHeader, DynamicSessionPublicKeyHeader, DynamicTraceElapsedTimeHeader, DynamicTraceIdHeader, ENCRYPTED_SHARES_STORAGE_SUFFIX, ENVIRONMENT_ENUM, EVM_COMPATIBLE_CHAINS, EarnClient, FEATURE_FLAGS, IFRAME_DOMAIN_MAP, Logger, MIDNIGHT_DERIVATION_PATHS, MPC_CHAIN_CONFIG, MPC_CONFIG, MPC_RELAY_DEV_API_URL, MPC_RELAY_PREPROD_API_URL, MPC_RELAY_PROD_API_URL, MPC_RELAY_URL_MAP, NETWORK_ERROR_CODE, NETWORK_ERROR_STATUS, NoopLogger, PREPROD_RELAY_API_KEY, PREPROD_RELAY_APP_ID, PROD_RELAY_API_KEY, PROD_RELAY_APP_ID, RELAY_API_KEY_HEADER, RELAY_APP_ID_HEADER, SDK_NAMESPACE, SERVER_SDK_ROUTE_PREFIX, SOLANA_RPC_URL, SignAndBroadcastRequestTooLargeError, SigningConsentRequiredError, SuccessEventType, ThresholdSignatureScheme, URL_PATTERNS, WAAS_EXPORT_INTENT_ACTION, WAAS_RESHARE_INTENT_ACTION, WalletApiError, WalletOperation, WalletReadyState, WasmUnavailableError, assertDynamicLocationsHaveExternalKeyShareId, assertWebAssemblyAvailable, attachRequestIds, buildForwardMpcEnclaveUrl, chain, chainEnumToVerifiedCredentialName, classifyForwardMpcError, createExportIntent, createRejectablePromise, createReshareIntent, createSigningIntent, extractServerErrorCode, formatNamespacedVersion, formatRawMessageForSigning, forwardMpcMayHaveJoinedRoom, generateUUID, getBitcoinChainConfig, getClientThreshold, getDynamicServerThreshold, getEnvironmentFromUrl, getMPCChainConfig, getRequiredExternalKeyShareId, getReshareConfig, getServerWalletReshareConfig, getTSSConfig, getVersionNamespace, getVersionWithoutNamespace, handleAxiosError, isBusinessAccountActionRequired, isEvmCompatibleChain, isRecoveredForwardMpcConnectionChurn, isWasmUnavailableErrorMessage, normalizeAndValidatePrivateKey, parseNamespacedVersion, pickSignerTarget, prepareRawMessageSigningPayload, runWithForwardMpcFallback, sanitizeBusinessAccountSignedIntent, serializeError, serializeMessageForForwardMPC, toJsonSafeContext, verifiedCredentialNameToChainEnum, withTraceId };