@dynamic-labs-wallet/node-evm 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,8 +1,9 @@
1
1
  import { toAccount } from 'viem/accounts';
2
- import { MessageHash, createLogError, createDelegatedWalletClient, delegatedSignMessage as delegatedSignMessage$1, stripHexPrefix, revokeDelegation as revokeDelegation$1, DynamicWalletClient, getMPCChainConfig, getExternalServerKeyShareBackupInfo, WalletOperation } from '@dynamic-labs-wallet/node';
3
- import { getAddress, stringToHex, bytesToHex, size, concat, hashTypedData, serializeSignature, parseSignature, serializeTransaction, createPublicClient, http, defineChain, createWalletClient } from 'viem';
2
+ import { MessageHash, createLogError, createDelegatedWalletClient, delegatedSignMessage as delegatedSignMessage$1, resolveRawSignContext, stripHexPrefix, revokeDelegation as revokeDelegation$1, DynamicWalletClient, getMPCChainConfig, WalletOperation, withDelegatedServerAuth } from '@dynamic-labs-wallet/node';
3
+ import { getAddress, stringToHex, bytesToHex, size, concat, hashTypedData, validateTypedData, serializeSignature, parseSignature, serializeTransaction, encodeFunctionData, defineChain, createPublicClient, http, createWalletClient } from 'viem';
4
4
  import { hashAuthorization } from 'viem/utils';
5
5
  import { mainnet } from 'viem/chains';
6
+ import { randomBytes } from 'node:crypto';
6
7
  import { initializeClient, refreshUser, getNetworksData, createDynamicClient } from '@dynamic-labs-sdk/client';
7
8
  import { assertDefined } from '@dynamic-labs-sdk/client/core';
8
9
  import { mapNetworkDataToViemChain } from '@dynamic-labs-sdk/evm/viem';
@@ -33,6 +34,20 @@ const ERROR_ACCOUNT_ADDRESS_REQUIRED = 'Account address is required';
33
34
  const ERROR_VERIFY_MESSAGE_SIGNATURE = 'Error verifying message signature';
34
35
  const ERROR_SIGN_RAW_MESSAGE = 'Error signing raw message';
35
36
 
37
+ const mapTransactionToEvmTransaction = (transaction)=>{
38
+ var _transaction_to, _transaction_chainId;
39
+ return {
40
+ to: (_transaction_to = transaction.to) != null ? _transaction_to : '',
41
+ data: transaction.data,
42
+ gas: transaction.gas ? `0x${transaction.gas.toString(16)}` : undefined,
43
+ gasPrice: transaction.gasPrice ? `0x${transaction.gasPrice.toString(16)}` : undefined,
44
+ maxFeePerGas: transaction.maxFeePerGas ? `0x${transaction.maxFeePerGas.toString(16)}` : undefined,
45
+ maxPriorityFeePerGas: transaction.maxPriorityFeePerGas ? `0x${transaction.maxPriorityFeePerGas.toString(16)}` : undefined,
46
+ nonce: transaction.nonce,
47
+ value: transaction.value ? `0x${transaction.value.toString(16)}` : undefined,
48
+ chainId: (_transaction_chainId = transaction.chainId) != null ? _transaction_chainId : 0
49
+ };
50
+ };
36
51
  const formatEVMMessage = (message_)=>{
37
52
  const message = (()=>{
38
53
  if (typeof message_ === 'string') return stringToHex(message_);
@@ -46,7 +61,32 @@ const formatEVMMessage = (message_)=>{
46
61
  ]);
47
62
  };
48
63
  const formatTypedData = (typedData)=>{
49
- return hashTypedData(typedData).slice(2);
64
+ try {
65
+ return hashTypedData(typedData).slice(2);
66
+ } catch (error) {
67
+ // hashTypedData throws opaque errors (e.g. "Cannot read properties of
68
+ // undefined (reading 'length')") when `message` doesn't match `types`.
69
+ // Re-throw with a clear, actionable message identifying the typedData as
70
+ // the cause. Two cases:
71
+ // 1) format issues (bad address, int out of range, wrong bytes size,
72
+ // invalid primaryType/struct) -> viem's validateTypedData pinpoints it.
73
+ // 2) a field declared in `types` is missing/undefined in `message`
74
+ // (incl. primitive `string`/`bytes`) -> validateTypedData does NOT
75
+ // flag this, so we surface it explicitly here.
76
+ const primaryType = typedData.primaryType;
77
+ try {
78
+ validateTypedData(typedData);
79
+ } catch (validationError) {
80
+ throw Object.assign(new Error(`Invalid EIP-712 typedData: ${validationError.message}`), {
81
+ cause: error
82
+ });
83
+ }
84
+ const primaryTypeSuffix = primaryType ? ` (primaryType "${primaryType}")` : '';
85
+ const message = `Invalid EIP-712 typedData: a field declared in \`types\` is missing or ` + `undefined in \`message\`${primaryTypeSuffix}. ` + `Every field declared in \`types\` must be present in \`message\`. ` + `Underlying error: ${error.message}`;
86
+ throw Object.assign(new Error(message), {
87
+ cause: error
88
+ });
89
+ }
50
90
  };
51
91
  const serializeECDSASignature = (signature)=>{
52
92
  return serializeSignature({
@@ -68,25 +108,25 @@ const deriveAccountAddress = ({ rawPublicKey })=>{
68
108
  };
69
109
  };
70
110
 
71
- const logError$1 = createLogError('node-evm');
111
+ const logError$3 = createLogError('node-evm');
72
112
  /**
73
113
  * Creates a delegated EVM wallet client for functional operations
74
- */ const createDelegatedEvmWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, apiKey, debug = false })=>{
114
+ */ const createDelegatedEvmWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, apiKey, debug = false, errorLogging })=>{
75
115
  const baseClient = createDelegatedWalletClient({
76
116
  environmentId,
77
117
  baseApiUrl,
78
118
  baseMPCRelayApiUrl,
79
119
  apiKey,
80
- debug
120
+ debug,
121
+ errorLogging
81
122
  });
82
- const evmClient = _extends({}, baseClient, {
123
+ return _extends({}, baseClient, {
83
124
  chainName: 'EVM'
84
125
  });
85
- return evmClient;
86
126
  };
87
127
  /**
88
128
  * Signs a message using delegated signing for EVM
89
- */ const delegatedSignMessage = async (client, { walletId, walletApiKey, keyShare, message, context, onError })=>{
129
+ */ const delegatedSignMessage = async (client, { walletId, shareSetId, walletApiKey, keyShare, message, derivationPath, context, onError })=>{
90
130
  try {
91
131
  if (!keyShare || !walletId || !walletApiKey) {
92
132
  throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign a message');
@@ -97,17 +137,18 @@ const logError$1 = createLogError('node-evm');
97
137
  };
98
138
  const signatureEcdsa = await delegatedSignMessage$1(client, {
99
139
  walletId,
140
+ shareSetId,
100
141
  walletApiKey,
101
142
  keyShare,
102
143
  message: formattedMessage,
103
144
  chainName: client.chainName,
145
+ derivationPath,
104
146
  context: resolvedContext,
105
147
  onError
106
148
  });
107
- const serializedSignature = serializeECDSASignature(signatureEcdsa);
108
- return serializedSignature;
149
+ return serializeECDSASignature(signatureEcdsa);
109
150
  } catch (error) {
110
- logError$1({
151
+ logError$3({
111
152
  message: 'Error in delegatedSignMessage',
112
153
  error: error,
113
154
  context: {
@@ -119,21 +160,29 @@ const logError$1 = createLogError('node-evm');
119
160
  };
120
161
  /**
121
162
  * Signs a transaction using delegated signing for EVM
122
- */ const delegatedSignTransaction = async (client, { walletId, walletApiKey, keyShare, transaction })=>{
163
+ */ const delegatedSignTransaction = async (client, { walletId, shareSetId, walletApiKey, keyShare, transaction, derivationPath, context, onError })=>{
123
164
  try {
165
+ if (!keyShare || !walletId || !walletApiKey) {
166
+ throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign a transaction');
167
+ }
124
168
  // Serialize the transaction
125
169
  const serializedTx = serializeTransaction(transaction);
126
170
  const serializedTxBytes = Uint8Array.from(Buffer.from(serializedTx.slice(2), 'hex'));
127
171
  if (!(serializedTxBytes instanceof Uint8Array)) {
128
- throw new Error('Invalid serializedTxBytes');
172
+ throw new TypeError('Invalid serializedTxBytes');
129
173
  }
130
- // Use the delegated sign message function from node package
131
174
  const signatureEcdsa = await delegatedSignMessage$1(client, {
132
175
  walletId,
176
+ shareSetId,
133
177
  walletApiKey,
134
178
  keyShare,
135
179
  message: serializedTxBytes,
136
- chainName: client.chainName
180
+ chainName: client.chainName,
181
+ derivationPath,
182
+ context: _extends({}, context, {
183
+ evmTransaction: mapTransactionToEvmTransaction(transaction)
184
+ }),
185
+ onError
137
186
  });
138
187
  if (!('r' in signatureEcdsa && 's' in signatureEcdsa && 'v' in signatureEcdsa)) {
139
188
  throw new Error('Invalid signature format returned from MPC signing');
@@ -147,10 +196,9 @@ const logError$1 = createLogError('node-evm');
147
196
  s: s,
148
197
  v: v
149
198
  });
150
- const serializedSignedTx = serializeTransaction(signedTx);
151
- return serializedSignedTx;
199
+ return serializeTransaction(signedTx);
152
200
  } catch (error) {
153
- logError$1({
201
+ logError$3({
154
202
  message: 'Error in delegatedSignTransaction',
155
203
  error: error,
156
204
  context: {
@@ -162,7 +210,7 @@ const logError$1 = createLogError('node-evm');
162
210
  };
163
211
  /**
164
212
  * Signs typed data using delegated signing for EVM
165
- */ const delegatedSignTypedData = async (client, { walletId, walletApiKey, keyShare, typedData })=>{
213
+ */ const delegatedSignTypedData = async (client, { walletId, shareSetId, walletApiKey, keyShare, typedData, derivationPath, onError })=>{
166
214
  try {
167
215
  if (!keyShare || !walletId || !walletApiKey) {
168
216
  throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign typed data');
@@ -170,19 +218,21 @@ const logError$1 = createLogError('node-evm');
170
218
  const formattedTypedData = formatTypedData(typedData);
171
219
  const signatureEcdsa = await delegatedSignMessage$1(client, {
172
220
  walletId,
221
+ shareSetId,
173
222
  walletApiKey,
174
223
  keyShare,
175
224
  message: formattedTypedData,
176
225
  chainName: client.chainName,
226
+ derivationPath,
177
227
  isFormatted: true,
178
228
  context: {
179
229
  evmTypedData: typedData
180
- }
230
+ },
231
+ onError
181
232
  });
182
- const serializedSignature = serializeECDSASignature(signatureEcdsa);
183
- return serializedSignature;
233
+ return serializeECDSASignature(signatureEcdsa);
184
234
  } catch (error) {
185
- logError$1({
235
+ logError$3({
186
236
  message: 'Error in delegatedSignTypedData',
187
237
  error: error,
188
238
  context: {
@@ -194,7 +244,7 @@ const logError$1 = createLogError('node-evm');
194
244
  };
195
245
  /**
196
246
  * Signs EIP-7702 authorization using delegated signing for EVM
197
- */ const delegatedSignAuthorization = async (client, { walletId, walletApiKey, keyShare, authorization })=>{
247
+ */ const delegatedSignAuthorization = async (client, { walletId, shareSetId, walletApiKey, keyShare, authorization, derivationPath, onError })=>{
198
248
  try {
199
249
  if (!keyShare || !walletId || !walletApiKey) {
200
250
  throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign authorization');
@@ -203,20 +253,22 @@ const logError$1 = createLogError('node-evm');
203
253
  const prehashed = digest.startsWith('0x') ? digest.slice(2) : digest;
204
254
  const signatureEcdsa = await delegatedSignMessage$1(client, {
205
255
  walletId,
256
+ shareSetId,
206
257
  walletApiKey,
207
258
  keyShare,
208
259
  message: prehashed,
209
260
  chainName: client.chainName,
261
+ derivationPath,
210
262
  isFormatted: true,
211
263
  context: {
212
264
  eip7702Auth: authorization
213
- }
265
+ },
266
+ onError
214
267
  });
215
268
  const serializedSignature = serializeECDSASignature(signatureEcdsa);
216
- const signature = parseSignature(serializedSignature);
217
- return signature;
269
+ return parseSignature(serializedSignature);
218
270
  } catch (error) {
219
- logError$1({
271
+ logError$3({
220
272
  message: 'Error in delegatedSignAuthorization',
221
273
  error: error,
222
274
  context: {
@@ -229,25 +281,31 @@ const logError$1 = createLogError('node-evm');
229
281
  /**
230
282
  * Signs a pre-formatted (raw) message using delegated signing for EVM.
231
283
  * The message must be a hex string representing already-hashed data.
232
- */ const delegatedSignRawMessage = async (client, { walletId, walletApiKey, keyShare, message, context, onError })=>{
284
+ *
285
+ * Provide either `rawSign` — the pre-image the digest comes from — or an
286
+ * explicit `context`, so a policy-enabled wallet can evaluate the request.
287
+ */ const delegatedSignRawMessage = async (client, { walletId, shareSetId, walletApiKey, keyShare, message, derivationPath, context, rawSign, onError })=>{
233
288
  try {
234
289
  if (!keyShare || !walletId || !walletApiKey) {
235
290
  throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign a raw message');
236
291
  }
292
+ const resolvedContext = resolveRawSignContext(context, rawSign);
237
293
  const prehashed = stripHexPrefix(message);
238
294
  const signatureEcdsa = await delegatedSignMessage$1(client, {
239
295
  walletId,
296
+ shareSetId,
240
297
  walletApiKey,
241
298
  keyShare,
242
299
  message: prehashed,
243
300
  chainName: client.chainName,
301
+ derivationPath,
244
302
  isFormatted: true,
245
- context,
303
+ context: resolvedContext,
246
304
  onError
247
305
  });
248
306
  return serializeECDSASignature(signatureEcdsa);
249
307
  } catch (error) {
250
- logError$1({
308
+ logError$3({
251
309
  message: 'Error in delegatedSignRawMessage',
252
310
  error: error,
253
311
  context: {
@@ -259,17 +317,20 @@ const logError$1 = createLogError('node-evm');
259
317
  };
260
318
  /**
261
319
  * Revoke delegation - delegates to the node package
262
- */ const revokeDelegation = async (client, params)=>{
263
- return revokeDelegation$1(client, params);
320
+ */ const revokeDelegation = async (client, { walletId })=>{
321
+ return revokeDelegation$1(client, {
322
+ walletId
323
+ });
264
324
  };
265
325
 
266
- const createAccountAdapter = ({ evmClient, accountAddress, password, externalServerKeyShares, delegated })=>{
326
+ const createAccountAdapter = ({ evmClient, walletMetadata, password, externalServerKeyShares, delegated })=>{
267
327
  return toAccount({
268
- address: accountAddress,
328
+ address: walletMetadata.accountAddress,
269
329
  signMessage: async ({ message })=>{
270
330
  if (delegated) {
271
331
  return delegatedSignMessage(delegated.delegatedClient, {
272
332
  walletId: delegated.walletId,
333
+ shareSetId: delegated.shareSetId,
273
334
  walletApiKey: delegated.walletApiKey,
274
335
  keyShare: delegated.keyShare,
275
336
  message: message
@@ -277,7 +338,7 @@ const createAccountAdapter = ({ evmClient, accountAddress, password, externalSer
277
338
  }
278
339
  const signature = await evmClient.signMessage({
279
340
  message: message,
280
- accountAddress,
341
+ walletMetadata,
281
342
  password,
282
343
  externalServerKeyShares
283
344
  });
@@ -287,13 +348,14 @@ const createAccountAdapter = ({ evmClient, accountAddress, password, externalSer
287
348
  if (delegated) {
288
349
  return delegatedSignTypedData(delegated.delegatedClient, {
289
350
  walletId: delegated.walletId,
351
+ shareSetId: delegated.shareSetId,
290
352
  walletApiKey: delegated.walletApiKey,
291
353
  keyShare: delegated.keyShare,
292
354
  typedData: typedData
293
355
  });
294
356
  }
295
357
  return evmClient.signTypedData({
296
- accountAddress,
358
+ walletMetadata,
297
359
  typedData: typedData,
298
360
  password: password,
299
361
  externalServerKeyShares
@@ -303,13 +365,14 @@ const createAccountAdapter = ({ evmClient, accountAddress, password, externalSer
303
365
  if (delegated) {
304
366
  return delegatedSignTransaction(delegated.delegatedClient, {
305
367
  walletId: delegated.walletId,
368
+ shareSetId: delegated.shareSetId,
306
369
  walletApiKey: delegated.walletApiKey,
307
370
  keyShare: delegated.keyShare,
308
371
  transaction
309
372
  });
310
373
  }
311
374
  const signedTx = await evmClient.signTransaction({
312
- senderAddress: accountAddress,
375
+ walletMetadata,
313
376
  transaction,
314
377
  password,
315
378
  externalServerKeyShares
@@ -320,6 +383,7 @@ const createAccountAdapter = ({ evmClient, accountAddress, password, externalSer
320
383
  if (delegated) {
321
384
  const signature = await delegatedSignAuthorization(delegated.delegatedClient, {
322
385
  walletId: delegated.walletId,
386
+ shareSetId: delegated.shareSetId,
323
387
  walletApiKey: delegated.walletApiKey,
324
388
  keyShare: delegated.keyShare,
325
389
  authorization
@@ -338,7 +402,7 @@ const createAccountAdapter = ({ evmClient, accountAddress, password, externalSer
338
402
  }
339
403
  const signature = await evmClient.signAuthorization({
340
404
  authorization,
341
- accountAddress,
405
+ walletMetadata,
342
406
  password,
343
407
  externalServerKeyShares
344
408
  });
@@ -357,8 +421,751 @@ const createAccountAdapter = ({ evmClient, accountAddress, password, externalSer
357
421
  });
358
422
  };
359
423
 
360
- const logError = createLogError('node-evm');
361
- const keySharesRequiredFor = (action)=>`External server key shares are required to ${action}. No backup shares available for recovery.`;
424
+ function _object_without_properties_loose(source, excluded) {
425
+ if (source == null) return {};
426
+ var target = {};
427
+ var sourceKeys = Object.keys(source);
428
+ var key, i;
429
+ for(i = 0; i < sourceKeys.length; i++){
430
+ key = sourceKeys[i];
431
+ if (excluded.indexOf(key) >= 0) continue;
432
+ target[key] = source[key];
433
+ }
434
+ return target;
435
+ }
436
+
437
+ const ERROR_EARN_NOT_EVM_WALLET = 'Wallet metadata is not for an EVM wallet';
438
+ const ERROR_EARN_MISSING_EVM_TRANSACTION = 'Earn signing payload is missing EVM transaction data';
439
+ const ERROR_EARN_CHAIN_MISMATCH = 'The provided chain does not match the chain the Earn transaction was prepared for';
440
+ const ERROR_EARN_APPROVAL_FAILED = 'The ERC-20 approval for the Earn transaction reverted';
441
+ const ERROR_EARN_CHAIN_REQUIRED = 'Either chain or rpcUrl is required to execute an Earn transaction. Provide an RPC URL for the vault chain.';
442
+ /**
443
+ * Vault deposits and withdrawals rebalance the underlying lending markets, so gas estimated at
444
+ * the current block is regularly lower than what execution needs once the transaction is mined.
445
+ */ const EARN_GAS_LIMIT_BUFFER_PERCENT = 30n;
446
+ const ERC20_ALLOWANCE_AND_APPROVE_ABI = [
447
+ {
448
+ name: 'allowance',
449
+ type: 'function',
450
+ stateMutability: 'view',
451
+ inputs: [
452
+ {
453
+ name: 'owner',
454
+ type: 'address'
455
+ },
456
+ {
457
+ name: 'spender',
458
+ type: 'address'
459
+ }
460
+ ],
461
+ outputs: [
462
+ {
463
+ name: '',
464
+ type: 'uint256'
465
+ }
466
+ ]
467
+ },
468
+ {
469
+ name: 'approve',
470
+ type: 'function',
471
+ stateMutability: 'nonpayable',
472
+ inputs: [
473
+ {
474
+ name: 'spender',
475
+ type: 'address'
476
+ },
477
+ {
478
+ name: 'amount',
479
+ type: 'uint256'
480
+ }
481
+ ],
482
+ outputs: [
483
+ {
484
+ name: '',
485
+ type: 'bool'
486
+ }
487
+ ]
488
+ }
489
+ ];
490
+
491
+ /**
492
+ * Builds a stateless Earn client for EVM vaults: it prepares vault actions through the
493
+ * Dynamic API and executes the returned unsigned transactions with the caller's wallet,
494
+ * sending an ERC-20 approval first when the vault requires one.
495
+ */ const createEvmEarnClient = ({ getEarnClient, createViemPublicClient, getWalletClient, sendSponsoredTransaction })=>{
496
+ const resolveChain = ({ chain, chainId, rpcUrl })=>{
497
+ if (chain) {
498
+ if (chain.id !== chainId) {
499
+ throw new Error(ERROR_EARN_CHAIN_MISMATCH);
500
+ }
501
+ return chain;
502
+ }
503
+ if (!rpcUrl) {
504
+ throw new Error(ERROR_EARN_CHAIN_REQUIRED);
505
+ }
506
+ return defineChain({
507
+ id: chainId,
508
+ name: `Chain ${chainId}`,
509
+ nativeCurrency: {
510
+ name: 'Ether',
511
+ symbol: 'ETH',
512
+ decimals: 18
513
+ },
514
+ rpcUrls: {
515
+ default: {
516
+ http: [
517
+ rpcUrl
518
+ ]
519
+ }
520
+ }
521
+ });
522
+ };
523
+ const buildGasLimitAndNonce = async ({ transaction, publicClient, accountAddress })=>{
524
+ const params = {};
525
+ if (transaction.gasLimit) {
526
+ params.gas = BigInt(transaction.gasLimit);
527
+ } else {
528
+ const estimatedGas = await publicClient.estimateGas({
529
+ account: accountAddress,
530
+ to: transaction.to,
531
+ data: transaction.data,
532
+ value: transaction.value
533
+ });
534
+ params.gas = estimatedGas + estimatedGas * EARN_GAS_LIMIT_BUFFER_PERCENT / 100n;
535
+ }
536
+ if (transaction.nonce !== undefined) {
537
+ params.nonce = transaction.nonce;
538
+ }
539
+ return params;
540
+ };
541
+ const relaySponsoredEarnTransaction = async ({ chainId, evmApproval, evmTransaction, externalServerKeyShares, onStepChange, password, publicClient, resolvedChain, rpcUrl, traceContext, walletMetadata })=>{
542
+ const calls = [];
543
+ if (evmApproval) {
544
+ const currentAllowance = await publicClient.readContract({
545
+ address: evmApproval.tokenAddress,
546
+ abi: ERC20_ALLOWANCE_AND_APPROVE_ABI,
547
+ functionName: 'allowance',
548
+ args: [
549
+ walletMetadata.accountAddress,
550
+ evmApproval.spenderAddress
551
+ ]
552
+ });
553
+ const requiredAllowance = BigInt(evmApproval.amount);
554
+ if (currentAllowance < requiredAllowance) {
555
+ onStepChange == null ? void 0 : onStepChange('approval');
556
+ calls.push({
557
+ target: evmApproval.tokenAddress,
558
+ data: encodeFunctionData({
559
+ abi: ERC20_ALLOWANCE_AND_APPROVE_ABI,
560
+ functionName: 'approve',
561
+ args: [
562
+ evmApproval.spenderAddress,
563
+ requiredAllowance
564
+ ]
565
+ }),
566
+ value: 0n
567
+ });
568
+ }
569
+ }
570
+ onStepChange == null ? void 0 : onStepChange('transaction');
571
+ calls.push({
572
+ target: evmTransaction.to,
573
+ data: evmTransaction.data,
574
+ value: evmTransaction.value ? BigInt(evmTransaction.value) : 0n
575
+ });
576
+ return sendSponsoredTransaction({
577
+ walletMetadata,
578
+ calls,
579
+ chainId,
580
+ password,
581
+ externalServerKeyShares,
582
+ // The relayer needs an RPC to read the wallet's on-chain state; fall back to the
583
+ // resolved chain's default when the caller passed `chain` without `rpcUrl`.
584
+ rpcUrl: rpcUrl != null ? rpcUrl : resolvedChain.rpcUrls.default.http[0],
585
+ traceContext,
586
+ autoDelegate: true
587
+ });
588
+ };
589
+ const executeEarnTransaction = async ({ signingPayload, traceContext, walletMetadata, password, externalServerKeyShares, sponsored, chain, rpcUrl, onStepChange })=>{
590
+ if (walletMetadata.chainName !== 'EVM') {
591
+ throw new Error(ERROR_EARN_NOT_EVM_WALLET);
592
+ }
593
+ const { evmTransaction, evmApproval } = signingPayload;
594
+ if (!evmTransaction) {
595
+ throw new Error(ERROR_EARN_MISSING_EVM_TRANSACTION);
596
+ }
597
+ const chainId = Number(signingPayload.chainId);
598
+ const resolvedChain = resolveChain({
599
+ chain,
600
+ chainId,
601
+ rpcUrl
602
+ });
603
+ const publicClient = createViemPublicClient({
604
+ chain: resolvedChain,
605
+ rpcUrl
606
+ });
607
+ // Sponsored execution relays the approval and vault call as one batch through the
608
+ // gasless relayer, so no gas estimation or EOA sending is needed.
609
+ if (sponsored === true) {
610
+ return relaySponsoredEarnTransaction({
611
+ chainId,
612
+ evmApproval,
613
+ evmTransaction,
614
+ externalServerKeyShares,
615
+ onStepChange,
616
+ password,
617
+ publicClient,
618
+ resolvedChain,
619
+ rpcUrl,
620
+ traceContext,
621
+ walletMetadata
622
+ });
623
+ }
624
+ const walletClient = await getWalletClient({
625
+ walletMetadata,
626
+ password,
627
+ externalServerKeyShares,
628
+ chain: resolvedChain,
629
+ rpcUrl
630
+ });
631
+ if (evmApproval) {
632
+ const currentAllowance = await publicClient.readContract({
633
+ address: evmApproval.tokenAddress,
634
+ abi: ERC20_ALLOWANCE_AND_APPROVE_ABI,
635
+ functionName: 'allowance',
636
+ args: [
637
+ walletMetadata.accountAddress,
638
+ evmApproval.spenderAddress
639
+ ]
640
+ });
641
+ const requiredAllowance = BigInt(evmApproval.amount);
642
+ if (currentAllowance < requiredAllowance) {
643
+ onStepChange == null ? void 0 : onStepChange('approval');
644
+ const approvalHash = await walletClient.sendTransaction({
645
+ to: evmApproval.tokenAddress,
646
+ data: encodeFunctionData({
647
+ abi: ERC20_ALLOWANCE_AND_APPROVE_ABI,
648
+ functionName: 'approve',
649
+ args: [
650
+ evmApproval.spenderAddress,
651
+ requiredAllowance
652
+ ]
653
+ }),
654
+ value: 0n
655
+ });
656
+ const approvalReceipt = await publicClient.waitForTransactionReceipt({
657
+ hash: approvalHash
658
+ });
659
+ if (approvalReceipt.status !== 'success') {
660
+ throw new Error(ERROR_EARN_APPROVAL_FAILED);
661
+ }
662
+ }
663
+ }
664
+ onStepChange == null ? void 0 : onStepChange('transaction');
665
+ let value = 0n;
666
+ if (evmTransaction.value) {
667
+ value = BigInt(evmTransaction.value);
668
+ }
669
+ const gasLimitAndNonce = await buildGasLimitAndNonce({
670
+ transaction: _extends({}, evmTransaction, {
671
+ value
672
+ }),
673
+ publicClient,
674
+ accountAddress: walletMetadata.accountAddress
675
+ });
676
+ const request = _extends({
677
+ to: evmTransaction.to,
678
+ data: evmTransaction.data,
679
+ value
680
+ }, gasLimitAndNonce);
681
+ const hasEip1559Fees = Boolean(evmTransaction.maxFeePerGas && evmTransaction.maxPriorityFeePerGas);
682
+ if (hasEip1559Fees) {
683
+ const transactionHash = await walletClient.sendTransaction(_extends({}, request, {
684
+ maxFeePerGas: BigInt(evmTransaction.maxFeePerGas),
685
+ maxPriorityFeePerGas: BigInt(evmTransaction.maxPriorityFeePerGas)
686
+ }));
687
+ return {
688
+ transactionHash
689
+ };
690
+ }
691
+ if (evmTransaction.gasPrice) {
692
+ const transactionHash = await walletClient.sendTransaction(_extends({}, request, {
693
+ gasPrice: BigInt(evmTransaction.gasPrice)
694
+ }));
695
+ return {
696
+ transactionHash
697
+ };
698
+ }
699
+ const transactionHash = await walletClient.sendTransaction(request);
700
+ return {
701
+ transactionHash
702
+ };
703
+ };
704
+ const depositToEarnVault = async (_param)=>{
705
+ var { vaultId, amount, receiverAddress, traceContext } = _param, walletParams = _object_without_properties_loose(_param, [
706
+ "vaultId",
707
+ "amount",
708
+ "receiverAddress",
709
+ "traceContext"
710
+ ]);
711
+ const signingPayload = await getEarnClient().prepareDeposit({
712
+ vaultId,
713
+ ownerAddress: walletParams.walletMetadata.accountAddress,
714
+ amount,
715
+ receiverAddress,
716
+ traceContext
717
+ });
718
+ return executeEarnTransaction(_extends({
719
+ signingPayload,
720
+ traceContext
721
+ }, walletParams));
722
+ };
723
+ const withdrawFromEarnVault = async (_param)=>{
724
+ var { vaultId, amount, receiverAddress, traceContext } = _param, walletParams = _object_without_properties_loose(_param, [
725
+ "vaultId",
726
+ "amount",
727
+ "receiverAddress",
728
+ "traceContext"
729
+ ]);
730
+ const signingPayload = await getEarnClient().prepareWithdrawal({
731
+ vaultId,
732
+ ownerAddress: walletParams.walletMetadata.accountAddress,
733
+ amount,
734
+ receiverAddress,
735
+ traceContext
736
+ });
737
+ return executeEarnTransaction(_extends({
738
+ signingPayload,
739
+ traceContext
740
+ }, walletParams));
741
+ };
742
+ const claimEarnRewards = async (_param)=>{
743
+ var { vaultId, traceContext } = _param, walletParams = _object_without_properties_loose(_param, [
744
+ "vaultId",
745
+ "traceContext"
746
+ ]);
747
+ const signingPayload = await getEarnClient().prepareClaimRewards({
748
+ vaultId,
749
+ ownerAddress: walletParams.walletMetadata.accountAddress,
750
+ traceContext
751
+ });
752
+ return executeEarnTransaction(_extends({
753
+ signingPayload,
754
+ traceContext
755
+ }, walletParams));
756
+ };
757
+ return {
758
+ executeEarnTransaction,
759
+ depositToEarnVault,
760
+ withdrawFromEarnVault,
761
+ claimEarnRewards
762
+ };
763
+ };
764
+
765
+ /** The Fireblocks Universal Gasless Delegate (UGD) contract address used for EIP-7702 delegation. */ const DELEGATION_CONTRACT_ADDRESS = '0x0000Fb7702036ff9f76044a501ac1aA74cbab16b';
766
+ /** Default sponsored transaction validity duration in seconds (10 minutes). */ const DEFAULT_VALID_FOR_SECONDS = 600;
767
+ /** EIP-7702 delegation code prefix used to identify delegated accounts. */ const DELEGATION_CODE_PREFIX = '0xef0100';
768
+ /** ERC-7579 batch call with opData and auth mode identifier. */ const BATCH_CALL_OPDATA_AUTH_MODE = '0x0100000000007821000100000000000000000000000000000000000000000000';
769
+ /** EIP-712 typed data types for UGD AuthorizedExecutions signing. */ const AUTHORIZED_EXECUTIONS_TYPES = {
770
+ AuthorizedExecutions: [
771
+ {
772
+ name: 'calls',
773
+ type: 'Execution[]'
774
+ },
775
+ {
776
+ name: 'deadline',
777
+ type: 'uint256'
778
+ },
779
+ {
780
+ name: 'mode',
781
+ type: 'bytes32'
782
+ },
783
+ {
784
+ name: 'nonce',
785
+ type: 'uint256'
786
+ },
787
+ {
788
+ name: 'relayer',
789
+ type: 'address'
790
+ }
791
+ ],
792
+ Execution: [
793
+ {
794
+ name: 'target',
795
+ type: 'address'
796
+ },
797
+ {
798
+ name: 'value',
799
+ type: 'uint256'
800
+ },
801
+ {
802
+ name: 'data',
803
+ type: 'bytes'
804
+ }
805
+ ]
806
+ };
807
+ /** Minimal ABI for the UGD contract's nonce validation function. */ const UGD_ABI = [
808
+ {
809
+ inputs: [
810
+ {
811
+ name: 'nonce',
812
+ type: 'uint256'
813
+ }
814
+ ],
815
+ name: 'isNonceUsed',
816
+ outputs: [
817
+ {
818
+ name: '',
819
+ type: 'bool'
820
+ }
821
+ ],
822
+ stateMutability: 'view',
823
+ type: 'function'
824
+ }
825
+ ];
826
+ /** Default polling interval for sponsored transaction status checks (milliseconds). */ const EVM_GASLESS_DEFAULT_POLL_INTERVAL_MS = 2000;
827
+ /** Default timeout for sponsored transaction polling (milliseconds). */ const EVM_GASLESS_DEFAULT_TIMEOUT_MS = 60000;
828
+ // Error messages
829
+ const ERROR_GASLESS_RPC_REQUIRED_FOR_AUTO_DELEGATE = 'rpcUrl is required when autoDelegate is true and no explicit authorization is provided. ' + 'Pass rpcUrl, pass an explicit authorization, or set autoDelegate: false.';
830
+ const ERROR_GASLESS_RELAY_FAILED = 'EVM sponsored transaction relay failed';
831
+ const ERROR_GASLESS_TIMEOUT = 'EVM sponsored transaction timed out waiting for terminal status';
832
+ const ERROR_GASLESS_MISSING_REQUEST_ID = 'Relay response did not include a requestId';
833
+ const ERROR_GASLESS_MISSING_YPARITY = 'Signed authorization is missing yParity';
834
+ const ERROR_GASLESS_RPC_REQUIRED = 'rpcUrl is required for this operation';
835
+
836
+ const logError$2 = createLogError('node-evm');
837
+ /**
838
+ * Builds a stateless gasless client for EVM sponsored transactions (Fireblocks-relayer
839
+ * native gasless via EIP-7702 / AuthorizedExecutions). It holds no wallet state — the
840
+ * signing primitives and API client are injected by the caller that owns the wallet.
841
+ */ const createEvmGaslessClient = ({ apiClient, createViemPublicClient, signAuthorization, signTypedData })=>{
842
+ const viemPublicClientForChain = (chainId, rpcUrl)=>{
843
+ if (!rpcUrl) {
844
+ throw new Error(ERROR_GASLESS_RPC_REQUIRED);
845
+ }
846
+ const chain = defineChain({
847
+ id: chainId,
848
+ name: `Chain ${chainId}`,
849
+ nativeCurrency: {
850
+ name: 'Ether',
851
+ symbol: 'ETH',
852
+ decimals: 18
853
+ },
854
+ rpcUrls: {
855
+ default: {
856
+ http: [
857
+ rpcUrl
858
+ ]
859
+ }
860
+ }
861
+ });
862
+ return createViemPublicClient({
863
+ chain,
864
+ rpcUrl
865
+ });
866
+ };
867
+ const generateRandomNonce = ()=>BigInt('0x' + randomBytes(32).toString('hex'));
868
+ const generateIntentNonce = async ({ walletAddress, chainId, rpcUrl })=>{
869
+ let nonce = generateRandomNonce();
870
+ if (rpcUrl) {
871
+ try {
872
+ const publicClient = viemPublicClientForChain(chainId, rpcUrl);
873
+ // On a brand-new (undelegated) wallet the address has no UGD code yet,
874
+ // so isNonceUsed reverts — the random value is safe regardless.
875
+ const isUsed = await publicClient.readContract({
876
+ address: walletAddress,
877
+ abi: UGD_ABI,
878
+ functionName: 'isNonceUsed',
879
+ args: [
880
+ nonce
881
+ ]
882
+ });
883
+ if (isUsed) {
884
+ nonce = generateRandomNonce();
885
+ }
886
+ } catch (e) {
887
+ // RPC failure is tolerable — 256-bit random collision is negligible
888
+ }
889
+ }
890
+ return nonce;
891
+ };
892
+ const is7702DelegationActive = async ({ walletAddress, chainId, rpcUrl })=>{
893
+ const publicClient = viemPublicClientForChain(chainId, rpcUrl);
894
+ const code = await publicClient.getCode({
895
+ address: walletAddress
896
+ });
897
+ if (!code) return false;
898
+ const expectedPrefix = DELEGATION_CODE_PREFIX + DELEGATION_CONTRACT_ADDRESS.slice(2).toLowerCase();
899
+ return code.toLowerCase().startsWith(expectedPrefix);
900
+ };
901
+ const sign7702Authorization = async ({ walletMetadata, chainId, rpcUrl, nonce, password, externalServerKeyShares })=>{
902
+ const address = walletMetadata.accountAddress;
903
+ try {
904
+ let eoaNonce;
905
+ if (nonce === undefined) {
906
+ if (!rpcUrl) {
907
+ throw new Error(ERROR_GASLESS_RPC_REQUIRED);
908
+ }
909
+ const publicClient = viemPublicClientForChain(chainId, rpcUrl);
910
+ eoaNonce = Number(await publicClient.getTransactionCount({
911
+ address
912
+ }));
913
+ } else {
914
+ eoaNonce = nonce;
915
+ }
916
+ const authorization = {
917
+ address: DELEGATION_CONTRACT_ADDRESS,
918
+ chainId,
919
+ nonce: eoaNonce
920
+ };
921
+ const sig = await signAuthorization({
922
+ authorization,
923
+ walletMetadata,
924
+ password,
925
+ externalServerKeyShares
926
+ });
927
+ if (sig.yParity === undefined) {
928
+ throw new Error(ERROR_GASLESS_MISSING_YPARITY);
929
+ }
930
+ return {
931
+ address: DELEGATION_CONTRACT_ADDRESS,
932
+ chainId,
933
+ nonce: eoaNonce,
934
+ r: sig.r,
935
+ s: sig.s,
936
+ yParity: sig.yParity
937
+ };
938
+ } catch (error) {
939
+ logError$2({
940
+ message: 'Error signing 7702 authorization',
941
+ error: error,
942
+ context: {
943
+ accountAddress: address,
944
+ chainId
945
+ }
946
+ });
947
+ throw error;
948
+ }
949
+ };
950
+ const getAvailableEvmGaslessRelayer = async ({ chainId, traceContext })=>{
951
+ const result = await apiClient.getAvailableEVMGaslessRelayer({
952
+ chainId,
953
+ traceContext
954
+ });
955
+ return {
956
+ relayerAddress: result.relayerAddress
957
+ };
958
+ };
959
+ const resolveSponsoredAuthorization = async ({ authorization, autoDelegate, walletMetadata, chainId, rpcUrl, password, externalServerKeyShares })=>{
960
+ if (authorization) {
961
+ return authorization;
962
+ }
963
+ if (!autoDelegate) {
964
+ return undefined;
965
+ }
966
+ // The EOA nonce and delegation status are only knowable on-chain; without
967
+ // an RPC we can't safely auto-sign a 7702 authorization, so fail loud
968
+ // instead of relaying an intent that would revert.
969
+ if (!rpcUrl) {
970
+ throw new Error(ERROR_GASLESS_RPC_REQUIRED_FOR_AUTO_DELEGATE);
971
+ }
972
+ const walletAddress = walletMetadata.accountAddress;
973
+ const isDelegated = await is7702DelegationActive({
974
+ walletAddress,
975
+ chainId,
976
+ rpcUrl
977
+ });
978
+ if (isDelegated) {
979
+ return undefined;
980
+ }
981
+ return sign7702Authorization({
982
+ walletMetadata,
983
+ chainId,
984
+ rpcUrl,
985
+ password,
986
+ externalServerKeyShares
987
+ });
988
+ };
989
+ const signSponsoredTransaction = async ({ walletMetadata, calls, chainId, rpcUrl, authorization, autoDelegate = true, nonce: providedNonce, validForSeconds = DEFAULT_VALID_FOR_SECONDS, password, externalServerKeyShares, traceContext })=>{
990
+ const walletAddress = walletMetadata.accountAddress;
991
+ try {
992
+ const resolvedAuth = await resolveSponsoredAuthorization({
993
+ authorization,
994
+ autoDelegate,
995
+ walletMetadata,
996
+ chainId,
997
+ rpcUrl,
998
+ password,
999
+ externalServerKeyShares
1000
+ });
1001
+ const nonce = providedNonce != null ? providedNonce : await generateIntentNonce({
1002
+ walletAddress,
1003
+ chainId,
1004
+ rpcUrl
1005
+ });
1006
+ const deadline = BigInt(Math.floor(Date.now() / 1000) + validForSeconds);
1007
+ const { relayerAddress } = await getAvailableEvmGaslessRelayer({
1008
+ chainId,
1009
+ traceContext
1010
+ });
1011
+ const signature = await signTypedData({
1012
+ walletMetadata,
1013
+ password,
1014
+ externalServerKeyShares,
1015
+ typedData: {
1016
+ domain: {
1017
+ chainId,
1018
+ verifyingContract: DELEGATION_CONTRACT_ADDRESS
1019
+ },
1020
+ message: {
1021
+ calls: calls.map((c)=>({
1022
+ data: c.data,
1023
+ target: c.target,
1024
+ value: c.value
1025
+ })),
1026
+ deadline,
1027
+ mode: BATCH_CALL_OPDATA_AUTH_MODE,
1028
+ nonce,
1029
+ relayer: relayerAddress
1030
+ },
1031
+ primaryType: 'AuthorizedExecutions',
1032
+ types: AUTHORIZED_EXECUTIONS_TYPES
1033
+ }
1034
+ });
1035
+ return {
1036
+ authorization: resolvedAuth,
1037
+ calls,
1038
+ chainId,
1039
+ deadline: String(deadline),
1040
+ nonce: String(nonce),
1041
+ relayer: relayerAddress,
1042
+ signature,
1043
+ walletAddress
1044
+ };
1045
+ } catch (error) {
1046
+ logError$2({
1047
+ message: 'Error signing sponsored transaction',
1048
+ error: error,
1049
+ context: {
1050
+ accountAddress: walletAddress,
1051
+ chainId
1052
+ }
1053
+ });
1054
+ throw error;
1055
+ }
1056
+ };
1057
+ const getEVMSponsoredTransactionStatus = async ({ requestId, traceContext })=>{
1058
+ const result = await apiClient.getEVMSponsoredTransactionStatus({
1059
+ requestId,
1060
+ traceContext
1061
+ });
1062
+ return result;
1063
+ };
1064
+ const isSignedTransactionParams = (params)=>'signedTransaction' in params;
1065
+ const relaySponsoredTransaction = async (params)=>{
1066
+ try {
1067
+ const signed = isSignedTransactionParams(params) ? params.signedTransaction : await signSponsoredTransaction(params);
1068
+ const { requestId } = await apiClient.sponsorEVMTransaction({
1069
+ traceContext: params.traceContext,
1070
+ request: _extends({
1071
+ authorization: signed.authorization,
1072
+ calls: signed.calls.map((c)=>({
1073
+ data: c.data,
1074
+ target: c.target,
1075
+ value: String(c.value)
1076
+ })),
1077
+ chainId: signed.chainId,
1078
+ deadline: signed.deadline,
1079
+ nonce: signed.nonce,
1080
+ relayer: signed.relayer,
1081
+ signature: signed.signature,
1082
+ walletAddress: signed.walletAddress
1083
+ }, params.userId ? {
1084
+ userId: params.userId
1085
+ } : {})
1086
+ });
1087
+ if (!requestId) {
1088
+ throw new Error(ERROR_GASLESS_MISSING_REQUEST_ID);
1089
+ }
1090
+ return {
1091
+ requestId
1092
+ };
1093
+ } catch (error) {
1094
+ const { accountAddress, chainId } = isSignedTransactionParams(params) ? {
1095
+ accountAddress: params.signedTransaction.walletAddress,
1096
+ chainId: params.signedTransaction.chainId
1097
+ } : {
1098
+ accountAddress: params.walletMetadata.accountAddress,
1099
+ chainId: params.chainId
1100
+ };
1101
+ logError$2({
1102
+ message: 'Error relaying sponsored transaction',
1103
+ error: error,
1104
+ context: {
1105
+ accountAddress,
1106
+ chainId,
1107
+ userId: params.userId
1108
+ }
1109
+ });
1110
+ throw error;
1111
+ }
1112
+ };
1113
+ const waitForSponsoredTransaction = async ({ requestId, pollInterval = EVM_GASLESS_DEFAULT_POLL_INTERVAL_MS, timeout = EVM_GASLESS_DEFAULT_TIMEOUT_MS, traceContext })=>{
1114
+ try {
1115
+ // A zero or negative pollInterval makes attempts Infinity and turns this into a
1116
+ // tight loop hammering the status API, so clamp it to a sane minimum.
1117
+ const effectivePoll = Math.max(1, pollInterval);
1118
+ const attempts = Math.max(1, Math.floor(timeout / effectivePoll));
1119
+ for(let i = 0; i < attempts; i++){
1120
+ const r = await getEVMSponsoredTransactionStatus({
1121
+ requestId,
1122
+ traceContext
1123
+ });
1124
+ if (r.status === 'failure') {
1125
+ var _r_errorMessage;
1126
+ throw new Error(`${ERROR_GASLESS_RELAY_FAILED}: ${(_r_errorMessage = r.errorMessage) != null ? _r_errorMessage : 'unknown'}`);
1127
+ }
1128
+ if (r.transactionHash) {
1129
+ return {
1130
+ transactionHash: r.transactionHash
1131
+ };
1132
+ }
1133
+ if (i < attempts - 1) {
1134
+ await new Promise((resolve)=>setTimeout(resolve, effectivePoll));
1135
+ }
1136
+ }
1137
+ throw new Error(`${ERROR_GASLESS_TIMEOUT}: ${requestId}`);
1138
+ } catch (error) {
1139
+ logError$2({
1140
+ message: 'Error waiting for sponsored transaction',
1141
+ error: error,
1142
+ context: {
1143
+ requestId
1144
+ }
1145
+ });
1146
+ throw error;
1147
+ }
1148
+ };
1149
+ const sendSponsoredTransaction = async (params)=>{
1150
+ const { requestId } = await relaySponsoredTransaction(params);
1151
+ return waitForSponsoredTransaction({
1152
+ requestId,
1153
+ traceContext: params.traceContext
1154
+ });
1155
+ };
1156
+ return {
1157
+ getAvailableEvmGaslessRelayer,
1158
+ getEVMSponsoredTransactionStatus,
1159
+ is7702DelegationActive,
1160
+ relaySponsoredTransaction,
1161
+ sendSponsoredTransaction,
1162
+ sign7702Authorization,
1163
+ signSponsoredTransaction,
1164
+ waitForSponsoredTransaction
1165
+ };
1166
+ };
1167
+
1168
+ const logError$1 = createLogError('node-evm');
362
1169
  class DynamicEvmWalletClient extends DynamicWalletClient {
363
1170
  get jwtAuthToken() {
364
1171
  return this.baseJWTAuthToken;
@@ -373,10 +1180,10 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
373
1180
  transport: http(rpcUrl)
374
1181
  });
375
1182
  }
376
- async getWalletClient({ accountAddress, password, externalServerKeyShares, chain, chainId, rpcUrl }) {
1183
+ async getWalletClient({ walletMetadata, password, externalServerKeyShares, chain, chainId, rpcUrl }) {
377
1184
  const account = createAccountAdapter({
378
1185
  evmClient: this,
379
- accountAddress: accountAddress,
1186
+ walletMetadata,
380
1187
  password,
381
1188
  externalServerKeyShares
382
1189
  });
@@ -417,95 +1224,82 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
417
1224
  * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet.
418
1225
  * @param password - The password to use for the wallet.
419
1226
  * @param onError - The function to call if an error occurs.
420
- * @param backUpToClientShareService - Whether to back up the external server key shares to the client share service. By default, it is false.
1227
+ * @param backUpToDynamic - Whether to back up the external server key shares to the client share service. By default, it is false.
421
1228
  * @returns The account address, public key, raw public key, external server key shares, and wallet id.
422
- */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, onError, backUpToClientShareService = false }) {
1229
+ */ async createWalletAccount({ thresholdSignatureScheme, password, onError, backUpToDynamic = false, returnEncryptedWalletApiKey }) {
423
1230
  try {
424
- let ceremonyCeremonyCompleteResolver;
425
- const ceremonyCompletePromise = new Promise((resolve)=>{
426
- ceremonyCeremonyCompleteResolver = resolve;
427
- });
1231
+ const ceremony = this.createCeremonyCompletionTracker();
428
1232
  // Generate key shares for given threshold signature scheme (TSS)
429
1233
  const { rawPublicKey, externalServerKeyShares } = await this.keyGen({
430
1234
  chainName: this.chainName,
431
1235
  thresholdSignatureScheme,
432
1236
  skipLock: true,
1237
+ password,
1238
+ backUpToDynamic,
1239
+ returnEncryptedWalletApiKey,
433
1240
  onError,
434
- onCeremonyComplete: (accountAddress, walletId)=>{
435
- // update wallet map
436
- const checksumAddress = getAddress(accountAddress);
437
- const chainConfig = getMPCChainConfig(this.chainName);
438
- this.walletMap[checksumAddress] = _extends({}, this.walletMap[checksumAddress] || {}, {
439
- accountAddress: checksumAddress,
440
- walletId,
441
- chainName: this.chainName,
442
- thresholdSignatureScheme,
443
- derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
444
- index,
445
- value
446
- ]))),
447
- externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
448
- });
449
- this.logger.debug('walletMap updated for wallet', {
450
- context: {
451
- accountAddress,
452
- walletId,
453
- walletMap: this.walletMap
454
- }
455
- });
456
- ceremonyCeremonyCompleteResolver(undefined);
457
- }
1241
+ onCeremonyComplete: ceremony.onCeremonyComplete
458
1242
  });
459
1243
  // Wait for the ceremony to complete before proceeding
460
- await ceremonyCompletePromise;
461
- if (!rawPublicKey || !externalServerKeyShares) {
1244
+ await ceremony.promise;
1245
+ const { walletId: resolvedWalletId, shareSetId: resolvedShareSetId } = ceremony.completion;
1246
+ if (!rawPublicKey || !externalServerKeyShares || !resolvedWalletId) {
462
1247
  throw new Error(ERROR_KEYGEN_FAILED);
463
1248
  }
464
1249
  // Get EVM address from public key
465
1250
  const { accountAddress, publicKeyHex } = deriveAccountAddress({
466
1251
  rawPublicKey: rawPublicKey
467
1252
  });
468
- const externalKeySharesWithBackupStatus = await this.storeEncryptedBackupByWalletWithRetry({
1253
+ const chainConfig = getMPCChainConfig(this.chainName);
1254
+ const walletMetadata = {
1255
+ walletId: resolvedWalletId,
1256
+ accountAddress,
1257
+ chainName: this.chainName,
1258
+ thresholdSignatureScheme,
1259
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
1260
+ index,
1261
+ value
1262
+ ]))),
1263
+ shareSetId: resolvedShareSetId
1264
+ };
1265
+ const { keySharesWithBackupStatus, backupInfo } = await this.storeEncryptedBackupByWalletWithRetry({
469
1266
  accountAddress,
470
1267
  externalServerKeyShares,
471
1268
  password,
472
- backUpToClientShareService
1269
+ backUpToDynamic,
1270
+ walletMetadata
473
1271
  });
1272
+ walletMetadata.externalServerKeySharesBackupInfo = backupInfo;
1273
+ var _ceremony_completion_encryptedWalletApiKey;
474
1274
  return {
475
- walletId: this.walletMap[accountAddress].walletId,
476
- accountAddress,
1275
+ walletMetadata,
477
1276
  rawPublicKey,
478
1277
  publicKeyHex,
479
1278
  externalServerKeyShares,
480
- externalKeySharesWithBackupStatus
1279
+ externalKeySharesWithBackupStatus: keySharesWithBackupStatus,
1280
+ encryptedWalletApiKey: (_ceremony_completion_encryptedWalletApiKey = ceremony.completion.encryptedWalletApiKey) != null ? _ceremony_completion_encryptedWalletApiKey : undefined
481
1281
  };
482
1282
  } catch (error) {
483
- logError({
1283
+ logError$1({
484
1284
  message: ERROR_CREATE_WALLET_ACCOUNT,
485
1285
  error: error,
486
1286
  context: {}
487
1287
  });
488
- throw new Error(ERROR_CREATE_WALLET_ACCOUNT);
1288
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT, {
1289
+ cause: error
1290
+ });
489
1291
  }
490
1292
  }
491
- async signMessage({ message, accountAddress, password = undefined, externalServerKeyShares, context, onError }) {
1293
+ async signMessage({ message, walletMetadata, password = undefined, externalServerKeyShares, context, onError }) {
1294
+ const { accountAddress } = walletMetadata;
492
1295
  try {
493
1296
  if (!accountAddress) {
494
1297
  throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
495
1298
  }
496
- // Format the message for EVM signing
497
1299
  const formattedMessage = formatEVMMessage(message);
498
1300
  const resolvedContext = context != null ? context : {
499
1301
  evmMessage: message
500
1302
  };
501
- // Attempt to recover key shares from backup if not provided
502
- await this.ensureKeySharesRecovered({
503
- accountAddress,
504
- password,
505
- walletOperation: WalletOperation.SIGN_MESSAGE,
506
- externalServerKeyShares,
507
- errorMessage: keySharesRequiredFor('sign a message')
508
- });
509
1303
  const signatureEcdsa = await this.sign({
510
1304
  message: formattedMessage,
511
1305
  accountAddress: accountAddress,
@@ -513,33 +1307,28 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
513
1307
  password,
514
1308
  externalServerKeyShares,
515
1309
  context: resolvedContext,
516
- onError
1310
+ onError,
1311
+ walletMetadata
517
1312
  });
518
- // Serialize the signature
519
- const serializedSignature = serializeECDSASignature(signatureEcdsa);
520
- return serializedSignature;
1313
+ return serializeECDSASignature(signatureEcdsa);
521
1314
  } catch (error) {
522
- logError({
1315
+ logError$1({
523
1316
  message: ERROR_SIGN_MESSAGE,
524
1317
  error: error,
525
1318
  context: {
526
1319
  accountAddress
527
1320
  }
528
1321
  });
529
- throw new Error(ERROR_SIGN_MESSAGE);
1322
+ throw new Error(ERROR_SIGN_MESSAGE, {
1323
+ cause: error
1324
+ });
530
1325
  }
531
1326
  }
532
1327
  isSignAuthorizationSupported() {
533
1328
  return true;
534
1329
  }
535
- async signPrehashedMessage({ prehashed, accountAddress, password, externalServerKeyShares, context, onError, recoverErrorMessage }) {
536
- await this.ensureKeySharesRecovered({
537
- accountAddress,
538
- password,
539
- walletOperation: WalletOperation.SIGN_MESSAGE,
540
- externalServerKeyShares,
541
- errorMessage: recoverErrorMessage
542
- });
1330
+ async signPrehashedMessage({ prehashed, walletMetadata, password, externalServerKeyShares, context, onError }) {
1331
+ const { accountAddress } = walletMetadata;
543
1332
  const signatureEcdsa = await this.sign({
544
1333
  message: prehashed,
545
1334
  accountAddress: accountAddress,
@@ -548,11 +1337,13 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
548
1337
  externalServerKeyShares,
549
1338
  isFormatted: true,
550
1339
  context,
551
- onError
1340
+ onError,
1341
+ walletMetadata
552
1342
  });
553
1343
  return serializeECDSASignature(signatureEcdsa);
554
1344
  }
555
- async signAuthorization({ authorization, accountAddress, password = undefined, externalServerKeyShares, onError }) {
1345
+ async signAuthorization({ authorization, walletMetadata, password = undefined, externalServerKeyShares, onError }) {
1346
+ const { accountAddress } = walletMetadata;
556
1347
  try {
557
1348
  if (!accountAddress) {
558
1349
  throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
@@ -561,77 +1352,87 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
561
1352
  const prehashed = digest.startsWith('0x') ? digest.slice(2) : digest;
562
1353
  const serializedSignature = await this.signPrehashedMessage({
563
1354
  prehashed,
564
- accountAddress,
1355
+ walletMetadata,
565
1356
  password,
566
1357
  externalServerKeyShares,
567
1358
  context: {
568
1359
  eip7702Auth: authorization
569
1360
  },
570
- onError,
571
- recoverErrorMessage: keySharesRequiredFor('sign authorization')
1361
+ onError
572
1362
  });
573
1363
  return parseSignature(serializedSignature);
574
1364
  } catch (error) {
575
- logError({
1365
+ logError$1({
576
1366
  message: ERROR_SIGN_MESSAGE,
577
1367
  error: error,
578
1368
  context: {
579
1369
  accountAddress
580
1370
  }
581
1371
  });
582
- throw new Error(ERROR_SIGN_MESSAGE);
1372
+ throw new Error(ERROR_SIGN_MESSAGE, {
1373
+ cause: error
1374
+ });
583
1375
  }
584
1376
  }
585
- async signRawMessage({ message, accountAddress, password = undefined, externalServerKeyShares, context, onError }) {
1377
+ /**
1378
+ * Signs an already-hashed digest. Provide either `rawSign` — the pre-image the
1379
+ * digest comes from — or an explicit `context`, so a policy-enabled wallet can
1380
+ * evaluate the request.
1381
+ */ async signRawMessage({ message, walletMetadata, password = undefined, externalServerKeyShares, context, rawSign, onError }) {
1382
+ const { accountAddress } = walletMetadata;
586
1383
  try {
587
1384
  if (!accountAddress) {
588
1385
  throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
589
1386
  }
1387
+ const resolvedContext = resolveRawSignContext(context, rawSign);
590
1388
  return await this.signPrehashedMessage({
591
1389
  prehashed: stripHexPrefix(message),
592
- accountAddress,
1390
+ walletMetadata,
593
1391
  password,
594
1392
  externalServerKeyShares,
595
- context,
596
- onError,
597
- recoverErrorMessage: keySharesRequiredFor('sign a raw message')
1393
+ context: resolvedContext,
1394
+ onError
598
1395
  });
599
1396
  } catch (error) {
600
- logError({
1397
+ logError$1({
601
1398
  message: ERROR_SIGN_RAW_MESSAGE,
602
1399
  error: error,
603
1400
  context: {
604
1401
  accountAddress
605
1402
  }
606
1403
  });
607
- throw new Error(ERROR_SIGN_RAW_MESSAGE);
1404
+ throw new Error(ERROR_SIGN_RAW_MESSAGE, {
1405
+ cause: error
1406
+ });
608
1407
  }
609
1408
  }
610
- async signTypedData({ accountAddress, typedData, password = undefined, externalServerKeyShares, onError }) {
1409
+ async signTypedData({ walletMetadata, typedData, password = undefined, externalServerKeyShares, onError }) {
1410
+ const { accountAddress } = walletMetadata;
611
1411
  try {
612
1412
  if (!accountAddress) {
613
1413
  throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
614
1414
  }
615
1415
  return await this.signPrehashedMessage({
616
1416
  prehashed: formatTypedData(typedData),
617
- accountAddress,
1417
+ walletMetadata,
618
1418
  password,
619
1419
  externalServerKeyShares,
620
1420
  context: {
621
1421
  evmTypedData: typedData
622
1422
  },
623
- onError,
624
- recoverErrorMessage: keySharesRequiredFor('sign typed data')
1423
+ onError
625
1424
  });
626
1425
  } catch (error) {
627
- logError({
1426
+ logError$1({
628
1427
  message: ERROR_SIGN_TYPED_DATA,
629
1428
  error: error,
630
1429
  context: {
631
1430
  accountAddress
632
1431
  }
633
1432
  });
634
- throw new Error(ERROR_SIGN_TYPED_DATA);
1433
+ throw new Error(ERROR_SIGN_TYPED_DATA, {
1434
+ cause: error
1435
+ });
635
1436
  }
636
1437
  }
637
1438
  async verifyMessageSignature({ accountAddress, message, signature }) {
@@ -647,7 +1448,7 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
647
1448
  });
648
1449
  return verified;
649
1450
  } catch (error) {
650
- logError({
1451
+ logError$1({
651
1452
  message: ERROR_VERIFY_MESSAGE_SIGNATURE,
652
1453
  error: error,
653
1454
  context: {
@@ -657,31 +1458,25 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
657
1458
  throw new Error(ERROR_VERIFY_MESSAGE_SIGNATURE);
658
1459
  }
659
1460
  }
660
- async signTransaction({ senderAddress, transaction, password = undefined, externalServerKeyShares }) {
661
- await this.verifyPassword({
662
- accountAddress: senderAddress,
663
- password
664
- });
665
- // Attempt to recover key shares from backup if not provided
666
- await this.ensureKeySharesRecovered({
667
- accountAddress: senderAddress,
668
- password,
669
- walletOperation: WalletOperation.SIGN_TRANSACTION,
670
- externalServerKeyShares,
671
- errorMessage: keySharesRequiredFor('sign transaction')
672
- });
1461
+ async signTransaction({ walletMetadata, transaction, password = undefined, externalServerKeyShares, context }) {
1462
+ const { accountAddress } = walletMetadata;
673
1463
  const serializedTx = serializeTransaction(transaction);
674
1464
  const serializedTxBytes = Uint8Array.from(Buffer.from(serializedTx.slice(2), 'hex'));
675
1465
  if (!(serializedTxBytes instanceof Uint8Array)) {
676
- throw new Error('Invalid serializedTxBytes');
1466
+ throw new TypeError('Invalid serializedTxBytes');
677
1467
  }
678
1468
  // Get signature using MPC (this will coordinate with server party)
679
1469
  const signatureEcdsa = await this.sign({
680
1470
  message: serializedTxBytes,
681
- accountAddress: senderAddress,
1471
+ accountAddress,
682
1472
  chainName: this.chainName,
683
1473
  password,
684
- externalServerKeyShares
1474
+ externalServerKeyShares,
1475
+ walletMetadata,
1476
+ walletOperation: WalletOperation.SIGN_TRANSACTION,
1477
+ context: _extends({}, context, {
1478
+ evmTransaction: mapTransactionToEvmTransaction(transaction)
1479
+ })
685
1480
  });
686
1481
  if (!('r' in signatureEcdsa && 's' in signatureEcdsa && 'v' in signatureEcdsa)) {
687
1482
  throw new Error('Invalid signature format returned from MPC signing');
@@ -697,40 +1492,35 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
697
1492
  });
698
1493
  return serializedSignedTx;
699
1494
  } catch (error) {
700
- logError({
1495
+ logError$1({
701
1496
  message: 'Error signing transaction:',
702
1497
  error: error,
703
1498
  context: {
704
- senderAddress
1499
+ accountAddress
705
1500
  }
706
1501
  });
707
1502
  throw error;
708
1503
  }
709
1504
  }
710
- async exportPrivateKey({ accountAddress, password = undefined, externalServerKeyShares }) {
711
- await this.verifyPassword({
712
- accountAddress,
713
- password
714
- });
715
- // Attempt to recover key shares from backup if not provided
716
- await this.ensureKeySharesRecovered({
717
- accountAddress,
718
- password,
719
- walletOperation: WalletOperation.EXPORT_PRIVATE_KEY,
720
- externalServerKeyShares,
721
- errorMessage: keySharesRequiredFor('export private key')
722
- });
1505
+ async exportPrivateKey({ walletMetadata, password = undefined, externalServerKeyShares }) {
1506
+ const { accountAddress } = walletMetadata;
723
1507
  const { derivedPrivateKey } = await this.exportKey({
724
1508
  accountAddress,
725
1509
  chainName: this.chainName,
726
1510
  password,
727
- externalServerKeyShares
1511
+ externalServerKeyShares,
1512
+ walletMetadata
728
1513
  });
729
1514
  return {
730
1515
  derivedPrivateKey
731
1516
  };
732
1517
  }
733
- async offlineExportPrivateKey({ keyShares, derivationPath }) {
1518
+ /**
1519
+ * `derivationPath` is the JSON-serialized index map that
1520
+ * `walletMetadata.derivationPath` carries (e.g. `'{"0":44,"1":60,"2":0,"3":0,"4":0}'`
1521
+ * or `'[44,60,0,0,0]'`). BIP-32 strings such as `"m/44'/60'/0'/0/0"` are rejected.
1522
+ * Omit it to export without path derivation.
1523
+ */ async offlineExportPrivateKey({ keyShares, derivationPath }) {
734
1524
  const { derivedPrivateKey } = await this.offlineExportKey({
735
1525
  chainName: this.chainName,
736
1526
  keyShares,
@@ -747,37 +1537,28 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
747
1537
  * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet.
748
1538
  * @param password - The password to use for the wallet.
749
1539
  * @param onError - The function to call if an error occurs.
750
- * @param backUpToClientShareService - Whether to back up the external server key shares to the client share service. By default, it is false.
1540
+ * @param backUpToDynamic - Whether to back up the external server key shares to the client share service. By default, it is false.
751
1541
  * @returns The account address, public key, raw public key, external server key shares.
752
- */ async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password = undefined, backUpToClientShareService = false, onError }) {
1542
+ */ async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password, backUpToDynamic = false, onError }) {
1543
+ let resolvedWalletId;
1544
+ let resolvedShareSetId;
753
1545
  let ceremonyCeremonyCompleteResolver;
754
1546
  const ceremonyCompletePromise = new Promise((resolve)=>{
755
1547
  ceremonyCeremonyCompleteResolver = resolve;
756
1548
  });
757
- // TODO: validate private key for EVM
758
1549
  const { rawPublicKey, externalServerKeyShares } = await this.importRawPrivateKey({
759
1550
  chainName,
760
1551
  privateKey,
761
1552
  thresholdSignatureScheme,
762
- onCeremonyComplete: (accountAddress, walletId)=>{
763
- // update wallet map
764
- const checksumAddress = getAddress(accountAddress);
765
- const chainConfig = getMPCChainConfig(this.chainName);
766
- this.walletMap[checksumAddress] = _extends({}, this.walletMap[checksumAddress] || {}, {
767
- accountAddress: checksumAddress,
768
- walletId,
769
- chainName: this.chainName,
770
- thresholdSignatureScheme,
771
- derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
772
- index,
773
- value
774
- ]))),
775
- externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
776
- });
1553
+ password,
1554
+ backUpToDynamic,
1555
+ onCeremonyComplete: ({ walletId, shareSetId })=>{
1556
+ resolvedWalletId = walletId;
1557
+ resolvedShareSetId = shareSetId;
777
1558
  ceremonyCeremonyCompleteResolver(undefined);
778
1559
  },
779
1560
  onError: (e)=>{
780
- logError({
1561
+ logError$1({
781
1562
  message: 'importPrivateKey: onError',
782
1563
  error: e,
783
1564
  context: {}
@@ -785,45 +1566,286 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
785
1566
  onError == null ? void 0 : onError(e);
786
1567
  }
787
1568
  });
788
- // Wait for the ceremony to complete before proceeding
789
1569
  await ceremonyCompletePromise;
790
- if (!rawPublicKey || !externalServerKeyShares) {
1570
+ if (!rawPublicKey || !externalServerKeyShares || !resolvedWalletId) {
791
1571
  throw new Error('Error creating wallet account');
792
1572
  }
793
1573
  const { accountAddress, publicKeyHex } = deriveAccountAddress({
794
1574
  rawPublicKey: rawPublicKey
795
1575
  });
796
- const externalKeySharesWithBackupStatus = await this.storeEncryptedBackupByWalletWithRetry({
1576
+ const chainConfig = getMPCChainConfig(this.chainName);
1577
+ const walletMetadata = {
1578
+ walletId: resolvedWalletId,
1579
+ accountAddress,
1580
+ chainName: this.chainName,
1581
+ thresholdSignatureScheme,
1582
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
1583
+ index,
1584
+ value
1585
+ ]))),
1586
+ shareSetId: resolvedShareSetId
1587
+ };
1588
+ const { keySharesWithBackupStatus, backupInfo } = await this.storeEncryptedBackupByWalletWithRetry({
797
1589
  accountAddress,
798
1590
  externalServerKeyShares,
799
1591
  password,
800
- backUpToClientShareService
1592
+ backUpToDynamic,
1593
+ walletMetadata
801
1594
  });
1595
+ walletMetadata.externalServerKeySharesBackupInfo = backupInfo;
802
1596
  return {
803
- accountAddress,
1597
+ walletMetadata,
804
1598
  rawPublicKey,
805
1599
  publicKeyHex,
806
1600
  externalServerKeyShares,
807
- externalKeySharesWithBackupStatus
1601
+ externalKeySharesWithBackupStatus: keySharesWithBackupStatus
808
1602
  };
809
1603
  }
810
- async getEvmWallets() {
811
- const wallets = await this.getWallets();
1604
+ /** @deprecated Use getWalletByAddress instead for better performance */ async getEvmWallets() {
1605
+ // Calling the deprecated getWallets() is the point of this shim, and it is
1606
+ // public and overridable, so routing around it would drop a consumer's override.
1607
+ const wallets = await this.getWallets(); // NOSONAR
812
1608
  const evmWallets = wallets.filter((wallet)=>wallet.chainName === 'EVM');
813
1609
  return evmWallets;
814
1610
  }
815
- constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug, enableMPCAccelerator, logger }){
1611
+ // ---------------------------------------------------------------------------
1612
+ // EVM gasless (Fireblocks-relayer native gasless via EIP-7702 / AuthorizedExecutions)
1613
+ // ---------------------------------------------------------------------------
1614
+ get evmGasless() {
1615
+ return createEvmGaslessClient({
1616
+ apiClient: this.apiClient,
1617
+ createViemPublicClient: (args)=>this.createViemPublicClient(args),
1618
+ signAuthorization: (args)=>this.signAuthorization(args),
1619
+ signTypedData: (args)=>this.signTypedData(args)
1620
+ });
1621
+ }
1622
+ /**
1623
+ * Checks whether the given wallet address has an active EIP-7702 delegation
1624
+ * to the Universal Gasless Delegate (UGD) contract.
1625
+ */ async is7702DelegationActive(params) {
1626
+ return this.evmGasless.is7702DelegationActive(params);
1627
+ }
1628
+ /**
1629
+ * Signs an EIP-7702 authorization that delegates the EOA to the UGD contract.
1630
+ * The EOA nonce is fetched from the chain unless explicitly provided.
1631
+ */ async sign7702Authorization(params) {
1632
+ return this.evmGasless.sign7702Authorization(params);
1633
+ }
1634
+ /**
1635
+ * Fetches the available gasless relayer address for a given chain.
1636
+ */ async getAvailableEvmGaslessRelayer(params) {
1637
+ return this.evmGasless.getAvailableEvmGaslessRelayer(params);
1638
+ }
1639
+ /**
1640
+ * Signs a sponsored transaction intent: resolves 7702 authorization, generates
1641
+ * a bitmap nonce, fetches the relayer, and MPC-signs the EIP-712 typed data.
1642
+ */ async signSponsoredTransaction(params) {
1643
+ return this.evmGasless.signSponsoredTransaction(params);
1644
+ }
1645
+ /**
1646
+ * Returns the current status of an EVM sponsored transaction relay request.
1647
+ */ async getEVMSponsoredTransactionStatus(params) {
1648
+ return this.evmGasless.getEVMSponsoredTransactionStatus(params);
1649
+ }
1650
+ /**
1651
+ * Relays a sponsored transaction to the Dynamic API.
1652
+ * Accepts either a pre-signed transaction or parameters to sign first.
1653
+ */ async relaySponsoredTransaction(params) {
1654
+ return this.evmGasless.relaySponsoredTransaction(params);
1655
+ }
1656
+ /**
1657
+ * Relay then poll to completion. Fixed 60s/2s default (matches js-sdk).
1658
+ * For a custom timeout, use relaySponsoredTransaction + waitForSponsoredTransaction.
1659
+ */ async sendSponsoredTransaction(params) {
1660
+ return this.evmGasless.sendSponsoredTransaction(params);
1661
+ }
1662
+ /**
1663
+ * Polls the relay status until a terminal state (success or failure) is reached.
1664
+ */ async waitForSponsoredTransaction(params) {
1665
+ return this.evmGasless.waitForSponsoredTransaction(params);
1666
+ }
1667
+ // ---------------------------------------------------------------------------
1668
+ // Earn (yield vaults)
1669
+ // ---------------------------------------------------------------------------
1670
+ get evmEarn() {
1671
+ return createEvmEarnClient({
1672
+ getEarnClient: ()=>this.earn,
1673
+ createViemPublicClient: (args)=>this.createViemPublicClient(args),
1674
+ getWalletClient: (args)=>this.getWalletClient(args),
1675
+ sendSponsoredTransaction: (args)=>this.sendSponsoredTransaction(args)
1676
+ });
1677
+ }
1678
+ /**
1679
+ * Executes an Earn signing payload returned by the prepare* methods, sending the
1680
+ * ERC-20 approval first when the vault requires one.
1681
+ */ async executeEarnTransaction(params) {
1682
+ return this.evmEarn.executeEarnTransaction(params);
1683
+ }
1684
+ /** Prepares and executes a deposit into an Earn vault. */ async depositToEarnVault(params) {
1685
+ return this.evmEarn.depositToEarnVault(params);
1686
+ }
1687
+ /** Prepares and executes a withdrawal from an Earn vault. */ async withdrawFromEarnVault(params) {
1688
+ return this.evmEarn.withdrawFromEarnVault(params);
1689
+ }
1690
+ /** Prepares and executes a claim of accrued Earn vault rewards. */ async claimEarnRewards(params) {
1691
+ return this.evmEarn.claimEarnRewards(params);
1692
+ }
1693
+ constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, baseClientKeysharesRelayApiUrl, debug, enableMPCAccelerator, logger, requestSigning }){
816
1694
  super({
817
1695
  environmentId,
818
1696
  baseApiUrl,
819
1697
  baseMPCRelayApiUrl,
1698
+ baseClientKeysharesRelayApiUrl,
820
1699
  debug,
821
1700
  enableMPCAccelerator,
822
- logger
1701
+ logger,
1702
+ requestSigning
823
1703
  }), this.chainName = 'EVM';
824
1704
  }
825
1705
  }
826
1706
 
1707
+ const logError = createLogError('node-evm');
1708
+ const ERROR_DELEGATED_GASLESS_CREDENTIALS_REQUIRED = 'Delegated key share, wallet ID, and wallet API key are required to sponsor a transaction';
1709
+ const ERROR_DELEGATED_GASLESS_USER_ID_REQUIRED = 'userId is required — a delegated wallet is always owned by an end user, so a sponsored transaction cannot be attributed to the calling service';
1710
+ const createViemPublicClient = ({ chain, rpcUrl })=>createPublicClient({
1711
+ chain,
1712
+ transport: http(rpcUrl)
1713
+ });
1714
+ const signerArgs = ({ keyShare, onError, shareSetId, walletApiKey, walletId })=>({
1715
+ keyShare,
1716
+ onError,
1717
+ shareSetId,
1718
+ walletApiKey,
1719
+ walletId
1720
+ });
1721
+ const gaslessFor = (client, apiClient, wallet)=>createEvmGaslessClient({
1722
+ apiClient,
1723
+ createViemPublicClient,
1724
+ signAuthorization: ({ authorization })=>delegatedSignAuthorization(client, _extends({}, signerArgs(wallet), {
1725
+ authorization
1726
+ })),
1727
+ signTypedData: ({ typedData })=>delegatedSignTypedData(client, _extends({}, signerArgs(wallet), {
1728
+ typedData
1729
+ }))
1730
+ });
1731
+ const walletRef = ({ walletAddress })=>({
1732
+ accountAddress: walletAddress
1733
+ });
1734
+ const assertDelegatedWallet = (wallet)=>{
1735
+ if (!wallet.keyShare || !wallet.walletId || !wallet.walletApiKey) {
1736
+ throw new Error(ERROR_DELEGATED_GASLESS_CREDENTIALS_REQUIRED);
1737
+ }
1738
+ if (!wallet.userId) {
1739
+ throw new Error(ERROR_DELEGATED_GASLESS_USER_ID_REQUIRED);
1740
+ }
1741
+ };
1742
+ const splitWallet = (params)=>{
1743
+ const { keyShare, onError, shareSetId, userId, walletAddress, walletApiKey, walletId } = params, intent = _object_without_properties_loose(params, [
1744
+ "keyShare",
1745
+ "onError",
1746
+ "shareSetId",
1747
+ "userId",
1748
+ "walletAddress",
1749
+ "walletApiKey",
1750
+ "walletId"
1751
+ ]);
1752
+ return {
1753
+ intent,
1754
+ wallet: {
1755
+ keyShare,
1756
+ onError,
1757
+ shareSetId,
1758
+ userId,
1759
+ walletAddress,
1760
+ walletApiKey,
1761
+ walletId
1762
+ }
1763
+ };
1764
+ };
1765
+ /**
1766
+ * Signs an EIP-7702 authorization delegating the end user's EOA to the UGD
1767
+ * contract, using the customer-held key share.
1768
+ */ const delegatedSign7702Authorization = async (client, params)=>{
1769
+ const { chainId, nonce, rpcUrl } = params, wallet = _object_without_properties_loose(params, [
1770
+ "chainId",
1771
+ "nonce",
1772
+ "rpcUrl"
1773
+ ]);
1774
+ assertDelegatedWallet(wallet);
1775
+ try {
1776
+ // The EOA nonce comes from the RPC and the signature from the delegated MPC
1777
+ // room, so this path makes no Dynamic-authenticated call.
1778
+ return await gaslessFor(client, client.createApiClient(), wallet).sign7702Authorization({
1779
+ chainId,
1780
+ nonce,
1781
+ rpcUrl,
1782
+ walletMetadata: walletRef(wallet)
1783
+ });
1784
+ } catch (error) {
1785
+ logError({
1786
+ message: 'Error in delegatedSign7702Authorization',
1787
+ error: error,
1788
+ context: {
1789
+ walletId: wallet.walletId
1790
+ }
1791
+ });
1792
+ throw error;
1793
+ }
1794
+ };
1795
+ /**
1796
+ * Signs the EIP-712 AuthorizedExecutions intent for a batch of calls, resolving
1797
+ * a first-use 7702 authorization along the way when the wallet is not yet delegated.
1798
+ *
1799
+ * The returned payload can be relayed later with `sendSponsoredTransaction` on a
1800
+ * `DynamicEvmWalletClient`, which needs no key share to submit an already-signed intent.
1801
+ */ const delegatedSignSponsoredTransaction = async (client, params)=>{
1802
+ const { intent, wallet } = splitWallet(params);
1803
+ assertDelegatedWallet(wallet);
1804
+ try {
1805
+ return await withDelegatedServerAuth(client, (apiClient)=>gaslessFor(client, apiClient, wallet).signSponsoredTransaction(_extends({}, intent, {
1806
+ walletMetadata: walletRef(wallet)
1807
+ })));
1808
+ } catch (error) {
1809
+ logError({
1810
+ message: 'Error in delegatedSignSponsoredTransaction',
1811
+ error: error,
1812
+ context: {
1813
+ walletId: wallet.walletId
1814
+ }
1815
+ });
1816
+ throw error;
1817
+ }
1818
+ };
1819
+ /**
1820
+ * Signs, relays, and waits for a sponsored transaction on behalf of the wallet's
1821
+ * owner, resolving once the relayer reports an on-chain hash.
1822
+ */ const delegatedSendSponsoredTransaction = async (client, params)=>{
1823
+ const { intent, wallet } = splitWallet(params);
1824
+ assertDelegatedWallet(wallet);
1825
+ try {
1826
+ // Relaying and polling each take their own server-auth JWT. Sharing one would
1827
+ // put the whole poll window inside a single retry scope, so a 401 on a late
1828
+ // poll would replay the relay and sponsor the transaction twice.
1829
+ const { requestId } = await withDelegatedServerAuth(client, (apiClient)=>gaslessFor(client, apiClient, wallet).relaySponsoredTransaction(_extends({}, intent, {
1830
+ userId: wallet.userId,
1831
+ walletMetadata: walletRef(wallet)
1832
+ })));
1833
+ return await withDelegatedServerAuth(client, (apiClient)=>gaslessFor(client, apiClient, wallet).waitForSponsoredTransaction({
1834
+ requestId,
1835
+ traceContext: intent.traceContext
1836
+ }));
1837
+ } catch (error) {
1838
+ logError({
1839
+ message: 'Error in delegatedSendSponsoredTransaction',
1840
+ error: error,
1841
+ context: {
1842
+ walletId: wallet.walletId
1843
+ }
1844
+ });
1845
+ throw error;
1846
+ }
1847
+ };
1848
+
827
1849
  const getJwtExpiration = (jwt)=>{
828
1850
  if (!jwt) {
829
1851
  return 0;
@@ -889,7 +1911,7 @@ class DynamicEvmZeroDevClient {
889
1911
  async createKernelClientForAddress(options) {
890
1912
  const viemSigner = createAccountAdapter({
891
1913
  evmClient: this.evmClient,
892
- accountAddress: options.address,
1914
+ walletMetadata: options.walletMetadata,
893
1915
  password: options.password,
894
1916
  externalServerKeyShares: options.externalServerKeyShares,
895
1917
  delegated: options.delegated
@@ -1007,4 +2029,4 @@ const createZerodevClient = async (evmClient)=>{
1007
2029
  return client;
1008
2030
  };
1009
2031
 
1010
- export { DynamicEvmWalletClient, ERROR_ACCOUNT_ADDRESS_REQUIRED, ERROR_CREATE_WALLET_ACCOUNT, ERROR_KEYGEN_FAILED, ERROR_SIGN_MESSAGE, ERROR_SIGN_RAW_MESSAGE, ERROR_SIGN_TYPED_DATA, ERROR_VERIFY_MESSAGE_SIGNATURE, EVM_SIGN_MESSAGE_PREFIX, createAccountAdapter, createDelegatedEvmWalletClient, createZerodevClient, delegatedSignAuthorization, delegatedSignMessage, delegatedSignRawMessage, delegatedSignTransaction, delegatedSignTypedData, deriveAccountAddress, formatEVMMessage, formatTypedData, revokeDelegation, serializeECDSASignature };
2032
+ export { AUTHORIZED_EXECUTIONS_TYPES, BATCH_CALL_OPDATA_AUTH_MODE, DEFAULT_VALID_FOR_SECONDS, DELEGATION_CODE_PREFIX, DELEGATION_CONTRACT_ADDRESS, DynamicEvmWalletClient, ERROR_ACCOUNT_ADDRESS_REQUIRED, ERROR_CREATE_WALLET_ACCOUNT, ERROR_DELEGATED_GASLESS_CREDENTIALS_REQUIRED, ERROR_DELEGATED_GASLESS_USER_ID_REQUIRED, ERROR_EARN_APPROVAL_FAILED, ERROR_EARN_CHAIN_MISMATCH, ERROR_EARN_CHAIN_REQUIRED, ERROR_EARN_MISSING_EVM_TRANSACTION, ERROR_EARN_NOT_EVM_WALLET, ERROR_GASLESS_MISSING_REQUEST_ID, ERROR_GASLESS_MISSING_YPARITY, ERROR_GASLESS_RELAY_FAILED, ERROR_GASLESS_RPC_REQUIRED, ERROR_GASLESS_RPC_REQUIRED_FOR_AUTO_DELEGATE, ERROR_GASLESS_TIMEOUT, ERROR_KEYGEN_FAILED, ERROR_SIGN_MESSAGE, ERROR_SIGN_RAW_MESSAGE, ERROR_SIGN_TYPED_DATA, ERROR_VERIFY_MESSAGE_SIGNATURE, EVM_GASLESS_DEFAULT_POLL_INTERVAL_MS, EVM_GASLESS_DEFAULT_TIMEOUT_MS, EVM_SIGN_MESSAGE_PREFIX, UGD_ABI, createAccountAdapter, createDelegatedEvmWalletClient, createEvmEarnClient, createZerodevClient, delegatedSendSponsoredTransaction, delegatedSign7702Authorization, delegatedSignAuthorization, delegatedSignMessage, delegatedSignRawMessage, delegatedSignSponsoredTransaction, delegatedSignTransaction, delegatedSignTypedData, deriveAccountAddress, formatEVMMessage, formatTypedData, mapTransactionToEvmTransaction, revokeDelegation, serializeECDSASignature };