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