@dynamic-labs-wallet/node-evm 0.0.0-preview.114.4 → 0.0.1-paolo-1

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,6 +1,19 @@
1
- import { MessageHash, DynamicWalletClient, getExternalServerKeyShareBackupInfo, WalletOperation } from '@dynamic-labs-wallet/node';
2
- import { getAddress, serializeSignature, createPublicClient, http, serializeTransaction } from 'viem';
1
+ import { toAccount } from 'viem/accounts';
2
+ import { MessageHash, createDelegatedWalletClient, delegatedSignMessage as delegatedSignMessage$1, revokeDelegation as revokeDelegation$1, DynamicWalletClient, getMPCChainConfig, getExternalServerKeyShareBackupInfo, WalletOperation } from '@dynamic-labs-wallet/node';
3
+ import { stringToHex, bytesToHex, size, concat, hashTypedData, serializeSignature, getAddress, serializeTransaction, parseSignature, createPublicClient, http, defineChain, createWalletClient } from 'viem';
4
+ import { hashAuthorization } from 'viem/utils';
5
+ import { Logger } from '@dynamic-labs/logger';
6
+ import { AxiosError } from 'axios';
7
+ import { handleAxiosError } from '@dynamic-labs-wallet/core';
3
8
  import { mainnet } from 'viem/chains';
9
+ import { initializeClient, refreshUser, getNetworksData, createDynamicClient } from '@dynamic-labs-sdk/client';
10
+ import { assertDefined } from '@dynamic-labs-sdk/client/core';
11
+ import { mapNetworkDataToViemChain } from '@dynamic-labs-sdk/evm/viem';
12
+ import { addWaasEvmExtension } from '@dynamic-labs-sdk/evm/waas';
13
+ import { addZerodevExtension } from '@dynamic-labs-sdk/zerodev';
14
+ import { getZerodevRpc, getPaymasterConfig, getZerodevProviderFromSettings, getEntryPoint, getKernelVersion, getEcdsaValidator } from '@dynamic-labs-sdk/zerodev/core';
15
+ import { createEcdsaKernelMigrationAccount } from '@zerodev/ecdsa-validator';
16
+ import { createKernelAccountClient, getUserOperationGasPrice, createKernelAccount, constants } from '@zerodev/sdk';
4
17
 
5
18
  function _extends() {
6
19
  _extends = Object.assign || function assign(target) {
@@ -18,11 +31,24 @@ const EVM_SIGN_MESSAGE_PREFIX = `\x19Ethereum Signed Message:\n`;
18
31
  const ERROR_KEYGEN_FAILED = 'Error with keygen';
19
32
  const ERROR_CREATE_WALLET_ACCOUNT = 'Error creating evm wallet account';
20
33
  const ERROR_SIGN_MESSAGE = 'Error signing message';
34
+ const ERROR_SIGN_TYPED_DATA = 'Error signing typed data';
21
35
  const ERROR_ACCOUNT_ADDRESS_REQUIRED = 'Account address is required';
22
36
  const ERROR_VERIFY_MESSAGE_SIGNATURE = 'Error verifying message signature';
23
37
 
24
- const formatEVMMessage = (message)=>{
25
- return `${EVM_SIGN_MESSAGE_PREFIX}${message.length}${message}`;
38
+ const formatEVMMessage = (message_)=>{
39
+ const message = (()=>{
40
+ if (typeof message_ === 'string') return stringToHex(message_);
41
+ if (typeof message_.raw === 'string') return message_.raw;
42
+ return bytesToHex(message_.raw);
43
+ })();
44
+ const prefix = stringToHex(`${EVM_SIGN_MESSAGE_PREFIX}${size(message)}`);
45
+ return concat([
46
+ prefix,
47
+ message
48
+ ]);
49
+ };
50
+ const formatTypedData = (typedData)=>{
51
+ return hashTypedData(typedData).slice(2);
26
52
  };
27
53
  const serializeECDSASignature = (signature)=>{
28
54
  return serializeSignature({
@@ -44,32 +70,373 @@ const deriveAccountAddress = ({ rawPublicKey })=>{
44
70
  };
45
71
  };
46
72
 
73
+ const logger = new Logger('DynamicWaasWalletClient');
74
+ const logError = ({ message, error, context })=>{
75
+ if (error instanceof AxiosError) {
76
+ handleAxiosError(error, message, context, logger);
77
+ }
78
+ logger.error('[DynamicWaasWalletClient] Error in node-evm client', {
79
+ error: error instanceof Error ? error.message : String(error),
80
+ context
81
+ });
82
+ };
83
+
84
+ /**
85
+ * Creates a delegated EVM wallet client for functional operations
86
+ */ const createDelegatedEvmWalletClient = ({ environmentId, baseApiUrl, baseMPCRelayApiUrl, apiKey, debug = false })=>{
87
+ const baseClient = createDelegatedWalletClient({
88
+ environmentId,
89
+ baseApiUrl,
90
+ baseMPCRelayApiUrl,
91
+ apiKey,
92
+ debug
93
+ });
94
+ const evmClient = _extends({}, baseClient, {
95
+ chainName: 'EVM'
96
+ });
97
+ return evmClient;
98
+ };
99
+ /**
100
+ * Signs a message using delegated signing for EVM
101
+ */ const delegatedSignMessage = async (client, { walletId, walletApiKey, keyShare, message, context, onError })=>{
102
+ try {
103
+ if (!keyShare || !walletId || !walletApiKey) {
104
+ throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign a message');
105
+ }
106
+ const formattedMessage = formatEVMMessage(message);
107
+ const resolvedContext = context != null ? context : {
108
+ evmMessage: message
109
+ };
110
+ const signatureEcdsa = await delegatedSignMessage$1(client, {
111
+ walletId,
112
+ walletApiKey,
113
+ keyShare,
114
+ message: formattedMessage,
115
+ chainName: client.chainName,
116
+ context: resolvedContext,
117
+ onError
118
+ });
119
+ const serializedSignature = serializeECDSASignature(signatureEcdsa);
120
+ return serializedSignature;
121
+ } catch (error) {
122
+ logError({
123
+ message: 'Error in delegatedSignMessage',
124
+ error: error,
125
+ context: {
126
+ walletId
127
+ }
128
+ });
129
+ throw error;
130
+ }
131
+ };
132
+ /**
133
+ * Signs a transaction using delegated signing for EVM
134
+ */ const delegatedSignTransaction = async (client, { walletId, walletApiKey, keyShare, transaction })=>{
135
+ try {
136
+ // Serialize the transaction
137
+ const serializedTx = serializeTransaction(transaction);
138
+ const serializedTxBytes = Uint8Array.from(Buffer.from(serializedTx.slice(2), 'hex'));
139
+ if (!(serializedTxBytes instanceof Uint8Array)) {
140
+ throw new Error('Invalid serializedTxBytes');
141
+ }
142
+ // Use the delegated sign message function from node package
143
+ const signatureEcdsa = await delegatedSignMessage$1(client, {
144
+ walletId,
145
+ walletApiKey,
146
+ keyShare,
147
+ message: serializedTxBytes,
148
+ chainName: client.chainName
149
+ });
150
+ if (!('r' in signatureEcdsa && 's' in signatureEcdsa && 'v' in signatureEcdsa)) {
151
+ throw new Error('Invalid signature format returned from MPC signing');
152
+ }
153
+ // Construct the signed transaction
154
+ const r = `0x${Buffer.from(signatureEcdsa.r).toString('hex')}`;
155
+ const s = `0x${Buffer.from(signatureEcdsa.s).toString('hex')}`;
156
+ const v = BigInt(signatureEcdsa.v);
157
+ const signedTx = _extends({}, transaction, {
158
+ r: r,
159
+ s: s,
160
+ v: v
161
+ });
162
+ const serializedSignedTx = serializeTransaction(signedTx);
163
+ return serializedSignedTx;
164
+ } catch (error) {
165
+ logError({
166
+ message: 'Error in delegatedSignTransaction',
167
+ error: error,
168
+ context: {
169
+ walletId
170
+ }
171
+ });
172
+ throw error;
173
+ }
174
+ };
175
+ /**
176
+ * Signs typed data using delegated signing for EVM
177
+ */ const delegatedSignTypedData = async (client, { walletId, walletApiKey, keyShare, typedData })=>{
178
+ try {
179
+ if (!keyShare || !walletId || !walletApiKey) {
180
+ throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign typed data');
181
+ }
182
+ const formattedTypedData = formatTypedData(typedData);
183
+ const signatureEcdsa = await delegatedSignMessage$1(client, {
184
+ walletId,
185
+ walletApiKey,
186
+ keyShare,
187
+ message: formattedTypedData,
188
+ chainName: client.chainName,
189
+ isFormatted: true,
190
+ context: {
191
+ evmTypedData: typedData
192
+ }
193
+ });
194
+ const serializedSignature = serializeECDSASignature(signatureEcdsa);
195
+ return serializedSignature;
196
+ } catch (error) {
197
+ logError({
198
+ message: 'Error in delegatedSignTypedData',
199
+ error: error,
200
+ context: {
201
+ walletId
202
+ }
203
+ });
204
+ throw error;
205
+ }
206
+ };
207
+ /**
208
+ * Signs EIP-7702 authorization using delegated signing for EVM
209
+ */ const delegatedSignAuthorization = async (client, { walletId, walletApiKey, keyShare, authorization })=>{
210
+ try {
211
+ if (!keyShare || !walletId || !walletApiKey) {
212
+ throw new Error('Delegated key share, wallet ID, and wallet API key are required to sign authorization');
213
+ }
214
+ const digest = hashAuthorization(authorization);
215
+ const prehashed = digest.startsWith('0x') ? digest.slice(2) : digest;
216
+ const signatureEcdsa = await delegatedSignMessage$1(client, {
217
+ walletId,
218
+ walletApiKey,
219
+ keyShare,
220
+ message: prehashed,
221
+ chainName: client.chainName,
222
+ isFormatted: true,
223
+ context: {
224
+ eip7702Auth: authorization
225
+ }
226
+ });
227
+ const serializedSignature = serializeECDSASignature(signatureEcdsa);
228
+ const signature = parseSignature(serializedSignature);
229
+ return signature;
230
+ } catch (error) {
231
+ logError({
232
+ message: 'Error in delegatedSignAuthorization',
233
+ error: error,
234
+ context: {
235
+ walletId
236
+ }
237
+ });
238
+ throw error;
239
+ }
240
+ };
241
+ /**
242
+ * Revoke delegation - delegates to the node package
243
+ */ const revokeDelegation = async (client, params)=>{
244
+ return revokeDelegation$1(client, params);
245
+ };
246
+
247
+ const createAccountAdapter = ({ evmClient, accountAddress, password, externalServerKeyShares, delegated })=>{
248
+ return toAccount({
249
+ address: accountAddress,
250
+ signMessage: async ({ message })=>{
251
+ if (delegated) {
252
+ return delegatedSignMessage(delegated.delegatedClient, {
253
+ walletId: delegated.walletId,
254
+ walletApiKey: delegated.walletApiKey,
255
+ keyShare: delegated.keyShare,
256
+ message: message
257
+ });
258
+ }
259
+ const signature = await evmClient.signMessage({
260
+ message: message,
261
+ accountAddress,
262
+ password,
263
+ externalServerKeyShares
264
+ });
265
+ return signature;
266
+ },
267
+ signTypedData: async (typedData)=>{
268
+ if (delegated) {
269
+ return delegatedSignTypedData(delegated.delegatedClient, {
270
+ walletId: delegated.walletId,
271
+ walletApiKey: delegated.walletApiKey,
272
+ keyShare: delegated.keyShare,
273
+ typedData: typedData
274
+ });
275
+ }
276
+ return evmClient.signTypedData({
277
+ accountAddress,
278
+ typedData: typedData,
279
+ password: password,
280
+ externalServerKeyShares
281
+ });
282
+ },
283
+ signTransaction: async (transaction)=>{
284
+ if (delegated) {
285
+ return delegatedSignTransaction(delegated.delegatedClient, {
286
+ walletId: delegated.walletId,
287
+ walletApiKey: delegated.walletApiKey,
288
+ keyShare: delegated.keyShare,
289
+ transaction
290
+ });
291
+ }
292
+ const signedTx = await evmClient.signTransaction({
293
+ senderAddress: accountAddress,
294
+ transaction,
295
+ password,
296
+ externalServerKeyShares
297
+ });
298
+ return signedTx;
299
+ },
300
+ signAuthorization: async (authorization)=>{
301
+ if (delegated) {
302
+ const signature = await delegatedSignAuthorization(delegated.delegatedClient, {
303
+ walletId: delegated.walletId,
304
+ walletApiKey: delegated.walletApiKey,
305
+ keyShare: delegated.keyShare,
306
+ authorization
307
+ });
308
+ var _authorization_address;
309
+ const signedAuthorization = {
310
+ address: (_authorization_address = authorization.address) != null ? _authorization_address : authorization.contractAddress,
311
+ chainId: authorization.chainId,
312
+ nonce: authorization.nonce,
313
+ r: signature.r,
314
+ s: signature.s,
315
+ v: signature.v,
316
+ yParity: signature.yParity
317
+ };
318
+ return signedAuthorization;
319
+ }
320
+ const signature = await evmClient.signAuthorization({
321
+ authorization,
322
+ accountAddress,
323
+ password,
324
+ externalServerKeyShares
325
+ });
326
+ var _authorization_address1;
327
+ const signedAuthorization = {
328
+ address: (_authorization_address1 = authorization.address) != null ? _authorization_address1 : authorization.contractAddress,
329
+ chainId: authorization.chainId,
330
+ nonce: authorization.nonce,
331
+ r: signature.r,
332
+ s: signature.s,
333
+ v: signature.v,
334
+ yParity: signature.yParity
335
+ };
336
+ return signedAuthorization;
337
+ }
338
+ });
339
+ };
340
+
47
341
  class DynamicEvmWalletClient extends DynamicWalletClient {
342
+ get jwtAuthToken() {
343
+ return this.baseJWTAuthToken;
344
+ }
345
+ get apiUrl() {
346
+ var _this_baseApiUrl;
347
+ return (_this_baseApiUrl = this.baseApiUrl) != null ? _this_baseApiUrl : 'https://app.dynamicauth.com';
348
+ }
48
349
  createViemPublicClient({ chain, rpcUrl }) {
49
350
  return createPublicClient({
50
351
  chain,
51
352
  transport: http(rpcUrl)
52
353
  });
53
354
  }
54
- async createWalletAccount({ thresholdSignatureScheme, password = undefined, onError }) {
355
+ async getWalletClient({ accountAddress, password, externalServerKeyShares, chain, chainId, rpcUrl }) {
356
+ const account = createAccountAdapter({
357
+ evmClient: this,
358
+ accountAddress: accountAddress,
359
+ password,
360
+ externalServerKeyShares
361
+ });
362
+ let viemChain;
363
+ if (chain) {
364
+ viemChain = chain;
365
+ } else if (chainId) {
366
+ if (!rpcUrl) {
367
+ throw new Error('rpcUrl is required when providing chainId. Please provide a valid RPC URL for the chain.');
368
+ }
369
+ viemChain = defineChain({
370
+ id: chainId,
371
+ name: `Chain ${chainId}`,
372
+ nativeCurrency: {
373
+ name: 'Ether',
374
+ symbol: 'ETH',
375
+ decimals: 18
376
+ },
377
+ rpcUrls: {
378
+ default: {
379
+ http: [
380
+ rpcUrl
381
+ ]
382
+ }
383
+ }
384
+ });
385
+ } else {
386
+ viemChain = mainnet;
387
+ }
388
+ return createWalletClient({
389
+ account,
390
+ chain: viemChain,
391
+ transport: http(rpcUrl)
392
+ });
393
+ }
394
+ /**
395
+ * Creates a new wallet account and stores the key shares in the wallet map.
396
+ * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet.
397
+ * @param password - The password to use for the wallet.
398
+ * @param onError - The function to call if an error occurs.
399
+ * @param backUpToClientShareService - Whether to back up the external server key shares to the client share service. By default, it is false.
400
+ * @returns The account address, public key, raw public key, external server key shares, and wallet id.
401
+ */ async createWalletAccount({ thresholdSignatureScheme, password = undefined, onError, backUpToClientShareService = false }) {
55
402
  try {
403
+ let ceremonyCeremonyCompleteResolver;
404
+ const ceremonyCompletePromise = new Promise((resolve)=>{
405
+ ceremonyCeremonyCompleteResolver = resolve;
406
+ });
56
407
  // Generate key shares for given threshold signature scheme (TSS)
57
408
  const { rawPublicKey, externalServerKeyShares } = await this.keyGen({
58
409
  chainName: this.chainName,
59
410
  thresholdSignatureScheme,
411
+ skipLock: true,
60
412
  onError,
61
413
  onCeremonyComplete: (accountAddress, walletId)=>{
62
414
  // update wallet map
63
415
  const checksumAddress = getAddress(accountAddress);
416
+ const chainConfig = getMPCChainConfig(this.chainName);
64
417
  this.walletMap[checksumAddress] = _extends({}, this.walletMap[checksumAddress] || {}, {
65
418
  accountAddress: checksumAddress,
66
419
  walletId,
67
420
  chainName: this.chainName,
68
421
  thresholdSignatureScheme,
422
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
423
+ index,
424
+ value
425
+ ]))),
69
426
  externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
70
427
  });
428
+ this.logger.debug('walletMap updated for wallet', {
429
+ context: {
430
+ accountAddress,
431
+ walletId,
432
+ walletMap: this.walletMap
433
+ }
434
+ });
435
+ ceremonyCeremonyCompleteResolver(undefined);
71
436
  }
72
437
  });
438
+ // Wait for the ceremony to complete before proceeding
439
+ await ceremonyCompletePromise;
73
440
  if (!rawPublicKey || !externalServerKeyShares) {
74
441
  throw new Error(ERROR_KEYGEN_FAILED);
75
442
  }
@@ -77,53 +444,152 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
77
444
  const { accountAddress, publicKeyHex } = deriveAccountAddress({
78
445
  rawPublicKey: rawPublicKey
79
446
  });
80
- void this.storeEncryptedBackupByWalletWithRetry({
447
+ await this.storeEncryptedBackupByWalletWithRetry({
81
448
  accountAddress,
82
449
  externalServerKeyShares,
83
- password
450
+ password,
451
+ backUpToClientShareService
84
452
  });
85
453
  return {
454
+ walletId: this.walletMap[accountAddress].walletId,
86
455
  accountAddress,
87
456
  rawPublicKey,
88
457
  publicKeyHex,
89
458
  externalServerKeyShares
90
459
  };
91
460
  } catch (error) {
92
- // this.logger.error(ERROR_CREATE_WALLET_ACCOUNT, error);
461
+ logError({
462
+ message: ERROR_CREATE_WALLET_ACCOUNT,
463
+ error: error,
464
+ context: {}
465
+ });
93
466
  throw new Error(ERROR_CREATE_WALLET_ACCOUNT);
94
467
  }
95
468
  }
96
- async signMessage({ message, accountAddress, password = undefined }) {
97
- await this.verifyPassword({
98
- accountAddress,
99
- password,
100
- walletOperation: WalletOperation.SIGN_MESSAGE
101
- });
102
- await this.getWallet({
103
- accountAddress,
104
- walletOperation: WalletOperation.SIGN_MESSAGE
105
- });
469
+ async signMessage({ message, accountAddress, password = undefined, externalServerKeyShares, context, onError }) {
106
470
  try {
107
471
  if (!accountAddress) {
108
472
  throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
109
473
  }
110
474
  // Format the message for EVM signing
111
475
  const formattedMessage = formatEVMMessage(message);
112
- // Sign the message using MPC
476
+ const resolvedContext = context != null ? context : {
477
+ evmMessage: message
478
+ };
479
+ // Attempt to recover key shares from backup if not provided
480
+ await this.ensureKeySharesRecovered({
481
+ accountAddress,
482
+ password,
483
+ walletOperation: WalletOperation.SIGN_MESSAGE,
484
+ externalServerKeyShares,
485
+ errorMessage: 'External server key shares are required to sign a message. No backup shares available for recovery.'
486
+ });
113
487
  const signatureEcdsa = await this.sign({
114
488
  message: formattedMessage,
115
489
  accountAddress: accountAddress,
116
490
  chainName: this.chainName,
117
- password
491
+ password,
492
+ externalServerKeyShares,
493
+ context: resolvedContext,
494
+ onError
118
495
  });
119
496
  // Serialize the signature
120
497
  const serializedSignature = serializeECDSASignature(signatureEcdsa);
121
498
  return serializedSignature;
122
499
  } catch (error) {
123
- this.logger.error(ERROR_SIGN_MESSAGE, error);
500
+ logError({
501
+ message: ERROR_SIGN_MESSAGE,
502
+ error: error,
503
+ context: {
504
+ accountAddress
505
+ }
506
+ });
507
+ throw new Error(ERROR_SIGN_MESSAGE);
508
+ }
509
+ }
510
+ isSignAuthorizationSupported() {
511
+ return true;
512
+ }
513
+ async signAuthorization({ authorization, accountAddress, password = undefined, externalServerKeyShares, onError }) {
514
+ try {
515
+ if (!accountAddress) {
516
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
517
+ }
518
+ const digest = hashAuthorization(authorization);
519
+ const prehashed = digest.startsWith('0x') ? digest.slice(2) : digest;
520
+ // Attempt to recover key shares from backup if not provided
521
+ await this.ensureKeySharesRecovered({
522
+ accountAddress,
523
+ password,
524
+ walletOperation: WalletOperation.SIGN_MESSAGE,
525
+ externalServerKeyShares,
526
+ errorMessage: 'External server key shares are required to sign authorization. No backup shares available for recovery.'
527
+ });
528
+ const signatureEcdsa = await this.sign({
529
+ message: prehashed,
530
+ accountAddress: accountAddress,
531
+ chainName: this.chainName,
532
+ password,
533
+ externalServerKeyShares,
534
+ isFormatted: true,
535
+ context: {
536
+ eip7702Auth: authorization
537
+ },
538
+ onError
539
+ });
540
+ const serializedSignature = serializeECDSASignature(signatureEcdsa);
541
+ const signature = parseSignature(serializedSignature);
542
+ return signature;
543
+ } catch (error) {
544
+ logError({
545
+ message: ERROR_SIGN_MESSAGE,
546
+ error: error,
547
+ context: {
548
+ accountAddress
549
+ }
550
+ });
124
551
  throw new Error(ERROR_SIGN_MESSAGE);
125
552
  }
126
553
  }
554
+ async signTypedData({ accountAddress, typedData, password = undefined, externalServerKeyShares, onError }) {
555
+ try {
556
+ if (!accountAddress) {
557
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
558
+ }
559
+ const formattedTypedData = formatTypedData(typedData);
560
+ // Attempt to recover key shares from backup if not provided
561
+ await this.ensureKeySharesRecovered({
562
+ accountAddress,
563
+ password,
564
+ walletOperation: WalletOperation.SIGN_MESSAGE,
565
+ externalServerKeyShares,
566
+ errorMessage: 'External server key shares are required to sign typed data. No backup shares available for recovery.'
567
+ });
568
+ const signatureEcdsa = await this.sign({
569
+ message: formattedTypedData,
570
+ accountAddress: accountAddress,
571
+ chainName: this.chainName,
572
+ password,
573
+ externalServerKeyShares,
574
+ isFormatted: true,
575
+ context: {
576
+ evmTypedData: typedData
577
+ },
578
+ onError
579
+ });
580
+ const serializedSignature = serializeECDSASignature(signatureEcdsa);
581
+ return serializedSignature;
582
+ } catch (error) {
583
+ logError({
584
+ message: ERROR_SIGN_TYPED_DATA,
585
+ error: error,
586
+ context: {
587
+ accountAddress
588
+ }
589
+ });
590
+ throw new Error(ERROR_SIGN_TYPED_DATA);
591
+ }
592
+ }
127
593
  async verifyMessageSignature({ accountAddress, message, signature }) {
128
594
  try {
129
595
  // Verify the signature using the public client
@@ -137,16 +603,30 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
137
603
  });
138
604
  return verified;
139
605
  } catch (error) {
140
- this.logger.error(ERROR_VERIFY_MESSAGE_SIGNATURE, error);
606
+ logError({
607
+ message: ERROR_VERIFY_MESSAGE_SIGNATURE,
608
+ error: error,
609
+ context: {
610
+ accountAddress
611
+ }
612
+ });
141
613
  throw new Error(ERROR_VERIFY_MESSAGE_SIGNATURE);
142
614
  }
143
615
  }
144
- async signTransaction({ senderAddress, transaction, password = undefined }) {
616
+ async signTransaction({ senderAddress, transaction, password = undefined, externalServerKeyShares }) {
145
617
  await this.verifyPassword({
146
618
  accountAddress: senderAddress,
147
619
  password,
148
620
  walletOperation: WalletOperation.SIGN_TRANSACTION
149
621
  });
622
+ // Attempt to recover key shares from backup if not provided
623
+ await this.ensureKeySharesRecovered({
624
+ accountAddress: senderAddress,
625
+ password,
626
+ walletOperation: WalletOperation.SIGN_TRANSACTION,
627
+ externalServerKeyShares,
628
+ errorMessage: 'External server key shares are required to sign transaction. No backup shares available for recovery.'
629
+ });
150
630
  const serializedTx = serializeTransaction(transaction);
151
631
  const serializedTxBytes = Uint8Array.from(Buffer.from(serializedTx.slice(2), 'hex'));
152
632
  if (!(serializedTxBytes instanceof Uint8Array)) {
@@ -157,7 +637,8 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
157
637
  message: serializedTxBytes,
158
638
  accountAddress: senderAddress,
159
639
  chainName: this.chainName,
160
- password
640
+ password,
641
+ externalServerKeyShares
161
642
  });
162
643
  if (!('r' in signatureEcdsa && 's' in signatureEcdsa && 'v' in signatureEcdsa)) {
163
644
  throw new Error('Invalid signature format returned from MPC signing');
@@ -174,20 +655,35 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
174
655
  const serializedSignedTx = serializeTransaction(signedTx);
175
656
  return serializedSignedTx;
176
657
  } catch (error) {
177
- this.logger.error('Error signing transaction:', error);
658
+ logError({
659
+ message: 'Error signing transaction:',
660
+ error: error,
661
+ context: {
662
+ senderAddress
663
+ }
664
+ });
178
665
  throw error;
179
666
  }
180
667
  }
181
- async exportPrivateKey({ accountAddress, password = undefined }) {
668
+ async exportPrivateKey({ accountAddress, password = undefined, externalServerKeyShares }) {
182
669
  await this.verifyPassword({
183
670
  accountAddress,
184
671
  password,
185
672
  walletOperation: WalletOperation.EXPORT_PRIVATE_KEY
186
673
  });
674
+ // Attempt to recover key shares from backup if not provided
675
+ await this.ensureKeySharesRecovered({
676
+ accountAddress,
677
+ password,
678
+ walletOperation: WalletOperation.EXPORT_PRIVATE_KEY,
679
+ externalServerKeyShares,
680
+ errorMessage: 'External server key shares are required to export private key. No backup shares available for recovery.'
681
+ });
187
682
  const { derivedPrivateKey } = await this.exportKey({
188
683
  accountAddress,
189
684
  chainName: this.chainName,
190
- password
685
+ password,
686
+ externalServerKeyShares
191
687
  });
192
688
  return {
193
689
  derivedPrivateKey
@@ -203,35 +699,64 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
203
699
  derivedPrivateKey
204
700
  };
205
701
  }
206
- async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password = undefined, onError }) {
702
+ /**
703
+ * Imports a private key and stores the key shares in the wallet map.
704
+ * @param privateKey - The private key to import.
705
+ * @param chainName - The chain name to use for the wallet.
706
+ * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet.
707
+ * @param password - The password to use for the wallet.
708
+ * @param onError - The function to call if an error occurs.
709
+ * @param backUpToClientShareService - Whether to back up the external server key shares to the client share service. By default, it is false.
710
+ * @returns The account address, public key, raw public key, external server key shares.
711
+ */ async importPrivateKey({ privateKey, chainName, thresholdSignatureScheme, password = undefined, backUpToClientShareService = false, onError }) {
712
+ let ceremonyCeremonyCompleteResolver;
713
+ const ceremonyCompletePromise = new Promise((resolve)=>{
714
+ ceremonyCeremonyCompleteResolver = resolve;
715
+ });
207
716
  // TODO: validate private key for EVM
208
717
  const { rawPublicKey, externalServerKeyShares } = await this.importRawPrivateKey({
209
718
  chainName,
210
719
  privateKey,
211
720
  thresholdSignatureScheme,
212
- onError,
213
721
  onCeremonyComplete: (accountAddress, walletId)=>{
214
722
  // update wallet map
215
723
  const checksumAddress = getAddress(accountAddress);
724
+ const chainConfig = getMPCChainConfig(this.chainName);
216
725
  this.walletMap[checksumAddress] = _extends({}, this.walletMap[checksumAddress] || {}, {
217
726
  accountAddress: checksumAddress,
218
727
  walletId,
219
728
  chainName: this.chainName,
220
729
  thresholdSignatureScheme,
730
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map((value, index)=>[
731
+ index,
732
+ value
733
+ ]))),
221
734
  externalServerKeySharesBackupInfo: getExternalServerKeyShareBackupInfo()
222
735
  });
736
+ ceremonyCeremonyCompleteResolver(undefined);
737
+ },
738
+ onError: (e)=>{
739
+ logError({
740
+ message: 'importPrivateKey: onError',
741
+ error: e,
742
+ context: {}
743
+ });
744
+ onError == null ? void 0 : onError(e);
223
745
  }
224
746
  });
747
+ // Wait for the ceremony to complete before proceeding
748
+ await ceremonyCompletePromise;
225
749
  if (!rawPublicKey || !externalServerKeyShares) {
226
750
  throw new Error('Error creating wallet account');
227
751
  }
228
752
  const { accountAddress, publicKeyHex } = deriveAccountAddress({
229
753
  rawPublicKey: rawPublicKey
230
754
  });
231
- void this.storeEncryptedBackupByWalletWithRetry({
755
+ await this.storeEncryptedBackupByWalletWithRetry({
232
756
  accountAddress,
233
757
  externalServerKeyShares,
234
- password
758
+ password,
759
+ backUpToClientShareService
235
760
  });
236
761
  return {
237
762
  accountAddress,
@@ -245,14 +770,198 @@ class DynamicEvmWalletClient extends DynamicWalletClient {
245
770
  const evmWallets = wallets.filter((wallet)=>wallet.chainName === 'eip155');
246
771
  return evmWallets;
247
772
  }
248
- constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug }){
773
+ constructor({ environmentId, baseApiUrl, baseMPCRelayApiUrl, debug, enableMPCAccelerator }){
249
774
  super({
250
775
  environmentId,
251
776
  baseApiUrl,
252
777
  baseMPCRelayApiUrl,
253
- debug
778
+ debug,
779
+ enableMPCAccelerator
254
780
  }), this.chainName = 'EVM';
255
781
  }
256
782
  }
257
783
 
258
- export { DynamicEvmWalletClient };
784
+ const getJwtExpiration = (jwt)=>{
785
+ if (!jwt) {
786
+ return 0;
787
+ }
788
+ return JSON.parse(Buffer.from(jwt.split('.')[1], 'base64').toString()).exp * 1000;
789
+ };
790
+ class MemoryStorageAdapter {
791
+ async getItem(key) {
792
+ if (key.includes('session')) {
793
+ // This is a workaround so we can pass the JWT that the authenticate the node SDK to
794
+ // the vanilla client, once set we can refresh the user and populate the user data, wallets and etc.
795
+ return JSON.stringify({
796
+ value: {
797
+ token: this.jwt,
798
+ sessionExpiration: getJwtExpiration(this.jwt),
799
+ legacyToken: null,
800
+ mfaToken: null,
801
+ captchaToken: null,
802
+ sessionKeys: null
803
+ }
804
+ });
805
+ }
806
+ var _this_store_get;
807
+ return (_this_store_get = this.store.get(key)) != null ? _this_store_get : null;
808
+ }
809
+ async setItem(key, value) {
810
+ this.store.set(key, value);
811
+ }
812
+ async removeItem(key) {
813
+ this.store.delete(key);
814
+ }
815
+ clear() {
816
+ this.store.clear();
817
+ }
818
+ get size() {
819
+ return this.store.size;
820
+ }
821
+ constructor(jwt){
822
+ this.store = new Map();
823
+ this.jwt = jwt;
824
+ }
825
+ }
826
+ const createMemoryStorageAdapter = (jwt)=>{
827
+ return new MemoryStorageAdapter(jwt);
828
+ };
829
+
830
+ class DynamicEvmZeroDevClient {
831
+ async initialize() {
832
+ await initializeClient(this.dynamicClient);
833
+ if ('jwtAuthToken' in this.evmClient) {
834
+ // Fetch user data to populate wallet accounts
835
+ await refreshUser(this.dynamicClient);
836
+ }
837
+ }
838
+ /**
839
+ * Get network data by networkId from project configuration
840
+ */ getNetworkData(networkId) {
841
+ const networksData = getNetworksData(this.dynamicClient);
842
+ const networkData = networksData.find((n)=>n.networkId === networkId);
843
+ assertDefined(networkData, `No network found with networkId: ${networkId}. Available networks: ${networksData.map((n)=>n.networkId).join(', ')}`);
844
+ return networkData;
845
+ }
846
+ async createKernelClientForAddress(options) {
847
+ const viemSigner = createAccountAdapter({
848
+ evmClient: this.evmClient,
849
+ accountAddress: options.address,
850
+ password: options.password,
851
+ externalServerKeyShares: options.externalServerKeyShares,
852
+ delegated: options.delegated
853
+ });
854
+ const activeNetworkData = this.getNetworkData(options.networkId);
855
+ const viemChain = mapNetworkDataToViemChain(activeNetworkData);
856
+ var _options_bundlerRpc;
857
+ const bundlerRpc = (_options_bundlerRpc = options.bundlerRpc) != null ? _options_bundlerRpc : getZerodevRpc({
858
+ bundlerProvider: options.bundlerProvider,
859
+ networkId: activeNetworkData.networkId,
860
+ rpcType: 'bundler'
861
+ }, this.dynamicClient);
862
+ const bundlerTransport = http(bundlerRpc);
863
+ const publicClient = createPublicClient({
864
+ chain: viemChain,
865
+ transport: bundlerTransport
866
+ });
867
+ const account = await this.createKernelAccountWithCustomSigner({
868
+ publicClient,
869
+ signer: viemSigner
870
+ });
871
+ var _options_paymasterRpc;
872
+ const paymasterRpc = (_options_paymasterRpc = options.paymasterRpc) != null ? _options_paymasterRpc : getZerodevRpc({
873
+ bundlerProvider: options.bundlerProvider,
874
+ networkId: activeNetworkData.networkId,
875
+ rpcType: 'paymaster'
876
+ }, this.dynamicClient);
877
+ var _options_withSponsorship;
878
+ const paymasterConfig = ((_options_withSponsorship = options.withSponsorship) != null ? _options_withSponsorship : true) ? getPaymasterConfig({
879
+ chain: viemChain,
880
+ gasTokenAddress: options.gasTokenAddress,
881
+ paymasterRpc
882
+ }) : {};
883
+ const kernelClient = createKernelAccountClient(_extends({
884
+ account,
885
+ bundlerTransport,
886
+ chain: viemChain,
887
+ client: publicClient,
888
+ userOperation: {
889
+ estimateFeesPerGas: async ({ bundlerClient })=>getUserOperationGasPrice(bundlerClient)
890
+ }
891
+ }, paymasterConfig));
892
+ return kernelClient;
893
+ }
894
+ async createKernelAccountWithCustomSigner({ publicClient, signer }) {
895
+ const zerodevProvider = getZerodevProviderFromSettings(this.dynamicClient);
896
+ assertDefined(zerodevProvider, 'Zerodev provider is not enabled in project settings');
897
+ const useEIP7702 = zerodevProvider.enableEIP7702;
898
+ const entryPointVersion = zerodevProvider.entryPointVersion;
899
+ const entryPoint = getEntryPoint(entryPointVersion);
900
+ if (useEIP7702) {
901
+ return createKernelAccount(publicClient, {
902
+ eip7702Account: signer,
903
+ entryPoint,
904
+ kernelVersion: constants.KERNEL_V3_3
905
+ });
906
+ }
907
+ const kernelVersionValue = zerodevProvider.kernelVersion;
908
+ const kernelVersion = getKernelVersion({
909
+ entryPoint,
910
+ kernelVersion: kernelVersionValue
911
+ });
912
+ var _zerodevProvider_enableKernelV3Migration;
913
+ const kernelV3MigrationEnabled = (_zerodevProvider_enableKernelV3Migration = zerodevProvider.enableKernelV3Migration) != null ? _zerodevProvider_enableKernelV3Migration : false;
914
+ if (kernelV3MigrationEnabled) {
915
+ const apiKernelVersion = getKernelVersion({
916
+ entryPoint,
917
+ kernelVersion: zerodevProvider.kernelVersion
918
+ });
919
+ return createEcdsaKernelMigrationAccount(publicClient, {
920
+ entryPoint,
921
+ migrationVersion: {
922
+ from: kernelVersion,
923
+ to: apiKernelVersion
924
+ },
925
+ signer
926
+ });
927
+ }
928
+ const validator = await getEcdsaValidator({
929
+ ecdsaProviderType: zerodevProvider.ecdsaProviderType,
930
+ entryPoint,
931
+ kernelVersion,
932
+ publicClient,
933
+ signer
934
+ });
935
+ return createKernelAccount(publicClient, {
936
+ entryPoint,
937
+ kernelVersion,
938
+ plugins: {
939
+ sudo: validator
940
+ }
941
+ });
942
+ }
943
+ constructor(evmClient){
944
+ this.evmClient = evmClient;
945
+ var _evmClient_jwtAuthToken;
946
+ const authToken = 'jwtAuthToken' in evmClient ? (_evmClient_jwtAuthToken = evmClient.jwtAuthToken) != null ? _evmClient_jwtAuthToken : null : null;
947
+ const storageAdapter = createMemoryStorageAdapter(authToken);
948
+ this.dynamicClient = createDynamicClient({
949
+ environmentId: evmClient.environmentId,
950
+ autoInitialize: false,
951
+ coreConfig: {
952
+ storageAdapter,
953
+ fetch: fetch,
954
+ apiBaseUrl: `${evmClient.apiUrl}/api/v0`
955
+ }
956
+ });
957
+ addZerodevExtension(this.dynamicClient);
958
+ addWaasEvmExtension(this.dynamicClient);
959
+ }
960
+ }
961
+ const createZerodevClient = async (evmClient)=>{
962
+ const client = new DynamicEvmZeroDevClient(evmClient);
963
+ await client.initialize();
964
+ return client;
965
+ };
966
+
967
+ export { DynamicEvmWalletClient, ERROR_ACCOUNT_ADDRESS_REQUIRED, ERROR_CREATE_WALLET_ACCOUNT, ERROR_KEYGEN_FAILED, ERROR_SIGN_MESSAGE, ERROR_SIGN_TYPED_DATA, ERROR_VERIFY_MESSAGE_SIGNATURE, EVM_SIGN_MESSAGE_PREFIX, createAccountAdapter, createDelegatedEvmWalletClient, createZerodevClient, delegatedSignAuthorization, delegatedSignMessage, delegatedSignTransaction, delegatedSignTypedData, deriveAccountAddress, formatEVMMessage, formatTypedData, revokeDelegation, serializeECDSASignature };