@dynamic-labs-wallet/node-svm 0.0.354 → 0.1.0-request-signing

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