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