@dynamic-labs-wallet/node-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,6 @@
1
- import { createLogError, DynamicWalletClient, getMPCChainConfig, getExternalServerKeyShareBackupInfo, WalletOperation, stripHexPrefix, SOLANA_RPC_URL, createDelegatedWalletClient, delegatedSignMessage as delegatedSignMessage$1, revokeDelegation as revokeDelegation$1 } from '@dynamic-labs-wallet/node';
2
- import { PublicKey, VersionedTransaction, Keypair, Transaction, Connection, SystemProgram } from '@solana/web3.js';
1
+ import { SOLANA_RPC_URL, createLogError, DynamicWalletClient, getMPCChainConfig, stripHexPrefix, resolveRawSignContext, WalletOperation, ClientValidationError, createDelegatedWalletClient, delegatedSignMessage as delegatedSignMessage$1, withDelegatedServerAuth, revokeDelegation as revokeDelegation$1 } from '@dynamic-labs-wallet/node';
2
+ import { SIGNATURE_LENGTH_IN_BYTES, VersionedTransaction, PublicKey, Connection, Transaction, SystemProgram, Keypair } from '@solana/web3.js';
3
+ import { randomUUID } from 'node:crypto';
3
4
 
4
5
  function _extends() {
5
6
  _extends = Object.assign || function assign(target) {
@@ -12,6 +13,143 @@ function _extends() {
12
13
  return _extends.apply(this, arguments);
13
14
  }
14
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
+
15
153
  const ERROR_CREATE_WALLET_ACCOUNT = 'Error creating svm wallet account';
16
154
  const ERROR_SIGN_RAW_MESSAGE = 'Error signing raw message';
17
155
 
@@ -82,69 +220,464 @@ function decodeBase58(str) {
82
220
  return out;
83
221
  }
84
222
 
223
+ function _object_without_properties_loose(source, excluded) {
224
+ if (source == null) return {};
225
+ var target = {};
226
+ var sourceKeys = Object.keys(source);
227
+ var key, i;
228
+ for(i = 0; i < sourceKeys.length; i++){
229
+ key = sourceKeys[i];
230
+ if (excluded.indexOf(key) >= 0) continue;
231
+ target[key] = source[key];
232
+ }
233
+ return target;
234
+ }
235
+
236
+ const ERROR_EARN_NOT_SVM_WALLET = 'Wallet metadata is not for an SVM wallet';
237
+ const ERROR_EARN_MISSING_TRANSACTIONS = 'Earn signing payload is missing the Solana transaction sequence';
238
+ const ERROR_EARN_NON_CONTIGUOUS_ORDINALS = 'Earn signing payload transaction ordinals must be contiguous from zero';
239
+ /** Default RPC per Dynamic Solana chain id (101 mainnet, 103 devnet); `rpcUrl` overrides. */ const EARN_SOLANA_RPC_BY_CHAIN_ID = {
240
+ '101': 'https://api.mainnet-beta.solana.com',
241
+ '103': 'https://api.devnet.solana.com'
242
+ };
243
+ /** Blockhash checks run at `processed`, the commitment that sees new blockhashes first. */ const EARN_SOLANA_BLOCKHASH_COMMITMENT = 'processed';
244
+ const EARN_CONFIRMATION_POLL_INTERVAL_MS = 1000;
245
+
246
+ async function getBalance({ address, rpcUrl = SOLANA_RPC_URL }) {
247
+ const connection = new Connection(rpcUrl != null ? rpcUrl : 'https://api.devnet.solana.com');
248
+ const balance = await connection.getBalance(new PublicKey(address));
249
+ return balance;
250
+ }
251
+ async function createSolanaTransaction({ senderSolanaAddress, amount, to, rpcUrl = 'https://api.devnet.solana.com' }) {
252
+ const connection = new Connection(rpcUrl != null ? rpcUrl : 'https://api.devnet.solana.com');
253
+ const balance = await getBalance({
254
+ address: senderSolanaAddress,
255
+ rpcUrl
256
+ });
257
+ if (balance < amount * 1e9) {
258
+ throw new Error('Insufficient balance');
259
+ }
260
+ const fromPubkey = new PublicKey(senderSolanaAddress);
261
+ const transaction = new Transaction().add(SystemProgram.transfer({
262
+ fromPubkey: fromPubkey,
263
+ toPubkey: new PublicKey(to),
264
+ lamports: amount * 1e9
265
+ }));
266
+ const { blockhash } = await connection.getLatestBlockhash();
267
+ transaction.recentBlockhash = blockhash;
268
+ transaction.feePayer = fromPubkey;
269
+ const serializedTransaction = transaction.serializeMessage();
270
+ return {
271
+ transaction,
272
+ serializedTransaction
273
+ };
274
+ }
275
+ const addSignatureToTransaction = ({ transaction, signature, signerPublicKey })=>{
276
+ transaction.addSignature(signerPublicKey, Buffer.from(signature));
277
+ return transaction;
278
+ };
279
+ function attachSignature({ transaction, signatureBase58, senderAddress }) {
280
+ const sigBytes = decodeBase58(signatureBase58);
281
+ const signerPubkey = new PublicKey(senderAddress);
282
+ return addSignatureToTransaction({
283
+ transaction,
284
+ signature: sigBytes,
285
+ signerPublicKey: signerPubkey
286
+ });
287
+ }
288
+ async function sendTransaction({ signedTransaction, rpcUrl = 'https://api.devnet.solana.com' }) {
289
+ const connection = new Connection(rpcUrl != null ? rpcUrl : 'https://api.devnet.solana.com');
290
+ const txid = await connection.sendRawTransaction(Buffer.from(signedTransaction));
291
+ return txid;
292
+ }
293
+
294
+ /**
295
+ * A transaction in the sequence could not land. Transactions before `ordinal` already
296
+ * confirmed on-chain, so the action may be partially applied.
297
+ */ class EarnSolanaStepError extends Error {
298
+ constructor({ cause, code, ordinal, reason, signature, total }){
299
+ const message = `Transaction ${ordinal + 1} of ${total} ${reason}.`;
300
+ const confirmed = ordinal === 1 ? 'transaction' : `${ordinal} transactions`;
301
+ super(ordinal === 0 ? message : `${message} The earlier ${confirmed} already confirmed on-chain, so the action is partially applied; check your position before retrying.`, {
302
+ cause
303
+ });
304
+ this.name = 'EarnSolanaStepError';
305
+ this.code = code;
306
+ this.ordinal = ordinal;
307
+ this.signature = signature;
308
+ }
309
+ }
310
+ // Versioned transactions are marked by the high bit on the first message byte after the
311
+ // signatures; legacy transactions start the message header there instead.
312
+ const deserializeEarnTransaction = (payload)=>{
313
+ const bytes = new Uint8Array(Buffer.from(payload, 'base64'));
314
+ var _bytes_;
315
+ const signatureCount = (_bytes_ = bytes[0]) != null ? _bytes_ : 0;
316
+ var _bytes_1;
317
+ const firstMessageByte = (_bytes_1 = bytes[1 + signatureCount * 64]) != null ? _bytes_1 : 0;
318
+ return (firstMessageByte & 0x80) !== 0 ? VersionedTransaction.deserialize(bytes) : Transaction.from(bytes);
319
+ };
320
+ const isStepExpired = async ({ connection, expiryBlockHeight, transaction })=>{
321
+ if (expiryBlockHeight !== undefined) {
322
+ return await connection.getBlockHeight('confirmed') > expiryBlockHeight;
323
+ }
324
+ const recentBlockhash = transaction instanceof VersionedTransaction ? transaction.message.recentBlockhash : transaction.recentBlockhash;
325
+ // A transaction with no blockhash cannot be judged; the network rejects it on send anyway.
326
+ if (!recentBlockhash) {
327
+ return false;
328
+ }
329
+ const { value: isBlockhashValid } = await connection.isBlockhashValid(recentBlockhash, {
330
+ commitment: EARN_SOLANA_BLOCKHASH_COMMITMENT
331
+ });
332
+ return !isBlockhashValid;
333
+ };
334
+ // Polls over HTTP rather than a websocket subscription, which some RPC providers refuse.
335
+ const waitForConfirmation = async ({ connection, isExpired, signature })=>{
336
+ const hasExpired = await isExpired();
337
+ // A missing status only means "never landed" once the blockhash lapsed, so the
338
+ // lookup then needs the full transaction history rather than the recent cache.
339
+ const { value: [status] } = await connection.getSignatureStatuses([
340
+ signature
341
+ ], {
342
+ searchTransactionHistory: hasExpired
343
+ });
344
+ if (status == null ? void 0 : status.err) {
345
+ return {
346
+ error: status.err,
347
+ outcome: 'failed'
348
+ };
349
+ }
350
+ if ((status == null ? void 0 : status.confirmationStatus) === 'confirmed' || (status == null ? void 0 : status.confirmationStatus) === 'finalized') {
351
+ return {
352
+ outcome: 'confirmed'
353
+ };
354
+ }
355
+ if (hasExpired && !status) {
356
+ return {
357
+ outcome: 'expired'
358
+ };
359
+ }
360
+ await new Promise((resolve)=>{
361
+ setTimeout(resolve, EARN_CONFIRMATION_POLL_INTERVAL_MS);
362
+ });
363
+ return waitForConfirmation({
364
+ connection,
365
+ isExpired,
366
+ signature
367
+ });
368
+ };
369
+ const serializeSigned = (transaction)=>Buffer.from(transaction instanceof VersionedTransaction ? transaction.serialize() : transaction.serialize({
370
+ verifySignatures: false
371
+ }));
372
+ // The transaction id is its first (fee payer) signature — for sponsored steps that is
373
+ // the sponsor's, not the wallet's — so the send result, not the signature
374
+ // `signTransaction` returned, is what must be confirmed.
375
+ const signAndSendStep = async ({ chainId, connection, context, externalServerKeyShares, ordinal, password, signTransaction, sponsored, total, transaction, walletMetadata })=>{
376
+ try {
377
+ const result = await signTransaction({
378
+ walletMetadata,
379
+ transaction,
380
+ password,
381
+ externalServerKeyShares,
382
+ sponsor: sponsored != null ? sponsored : false,
383
+ chainId,
384
+ context
385
+ });
386
+ const signedTransaction = typeof result === 'string' ? attachSignature({
387
+ transaction,
388
+ signatureBase58: result,
389
+ senderAddress: walletMetadata.accountAddress
390
+ }) : result.transaction;
391
+ return await connection.sendRawTransaction(serializeSigned(signedTransaction), {
392
+ preflightCommitment: EARN_SOLANA_BLOCKHASH_COMMITMENT
393
+ });
394
+ } catch (error) {
395
+ throw new EarnSolanaStepError({
396
+ cause: error instanceof Error ? error : undefined,
397
+ code: 'yield_step_send_failed',
398
+ ordinal,
399
+ reason: 'could not be signed or sent',
400
+ total
401
+ });
402
+ }
403
+ };
404
+ /**
405
+ * Builds a stateless Earn client for Solana vaults: it prepares vault actions through the
406
+ * Dynamic API and executes the returned ordered transaction sequence one transaction at a
407
+ * time — never in parallel, because a later transaction can depend on the state an earlier
408
+ * one wrote. If one fails, the sequence stops and the thrown {@link EarnSolanaStepError}
409
+ * reports how much of the action already landed.
410
+ *
411
+ * Gas sponsorship is opt-in (`sponsored: true`): vault transactions are built with the
412
+ * owner as fee payer, unlike the browser SDK which sponsors automatically.
413
+ */ const createSvmEarnClient = ({ getEarnClient, signTransaction })=>{
414
+ const executeStep = async ({ connection, context, externalServerKeyShares, chainId, onStepChange, onTransactionStepChange, password, sponsored, step, total, walletMetadata })=>{
415
+ const transaction = deserializeEarnTransaction(step.payload);
416
+ const { ordinal } = step;
417
+ const isExpired = ()=>isStepExpired({
418
+ connection,
419
+ expiryBlockHeight: step.expiryBlockHeight,
420
+ transaction
421
+ });
422
+ // The blockhash was fixed when the payload was built, so earlier slow steps can
423
+ // leave later ones unsendable — check before spending a signature.
424
+ if (await isExpired()) {
425
+ throw new EarnSolanaStepError({
426
+ code: 'yield_step_expired',
427
+ ordinal,
428
+ reason: 'expired before it could be signed',
429
+ total
430
+ });
431
+ }
432
+ onStepChange == null ? void 0 : onStepChange('transaction');
433
+ const progress = {
434
+ ordinal,
435
+ total
436
+ };
437
+ if (step.label !== undefined) {
438
+ progress.label = step.label;
439
+ }
440
+ onTransactionStepChange == null ? void 0 : onTransactionStepChange(progress);
441
+ const signature = await signAndSendStep({
442
+ chainId,
443
+ connection,
444
+ context,
445
+ externalServerKeyShares,
446
+ ordinal,
447
+ password,
448
+ signTransaction,
449
+ sponsored,
450
+ total,
451
+ transaction,
452
+ walletMetadata
453
+ });
454
+ // A sent transaction may still land even when the poll itself fails, so wrap any RPC
455
+ // error and keep the send signature on it for reconciliation.
456
+ let confirmation;
457
+ try {
458
+ confirmation = await waitForConfirmation({
459
+ connection,
460
+ isExpired,
461
+ signature
462
+ });
463
+ } catch (error) {
464
+ throw new EarnSolanaStepError({
465
+ cause: error instanceof Error ? error : undefined,
466
+ code: 'yield_step_confirmation_unknown',
467
+ ordinal,
468
+ reason: 'was sent but its confirmation could not be checked',
469
+ signature,
470
+ total
471
+ });
472
+ }
473
+ if (confirmation.outcome === 'failed') {
474
+ throw new EarnSolanaStepError({
475
+ code: 'yield_step_failed',
476
+ ordinal,
477
+ reason: `failed on-chain: ${JSON.stringify(confirmation.error)}`,
478
+ signature,
479
+ total
480
+ });
481
+ }
482
+ if (confirmation.outcome === 'expired') {
483
+ throw new EarnSolanaStepError({
484
+ code: 'yield_step_expired',
485
+ ordinal,
486
+ reason: 'was not confirmed before its blockhash expired',
487
+ signature,
488
+ total
489
+ });
490
+ }
491
+ return signature;
492
+ };
493
+ const executeEarnTransaction = async ({ signingPayload, walletMetadata, password, externalServerKeyShares, sponsored, rpcUrl, chainId, context, onStepChange, onTransactionStepChange })=>{
494
+ if (walletMetadata.chainName !== 'SVM') {
495
+ throw new Error(ERROR_EARN_NOT_SVM_WALLET);
496
+ }
497
+ if (!walletMetadata.accountAddress) {
498
+ throw new Error('Account address is required');
499
+ }
500
+ var _signingPayload_transactions;
501
+ const steps = [
502
+ ...(_signingPayload_transactions = signingPayload.transactions) != null ? _signingPayload_transactions : []
503
+ ].sort((first, second)=>first.ordinal - second.ordinal);
504
+ if (steps.length === 0) {
505
+ throw new Error(ERROR_EARN_MISSING_TRANSACTIONS);
506
+ }
507
+ if (steps.some((step, index)=>step.ordinal !== index)) {
508
+ throw new Error(ERROR_EARN_NON_CONTIGUOUS_ORDINALS);
509
+ }
510
+ var _ref;
511
+ const connection = new Connection((_ref = rpcUrl != null ? rpcUrl : EARN_SOLANA_RPC_BY_CHAIN_ID[chainId != null ? chainId : signingPayload.chainId]) != null ? _ref : SOLANA_RPC_URL);
512
+ // A rejection stops the sequence at the first failure; everything after it is skipped.
513
+ const transactionHash = await steps.reduce(async (previousStep, step)=>{
514
+ await previousStep;
515
+ return executeStep({
516
+ connection,
517
+ context,
518
+ externalServerKeyShares,
519
+ chainId: chainId != null ? chainId : signingPayload.chainId,
520
+ onStepChange,
521
+ onTransactionStepChange,
522
+ password,
523
+ sponsored,
524
+ step,
525
+ total: steps.length,
526
+ walletMetadata
527
+ });
528
+ }, Promise.resolve(''));
529
+ return {
530
+ transactionHash
531
+ };
532
+ };
533
+ return {
534
+ executeEarnTransaction,
535
+ depositToEarnVault: async (_param)=>{
536
+ var { vaultId, amount, receiverAddress, traceContext } = _param, walletParams = _object_without_properties_loose(_param, [
537
+ "vaultId",
538
+ "amount",
539
+ "receiverAddress",
540
+ "traceContext"
541
+ ]);
542
+ const signingPayload = await getEarnClient().prepareDeposit({
543
+ vaultId,
544
+ ownerAddress: walletParams.walletMetadata.accountAddress,
545
+ amount,
546
+ receiverAddress,
547
+ traceContext
548
+ });
549
+ return executeEarnTransaction(_extends({
550
+ signingPayload
551
+ }, walletParams));
552
+ },
553
+ withdrawFromEarnVault: async (_param)=>{
554
+ var { vaultId, amount, receiverAddress, traceContext } = _param, walletParams = _object_without_properties_loose(_param, [
555
+ "vaultId",
556
+ "amount",
557
+ "receiverAddress",
558
+ "traceContext"
559
+ ]);
560
+ const signingPayload = await getEarnClient().prepareWithdrawal({
561
+ vaultId,
562
+ ownerAddress: walletParams.walletMetadata.accountAddress,
563
+ amount,
564
+ receiverAddress,
565
+ traceContext
566
+ });
567
+ return executeEarnTransaction(_extends({
568
+ signingPayload
569
+ }, walletParams));
570
+ },
571
+ claimEarnRewards: async (_param)=>{
572
+ var { vaultId, traceContext } = _param, walletParams = _object_without_properties_loose(_param, [
573
+ "vaultId",
574
+ "traceContext"
575
+ ]);
576
+ const signingPayload = await getEarnClient().prepareClaimRewards({
577
+ vaultId,
578
+ ownerAddress: walletParams.walletMetadata.accountAddress,
579
+ traceContext
580
+ });
581
+ return executeEarnTransaction(_extends({
582
+ signingPayload
583
+ }, walletParams));
584
+ }
585
+ };
586
+ };
587
+
85
588
  const logError$1 = createLogError('node-svm');
86
589
  // Helper: normalize bytes to hex without triggering Buffer.from(string, encoding) overload
87
590
  const toHex = (bytes)=>(Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes)).toString('hex');
591
+ const ERROR_SIGN_TRANSACTION_CONTEXT_REQUIRED = 'SVM transaction signing requires a chainId or an explicit context.svmTransaction.';
592
+ const ERROR_SIGN_TRANSACTION_RAW_HEX_CONTEXT_REQUIRED = 'SVM transaction signing requires an explicit context.svmTransaction when transaction is a raw hex string.';
593
+ const validateSignTransactionContext = (context, chainId, transaction)=>{
594
+ if ((context == null ? void 0 : context.svmTransaction) !== undefined) {
595
+ return;
596
+ }
597
+ if (typeof transaction === 'string') {
598
+ throw new ClientValidationError(ERROR_SIGN_TRANSACTION_RAW_HEX_CONTEXT_REQUIRED);
599
+ }
600
+ if (chainId === undefined) {
601
+ throw new ClientValidationError(ERROR_SIGN_TRANSACTION_CONTEXT_REQUIRED);
602
+ }
603
+ };
604
+ const buildSignTransactionContext = (context, chainId, transaction)=>{
605
+ if ((context == null ? void 0 : context.svmTransaction) !== undefined) {
606
+ return context;
607
+ }
608
+ if (typeof transaction === 'string') {
609
+ throw new ClientValidationError(ERROR_SIGN_TRANSACTION_RAW_HEX_CONTEXT_REQUIRED);
610
+ }
611
+ if (chainId === undefined) {
612
+ throw new ClientValidationError(ERROR_SIGN_TRANSACTION_CONTEXT_REQUIRED);
613
+ }
614
+ return _extends({}, context, {
615
+ svmTransaction: {
616
+ chainId,
617
+ method: 'signAndSendTransaction',
618
+ serializedTransactions: [
619
+ encodeBase58(transaction instanceof VersionedTransaction ? transaction.serialize() : transaction.serialize({
620
+ requireAllSignatures: false,
621
+ verifySignatures: false
622
+ }))
623
+ ]
624
+ }
625
+ });
626
+ };
88
627
  class DynamicSvmWalletClient extends DynamicWalletClient {
89
628
  /**
90
629
  * Creates a wallet account on the Solana chain
91
630
  *
92
631
  * @param thresholdSignatureScheme The threshold signature scheme to use
93
- * @returns The account address, public key hex, raw public key, and client key shares
94
- */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, onError, backUpToClientShareService = false }) {
632
+ * @returns The walletMetadata, raw public key, and client key shares
633
+ */ async createWalletAccount({ thresholdSignatureScheme, password, onError, backUpToDynamic = false }) {
95
634
  try {
96
- let ceremonyCeremonyCompleteResolver;
97
- const ceremonyCompletePromise = new Promise((resolve)=>{
98
- ceremonyCeremonyCompleteResolver = resolve;
99
- });
635
+ const ceremony = this.createCeremonyCompletionTracker();
100
636
  const { rawPublicKey, externalServerKeyShares } = await this.keyGen({
101
637
  chainName: this.chainName,
102
638
  thresholdSignatureScheme,
639
+ password,
640
+ backUpToDynamic,
103
641
  onError,
104
- onCeremonyComplete: (accountAddress, walletId)=>{
105
- // update wallet map
106
- const chainConfig = getMPCChainConfig(this.chainName);
107
- this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress] || {}, {
108
- accountAddress,
109
- walletId,
110
- chainName: this.chainName,
111
- thresholdSignatureScheme,
112
- derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
113
- index,
114
- value
115
- ]))),
116
- externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
117
- });
118
- this.logger.debug('walletMap updated for wallet', {
119
- context: {
120
- accountAddress,
121
- walletId,
122
- walletMap: this.walletMap
123
- }
124
- });
125
- ceremonyCeremonyCompleteResolver(undefined);
126
- }
642
+ onCeremonyComplete: ceremony.onCeremonyComplete
127
643
  });
128
644
  // Wait for the ceremony to complete before proceeding
129
- await ceremonyCompletePromise;
645
+ await ceremony.promise;
646
+ const { walletId: resolvedWalletId, shareSetId: resolvedShareSetId } = ceremony.completion;
130
647
  if (!rawPublicKey || !(rawPublicKey instanceof Uint8Array || typeof rawPublicKey === 'string')) {
131
648
  throw new Error('Raw public key is not a Uint8Array or string' + typeof rawPublicKey);
132
649
  }
133
- if (!externalServerKeyShares) {
650
+ if (!externalServerKeyShares || !resolvedWalletId) {
134
651
  throw new Error('Error creating wallet account');
135
652
  }
136
653
  const { accountAddress } = await this.deriveAccountAddress(rawPublicKey);
137
- const externalKeySharesWithBackupStatus = await this.storeEncryptedBackupByWalletWithRetry({
654
+ const chainConfig = getMPCChainConfig(this.chainName);
655
+ const walletMetadata = {
656
+ walletId: resolvedWalletId,
657
+ accountAddress,
658
+ chainName: this.chainName,
659
+ thresholdSignatureScheme,
660
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
661
+ index,
662
+ value
663
+ ]))),
664
+ shareSetId: resolvedShareSetId
665
+ };
666
+ const { keySharesWithBackupStatus, backupInfo } = await this.storeEncryptedBackupByWalletWithRetry({
138
667
  accountAddress,
139
668
  externalServerKeyShares,
140
669
  password,
141
- backUpToClientShareService
670
+ backUpToDynamic,
671
+ walletMetadata
142
672
  });
673
+ walletMetadata.externalServerKeySharesBackupInfo = backupInfo;
674
+ var _ceremony_completion_encryptedWalletApiKey;
143
675
  return {
144
- accountAddress,
676
+ walletMetadata,
145
677
  rawPublicKey,
146
678
  externalServerKeyShares,
147
- externalKeySharesWithBackupStatus
679
+ externalKeySharesWithBackupStatus: keySharesWithBackupStatus,
680
+ encryptedWalletApiKey: (_ceremony_completion_encryptedWalletApiKey = ceremony.completion.encryptedWalletApiKey) != null ? _ceremony_completion_encryptedWalletApiKey : undefined
148
681
  };
149
682
  } catch (error) {
150
683
  logError$1({
@@ -152,7 +685,9 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
152
685
  error: error,
153
686
  context: {}
154
687
  });
155
- throw new Error(ERROR_CREATE_WALLET_ACCOUNT);
688
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT, {
689
+ cause: error
690
+ });
156
691
  }
157
692
  }
158
693
  // Function to properly derive account address
@@ -171,30 +706,27 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
171
706
  * This function takes a message and returns it after being signed with MPC
172
707
  *
173
708
  * @param message The message to sign (Uint8Array)
174
- * @param accountAddress Solana address (base58 encoded)
709
+ * @param walletMetadata Wallet metadata (the full object returned by createWalletAccount/importPrivateKey, with backupInfo merged from any subsequent updatePassword/refresh/reshare)
175
710
  * @param password The password for encrypted backup shares
176
- */ async signMessage({ message, accountAddress, password = undefined, externalServerKeyShares }) {
177
- // Validate inputs early
711
+ */ async signMessage({ message, walletMetadata, password = undefined, externalServerKeyShares, context }) {
712
+ const { accountAddress } = walletMetadata;
178
713
  if (!accountAddress) {
179
714
  throw new Error('Account address is required');
180
715
  }
181
716
  try {
182
- // Attempt to recover key shares from backup if not provided
183
- await this.ensureKeySharesRecovered({
184
- accountAddress,
185
- password,
186
- walletOperation: WalletOperation.SIGN_MESSAGE,
187
- externalServerKeyShares,
188
- errorMessage: 'External server key shares are required to sign a message. No backup shares available for recovery.'
189
- });
190
717
  const messageBytes = typeof message === 'string' ? new TextEncoder().encode(message) : message;
191
718
  const messageHex = toHex(messageBytes);
719
+ const resolvedContext = context != null ? context : {
720
+ svmMessage: typeof message === 'string' ? message : messageHex
721
+ };
192
722
  const signatureEd25519 = await this.sign({
193
723
  message: messageHex,
194
724
  accountAddress,
195
725
  chainName: this.chainName,
196
726
  password,
197
- externalServerKeyShares
727
+ externalServerKeyShares,
728
+ walletMetadata,
729
+ context: resolvedContext
198
730
  });
199
731
  return encodeBase58(signatureEd25519);
200
732
  } catch (error) {
@@ -213,29 +745,27 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
213
745
  * The message must be a hex string representing already-hashed data.
214
746
  *
215
747
  * @param message The pre-formatted hex message to sign
216
- * @param accountAddress Solana address (base58 encoded)
748
+ * @param walletMetadata Wallet metadata (the full object returned by createWalletAccount/importPrivateKey, with backupInfo merged from any subsequent updatePassword/refresh/reshare)
217
749
  * @param password The password for encrypted backup shares
218
- */ async signRawMessage({ message, accountAddress, password = undefined, externalServerKeyShares }) {
750
+ * @param rawSign Pre-image the digest is derived from, used to build the policy context
751
+ * @param context Explicit policy context, when the caller builds one itself
752
+ */ async signRawMessage({ message, walletMetadata, password = undefined, externalServerKeyShares, context, rawSign }) {
753
+ const { accountAddress } = walletMetadata;
219
754
  if (!accountAddress) {
220
755
  throw new Error('Account address is required');
221
756
  }
222
757
  try {
223
- // Attempt to recover key shares from backup if not provided
224
- await this.ensureKeySharesRecovered({
225
- accountAddress,
226
- password,
227
- walletOperation: WalletOperation.SIGN_MESSAGE,
228
- externalServerKeyShares,
229
- errorMessage: 'External server key shares are required to sign a raw message. No backup shares available for recovery.'
230
- });
231
758
  const messageHex = stripHexPrefix(message);
759
+ const resolvedContext = resolveRawSignContext(context, rawSign);
232
760
  const signatureEd25519 = await this.sign({
233
761
  message: messageHex,
234
762
  accountAddress,
235
763
  chainName: this.chainName,
236
764
  password,
237
765
  externalServerKeyShares,
238
- isFormatted: true
766
+ isFormatted: true,
767
+ walletMetadata,
768
+ context: resolvedContext
239
769
  });
240
770
  return encodeBase58(signatureEd25519);
241
771
  } catch (error) {
@@ -246,80 +776,89 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
246
776
  accountAddress
247
777
  }
248
778
  });
249
- throw new Error(ERROR_SIGN_RAW_MESSAGE);
779
+ throw new Error(ERROR_SIGN_RAW_MESSAGE, {
780
+ cause: error
781
+ });
250
782
  }
251
783
  }
252
- //todo:should txn just be a string?
253
- async signTransaction({ senderAddress, transaction, password = undefined, externalServerKeyShares, sponsor = false }) {
254
- // Validate inputs early
255
- if (!senderAddress) {
256
- throw new Error('Sender address is required');
784
+ async signTransaction({ walletMetadata, transaction, password = undefined, externalServerKeyShares, sponsor = false, chainId, context }) {
785
+ const { accountAddress } = walletMetadata;
786
+ if (!accountAddress) {
787
+ throw new Error('Account address is required');
257
788
  }
789
+ let resolvedTransaction = transaction;
258
790
  if (sponsor) {
259
- if (typeof transaction === 'string') {
791
+ if (typeof resolvedTransaction === 'string') {
260
792
  throw new TypeError('sponsor=true requires a Transaction or VersionedTransaction object, not a hex string');
261
793
  }
262
- transaction = await this.sponsorTransaction({
263
- transaction
794
+ validateSignTransactionContext(context, chainId, resolvedTransaction);
795
+ resolvedTransaction = await this.sponsorTransaction({
796
+ transaction: resolvedTransaction
264
797
  });
265
798
  }
266
- await this.verifyPassword({
267
- accountAddress: senderAddress,
268
- password
269
- });
270
799
  try {
271
- // Attempt to recover key shares from backup if not provided
272
- await this.ensureKeySharesRecovered({
273
- accountAddress: senderAddress,
274
- password,
275
- walletOperation: WalletOperation.SIGN_TRANSACTION,
276
- externalServerKeyShares,
277
- errorMessage: 'External server key shares are required to sign transaction. No backup shares available for recovery.'
278
- });
800
+ const resolvedContext = buildSignTransactionContext(context, chainId, resolvedTransaction);
279
801
  let messageToSign;
280
- if (typeof transaction === 'string') {
281
- messageToSign = transaction.startsWith('0x') ? transaction.slice(2) : transaction;
282
- } else if (transaction instanceof VersionedTransaction) {
283
- const messageBytes = transaction.message.serialize();
802
+ if (typeof resolvedTransaction === 'string') {
803
+ messageToSign = resolvedTransaction.startsWith('0x') ? resolvedTransaction.slice(2) : resolvedTransaction;
804
+ } else if (resolvedTransaction instanceof VersionedTransaction) {
805
+ const messageBytes = resolvedTransaction.message.serialize();
284
806
  messageToSign = toHex(messageBytes);
285
807
  } else {
286
- const messageBytes = transaction.serializeMessage();
808
+ const messageBytes = resolvedTransaction.serializeMessage();
287
809
  messageToSign = toHex(Buffer.isBuffer(messageBytes) ? messageBytes : messageBytes);
288
810
  }
289
811
  const signatureEd25519 = await this.sign({
290
812
  message: messageToSign,
291
- accountAddress: senderAddress,
813
+ accountAddress,
292
814
  chainName: this.chainName,
293
815
  password,
294
- externalServerKeyShares
816
+ externalServerKeyShares,
817
+ walletMetadata,
818
+ walletOperation: WalletOperation.SIGN_TRANSACTION,
819
+ context: resolvedContext
295
820
  });
296
821
  if (!signatureEd25519) {
297
822
  throw new Error('Signature is undefined');
298
823
  }
299
- return encodeBase58(signatureEd25519);
824
+ const signature = encodeBase58(signatureEd25519);
825
+ if (sponsor) {
826
+ const signedTransaction = addSignatureToTransaction({
827
+ transaction: resolvedTransaction,
828
+ signature: signatureEd25519,
829
+ signerPublicKey: new PublicKey(accountAddress)
830
+ });
831
+ return {
832
+ signature,
833
+ transaction: signedTransaction
834
+ };
835
+ }
836
+ return signature;
300
837
  } catch (error) {
301
838
  logError$1({
302
839
  message: 'Error in signTransaction:',
303
840
  error: error,
304
841
  context: {
305
- senderAddress
842
+ accountAddress
306
843
  }
307
844
  });
308
845
  throw error;
309
846
  }
310
847
  }
311
848
  /**
312
- * Exports the private key for a given account address
849
+ * Exports the private key for a given wallet
313
850
  *
314
- * @param accountAddress The account address to export the private key for
851
+ * @param walletMetadata Wallet metadata (the full object returned by createWalletAccount/importPrivateKey, with backupInfo merged from any subsequent updatePassword/refresh/reshare)
315
852
  * @param password The password for encrypted backup shares
316
853
  * @returns The private key
317
- */ async exportPrivateKey({ accountAddress, password = undefined, externalServerKeyShares }) {
854
+ */ async exportPrivateKey({ walletMetadata, password = undefined, externalServerKeyShares }) {
855
+ const { accountAddress } = walletMetadata;
318
856
  const { derivedPrivateKey } = await this.exportKey({
319
857
  accountAddress,
320
858
  chainName: this.chainName,
321
859
  password,
322
- externalServerKeyShares
860
+ externalServerKeyShares,
861
+ walletMetadata
323
862
  });
324
863
  if (!derivedPrivateKey) {
325
864
  throw new Error('Derived private key is undefined');
@@ -334,6 +873,11 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
334
873
  *
335
874
  * @param keyShares The key shares to export the private key for
336
875
  * @returns The private key
876
+ *
877
+ * `derivationPath` is the JSON-serialized index map that
878
+ * `walletMetadata.derivationPath` carries (e.g. `'{"0":44,"1":60,"2":0,"3":0,"4":0}'`
879
+ * or `'[44,60,0,0,0]'`). BIP-32 strings such as `"m/44'/60'/0'/0/0"` are rejected.
880
+ * Omit it to export without path derivation.
337
881
  */ async offlineExportPrivateKey({ keyShares, derivationPath }) {
338
882
  const { derivedPrivateKey } = await this.offlineExportKey({
339
883
  chainName: this.chainName,
@@ -376,187 +920,442 @@ class DynamicSvmWalletClient extends DynamicWalletClient {
376
920
  * @param chainName The chain name to import the private key for
377
921
  * @param thresholdSignatureScheme The threshold signature scheme to use
378
922
  * @param password The password for encrypted backup shares
379
- * @returns The account address, raw public key, and client key shares
380
- */ async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password = undefined, onError, backUpToClientShareService = false }) {
923
+ * @returns The walletMetadata, raw public key, and client key shares
924
+ */ async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password, onError, backUpToDynamic = false }) {
925
+ let resolvedWalletId;
926
+ let resolvedShareSetId;
381
927
  let ceremonyCeremonyCompleteResolver;
382
928
  const ceremonyCompletePromise = new Promise((resolve)=>{
383
929
  ceremonyCeremonyCompleteResolver = resolve;
384
930
  });
385
931
  //get public key from private key
386
932
  const publicKey = this.getPublicKeyFromPrivateKey(privateKey);
387
- const formattedPrivateKey = await this.decodePrivateKeyForSolana(privateKey);
933
+ const formattedPrivateKey = this.decodePrivateKeyForSolana(privateKey);
388
934
  const { rawPublicKey, externalServerKeyShares } = await this.importRawPrivateKey({
389
935
  chainName,
390
936
  privateKey: formattedPrivateKey,
391
937
  thresholdSignatureScheme,
938
+ password,
939
+ backUpToDynamic,
392
940
  onError,
393
- onCeremonyComplete: (accountAddress, walletId)=>{
394
- // update wallet map
395
- const chainConfig = getMPCChainConfig(this.chainName);
396
- this.walletMap[accountAddress] = _extends({}, this.walletMap[accountAddress] || {}, {
397
- accountAddress,
398
- walletId,
399
- chainName: this.chainName,
400
- thresholdSignatureScheme,
401
- derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
402
- index,
403
- value
404
- ]))),
405
- externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
406
- });
941
+ onCeremonyComplete: ({ walletId, shareSetId })=>{
942
+ resolvedWalletId = walletId;
943
+ resolvedShareSetId = shareSetId;
407
944
  ceremonyCeremonyCompleteResolver(undefined);
408
945
  }
409
946
  });
410
947
  // Wait for the ceremony to complete before proceeding
411
948
  await ceremonyCompletePromise;
412
- if (!rawPublicKey || !externalServerKeyShares) {
949
+ if (!rawPublicKey || !externalServerKeyShares || !resolvedWalletId) {
413
950
  throw new Error('Error creating wallet account');
414
951
  }
415
952
  const { accountAddress } = await this.deriveAccountAddress(rawPublicKey);
416
953
  if (accountAddress !== publicKey) {
417
954
  throw new Error(`Public key mismatch: derived address ${accountAddress} !== public key ${publicKey}`);
418
955
  }
419
- const externalKeySharesWithBackupStatus = await this.storeEncryptedBackupByWalletWithRetry({
956
+ const chainConfig = getMPCChainConfig(this.chainName);
957
+ const walletMetadata = {
958
+ walletId: resolvedWalletId,
959
+ accountAddress,
960
+ chainName: this.chainName,
961
+ thresholdSignatureScheme,
962
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
963
+ index,
964
+ value
965
+ ]))),
966
+ shareSetId: resolvedShareSetId
967
+ };
968
+ const { keySharesWithBackupStatus, backupInfo } = await this.storeEncryptedBackupByWalletWithRetry({
420
969
  accountAddress,
421
970
  externalServerKeyShares,
422
971
  password,
423
- backUpToClientShareService
972
+ backUpToDynamic,
973
+ walletMetadata
424
974
  });
975
+ walletMetadata.externalServerKeySharesBackupInfo = backupInfo;
425
976
  return {
426
- accountAddress,
977
+ walletMetadata,
427
978
  rawPublicKey: rawPublicKey,
428
979
  externalServerKeyShares,
429
- externalKeySharesWithBackupStatus
980
+ externalKeySharesWithBackupStatus: keySharesWithBackupStatus
430
981
  };
431
982
  }
432
983
  /**
433
984
  * Sponsors a Solana transaction via the Dynamic gas sponsorship API.
434
985
  *
435
986
  * Sends the unsigned transaction to Dynamic's sponsorTransaction endpoint,
436
- * which replaces the fee payer with the sponsor's address. The returned
437
- * transaction object has the sponsor as fee payer and should be passed to
438
- * {@link signTransaction} instead of the original transaction.
987
+ * which replaces the fee payer with the sponsor's address. The endpoint
988
+ * always returns a v0 versioned transaction, which is deserialized and
989
+ * returned. It should be passed to {@link signTransaction} instead of the
990
+ * original transaction.
439
991
  *
440
992
  * Gas sponsorship must be enabled for your environment in the Dynamic
441
993
  * dashboard before calling this method.
442
994
  *
443
995
  * @param transaction - Unsigned Solana transaction (legacy or versioned).
444
- * @returns The sponsored transaction with the gas sponsor as fee payer.
445
- */ async sponsorTransaction({ transaction, traceContext }) {
996
+ * @param userId - End user the transaction is for. Required when the signer is
997
+ * that user's wallet rather than one of the caller's own server wallets.
998
+ * @returns The sponsored v0 transaction with the gas sponsor as fee payer.
999
+ */ async sponsorTransaction({ transaction, userId, traceContext }) {
446
1000
  // Serialize the unsigned transaction to base64 wire format
447
1001
  const serialized = transaction instanceof VersionedTransaction ? transaction.serialize() : transaction.serialize({
448
1002
  requireAllSignatures: false,
449
1003
  verifySignatures: false
450
1004
  });
451
1005
  const txBase64 = Buffer.from(serialized).toString('base64');
452
- const { transaction: sponsoredBase64 } = await this.apiClient.requestSvmSponsoredTransaction({
453
- transaction: txBase64,
1006
+ const { transaction: sponsoredBase64 } = await this.apiClient.requestSvmSponsoredTransaction(_extends({
1007
+ transaction: txBase64
1008
+ }, userId ? {
1009
+ userId
1010
+ } : {}, {
454
1011
  traceContext
455
- });
1012
+ }));
456
1013
  const sponsoredBytes = Buffer.from(sponsoredBase64, 'base64');
457
- // Deserialize back to the same transaction type
458
- if (transaction instanceof VersionedTransaction) {
459
- return VersionedTransaction.deserialize(sponsoredBytes);
1014
+ // The sponsor endpoint always returns a v0 versioned transaction.
1015
+ return VersionedTransaction.deserialize(sponsoredBytes);
1016
+ }
1017
+ /**
1018
+ * Reads the address that signs as fee payer for sponsored transactions in
1019
+ * this environment. Build transactions that name it as fee payer (for example
1020
+ * LI.FI `svmSponsor`) before passing them to {@link sponsorTransaction}.
1021
+ *
1022
+ * Gas sponsorship must be enabled for your environment in the Dynamic
1023
+ * dashboard.
1024
+ */ async getSponsorAddress({ traceContext } = {}) {
1025
+ const { sponsorAddress } = await this.apiClient.getSvmSponsorAddress({
1026
+ traceContext
1027
+ });
1028
+ return sponsorAddress;
1029
+ }
1030
+ /**
1031
+ * Generates a Token-2022 confidential-transfer seed inside the enclave and
1032
+ * stores the sealed result in CKS. Returns the ElGamal public key and the
1033
+ * derivation version — persist it for later confidential operations.
1034
+ */ async createConfidentialSeed({ walletId, solanaAddress, derivationVersion, traceContext }) {
1035
+ return this.apiClient.createConfidentialSeed({
1036
+ walletId,
1037
+ request: {
1038
+ derivationVersion,
1039
+ solanaAddress
1040
+ },
1041
+ traceContext
1042
+ });
1043
+ }
1044
+ /**
1045
+ * Decrypts a confidential token account's available and pending balances
1046
+ * inside the enclave. Reads the account from `rpcUrl` unless `accountState`
1047
+ * is supplied. Balances are decimal strings in base units.
1048
+ */ async getConfidentialBalance({ walletId, solanaAddress, mint, tokenAccount, accountState, derivationVersion, rpcUrl, traceContext }) {
1049
+ let state = accountState;
1050
+ if (!state) {
1051
+ if (!rpcUrl) {
1052
+ throw new ClientValidationError('getConfidentialBalance requires rpcUrl or accountState');
1053
+ }
1054
+ state = await this.svmAccountState(new Connection(this.assertConfidentialRpcUrl(rpcUrl)), tokenAccount);
460
1055
  }
461
- return Transaction.from(sponsoredBytes);
1056
+ return this.apiClient.getSvmConfidentialBalance({
1057
+ walletId,
1058
+ request: {
1059
+ accountState: state,
1060
+ derivationVersion,
1061
+ mint,
1062
+ solanaAddress,
1063
+ tokenAccount
1064
+ },
1065
+ traceContext
1066
+ });
462
1067
  }
463
- async getSvmWallets() {
464
- const wallets = await this.getWallets();
1068
+ /**
1069
+ * Builds and signs Token-2022 confidential-transfer transactions.
1070
+ *
1071
+ * The enclave is offline, so any missing `accountState` /
1072
+ * `destinationAccountState` and the latest blockhash are fetched from
1073
+ * `rpcUrl` on the caller's behalf. The enclave builds one unsigned v1
1074
+ * transaction bound by a `transactionsTag`; `signConfidentialTransactions`
1075
+ * provisions one MPC room for the operation and the client share joins it
1076
+ * like an ordinary `signTransaction` ceremony. Pass `broadcast: true` to
1077
+ * also submit the signed transaction to the cluster.
1078
+ *
1079
+ * @returns The signed transactions (base64, broadcast order), their
1080
+ * signatures, and — when broadcast — the submitted transaction ids.
1081
+ */ async signConfidentialTransfer({ walletId, walletMetadata, operation, solanaAddress, mint, tokenAccount, destinationTokenAccount, amount, decimals, accountState, destinationAccountState, auditorElgamalPubkey, feePayer, derivationVersion, chainId = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp', lamportsPerByte = '6960', recentBlockhash, lastValidBlockHeight, rpcUrl, broadcast = false, broadcastOptions, password, externalServerKeyShares, traceContext }) {
1082
+ if (walletMetadata.walletId !== walletId || walletMetadata.accountAddress !== solanaAddress) {
1083
+ throw new ClientValidationError('walletId and solanaAddress must match walletMetadata');
1084
+ }
1085
+ const resolved = await this.resolveConfidentialInputs({
1086
+ operation,
1087
+ tokenAccount,
1088
+ destinationTokenAccount,
1089
+ accountState,
1090
+ destinationAccountState,
1091
+ recentBlockhash,
1092
+ lastValidBlockHeight,
1093
+ rpcUrl,
1094
+ broadcast
1095
+ });
1096
+ const built = await this.apiClient.signConfidentialTransfer({
1097
+ walletId,
1098
+ request: {
1099
+ accountState: resolved.accountState,
1100
+ amount,
1101
+ auditorElgamalPubkey,
1102
+ chainId,
1103
+ decimals,
1104
+ derivationVersion,
1105
+ destinationAccountState: resolved.destinationAccountState,
1106
+ destinationTokenAccount,
1107
+ feePayer,
1108
+ lamportsPerByte,
1109
+ lastValidBlockHeight: resolved.lastValidBlockHeight,
1110
+ mint,
1111
+ operation,
1112
+ recentBlockhash: resolved.recentBlockhash,
1113
+ solanaAddress,
1114
+ tokenAccount
1115
+ },
1116
+ traceContext
1117
+ });
1118
+ checkConfidentialTransactions({
1119
+ serializedTransactions: built.serializedTransactions,
1120
+ solanaAddress,
1121
+ operation,
1122
+ mint,
1123
+ tokenAccount,
1124
+ destinationTokenAccount,
1125
+ amount,
1126
+ decimals
1127
+ });
1128
+ // Same credential resolution as sign(): supplied shares are verified
1129
+ // against the backup password, otherwise shares are recovered by it.
1130
+ const backupInfo = walletMetadata.externalServerKeySharesBackupInfo;
1131
+ const resolvedShares = await this.resolveKeyShares({
1132
+ accountAddress: solanaAddress,
1133
+ password,
1134
+ walletOperation: WalletOperation.SIGN_TRANSACTION,
1135
+ externalServerKeyShares,
1136
+ errorMessage: 'External server key shares are required to sign confidential transactions',
1137
+ walletMetadata,
1138
+ backupInfo
1139
+ });
1140
+ if (resolvedShares === externalServerKeyShares) {
1141
+ if (!backupInfo) {
1142
+ throw new ClientValidationError('walletMetadata.externalServerKeySharesBackupInfo is required to verify the password when signing with caller-supplied externalServerKeyShares.');
1143
+ }
1144
+ await this.verifyPassword({
1145
+ accountAddress: solanaAddress,
1146
+ password,
1147
+ walletMetadata,
1148
+ backupInfo
1149
+ });
1150
+ }
1151
+ const { roomIds } = await this.apiClient.signConfidentialTransactions({
1152
+ walletId,
1153
+ request: {
1154
+ solanaAddress,
1155
+ serializedTransactions: built.serializedTransactions,
1156
+ transactionsTag: built.transactionsTag,
1157
+ chainId
1158
+ },
1159
+ traceContext
1160
+ });
1161
+ if (roomIds.length !== 1) {
1162
+ throw new Error('signConfidentialTransactions must return exactly one room');
1163
+ }
1164
+ const derivationPath = walletMetadata.derivationPath && walletMetadata.derivationPath !== '' ? new Uint32Array(Object.values(JSON.parse(walletMetadata.derivationPath))) : undefined;
1165
+ const wireBytes = new Uint8Array(Buffer.from(built.serializedTransactions[0], 'base64'));
1166
+ // v1 wire: message || signature slots; the check guarantees a sole signer.
1167
+ const signatureEd25519 = await this.externalServerSign({
1168
+ chainName: this.chainName,
1169
+ message: toHex(confidentialSignedMessageBytes(wireBytes, 1)),
1170
+ roomId: roomIds[0],
1171
+ keyShare: resolvedShares[0],
1172
+ derivationPath,
1173
+ isFormatted: false,
1174
+ dynamicRequestId: randomUUID()
1175
+ });
1176
+ const signedTransactions = [
1177
+ Buffer.from(injectConfidentialSignature(wireBytes, signatureEd25519)).toString('base64')
1178
+ ];
1179
+ const signatures = [
1180
+ encodeBase58(signatureEd25519)
1181
+ ];
1182
+ const transactionIds = broadcast ? await this.broadcastConfidentialTransactions(resolved.connection, signedTransactions, broadcastOptions, {
1183
+ blockhash: resolved.recentBlockhash,
1184
+ lastValidBlockHeight: Number(resolved.lastValidBlockHeight)
1185
+ }) : undefined;
1186
+ return {
1187
+ serializedTransactions: signedTransactions,
1188
+ signatures,
1189
+ transactionIds
1190
+ };
1191
+ }
1192
+ /** @deprecated Use getWalletByAddress instead for better performance */ async getSvmWallets() {
1193
+ // Calling the deprecated getWallets() is the point of this shim, and it is
1194
+ // public and overridable, so routing around it would drop a consumer's override.
1195
+ const wallets = await this.getWallets(); // NOSONAR
465
1196
  const svmWallets = wallets.filter((wallet)=>wallet.chainName === 'SVM');
466
1197
  return svmWallets;
467
1198
  }
468
- constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, enableMPCAccelerator, logger, debug }){
1199
+ // ---------------------------------------------------------------------------
1200
+ // Earn (yield vaults)
1201
+ // ---------------------------------------------------------------------------
1202
+ get svmEarn() {
1203
+ return createSvmEarnClient({
1204
+ getEarnClient: ()=>this.earn,
1205
+ signTransaction: (args)=>this.signTransaction(args)
1206
+ });
1207
+ }
1208
+ /**
1209
+ * Executes an Earn signing payload returned by the prepare* methods, signing and
1210
+ * sending its ordered Solana transaction sequence one transaction at a time.
1211
+ */ async executeEarnTransaction(params) {
1212
+ return this.svmEarn.executeEarnTransaction(params);
1213
+ }
1214
+ /** Prepares and executes a deposit into an Earn vault. */ async depositToEarnVault(params) {
1215
+ return this.svmEarn.depositToEarnVault(params);
1216
+ }
1217
+ /** Prepares and executes a withdrawal from an Earn vault. */ async withdrawFromEarnVault(params) {
1218
+ return this.svmEarn.withdrawFromEarnVault(params);
1219
+ }
1220
+ /** Prepares and executes a claim of accrued Earn vault rewards. */ async claimEarnRewards(params) {
1221
+ return this.svmEarn.claimEarnRewards(params);
1222
+ }
1223
+ constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, enableMPCAccelerator, logger, requestSigning, debug }){
469
1224
  super({
470
1225
  environmentId,
471
1226
  baseApiUrl,
472
1227
  baseMPCRelayApiUrl,
473
1228
  enableMPCAccelerator,
474
1229
  logger,
1230
+ requestSigning,
475
1231
  debug
476
- }), this.chainName = 'SVM';
477
- }
478
- }
479
-
480
- async function getBalance({ address, rpcUrl = SOLANA_RPC_URL }) {
481
- const connection = new Connection(rpcUrl != null ? rpcUrl : 'https://api.devnet.solana.com');
482
- const balance = await connection.getBalance(new PublicKey(address));
483
- return balance;
484
- }
485
- async function createSolanaTransaction({ senderSolanaAddress, amount, to, rpcUrl = 'https://api.devnet.solana.com' }) {
486
- const connection = new Connection(rpcUrl != null ? rpcUrl : 'https://api.devnet.solana.com');
487
- const balance = await getBalance({
488
- address: senderSolanaAddress,
489
- rpcUrl
490
- });
491
- if (balance < amount * 1e9) {
492
- throw new Error('Insufficient balance');
1232
+ }), this.chainName = 'SVM', // ---------------------------------------------------------------------------
1233
+ // Token-2022 confidential transfers
1234
+ // ---------------------------------------------------------------------------
1235
+ this.svmAccountState = async (connection, account)=>{
1236
+ // Read at the commitment the broadcast confirms at, or a just-confirmed transaction decrypts as stale state.
1237
+ const info = await connection.getAccountInfo(new PublicKey(account), 'confirmed');
1238
+ if (!info) {
1239
+ throw new Error(`Solana account not found: ${account}`);
1240
+ }
1241
+ return {
1242
+ data: info.data.toString('base64'),
1243
+ lamports: String(info.lamports),
1244
+ owner: info.owner.toBase58()
1245
+ };
1246
+ }, this.confidentialBlockhash = async (connection)=>{
1247
+ const latest = connection ? await connection.getLatestBlockhash() : undefined;
1248
+ const recentBlockhash = latest == null ? void 0 : latest.blockhash;
1249
+ const lastValidBlockHeight = latest ? String(latest.lastValidBlockHeight) : undefined;
1250
+ if (!recentBlockhash || !lastValidBlockHeight) {
1251
+ throw new ClientValidationError('signConfidentialTransfer requires rpcUrl to fetch the latest blockhash');
1252
+ }
1253
+ return {
1254
+ lastValidBlockHeight,
1255
+ recentBlockhash
1256
+ };
1257
+ }, this.broadcastConfidentialTransactions = async (connection, serializedTransactions, broadcastOptions, confirmationStrategy)=>serializedTransactions.reduce(async (accPromise, serializedTransaction)=>{
1258
+ const acc = await accPromise;
1259
+ const transactionId = await connection.sendRawTransaction(Buffer.from(serializedTransaction, 'base64'), _extends({
1260
+ preflightCommitment: 'confirmed'
1261
+ }, broadcastOptions));
1262
+ // Confidential plans are order-dependent: confirm before submitting
1263
+ // the next transaction or Solana may process them out of order.
1264
+ // confirmTransaction resolves with value.err on a failed transaction
1265
+ // rather than rejecting — surface it instead of broadcasting the rest.
1266
+ const confirmation = await connection.confirmTransaction(_extends({}, confirmationStrategy, {
1267
+ signature: transactionId
1268
+ }), 'confirmed');
1269
+ if (confirmation.value.err) {
1270
+ throw new Error(`Confidential transaction ${transactionId} failed: ${JSON.stringify(confirmation.value.err)}`);
1271
+ }
1272
+ acc.push(transactionId);
1273
+ return acc;
1274
+ }, Promise.resolve([])), /**
1275
+ * Validates `rpcUrl`, fetches missing account states and the latest
1276
+ * blockhash, and returns the inputs the enclave request needs.
1277
+ */ this.resolveConfidentialInputs = async ({ operation, tokenAccount, destinationTokenAccount, accountState, destinationAccountState, recentBlockhash, lastValidBlockHeight, rpcUrl, broadcast })=>{
1278
+ const needsAccountState = operation === 'transfer' || operation === 'withdraw' || operation === 'applyPendingBalance';
1279
+ const needsDestinationAccountState = operation === 'transfer';
1280
+ const mustFetch = broadcast || needsAccountState && !accountState || needsDestinationAccountState && !destinationAccountState || !recentBlockhash || !lastValidBlockHeight;
1281
+ if (mustFetch && !rpcUrl) {
1282
+ throw new ClientValidationError('signConfidentialTransfer requires rpcUrl to fetch account state, blockhash, or broadcast');
1283
+ }
1284
+ const connection = rpcUrl ? new Connection(this.assertConfidentialRpcUrl(rpcUrl)) : undefined;
1285
+ if (connection) {
1286
+ if (needsAccountState && !accountState) {
1287
+ accountState = await this.svmAccountState(connection, tokenAccount);
1288
+ }
1289
+ if (needsDestinationAccountState && !destinationAccountState && destinationTokenAccount) {
1290
+ destinationAccountState = await this.svmAccountState(connection, destinationTokenAccount);
1291
+ }
1292
+ }
1293
+ if (!recentBlockhash || !lastValidBlockHeight) {
1294
+ const latest = await this.confidentialBlockhash(connection);
1295
+ recentBlockhash = latest.recentBlockhash;
1296
+ lastValidBlockHeight = latest.lastValidBlockHeight;
1297
+ }
1298
+ return {
1299
+ accountState,
1300
+ connection,
1301
+ destinationAccountState,
1302
+ lastValidBlockHeight,
1303
+ recentBlockhash
1304
+ };
1305
+ }, this.assertConfidentialRpcUrl = (rpcUrl)=>{
1306
+ const parsed = new URL(rpcUrl);
1307
+ const isLocalHttp = parsed.protocol === 'http:' && [
1308
+ 'localhost',
1309
+ '127.0.0.1',
1310
+ '[::1]'
1311
+ ].includes(parsed.hostname);
1312
+ if (parsed.protocol !== 'https:' && !isLocalHttp) {
1313
+ throw new ClientValidationError(`Unsupported rpcUrl protocol: ${parsed.protocol}`);
1314
+ }
1315
+ return rpcUrl;
1316
+ };
493
1317
  }
494
- const fromPubkey = new PublicKey(senderSolanaAddress);
495
- const transaction = new Transaction().add(SystemProgram.transfer({
496
- fromPubkey: fromPubkey,
497
- toPubkey: new PublicKey(to),
498
- lamports: amount * 1e9
499
- }));
500
- const { blockhash } = await connection.getLatestBlockhash();
501
- transaction.recentBlockhash = blockhash;
502
- transaction.feePayer = fromPubkey;
503
- const serializedTransaction = transaction.serializeMessage();
504
- return {
505
- transaction,
506
- serializedTransaction
507
- };
508
- }
509
- const addSignatureToTransaction = ({ transaction, signature, signerPublicKey })=>{
510
- transaction.addSignature(signerPublicKey, Buffer.from(signature));
511
- return transaction;
512
- };
513
- function attachSignature({ transaction, signatureBase58, senderAddress }) {
514
- const sigBytes = decodeBase58(signatureBase58);
515
- const signerPubkey = new PublicKey(senderAddress);
516
- return addSignatureToTransaction({
517
- transaction,
518
- signature: sigBytes,
519
- signerPublicKey: signerPubkey
520
- });
521
- }
522
- async function sendTransaction({ signedTransaction, rpcUrl = 'https://api.devnet.solana.com' }) {
523
- const connection = new Connection(rpcUrl != null ? rpcUrl : 'https://api.devnet.solana.com');
524
- const txid = await connection.sendRawTransaction(Buffer.from(signedTransaction));
525
- return txid;
526
1318
  }
527
1319
 
528
1320
  const logError = createLogError('node-svm');
529
1321
  /**
530
1322
  * Creates a delegated SVM wallet client for functional operations
531
- */ const createDelegatedSvmWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, apiKey, debug = false })=>{
1323
+ */ const createDelegatedSvmWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, apiKey, debug = false, errorLogging })=>{
532
1324
  const baseClient = createDelegatedWalletClient({
533
1325
  environmentId,
534
1326
  baseApiUrl,
535
1327
  baseMPCRelayApiUrl,
536
1328
  apiKey,
537
- debug
1329
+ debug,
1330
+ errorLogging
538
1331
  });
539
- const svmClient = _extends({}, baseClient, {
1332
+ return _extends({}, baseClient, {
540
1333
  chainName: 'SVM'
541
1334
  });
542
- return svmClient;
543
1335
  };
544
1336
  /**
545
1337
  * Signs a message using delegated signing for SVM
546
- */ const delegatedSignMessage = async (client, { walletId, walletApiKey, keyShare, message, isFormatted = false })=>{
1338
+ */ const delegatedSignMessage = async (client, { walletId, shareSetId, walletApiKey, keyShare, message, derivationPath, isFormatted = false, context, onError })=>{
547
1339
  try {
548
- // Use the delegated sign message function from node package
1340
+ if (!keyShare || !walletId || !walletApiKey) {
1341
+ throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign a message');
1342
+ }
1343
+ const resolvedContext = context != null ? context : {
1344
+ svmMessage: message
1345
+ };
549
1346
  const signatureEd25519 = await delegatedSignMessage$1(client, {
550
1347
  walletId,
1348
+ shareSetId,
551
1349
  walletApiKey,
552
1350
  keyShare,
553
1351
  message,
554
1352
  chainName: client.chainName,
555
- isFormatted
1353
+ derivationPath,
1354
+ isFormatted,
1355
+ context: resolvedContext,
1356
+ onError
556
1357
  });
557
- // Use PublicKey to encode signature as base58 (SVM format)
558
- const base58Signature = encodeBase58(signatureEd25519);
559
- return base58Signature;
1358
+ return encodeBase58(signatureEd25519);
560
1359
  } catch (error) {
561
1360
  logError({
562
1361
  message: 'Error in delegatedSignMessage',
@@ -607,56 +1406,144 @@ const logError = createLogError('node-svm');
607
1406
  * signerAddress: senderAddress, // Explicitly specify who signs
608
1407
  * });
609
1408
  *
610
- */ const delegatedSignTransaction = async (client, { walletId, walletApiKey, keyShare, transaction, signerAddress })=>{
1409
+ */ /**
1410
+ * Sponsors a Solana transaction for a delegated wallet's end user, swapping its
1411
+ * fee payer for a Dynamic-funded sponsor. Grid's response is always a v0
1412
+ * `VersionedTransaction` regardless of the input type, so pass the result to
1413
+ * {@link delegatedSignTransaction} with an explicit `signerAddress` — the
1414
+ * caller must sign as the *user*, not as the new fee payer.
1415
+ *
1416
+ * @param client - The delegated SVM wallet client
1417
+ * @param options.transaction - Unsigned transaction (legacy or versioned). Its fee payer must be the delegated wallet's address.
1418
+ * @param options.userId - UUID of the end user who owns the wallet — the `userId` field of the `wallet.delegation.created` webhook payload.
1419
+ *
1420
+ * @returns The sponsored transaction, always as a `VersionedTransaction`.
1421
+ */ const serializeSvmTransaction = (transaction)=>transaction instanceof VersionedTransaction ? transaction.serialize() : transaction.serialize({
1422
+ requireAllSignatures: false,
1423
+ verifySignatures: false
1424
+ });
1425
+ const delegatedSponsorTransaction = async (client, { transaction, userId, traceContext })=>{
1426
+ const serialized = serializeSvmTransaction(transaction);
1427
+ const { transaction: sponsoredBase64 } = await withDelegatedServerAuth(client, (apiClient)=>apiClient.requestSvmSponsoredTransaction({
1428
+ transaction: Buffer.from(serialized).toString('base64'),
1429
+ userId,
1430
+ traceContext
1431
+ }));
1432
+ // Grid always returns a v0 versioned transaction regardless of what went in;
1433
+ // deserializing a legacy input here with Transaction.from() would be wrong.
1434
+ return VersionedTransaction.deserialize(Buffer.from(sponsoredBase64, 'base64'));
1435
+ };
1436
+ const sponsorTransactionIfRequested = async (client, { sponsor, userId, signerAddress, transaction, traceContext })=>{
1437
+ if (!sponsor) {
1438
+ return transaction;
1439
+ }
1440
+ if (!userId) {
1441
+ throw new Error('userId is required when sponsor is true');
1442
+ }
1443
+ // Grid becomes the fee payer, so the signerAddress fallback below would
1444
+ // attach the user's signature under the sponsor's key and produce a
1445
+ // transaction that fails on broadcast.
1446
+ if (!signerAddress) {
1447
+ throw new Error('signerAddress is required when sponsor is true');
1448
+ }
1449
+ return delegatedSponsorTransaction(client, {
1450
+ transaction,
1451
+ userId,
1452
+ traceContext
1453
+ });
1454
+ };
1455
+ const computeMessageToSignHex = (transaction)=>{
1456
+ if (transaction instanceof VersionedTransaction) {
1457
+ // For versioned transactions, we need to sign the message directly
1458
+ return Buffer.from(Array.from(transaction.message.serialize())).toString('hex');
1459
+ }
1460
+ // For legacy transactions, serialize the message
1461
+ return transaction.serializeMessage().toString('hex');
1462
+ };
1463
+ const ERROR_DELEGATED_SIGN_TRANSACTION_CONTEXT_REQUIRED = 'SVM transaction signing requires a chainId or an explicit context.svmTransaction.';
1464
+ const validateSignMessageContext = (context, chainId)=>{
1465
+ if ((context == null ? void 0 : context.svmTransaction) !== undefined || chainId !== undefined) {
1466
+ return;
1467
+ }
1468
+ throw new ClientValidationError(ERROR_DELEGATED_SIGN_TRANSACTION_CONTEXT_REQUIRED);
1469
+ };
1470
+ const buildSignMessageContext = (context, chainId, transaction)=>{
1471
+ if ((context == null ? void 0 : context.svmTransaction) !== undefined) {
1472
+ return context;
1473
+ }
1474
+ if (chainId === undefined) {
1475
+ throw new ClientValidationError(ERROR_DELEGATED_SIGN_TRANSACTION_CONTEXT_REQUIRED);
1476
+ }
1477
+ return _extends({}, context, {
1478
+ svmTransaction: {
1479
+ chainId,
1480
+ method: 'signAndSendTransaction',
1481
+ serializedTransactions: [
1482
+ encodeBase58(serializeSvmTransaction(transaction))
1483
+ ]
1484
+ }
1485
+ });
1486
+ };
1487
+ const resolveSignerAddress = (transaction, signerAddress)=>{
1488
+ var _transaction_feePayer;
1489
+ if (signerAddress !== undefined) {
1490
+ return signerAddress;
1491
+ }
1492
+ if (transaction instanceof VersionedTransaction) {
1493
+ var _transaction_message_staticAccountKeys_;
1494
+ var _transaction_message_staticAccountKeys__toBase58;
1495
+ return (_transaction_message_staticAccountKeys__toBase58 = (_transaction_message_staticAccountKeys_ = transaction.message.staticAccountKeys[0]) == null ? void 0 : _transaction_message_staticAccountKeys_.toBase58()) != null ? _transaction_message_staticAccountKeys__toBase58 : '';
1496
+ }
1497
+ var _transaction_feePayer_toBase58;
1498
+ return (_transaction_feePayer_toBase58 = (_transaction_feePayer = transaction.feePayer) == null ? void 0 : _transaction_feePayer.toBase58()) != null ? _transaction_feePayer_toBase58 : '';
1499
+ };
1500
+ const toSignerPublicKey = (resolvedSignerAddress)=>{
1501
+ try {
1502
+ return new PublicKey(resolvedSignerAddress);
1503
+ } catch (error) {
1504
+ throw new Error(`Invalid signer address: ${resolvedSignerAddress}. ${error instanceof Error ? error.message : 'Unknown error'}`);
1505
+ }
1506
+ };
1507
+ const delegatedSignTransaction = async (client, { walletId, shareSetId, walletApiKey, keyShare, transaction, signerAddress, derivationPath, chainId, context, sponsor = false, userId, traceContext, onError })=>{
611
1508
  try {
612
- let messageToSign;
613
- if (transaction instanceof VersionedTransaction) {
614
- // For versioned transactions, we need to sign the message directly
615
- const messageBytes = transaction.message.serialize();
616
- messageToSign = Buffer.from(Array.from(messageBytes)).toString('hex');
617
- } else {
618
- // For legacy transactions, serialize the message
619
- const messageBytes = transaction.serializeMessage();
620
- messageToSign = messageBytes.toString('hex');
621
- }
622
- // Use the delegated sign message function from node package
1509
+ if (!keyShare || !walletId || !walletApiKey) {
1510
+ throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign a transaction');
1511
+ }
1512
+ validateSignMessageContext(context, chainId);
1513
+ transaction = await sponsorTransactionIfRequested(client, {
1514
+ sponsor,
1515
+ userId,
1516
+ signerAddress,
1517
+ transaction,
1518
+ traceContext
1519
+ });
1520
+ const resolvedContext = buildSignMessageContext(context, chainId, transaction);
1521
+ const messageToSign = computeMessageToSignHex(transaction);
623
1522
  const signatureEd25519 = await delegatedSignMessage$1(client, {
624
1523
  walletId,
1524
+ shareSetId,
625
1525
  walletApiKey,
626
1526
  keyShare,
627
1527
  message: messageToSign,
628
1528
  chainName: client.chainName,
629
- isFormatted: false
1529
+ derivationPath,
1530
+ isFormatted: false,
1531
+ context: resolvedContext,
1532
+ onError
630
1533
  });
631
1534
  if (!signatureEd25519) {
632
1535
  throw new Error('Signature is undefined');
633
1536
  }
634
- const resolvedSignerAddress = signerAddress != null ? signerAddress : (()=>{
635
- var _transaction_feePayer;
636
- if (transaction instanceof VersionedTransaction) {
637
- var _signers_;
638
- const signers = transaction.message.staticAccountKeys;
639
- var _signers__toBase58;
640
- return (_signers__toBase58 = (_signers_ = signers[0]) == null ? void 0 : _signers_.toBase58()) != null ? _signers__toBase58 : '';
641
- }
642
- var _transaction_feePayer_toBase58;
643
- return (_transaction_feePayer_toBase58 = (_transaction_feePayer = transaction.feePayer) == null ? void 0 : _transaction_feePayer.toBase58()) != null ? _transaction_feePayer_toBase58 : '';
644
- })();
1537
+ const resolvedSignerAddress = resolveSignerAddress(transaction, signerAddress);
645
1538
  if (!resolvedSignerAddress) {
646
1539
  throw new Error('Could not determine signer address. Provide signerAddress explicitly or ensure transaction has a fee payer.');
647
1540
  }
648
- let signerPublicKey;
649
- try {
650
- signerPublicKey = new PublicKey(resolvedSignerAddress);
651
- } catch (error) {
652
- throw new Error(`Invalid signer address: ${resolvedSignerAddress}. ${error instanceof Error ? error.message : 'Unknown error'}`);
653
- }
654
- const signedTransaction = addSignatureToTransaction({
1541
+ const signerPublicKey = toSignerPublicKey(resolvedSignerAddress);
1542
+ return addSignatureToTransaction({
655
1543
  transaction,
656
1544
  signature: signatureEd25519,
657
1545
  signerPublicKey
658
1546
  });
659
- return signedTransaction;
660
1547
  } catch (error) {
661
1548
  logError({
662
1549
  message: 'Error in delegatedSignTransaction',
@@ -678,40 +1565,40 @@ const logError = createLogError('node-svm');
678
1565
  * @param options.walletApiKey - The wallet API key
679
1566
  * @param options.keyShare - The server key share
680
1567
  * @param options.message - Hex string of the already-hashed data to sign
1568
+ * @param options.rawSign - Pre-image the digest is derived from, used to build the policy context
1569
+ * @param options.context - Explicit policy context, when the caller builds one itself
681
1570
  *
682
1571
  * @returns The base58-encoded signature
683
1572
  *
684
1573
  * @example
685
- * // Sign a pre-hashed message
686
- * const signature = await delegatedSignRawMessage(client, {
687
- * walletId,
688
- * walletApiKey,
689
- * keyShare,
690
- * message: preHashedHex, // hex string of already-hashed data
691
- * });
692
- *
693
- * @example
694
1574
  * // Sign a SHA-256 hash derived from arbitrary application data
695
1575
  * import { createHash } from 'crypto';
696
- * const hash = createHash('sha256').update('my application data').digest('hex');
1576
+ * const payload = Buffer.from('my application data', 'utf8').toString('hex');
1577
+ * const hash = createHash('sha256').update(Buffer.from(payload, 'hex')).digest('hex');
697
1578
  * const signature = await delegatedSignRawMessage(client, {
698
1579
  * walletId,
699
1580
  * walletApiKey,
700
1581
  * keyShare,
701
1582
  * message: hash,
1583
+ * rawSign: { hashFunction: SignMessageRawSignHashFunctionEnum.Sha256, payload },
702
1584
  * });
703
1585
  *
704
- */ const delegatedSignRawMessage = async (client, { walletId, walletApiKey, keyShare, message })=>{
1586
+ */ const delegatedSignRawMessage = async (client, { walletId, shareSetId, walletApiKey, keyShare, message, derivationPath, context, rawSign, onError })=>{
705
1587
  if (!keyShare || !walletId || !walletApiKey) {
706
1588
  throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign a raw message');
707
1589
  }
708
1590
  try {
1591
+ const resolvedContext = resolveRawSignContext(context, rawSign);
709
1592
  return await delegatedSignMessage(client, {
710
1593
  walletId,
1594
+ shareSetId,
711
1595
  walletApiKey,
712
1596
  keyShare,
713
1597
  message: stripHexPrefix(message),
714
- isFormatted: true
1598
+ derivationPath,
1599
+ isFormatted: true,
1600
+ context: resolvedContext,
1601
+ onError
715
1602
  });
716
1603
  } catch (error) {
717
1604
  logError({
@@ -726,8 +1613,10 @@ const logError = createLogError('node-svm');
726
1613
  };
727
1614
  /**
728
1615
  * Revoke delegation - delegates to the node package
729
- */ const revokeDelegation = async (client, params)=>{
730
- return revokeDelegation$1(client, params);
1616
+ */ const revokeDelegation = async (client, { walletId })=>{
1617
+ return revokeDelegation$1(client, {
1618
+ walletId
1619
+ });
731
1620
  };
732
1621
 
733
- export { DynamicSvmWalletClient, ERROR_CREATE_WALLET_ACCOUNT, ERROR_SIGN_RAW_MESSAGE, addSignatureToTransaction, attachSignature, createDelegatedSvmWalletClient, createSolanaTransaction, decodeBase58, delegatedSignMessage, delegatedSignRawMessage, delegatedSignTransaction, encodeBase58, getBalance, revokeDelegation, sendTransaction };
1622
+ export { DynamicSvmWalletClient, ERROR_CREATE_WALLET_ACCOUNT, ERROR_DELEGATED_SIGN_TRANSACTION_CONTEXT_REQUIRED, ERROR_SIGN_RAW_MESSAGE, ERROR_SIGN_TRANSACTION_CONTEXT_REQUIRED, ERROR_SIGN_TRANSACTION_RAW_HEX_CONTEXT_REQUIRED, EarnSolanaStepError, addSignatureToTransaction, attachSignature, createDelegatedSvmWalletClient, createSolanaTransaction, createSvmEarnClient, decodeBase58, delegatedSignMessage, delegatedSignRawMessage, delegatedSignTransaction, delegatedSponsorTransaction, encodeBase58, getBalance, revokeDelegation, sendTransaction };