@dynamic-labs-wallet/svm 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.esm.js CHANGED
@@ -1,5 +1,5 @@
1
- import { DynamicWalletClient, getMPCChainConfig, ERROR_KEYGEN_FAILED, ERROR_PASSWORD_MISMATCH, ERROR_CREATE_WALLET_ACCOUNT, ERROR_ACCOUNT_ADDRESS_REQUIRED, ERROR_SIGN_MESSAGE, ERROR_IMPORT_PRIVATE_KEY, AuthMode } from '@dynamic-labs-wallet/browser';
2
- import { VersionedMessage, VersionedTransaction, Keypair } from '@solana/web3.js';
1
+ import { DynamicWalletClient, getMPCChainConfig, ERROR_KEYGEN_FAILED, ERROR_PASSWORD_MISMATCH, ERROR_MULTIPLE_WALLETS_PER_CHAIN, ERROR_CREATE_WALLET_ACCOUNT, ERROR_ACCOUNT_ADDRESS_REQUIRED, ERROR_SIGN_MESSAGE, getEd25519PublicKeyFromRawScalar, ERROR_IMPORT_PRIVATE_KEY } from '@dynamic-labs-wallet/browser';
2
+ import { SIGNATURE_LENGTH_IN_BYTES, VersionedTransaction, VersionedMessage, Keypair, PublicKey, SystemProgram, Message, MessageV0 } from '@solana/web3.js';
3
3
  import bs58 from 'bs58';
4
4
 
5
5
  function _extends() {
@@ -13,13 +13,150 @@ function _extends() {
13
13
  return _extends.apply(this, arguments);
14
14
  }
15
15
 
16
+ const TOKEN_2022 = 'TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb';
17
+ const ASSOCIATED_TOKEN = 'ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL';
18
+ const SYSTEM = '11111111111111111111111111111111';
19
+ const ZK_ELGAMAL_PROOF = 'ZkE1Gama1Proof11111111111111111111111111111';
20
+ const COMPUTE_BUDGET = 'ComputeBudget111111111111111111111111111111';
21
+ const ALLOWED_PROGRAMS = new Set([
22
+ TOKEN_2022,
23
+ ASSOCIATED_TOKEN,
24
+ SYSTEM,
25
+ ZK_ELGAMAL_PROOF,
26
+ COMPUTE_BUDGET
27
+ ]);
28
+ // Helper instructions the planner may emit alongside the confidential one.
29
+ const COMPUTE_SET_UNIT_LIMIT = 2;
30
+ const COMPUTE_SET_UNIT_PRICE = 3;
31
+ const ATA_CREATE = 0;
32
+ const ATA_CREATE_IDEMPOTENT = 1;
33
+ const SYSTEM_CREATE_ACCOUNT = 0;
34
+ const TOKEN_REALLOCATE = 29;
35
+ // Token-2022 ConfidentialTransferExtension (27) sub-instruction per operation.
36
+ const CONFIDENTIAL_EXTENSION = 27;
37
+ const SUB_INSTRUCTION = {
38
+ configureAccount: 2,
39
+ deposit: 5,
40
+ withdraw: 6,
41
+ transfer: 7,
42
+ applyPendingBalance: 8
43
+ };
44
+ const V1_PREFIX = 0x81;
45
+ const refuse = (reason)=>{
46
+ throw new Error(`Refusing to sign confidential transaction: ${reason}`);
47
+ };
48
+ /** Message bytes an MPC signer signs: a v1 wire is message || 64B signature slots. */ const confidentialSignedMessageBytes = (wire, numRequiredSignatures)=>wire.slice(0, wire.length - numRequiredSignatures * SIGNATURE_LENGTH_IN_BYTES);
49
+ /** Insert the wallet signature into the sole v1 signature slot (signer index 0). */ const injectConfidentialSignature = (wire, signature)=>Uint8Array.from([
50
+ ...wire.slice(0, wire.length - SIGNATURE_LENGTH_IN_BYTES),
51
+ ...signature
52
+ ]);
53
+ const decodeV1Message = (encoded, solanaAddress)=>{
54
+ const wire = new Uint8Array(Buffer.from(encoded, 'base64'));
55
+ if (wire[0] !== V1_PREFIX) {
56
+ refuse('not a version 1 transaction');
57
+ }
58
+ let message;
59
+ try {
60
+ message = VersionedTransaction.deserialize(wire).message;
61
+ } catch (e) {
62
+ return refuse('malformed transaction');
63
+ }
64
+ if (message.version !== 1) {
65
+ refuse('not a version 1 transaction');
66
+ }
67
+ if (message.header.numRequiredSignatures !== 1) {
68
+ refuse('unexpected extra signers');
69
+ }
70
+ const keys = message.staticAccountKeys.map((key)=>key.toBase58());
71
+ if (keys[0] !== solanaAddress) {
72
+ refuse('the wallet is not the fee payer');
73
+ }
74
+ return {
75
+ message,
76
+ keys
77
+ };
78
+ };
79
+ const isAllowedHelperInstruction = (program, data)=>{
80
+ switch(program){
81
+ case COMPUTE_BUDGET:
82
+ return data[0] === COMPUTE_SET_UNIT_LIMIT || data[0] === COMPUTE_SET_UNIT_PRICE;
83
+ case ASSOCIATED_TOKEN:
84
+ return data.length === 0 || data[0] === ATA_CREATE || data[0] === ATA_CREATE_IDEMPOTENT;
85
+ case SYSTEM:
86
+ return data.length >= 4 && Buffer.from(data).readUInt32LE(0) === SYSTEM_CREATE_ACCOUNT;
87
+ case TOKEN_2022:
88
+ return data[0] === TOKEN_REALLOCATE;
89
+ default:
90
+ return program === ZK_ELGAMAL_PROOF;
91
+ }
92
+ };
93
+ const checkOperationInstruction = (data, accounts, params)=>{
94
+ const { operation, mint, tokenAccount, destinationTokenAccount, amount, decimals } = params;
95
+ if (data[1] !== SUB_INSTRUCTION[operation]) {
96
+ refuse(`confidential instruction ${data[1]} does not match ${operation}`);
97
+ }
98
+ if (accounts[0] !== tokenAccount) {
99
+ refuse('instruction targets an unexpected token account');
100
+ }
101
+ if (operation !== 'applyPendingBalance' && accounts[1] !== mint) {
102
+ refuse('instruction uses an unexpected mint');
103
+ }
104
+ if (operation === 'transfer' && (!destinationTokenAccount || accounts[2] !== destinationTokenAccount)) {
105
+ refuse('transfer destination does not match the request');
106
+ }
107
+ if (operation !== 'deposit' && operation !== 'withdraw') {
108
+ return;
109
+ }
110
+ // Confidential amount layout: [27, sub, amount u64 LE, decimals u8, ...].
111
+ const bytes = Buffer.from(data);
112
+ if (amount === undefined || bytes.length < 11 || bytes.readBigUInt64LE(2).toString() !== amount) {
113
+ refuse(`${operation} amount does not match the request`);
114
+ }
115
+ if (decimals === undefined || bytes[10] !== decimals) {
116
+ refuse(`${operation} decimals do not match the request`);
117
+ }
118
+ };
119
+ /**
120
+ * Structural check on the enclave-built confidential transaction before the
121
+ * client share joins the MPC room: must be one v1 message, the wallet must be
122
+ * fee payer and only signer, only expected programs and instruction kinds may
123
+ * appear, and the confidential instruction must match the requested
124
+ * operation, mint, token accounts and amounts. The enclave's
125
+ * `transactionsTag` binds the build; this only guards against a bad build
126
+ * reaching the ceremony.
127
+ */ const checkConfidentialTransactions = (params)=>{
128
+ if (params.serializedTransactions.length !== 1) {
129
+ refuse('expected exactly one version 1 transaction');
130
+ }
131
+ const { message, keys } = decodeV1Message(params.serializedTransactions[0], params.solanaAddress);
132
+ let sawOperation = false;
133
+ for (const ix of message.compiledInstructions){
134
+ const program = keys[ix.programIdIndex];
135
+ if (!program || !ALLOWED_PROGRAMS.has(program)) {
136
+ refuse(`unexpected program ${program}`);
137
+ }
138
+ if (program === TOKEN_2022 && ix.data[0] === CONFIDENTIAL_EXTENSION) {
139
+ if (sawOperation) {
140
+ refuse('more than one confidential instruction');
141
+ }
142
+ checkOperationInstruction(ix.data, ix.accountKeyIndexes.map((i)=>keys[i]), params);
143
+ sawOperation = true;
144
+ } else if (!isAllowedHelperInstruction(program, ix.data)) {
145
+ refuse(`unexpected instruction ${ix.data[0]} for program ${program}`);
146
+ }
147
+ }
148
+ if (!sawOperation) {
149
+ refuse(`no confidential instruction for ${params.operation}`);
150
+ }
151
+ };
152
+
16
153
  class DynamicSvmWalletClient extends DynamicWalletClient {
17
154
  /**
18
155
  * Creates a wallet account on the Solana chain
19
156
  *
20
157
  * @param thresholdSignatureScheme The threshold signature scheme to use
21
158
  * @returns The account address, public key hex, raw public key, and client key shares
22
- */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, signedSessionId, traceContext }) {
159
+ */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, signedSessionId, traceContext, businessAccountId }) {
23
160
  try {
24
161
  let ceremonyCeremonyCompleteResolver;
25
162
  const ceremonyCompletePromise = new Promise((resolve)=>{
@@ -27,8 +164,9 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
27
164
  });
28
165
  const { rawPublicKey, clientKeyShares } = await this.keyGen({
29
166
  chainName: this.chainName,
167
+ businessAccountId,
30
168
  thresholdSignatureScheme,
31
- onCeremonyComplete: (accountAddress, walletId)=>{
169
+ onCeremonyComplete: ({ accountAddress, walletId, shareSetId })=>{
32
170
  const chainConfig = getMPCChainConfig(this.chainName);
33
171
  this.initializeWalletMapEntry({
34
172
  accountAddress,
@@ -38,7 +176,8 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
38
176
  derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
39
177
  index,
40
178
  value
41
- ])))
179
+ ]))),
180
+ shareSetId
42
181
  });
43
182
  ceremonyCeremonyCompleteResolver(undefined);
44
183
  },
@@ -63,19 +202,22 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
63
202
  accountAddress,
64
203
  clientKeyShares,
65
204
  password,
66
- signedSessionId
205
+ signedSessionId,
206
+ businessAccountId
67
207
  });
68
208
  return {
69
209
  accountAddress,
70
210
  rawPublicKey
71
211
  };
72
212
  } catch (error) {
73
- // Re-throw password mismatch errors without wrapping
74
- if (error instanceof Error && error.message === ERROR_PASSWORD_MISMATCH) {
213
+ // Re-throw known business-rule rejections without wrapping
214
+ if (error instanceof Error && (error.message === ERROR_PASSWORD_MISMATCH || error.message === ERROR_MULTIPLE_WALLETS_PER_CHAIN)) {
75
215
  throw error;
76
216
  }
77
217
  this.logger.error(ERROR_CREATE_WALLET_ACCOUNT, error);
78
- throw new Error(ERROR_CREATE_WALLET_ACCOUNT);
218
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT, {
219
+ cause: error
220
+ });
79
221
  }
80
222
  }
81
223
  async deriveAccountAddress(rawPublicKey) {
@@ -91,7 +233,7 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
91
233
  * @param message The message to sign (Uint8Array)
92
234
  * @param accountAddress Solana address (base58 encoded)
93
235
  * @param password The password for encrypted backup shares
94
- */ async signMessage({ message, accountAddress, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, onError, traceContext }) {
236
+ */ async signMessage({ message, accountAddress, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, approvalQuorum, onError, traceContext }) {
95
237
  await this.verifyPassword({
96
238
  accountAddress,
97
239
  password,
@@ -112,17 +254,20 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
112
254
  context: {
113
255
  svmMessage: message
114
256
  },
257
+ approvalQuorum,
115
258
  onError,
116
259
  traceContext
117
260
  });
118
261
  const base58Signature = bs58.encode(signatureEd25519);
119
262
  return base58Signature;
120
263
  } catch (error) {
121
- this.logger.error(ERROR_SIGN_MESSAGE, error);
122
- throw new Error(ERROR_SIGN_MESSAGE);
264
+ this.logOperationFailure(ERROR_SIGN_MESSAGE, error);
265
+ throw new Error(ERROR_SIGN_MESSAGE, {
266
+ cause: error
267
+ });
123
268
  }
124
269
  }
125
- async signTransaction({ senderAddress, transaction, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, chainId, context, onError, traceContext }) {
270
+ async signTransaction({ senderAddress, transaction, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, chainId, context, approvalQuorum, onError, traceContext }) {
126
271
  await this.verifyPassword({
127
272
  accountAddress: senderAddress,
128
273
  password,
@@ -139,7 +284,8 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
139
284
  elevatedAccessToken,
140
285
  chainId,
141
286
  base58SerializedTransaction,
142
- context
287
+ context,
288
+ approvalQuorum
143
289
  });
144
290
  const signatureEd25519 = await this.sign(_extends({}, signParams, {
145
291
  onError,
@@ -157,6 +303,55 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
157
303
  throw error;
158
304
  }
159
305
  }
306
+ /**
307
+ * Signs a Solana transaction for Dynamic to broadcast.
308
+ *
309
+ * @param params.senderAddress - The wallet's address.
310
+ * @param params.transaction - The transaction message as hex, the same bytes `signTransaction` signs.
311
+ * @param params.chainId - The Solana network id (e.g. `101`). Dynamic checks it against the wallet's network.
312
+ * @param params.skipPreflight - Skip the network's pre-send dry run. Faster, but a doomed transaction still costs a fee.
313
+ * @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`.
314
+ * @param params.externalReference - Your own label, returned on every event. Not unique.
315
+ * @param params.idempotencyKey - Makes a retry safe: the same key replays the stored answer instead of sending twice. A new one is made when omitted.
316
+ * @param params.password - The wallet's backup password, if it has one.
317
+ * @param params.signedSessionId - The signed-in session, used to unlock the wallet's key share.
318
+ * @param params.mfaToken - Proof of the user's multi-factor check, when the wallet needs one.
319
+ * @param params.elevatedAccessToken - Proof of a recent re-login, when the wallet needs one.
320
+ * @param params.approvalQuorum - Approvers' consent for a governed wallet, sent on the retry after `intent_required`.
321
+ * @param params.onError - Called with the failure's message, never the raw error.
322
+ * @param params.traceContext - Ties this call's logs to the server's, across retries. Created when omitted.
323
+ * @returns The transaction record.
324
+ * @throws Error when `chainId` is missing.
325
+ */ async signAndBroadcastTransaction({ senderAddress, transaction, chainId, skipPreflight, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, approvalQuorum, requestedCertainty, externalReference, idempotencyKey, onError, traceContext }) {
326
+ if (!chainId) {
327
+ throw new Error('Sign and broadcast on Solana needs the network id as `chainId`');
328
+ }
329
+ const base58SerializedTransaction = this.prepareTransactionForSigning(transaction);
330
+ return await this.signAndBroadcast({
331
+ accountAddress: senderAddress,
332
+ chainName: this.chainName,
333
+ context: {
334
+ svmTransaction: this.buildSvmTransactionContext({
335
+ chainId,
336
+ base58SerializedTransaction
337
+ })
338
+ },
339
+ broadcastOptions: skipPreflight === undefined ? undefined : {
340
+ skipPreflight
341
+ },
342
+ message: transaction,
343
+ password,
344
+ signedSessionId,
345
+ mfaToken,
346
+ elevatedAccessToken,
347
+ approvalQuorum,
348
+ requestedCertainty,
349
+ externalReference,
350
+ idempotencyKey,
351
+ onError,
352
+ traceContext
353
+ });
354
+ }
160
355
  prepareTransactionForSigning(transaction) {
161
356
  const transactionBytes = new Uint8Array(Buffer.from(transaction, 'hex'));
162
357
  const deserializedTransaction = VersionedMessage.deserialize(transactionBytes);
@@ -164,7 +359,21 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
164
359
  const serializedTransaction = versionedTransaction.serialize();
165
360
  return bs58.encode(serializedTransaction);
166
361
  }
167
- buildSignParams({ transaction, senderAddress, password, signedSessionId, mfaToken, elevatedAccessToken, chainId, base58SerializedTransaction, context }) {
362
+ /**
363
+ * The Solana part of a signing context: which network, how it is sent, and the transaction in base58. Shared by sign and sign-and-broadcast so both describe it the same way.
364
+ *
365
+ * @param params.chainId - The Solana network id.
366
+ * @param params.base58SerializedTransaction - The transaction, base58-encoded.
367
+ */ buildSvmTransactionContext({ chainId, base58SerializedTransaction }) {
368
+ return {
369
+ chainId,
370
+ method: 'signAndSendTransaction',
371
+ serializedTransactions: [
372
+ base58SerializedTransaction
373
+ ]
374
+ };
375
+ }
376
+ buildSignParams({ transaction, senderAddress, password, signedSessionId, mfaToken, elevatedAccessToken, chainId, base58SerializedTransaction, context, approvalQuorum }) {
168
377
  const signParams = {
169
378
  message: transaction,
170
379
  accountAddress: senderAddress,
@@ -172,17 +381,15 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
172
381
  password,
173
382
  signedSessionId,
174
383
  mfaToken,
175
- elevatedAccessToken
384
+ elevatedAccessToken,
385
+ approvalQuorum
176
386
  };
177
387
  if (chainId !== undefined) {
178
388
  signParams.context = _extends({}, context, {
179
- svmTransaction: {
389
+ svmTransaction: this.buildSvmTransactionContext({
180
390
  chainId,
181
- method: 'signAndSendTransaction',
182
- serializedTransactions: [
183
- base58SerializedTransaction
184
- ]
185
- }
391
+ base58SerializedTransaction
392
+ })
186
393
  });
187
394
  }
188
395
  return signParams;
@@ -193,7 +400,7 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
193
400
  * @param accountAddress The account address to export the private key for
194
401
  * @param password The password for encrypted backup shares
195
402
  * @returns The private key
196
- */ async exportPrivateKey({ accountAddress, password = undefined, signedSessionId, mfaToken, elevatedAccessToken }) {
403
+ */ async exportPrivateKey({ accountAddress, password = undefined, signedSessionId, mfaToken, elevatedAccessToken, approvalQuorum, proposalId }) {
197
404
  await this.verifyPassword({
198
405
  accountAddress,
199
406
  password,
@@ -205,7 +412,9 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
205
412
  password,
206
413
  signedSessionId,
207
414
  mfaToken,
208
- elevatedAccessToken
415
+ elevatedAccessToken,
416
+ approvalQuorum,
417
+ proposalId
209
418
  });
210
419
  if (!derivedPrivateKey) {
211
420
  throw new Error('Derived private key is undefined');
@@ -245,7 +454,13 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
245
454
  const slicedBytes = decoded.slice(0, 32);
246
455
  return Buffer.from(slicedBytes).toString('hex');
247
456
  }
248
- getPublicKeyFromPrivateKey(privateKey) {
457
+ getPublicKeyFromPrivateKey(privateKey, opts) {
458
+ if (opts == null ? void 0 : opts.isRawScalar) {
459
+ // `privateKey` is a raw 32-byte ed25519 signing scalar (hex), not a seed.
460
+ // Derive the address as A = s·B rather than seed-expanding it.
461
+ const publicKeyBytes = getEd25519PublicKeyFromRawScalar(privateKey);
462
+ return bs58.encode(publicKeyBytes);
463
+ }
249
464
  const privateKeyBytes = bs58.decode(privateKey);
250
465
  const keypair = Keypair.fromSecretKey(privateKeyBytes);
251
466
  const publicKeyBase58 = keypair.publicKey.toBase58();
@@ -262,28 +477,35 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
262
477
  * @param thresholdSignatureScheme The threshold signature scheme to use
263
478
  * @param password The password for encrypted backup shares
264
479
  * @returns The account address, raw public key, and client key shares
265
- */ async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password = undefined, onError, signedSessionId, publicAddressCheck, legacyWalletId }) {
480
+ */ async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password = undefined, onError, signedSessionId, publicAddressCheck, legacyWalletId, isRawScalarImport }) {
266
481
  try {
267
482
  let ceremonyCeremonyCompleteResolver;
268
483
  const ceremonyCompletePromise = new Promise((resolve)=>{
269
484
  ceremonyCeremonyCompleteResolver = resolve;
270
485
  });
271
486
  //get public key from private key
272
- const publicKey = this.getPublicKeyFromPrivateKey(privateKey);
487
+ const publicKey = this.getPublicKeyFromPrivateKey(privateKey, {
488
+ isRawScalar: isRawScalarImport
489
+ });
273
490
  if (publicAddressCheck && publicKey !== publicAddressCheck) {
274
491
  throw new Error(`Public address mismatch: derived address ${publicKey} !== public address ${publicAddressCheck}`);
275
492
  }
276
- const formattedPrivateKey = this.decodePrivateKeyForSolana(privateKey);
493
+ // Raw scalar: pass the 32-byte scalar hex straight through to the MPC importer.
494
+ // Seed-based: decode the bs58 secret key down to its 32-byte seed (hex).
495
+ const formattedPrivateKey = isRawScalarImport ? privateKey.replace(/^0x/, '') : this.decodePrivateKeyForSolana(privateKey);
277
496
  const { rawPublicKey, clientKeyShares } = await this.importRawPrivateKey({
278
497
  chainName,
279
498
  privateKey: formattedPrivateKey,
280
499
  thresholdSignatureScheme,
281
- onCeremonyComplete: (accountAddress, walletId)=>{
500
+ isRawScalarImport,
501
+ onCeremonyComplete: ({ accountAddress, walletId, shareSetId })=>{
282
502
  this.initializeWalletMapEntry({
283
503
  accountAddress,
284
504
  walletId,
285
505
  chainName: this.chainName,
286
- thresholdSignatureScheme
506
+ thresholdSignatureScheme,
507
+ shareSetId,
508
+ variant: isRawScalarImport ? 'ed25519Standard' : undefined
287
509
  });
288
510
  ceremonyCeremonyCompleteResolver(undefined);
289
511
  },
@@ -317,32 +539,435 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
317
539
  rawPublicKey: rawPublicKey
318
540
  };
319
541
  } catch (error) {
320
- this.logger.error(ERROR_IMPORT_PRIVATE_KEY, error);
542
+ const message = error instanceof Error ? error.message : '';
543
+ const isPublicAddressMismatch = message.startsWith('Public address mismatch:');
544
+ if (!isPublicAddressMismatch) {
545
+ this.logger.error(ERROR_IMPORT_PRIVATE_KEY, error);
546
+ }
321
547
  onError == null ? void 0 : onError(error);
548
+ const isAddressValidationError = isPublicAddressMismatch || message.startsWith('Public key mismatch:');
549
+ if (isAddressValidationError) {
550
+ throw error;
551
+ }
322
552
  throw new Error(ERROR_IMPORT_PRIVATE_KEY);
323
553
  }
324
554
  }
555
+ /**
556
+ * Generates a Token-2022 confidential-transfer seed inside the enclave and
557
+ * stores the sealed result in CKS. Returns the ElGamal public key.
558
+ */ createConfidentialSeed({ walletId, solanaAddress, derivationVersion, traceContext }) {
559
+ return this.apiClient.createConfidentialSeed({
560
+ walletId,
561
+ request: {
562
+ derivationVersion,
563
+ solanaAddress
564
+ },
565
+ traceContext
566
+ });
567
+ }
568
+ /**
569
+ * Builds and signs a Token-2022 confidential-transfer transaction.
570
+ *
571
+ * The enclave is offline, so missing account states and the latest
572
+ * blockhash are fetched from `rpcUrl`. The enclave builds one unsigned v1
573
+ * transaction bound by a `transactionsTag`; `signConfidentialTransactions`
574
+ * provisions one MPC room for the operation and the client share joins it.
575
+ * Pass `broadcast: true` to submit the signed transaction to the cluster.
576
+ */ async signConfidentialTransfer({ walletId, operation, solanaAddress, mint, tokenAccount, destinationTokenAccount, amount, decimals, accountState, destinationAccountState, auditorElgamalPubkey, feePayer, derivationVersion, chainId = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', lamportsPerByte = '6960', recentBlockhash, lastValidBlockHeight, rpcUrl, broadcast = false, broadcastOptions, password, signedSessionId, mfaToken, elevatedAccessToken, traceContext }) {
577
+ const needsAccountState = operation === 'transfer' || operation === 'withdraw' || operation === 'applyPendingBalance';
578
+ const needsDestinationAccountState = operation === 'transfer';
579
+ const mustFetch = broadcast || needsAccountState && !accountState || needsDestinationAccountState && !destinationAccountState || !recentBlockhash || !lastValidBlockHeight;
580
+ if (mustFetch && !rpcUrl) {
581
+ throw new Error('signConfidentialTransfer requires rpcUrl to fetch account state, blockhash, or broadcast');
582
+ }
583
+ if (rpcUrl) {
584
+ if (needsAccountState && !accountState) {
585
+ accountState = await this.svmAccountState(rpcUrl, tokenAccount);
586
+ }
587
+ if (needsDestinationAccountState && !destinationAccountState && destinationTokenAccount) {
588
+ destinationAccountState = await this.svmAccountState(rpcUrl, destinationTokenAccount);
589
+ }
590
+ }
591
+ const blockhashFields = recentBlockhash && lastValidBlockHeight ? {
592
+ recentBlockhash,
593
+ lastValidBlockHeight
594
+ } : await this.confidentialBlockhash(rpcUrl);
595
+ const built = await this.apiClient.signConfidentialTransfer({
596
+ walletId,
597
+ request: {
598
+ accountState,
599
+ amount,
600
+ auditorElgamalPubkey,
601
+ chainId,
602
+ decimals,
603
+ derivationVersion,
604
+ destinationAccountState,
605
+ destinationTokenAccount,
606
+ feePayer,
607
+ lamportsPerByte,
608
+ lastValidBlockHeight: blockhashFields.lastValidBlockHeight,
609
+ mint,
610
+ operation,
611
+ recentBlockhash: blockhashFields.recentBlockhash,
612
+ solanaAddress,
613
+ tokenAccount
614
+ },
615
+ traceContext
616
+ });
617
+ checkConfidentialTransactions({
618
+ serializedTransactions: built.serializedTransactions,
619
+ solanaAddress,
620
+ operation,
621
+ mint,
622
+ tokenAccount,
623
+ destinationTokenAccount,
624
+ amount,
625
+ decimals
626
+ });
627
+ const wireBytes = new Uint8Array(Buffer.from(built.serializedTransactions[0], 'base64'));
628
+ const signature = await this.queueSign(solanaAddress, async ()=>{
629
+ const { wallet, derivationPath, clientKeyShares } = await this.prepareWalletForSign({
630
+ accountAddress: solanaAddress,
631
+ password,
632
+ signedSessionId
633
+ });
634
+ const { roomIds } = await this.apiClient.signConfidentialTransactions({
635
+ walletId,
636
+ request: {
637
+ solanaAddress,
638
+ serializedTransactions: built.serializedTransactions,
639
+ transactionsTag: built.transactionsTag,
640
+ chainId
641
+ },
642
+ mfaToken,
643
+ elevatedAccessToken,
644
+ traceContext
645
+ });
646
+ if (roomIds.length !== 1) {
647
+ throw new Error('signConfidentialTransactions must return exactly one room');
648
+ }
649
+ // Join the one room redcoast provisioned over the relay (the enclave is already in);
650
+ // the check guarantees the wallet is the sole signer of the v1 message.
651
+ return await this.clientSign({
652
+ chainName: this.chainName,
653
+ message: confidentialSignedMessageBytes(wireBytes, 1),
654
+ roomId: roomIds[0],
655
+ keyShare: clientKeyShares[0],
656
+ derivationPath,
657
+ isFormatted: false,
658
+ dynamicRequestId: crypto.randomUUID(),
659
+ skipForwardMPC: true,
660
+ variant: wallet.variant,
661
+ traceContext
662
+ });
663
+ });
664
+ const signedTransactions = [
665
+ Buffer.from(injectConfidentialSignature(wireBytes, signature)).toString('base64')
666
+ ];
667
+ const signatures = [
668
+ bs58.encode(signature)
669
+ ];
670
+ const transactionIds = broadcast ? await this.broadcastConfidentialTransactions(rpcUrl, signedTransactions, broadcastOptions) : undefined;
671
+ return {
672
+ serializedTransactions: signedTransactions,
673
+ signatures,
674
+ transactionIds
675
+ };
676
+ }
677
+ /**
678
+ * Returns the available and pending Token-2022 confidential balances for a
679
+ * token account. When `accountState` is omitted it is fetched from `rpcUrl`.
680
+ */ async getConfidentialBalance({ walletId, solanaAddress, tokenAccount, mint, accountState, rpcUrl, derivationVersion, traceContext }) {
681
+ if (!accountState) {
682
+ if (!rpcUrl) {
683
+ throw new Error('getConfidentialBalance requires rpcUrl to fetch account state');
684
+ }
685
+ accountState = await this.svmAccountState(rpcUrl, tokenAccount);
686
+ }
687
+ return this.apiClient.getSvmConfidentialBalance({
688
+ walletId,
689
+ request: {
690
+ accountState,
691
+ derivationVersion,
692
+ mint,
693
+ solanaAddress,
694
+ tokenAccount
695
+ },
696
+ traceContext
697
+ });
698
+ }
325
699
  async getSvmWallets() {
326
700
  const wallets = await this.getWallets();
327
701
  const svmWallets = wallets.filter((wallet)=>wallet.chainName === 'SVM');
328
702
  return svmWallets;
329
703
  }
330
- constructor({ environmentId, authToken, backupServiceAuthToken, baseApiUrl, baseMPCRelayApiUrl, storageKey, debug, featureFlags, authMode = AuthMode.HEADER, sdkVersion, forwardMPCClient, logger }, internalOptions){
331
- super({
332
- environmentId,
333
- authToken,
334
- backupServiceAuthToken,
335
- baseApiUrl,
336
- baseMPCRelayApiUrl,
337
- storageKey,
338
- debug,
339
- featureFlags,
340
- authMode,
341
- sdkVersion,
342
- forwardMPCClient,
343
- logger
344
- }, internalOptions), this.chainName = 'SVM';
704
+ constructor(...args){
705
+ super(...args), this.chainName = 'SVM', // ---------------------------------------------------------------------------
706
+ // Token-2022 confidential transfers
707
+ // ---------------------------------------------------------------------------
708
+ this.svmRpcCall = async (rpcUrl, method, params)=>{
709
+ const parsedUrl = new URL(rpcUrl);
710
+ const isLocalHttp = parsedUrl.protocol === 'http:' && [
711
+ 'localhost',
712
+ '127.0.0.1',
713
+ '[::1]'
714
+ ].includes(parsedUrl.hostname);
715
+ if (parsedUrl.protocol !== 'https:' && !isLocalHttp) {
716
+ throw new Error(`Unsupported rpcUrl protocol: ${parsedUrl.protocol}`);
717
+ }
718
+ const response = await fetch(parsedUrl, {
719
+ method: 'POST',
720
+ headers: {
721
+ 'content-type': 'application/json'
722
+ },
723
+ body: JSON.stringify({
724
+ jsonrpc: '2.0',
725
+ id: 1,
726
+ method,
727
+ params
728
+ })
729
+ });
730
+ const body = await response.json();
731
+ if (body.error) {
732
+ var _body_error;
733
+ var _body_error_message;
734
+ throw new Error(`Solana RPC ${method} failed: ${(_body_error_message = (_body_error = body.error) == null ? void 0 : _body_error.message) != null ? _body_error_message : JSON.stringify(body.error)}`);
735
+ }
736
+ return body.result;
737
+ }, this.svmAccountState = async (rpcUrl, account)=>{
738
+ const result = await this.svmRpcCall(rpcUrl, 'getAccountInfo', [
739
+ account,
740
+ {
741
+ encoding: 'base64',
742
+ commitment: 'confirmed'
743
+ }
744
+ ]);
745
+ if (!(result == null ? void 0 : result.value)) {
746
+ throw new Error(`Solana account not found: ${account}`);
747
+ }
748
+ const { data, lamports, owner } = result.value;
749
+ return {
750
+ data: Array.isArray(data) ? data[0] : data,
751
+ lamports: String(lamports),
752
+ owner: String(owner)
753
+ };
754
+ }, this.confidentialBlockhash = async (rpcUrl)=>{
755
+ var _latest_value;
756
+ const latest = rpcUrl ? await this.svmRpcCall(rpcUrl, 'getLatestBlockhash', []) : undefined;
757
+ const recentBlockhash = latest == null ? void 0 : (_latest_value = latest.value) == null ? void 0 : _latest_value.blockhash;
758
+ const lastValidBlockHeight = (latest == null ? void 0 : latest.value) ? String(latest.value.lastValidBlockHeight) : undefined;
759
+ if (!recentBlockhash || !lastValidBlockHeight) {
760
+ throw new Error('signConfidentialTransfer requires rpcUrl to fetch the latest blockhash');
761
+ }
762
+ return {
763
+ lastValidBlockHeight,
764
+ recentBlockhash
765
+ };
766
+ }, this.broadcastConfidentialTransactions = async (rpcUrl, serializedTransactions, broadcastOptions)=>serializedTransactions.reduce(async (accPromise, serializedTransaction)=>{
767
+ const acc = await accPromise;
768
+ const transactionId = await this.svmRpcCall(rpcUrl, 'sendTransaction', [
769
+ serializedTransaction,
770
+ _extends({
771
+ encoding: 'base64',
772
+ preflightCommitment: 'confirmed'
773
+ }, broadcastOptions)
774
+ ]);
775
+ // Confidential plans are order-dependent: confirm before submitting
776
+ // the next transaction or Solana may process them out of order.
777
+ await this.waitForConfidentialConfirmation(rpcUrl, transactionId);
778
+ acc.push(transactionId);
779
+ return acc;
780
+ }, Promise.resolve([])), this.waitForConfidentialConfirmation = async (rpcUrl, transactionId, attemptsLeft = 30)=>{
781
+ var _result_value;
782
+ const result = await this.svmRpcCall(rpcUrl, 'getSignatureStatuses', [
783
+ [
784
+ transactionId
785
+ ]
786
+ ]);
787
+ const status = result == null ? void 0 : (_result_value = result.value) == null ? void 0 : _result_value[0];
788
+ if (status == null ? void 0 : status.err) {
789
+ throw new Error(`Confidential transaction failed: ${JSON.stringify({
790
+ transactionId,
791
+ err: status.err
792
+ })}`);
793
+ }
794
+ if ((status == null ? void 0 : status.confirmationStatus) === 'confirmed' || (status == null ? void 0 : status.confirmationStatus) === 'finalized') {
795
+ return;
796
+ }
797
+ if (attemptsLeft <= 1) {
798
+ throw new Error(`Timed out waiting for confidential transaction ${transactionId} to confirm`);
799
+ }
800
+ await new Promise((resolve)=>setTimeout(resolve, 1000));
801
+ await this.waitForConfidentialConfirmation(rpcUrl, transactionId, attemptsLeft - 1);
802
+ };
345
803
  }
346
804
  }
347
805
 
348
- export { DynamicSvmWalletClient };
806
+ const ADVANCE_NONCE_ACCOUNT_INSTRUCTION = 4;
807
+ const isHexBytes = (value)=>/^(?:[0-9a-fA-F]{2})+$/.test(value);
808
+ const assertNetworkChainId = (chainId)=>{
809
+ if (!(chainId == null ? void 0 : chainId.trim()) || chainId.trim() !== chainId) {
810
+ throw new Error('SVM signing intent requires a network chainId');
811
+ }
812
+ return chainId;
813
+ };
814
+ const parseUnsignedMessage = (transaction)=>{
815
+ if (!isHexBytes(transaction)) {
816
+ throw new Error('SVM signing intent requires a hex serialized message');
817
+ }
818
+ const message = VersionedMessage.deserialize(Uint8Array.from(Buffer.from(transaction, 'hex')));
819
+ // Compare as hex: the browser Buffer polyfill's equals() rejects a plain Uint8Array.
820
+ if (Buffer.from(message.serialize()).toString('hex') !== transaction.toLowerCase()) {
821
+ throw new Error('SVM signing intent requires one complete unsigned message');
822
+ }
823
+ return message;
824
+ };
825
+ const assertSupportedMessageShape = (message)=>{
826
+ if (message.version !== 'legacy' && message.version !== 0) {
827
+ throw new Error('Unsupported SVM message version');
828
+ }
829
+ if (message.addressTableLookups.length !== 0) {
830
+ throw new Error('SVM signing intent does not support address-table lookups');
831
+ }
832
+ };
833
+ const resolveFeePayer = (message, accountAddress)=>{
834
+ var _message_staticAccountKeys_;
835
+ const feePayer = (_message_staticAccountKeys_ = message.staticAccountKeys[0]) == null ? void 0 : _message_staticAccountKeys_.toBase58();
836
+ if (!feePayer || feePayer !== accountAddress || message.header.numRequiredSignatures < 1) {
837
+ throw new Error('SVM fee payer must be the signing account');
838
+ }
839
+ return feePayer;
840
+ };
841
+ const isAdvanceNonceInstruction = (message, instruction)=>{
842
+ const program = message.staticAccountKeys[instruction.programIdIndex];
843
+ const data = Buffer.from(instruction.data);
844
+ return Boolean(program == null ? void 0 : program.equals(SystemProgram.programId)) && data.length >= 4 && data.readUInt32LE(0) === ADVANCE_NONCE_ACCOUNT_INSTRUCTION;
845
+ };
846
+ const assertNoDurableNonce = (message)=>{
847
+ if (message.compiledInstructions.some((instruction)=>isAdvanceNonceInstruction(message, instruction))) {
848
+ throw new Error('SVM signing intent does not support durable nonce transactions');
849
+ }
850
+ };
851
+ const messageVersionOf = (message)=>{
852
+ if (message.version === 'legacy') return 'legacy';
853
+ return 'v0';
854
+ };
855
+ const toTransactionOperation = (message, chainId, feePayer)=>({
856
+ kind: 'transaction',
857
+ chainName: 'SVM',
858
+ chainId,
859
+ messageVersion: messageVersionOf(message),
860
+ feePayer,
861
+ header: {
862
+ numRequiredSignatures: message.header.numRequiredSignatures,
863
+ numReadonlySignedAccounts: message.header.numReadonlySignedAccounts,
864
+ numReadonlyUnsignedAccounts: message.header.numReadonlyUnsignedAccounts
865
+ },
866
+ staticAccountKeys: message.staticAccountKeys.map((key)=>key.toBase58()),
867
+ instructions: message.compiledInstructions.map((instruction)=>({
868
+ programIdIndex: instruction.programIdIndex,
869
+ accountKeyIndexes: [
870
+ ...instruction.accountKeyIndexes
871
+ ],
872
+ data: `0x${Buffer.from(instruction.data).toString('hex')}`
873
+ }))
874
+ });
875
+ const prepareSvmTransactionSigningOperation = ({ transaction, accountAddress, chainId })=>{
876
+ const networkChainId = assertNetworkChainId(chainId);
877
+ const message = parseUnsignedMessage(transaction);
878
+ assertSupportedMessageShape(message);
879
+ const feePayer = resolveFeePayer(message, accountAddress);
880
+ assertNoDurableNonce(message);
881
+ return {
882
+ operation: toTransactionOperation(message, networkChainId, feePayer),
883
+ lifetime: {
884
+ refreshable: 'blockhash'
885
+ }
886
+ };
887
+ };
888
+ const BLOCKHASH_BYTES = 32;
889
+ const signedSvmOperation = (intent)=>{
890
+ var _intent_lifetime;
891
+ const { operation } = intent;
892
+ if (operation.kind !== 'transaction' || operation.chainName !== 'SVM' || ((_intent_lifetime = intent.lifetime) == null ? void 0 : _intent_lifetime.refreshable) !== 'blockhash') {
893
+ throw new Error('Stored signing intent is not an SVM transaction');
894
+ }
895
+ return operation;
896
+ };
897
+ const assertBlockhash = (blockhash)=>{
898
+ if (!blockhash || new PublicKey(blockhash).toBytes().length !== BLOCKHASH_BYTES) {
899
+ throw new Error('SVM transaction intent requires a blockhash');
900
+ }
901
+ return blockhash;
902
+ };
903
+ const instructionData = (data)=>Uint8Array.from(Buffer.from(data.slice(2), 'hex'));
904
+ const buildLegacyMessage = (operation, recentBlockhash)=>new Message({
905
+ header: operation.header,
906
+ accountKeys: operation.staticAccountKeys.map((key)=>new PublicKey(key)),
907
+ recentBlockhash,
908
+ instructions: operation.instructions.map((instruction)=>({
909
+ programIdIndex: instruction.programIdIndex,
910
+ accounts: [
911
+ ...instruction.accountKeyIndexes
912
+ ],
913
+ data: bs58.encode(instructionData(instruction.data))
914
+ }))
915
+ });
916
+ const buildV0Message = (operation, recentBlockhash)=>new MessageV0({
917
+ header: operation.header,
918
+ staticAccountKeys: operation.staticAccountKeys.map((key)=>new PublicKey(key)),
919
+ recentBlockhash,
920
+ compiledInstructions: operation.instructions.map((instruction)=>({
921
+ programIdIndex: instruction.programIdIndex,
922
+ accountKeyIndexes: [
923
+ ...instruction.accountKeyIndexes
924
+ ],
925
+ data: instructionData(instruction.data)
926
+ })),
927
+ addressTableLookups: []
928
+ });
929
+ const buildMessage = (operation, recentBlockhash)=>{
930
+ if (operation.messageVersion === 'legacy') return buildLegacyMessage(operation, recentBlockhash);
931
+ return buildV0Message(operation, recentBlockhash);
932
+ };
933
+ /** Orders the signed operation's fields as `prepareSvmTransactionSigningOperation` does, for comparison. */ const canonicalSvmOperation = (operation)=>({
934
+ kind: operation.kind,
935
+ chainName: operation.chainName,
936
+ chainId: operation.chainId,
937
+ messageVersion: operation.messageVersion,
938
+ feePayer: operation.feePayer,
939
+ header: {
940
+ numRequiredSignatures: operation.header.numRequiredSignatures,
941
+ numReadonlySignedAccounts: operation.header.numReadonlySignedAccounts,
942
+ numReadonlyUnsignedAccounts: operation.header.numReadonlyUnsignedAccounts
943
+ },
944
+ staticAccountKeys: operation.staticAccountKeys,
945
+ instructions: operation.instructions.map((instruction)=>({
946
+ programIdIndex: instruction.programIdIndex,
947
+ accountKeyIndexes: instruction.accountKeyIndexes,
948
+ data: instruction.data.toLowerCase()
949
+ }))
950
+ });
951
+ const assertRebuiltMatchesOperation = (transaction, accountAddress, operation)=>{
952
+ const rebuilt = prepareSvmTransactionSigningOperation({
953
+ transaction,
954
+ accountAddress,
955
+ chainId: operation.chainId
956
+ }).operation;
957
+ if (JSON.stringify(rebuilt) !== JSON.stringify(canonicalSvmOperation(operation))) {
958
+ throw new Error('Stored SVM transaction intent is malformed');
959
+ }
960
+ };
961
+ /**
962
+ * Reconstructs the unsigned serialized message (hex) from an approved intent.
963
+ * The signed intent carries no blockhash, so the caller supplies one. Passing the
964
+ * blockhash of the original message is fine while it is still valid.
965
+ */ const resumeSvmTransactionSigningIntent = ({ intent, lifetimeValue })=>{
966
+ const operation = signedSvmOperation(intent);
967
+ const recentBlockhash = assertBlockhash(lifetimeValue);
968
+ const transaction = Buffer.from(buildMessage(operation, recentBlockhash).serialize()).toString('hex');
969
+ assertRebuiltMatchesOperation(transaction, intent.accountAddress, operation);
970
+ return transaction;
971
+ };
972
+
973
+ export { DynamicSvmWalletClient, prepareSvmTransactionSigningOperation, resumeSvmTransactionSigningIntent };