@tetherto/wdk-wallet-evm-erc-4337 1.0.0-beta.19 → 1.0.0-beta.20

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/README.md CHANGED
@@ -43,11 +43,33 @@ console.log('Smart account address:', address)
43
43
  wallet.dispose()
44
44
  ```
45
45
 
46
+ ### Authenticated bundlers and paymasters
47
+
48
+ Some providers require an API key sent as an HTTP header. Pass `bundlerHeaders` and/or
49
+ `paymasterHeaders` to attach headers to every request to those services:
50
+
51
+ ```javascript
52
+ const wallet = new WalletManagerEvmErc4337(seedPhrase, {
53
+ chainId: 11155111,
54
+ provider: 'https://sepolia.drpc.org',
55
+ bundlerUrl: 'https://bundler.example.com/rpc',
56
+ bundlerHeaders: { Authorization: 'Bearer YOUR_KEY' },
57
+ safeModulesVersion: '0.3.0',
58
+ isSponsored: true,
59
+ paymasterUrl: 'https://paymaster.example.com/rpc',
60
+ paymasterHeaders: { Authorization: 'Bearer YOUR_KEY' },
61
+ })
62
+ ```
63
+
64
+ Both fields are optional. When omitted, requests are sent without extra headers, so providers
65
+ that authenticate via the URL (e.g. an `apikey` query parameter) keep working unchanged.
66
+
46
67
  ## Key Capabilities
47
68
 
48
69
  - **ERC-4337 Account Abstraction**: Full implementation of the ERC-4337 standard
49
70
  - **Multiple Gas Payment Modes**: Pay fees with native coins, ERC-20 tokens via paymaster, or sponsored transactions
50
71
  - **UserOperation Management**: Create and send UserOperations through bundlers
72
+ - **Authenticated Bundlers & Paymasters**: Attach custom HTTP headers (e.g. `Authorization`) to bundler and paymaster requests
51
73
  - **BIP-44 Derivation Paths**: Standard Ethereum derivation (m/44'/60')
52
74
  - **Multi-Account Management**: Derive multiple smart accounts from a single seed phrase
53
75
  - **ERC-20 Token Support**: Query balances and transfer tokens via UserOperations
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tetherto/wdk-wallet-evm-erc-4337",
3
- "version": "1.0.0-beta.19",
3
+ "version": "1.0.0-beta.20",
4
4
  "description": "A simple package to manage BIP-32 wallets for evm blockchains, which implement the erc-4337 standard and its account abstraction features",
5
5
  "keywords": [
6
6
  "wdk",
@@ -20,7 +20,7 @@ import { MaximumFeeExceededError, ProviderRequiredError, TransactionError, Trans
20
20
 
21
21
  import { WalletAccountEvm } from '@tetherto/wdk-wallet-evm'
22
22
 
23
- import { AbstractionKitError, ENTRYPOINT_V7, calculateUserOperationMaxGasCost, fetchAccountNonce } from 'abstractionkit'
23
+ import { ENTRYPOINT_V7, calculateUserOperationMaxGasCost, fetchAccountNonce } from 'abstractionkit'
24
24
 
25
25
  import WalletAccountReadOnlyEvmErc4337, { FEE_TOLERANCE_COEFFICIENT } from './wallet-account-read-only-evm-erc-4337.js'
26
26
 
@@ -419,7 +419,18 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
419
419
  ...(nonce !== undefined ? { nonce } : {})
420
420
  }
421
421
 
422
- const { userOp, smartAccount, chainId, tokenQuote } = await this._buildUserOperation(calls, config, txOverrides)
422
+ let userOp, smartAccount, chainId, tokenQuote
423
+ try {
424
+ ;({ userOp, smartAccount, chainId, tokenQuote } = await this._buildUserOperation(calls, config, txOverrides))
425
+ } catch (err) {
426
+ if (WalletAccountReadOnlyEvmErc4337._isAA50Error(err)) {
427
+ throw new TransactionError('Not enough funds on the safe account to repay the paymaster.', {
428
+ reason: TransactionErrorReason.INSUFFICIENT_BALANCE,
429
+ cause: err
430
+ })
431
+ }
432
+ throw err
433
+ }
423
434
 
424
435
  const fee = config.isSponsored
425
436
  ? 0n
@@ -503,7 +514,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
503
514
 
504
515
  return await this._getBundler().sendUserOperation(userOp, smartAccount.entrypointAddress)
505
516
  } catch (err) {
506
- if (err instanceof AbstractionKitError && err.message.includes('AA50')) {
517
+ if (WalletAccountReadOnlyEvmErc4337._isAA50Error(err)) {
507
518
  throw new TransactionError('Not enough funds on the safe account to repay the paymaster.', {
508
519
  reason: TransactionErrorReason.INSUFFICIENT_BALANCE,
509
520
  cause: err
@@ -525,7 +536,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
525
536
  try {
526
537
  return await this._getBundler().sendUserOperation(userOp, ENTRYPOINT_V7)
527
538
  } catch (err) {
528
- if (err instanceof AbstractionKitError && err.message.includes('AA50')) {
539
+ if (WalletAccountReadOnlyEvmErc4337._isAA50Error(err)) {
529
540
  throw new TransactionError('Not enough funds on the safe account to repay the paymaster.', {
530
541
  reason: TransactionErrorReason.INSUFFICIENT_BALANCE,
531
542
  cause: err
@@ -26,6 +26,7 @@ import {
26
26
  AbstractionKitError,
27
27
  Bundler,
28
28
  Erc7677Paymaster,
29
+ HttpTransport,
29
30
  ENTRYPOINT_V7,
30
31
  calculateUserOperationMaxGasCost
31
32
  } from 'abstractionkit'
@@ -133,6 +134,7 @@ export const FEE_TOLERANCE_COEFFICIENT = 120n
133
134
  * @property {string | Eip1193Provider | Array<string | Eip1193Provider>} provider - The url of the rpc provider, or an instance of a class that implements eip-1193. It's also possible to provide an array of urls or EIP 1193 providers instead. In such case, connection errors will cause the wallet to automatically fallback on the next provider in the list.
134
135
  * @property {number} [retries] - If set and if 'provider' is a list of urls or EIP 1193 providers, the number of additional retry attempts after the initial call fails. Total attempts = `1 + retries`. For example, `retries: 3` with 4 providers will try each provider once before throwing. If `retries` exceeds the number of providers, the failover will loop back and retry already-failed providers in round-robin order. Default: 3.
135
136
  * @property {string} bundlerUrl - The url of the bundler service.
137
+ * @property {Record<string, string>} [bundlerHeaders] - Optional HTTP headers sent on every request to the bundler (e.g. `{ Authorization: 'Bearer <key>' }`). Use for bundlers that require authentication.
136
138
  * @property {string} safeModulesVersion - Version of the Safe 4337 module set to deploy with the account (e.g. "0.3.0"). Determines the module addresses used in init code.
137
139
  * @property {OnChainIdentifier | string} [onChainIdentifier] - Optional on-chain identifier. Appends a 50-byte project marker to every UserOperation callData. Pass a string to reuse it as the project name, or a full object for more control.
138
140
  * @property {boolean} [parallel] - When true, each send is placed in a fresh, independent nonce lane (a random 192-bit key at sequence 0) so concurrent or back-to-back sends don't collide on the nonce. Ordering between such sends is not guaranteed and each consumes a new EntryPoint nonce slot. Ignored when `nonceKey` is set. Overridable per call.
@@ -144,6 +146,7 @@ export const FEE_TOLERANCE_COEFFICIENT = 120n
144
146
  * @property {false} [isSponsored] - Whether the paymaster is sponsoring the account.
145
147
  * @property {false} [useNativeCoins] - Whether to use native coins instead of a paymaster to pay for gas fees.
146
148
  * @property {string} paymasterUrl - The url of the paymaster service.
149
+ * @property {Record<string, string>} [paymasterHeaders] - Optional HTTP headers sent on every request to the paymaster (e.g. `{ Authorization: 'Bearer <key>' }`). Use for paymasters that require authentication.
147
150
  * @property {string} paymasterAddress - The address of the paymaster smart contract.
148
151
  * @property {Object} paymasterToken - The paymaster token configuration.
149
152
  * @property {string} paymasterToken.address - The address of the paymaster token.
@@ -156,6 +159,7 @@ export const FEE_TOLERANCE_COEFFICIENT = 120n
156
159
  * @property {true} isSponsored - Whether the paymaster is sponsoring the account.
157
160
  * @property {false} [useNativeCoins] - Whether to use native coins instead of a paymaster to pay for gas fees.
158
161
  * @property {string} paymasterUrl - The url of the paymaster service.
162
+ * @property {Record<string, string>} [paymasterHeaders] - Optional HTTP headers sent on every request to the paymaster (e.g. `{ Authorization: 'Bearer <key>' }`). Use for paymasters that require authentication.
159
163
  * @property {string} [sponsorshipPolicyId] - Identifier of the paymaster sponsorship policy to apply (provider-specific). Optional; some paymasters infer the policy from the project key.
160
164
  */
161
165
 
@@ -629,6 +633,21 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
629
633
  return SafeAccount030.initializeNewAccount([this._ownerAccountAddress], overrides)
630
634
  }
631
635
 
636
+ /**
637
+ * Builds the RPC transport for an AbstractionKit client (Bundler / Erc7677Paymaster).
638
+ *
639
+ * When `headers` are provided, the transport injects them on every request (e.g.
640
+ * `{ Authorization: 'Bearer <key>' }` for authenticated bundlers/paymasters).
641
+ *
642
+ * @protected
643
+ * @param {string} url - The bundler or paymaster RPC url.
644
+ * @param {Record<string, string>} [headers] - Optional HTTP headers to inject on every request.
645
+ * @returns {HttpTransport} An HttpTransport for the url, carrying the headers when set.
646
+ */
647
+ static _rpcTarget (url, headers) {
648
+ return new HttpTransport(url, headers ? { headers } : {})
649
+ }
650
+
632
651
  /**
633
652
  * Returns an AbstractionKit Bundler for querying UserOperations.
634
653
  *
@@ -637,18 +656,21 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
637
656
  */
638
657
  _getBundler () {
639
658
  if (!this._bundler) {
640
- this._bundler = new Bundler(this._config.bundlerUrl)
659
+ const rpc = WalletAccountReadOnlyEvmErc4337._rpcTarget(this._config.bundlerUrl, this._config.bundlerHeaders)
660
+ this._bundler = new Bundler(rpc)
641
661
  }
642
662
  return this._bundler
643
663
  }
644
664
 
645
665
  /** @private */
646
- _getPaymaster (url, options = {}) {
647
- if (!this._paymasters.has(url)) {
666
+ _getPaymaster (url, headers, options = {}) {
667
+ const key = JSON.stringify([url, headers ?? null])
668
+ if (!this._paymasters.has(key)) {
648
669
  const provider = WalletAccountReadOnlyEvmErc4337._detectProvider(url)
649
- this._paymasters.set(url, new Erc7677Paymaster(url, { ...options, provider }))
670
+ const rpc = WalletAccountReadOnlyEvmErc4337._rpcTarget(url, headers)
671
+ this._paymasters.set(key, new Erc7677Paymaster(rpc, { ...options, provider }))
650
672
  }
651
- return this._paymasters.get(url)
673
+ return this._paymasters.get(key)
652
674
  }
653
675
 
654
676
  /**
@@ -798,15 +820,16 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
798
820
  ? WalletAccountReadOnlyEvmErc4337._detectProvider(config.paymasterUrl)
799
821
  : null
800
822
 
801
- const gasPrice = await this._fetchBundlerGasPrice(config.bundlerUrl)
823
+ const gasPrice = await this._fetchBundlerGasPrice(config.bundlerUrl, config.bundlerHeaders)
802
824
 
803
825
  const feePairOverridden = txOverrides.maxFeePerGas !== undefined || txOverrides.maxPriorityFeePerGas !== undefined
804
826
  const overrides = feePairOverridden
805
827
  ? { ...txOverrides }
806
828
  : { ...gasPrice, ...txOverrides }
807
829
 
830
+ const bundlerRpc = WalletAccountReadOnlyEvmErc4337._rpcTarget(config.bundlerUrl, config.bundlerHeaders)
808
831
  const baseUserOp = (mode === PaymasterMode.NATIVE || provider === 'candide')
809
- ? await smartAccount.createUserOperation(calls, this._provider, config.bundlerUrl, overrides)
832
+ ? await smartAccount.createUserOperation(calls, this._provider, bundlerRpc, overrides)
810
833
  : await smartAccount.createUserOperation(calls, this._provider, undefined, { skipGasEstimation: true, ...overrides })
811
834
 
812
835
  if (mode === PaymasterMode.NATIVE) {
@@ -841,6 +864,20 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
841
864
  return overrides
842
865
  }
843
866
 
867
+ /**
868
+ * Determines whether an error from AbstractionKit is an AA50 paymaster funds error.
869
+ *
870
+ * Checked via `aaCode` first; falls back to matching the substring in `message` for
871
+ * bundlers/paymasters that don't populate `aaCode`.
872
+ *
873
+ * @protected
874
+ * @param {unknown} err - The error to inspect.
875
+ * @returns {boolean} `true` if `err` represents an AA50 error.
876
+ */
877
+ static _isAA50Error (err) {
878
+ return err instanceof AbstractionKitError && (err.aaCode === 'AA50' || err.message.includes('AA50'))
879
+ }
880
+
844
881
  /**
845
882
  * Builds a UserOperation and returns its estimated gas cost.
846
883
  *
@@ -869,7 +906,7 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
869
906
 
870
907
  return { fee, ...buildResult }
871
908
  } catch (error) {
872
- if (error instanceof AbstractionKitError && error.message.includes('AA50')) {
909
+ if (WalletAccountReadOnlyEvmErc4337._isAA50Error(error)) {
873
910
  throw new TransactionError(
874
911
  'Token paymaster requires the account to hold the paymaster token for fee estimation. ' +
875
912
  'Fund the account with the paymaster token before quoting.',
@@ -888,10 +925,10 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
888
925
  }
889
926
 
890
927
  /** @private */
891
- async _fetchBundlerGasPrice (bundlerUrl) {
928
+ async _fetchBundlerGasPrice (bundlerUrl, bundlerHeaders) {
892
929
  if (WalletAccountReadOnlyEvmErc4337._detectProvider(bundlerUrl) !== 'pimlico') return undefined
893
930
 
894
- const erc7677 = this._getPaymaster(bundlerUrl)
931
+ const erc7677 = new Erc7677Paymaster(WalletAccountReadOnlyEvmErc4337._rpcTarget(bundlerUrl, bundlerHeaders))
895
932
  const result = await erc7677.sendRPCRequest('pimlico_getUserOperationGasPrice', [])
896
933
  if (!result?.fast) return undefined
897
934
 
@@ -912,7 +949,7 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
912
949
 
913
950
  /** @private */
914
951
  async _applyPaymasterToUserOp ({ mode, smartAccount, userOp, config, chainId, txOverrides = {} }) {
915
- const erc7677 = this._getPaymaster(config.paymasterUrl, { chainId: BigInt(chainId) })
952
+ const erc7677 = this._getPaymaster(config.paymasterUrl, config.paymasterHeaders, { chainId: BigInt(chainId) })
916
953
 
917
954
  const context = mode === PaymasterMode.TOKEN
918
955
  ? { token: config.paymasterToken.address }
@@ -923,10 +960,11 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
923
960
  if (txOverrides.verificationGasLimit !== undefined) paymasterOverrides.verificationGasLimit = txOverrides.verificationGasLimit
924
961
  if (txOverrides.preVerificationGas !== undefined) paymasterOverrides.preVerificationGas = txOverrides.preVerificationGas
925
962
 
963
+ const bundlerRpc = WalletAccountReadOnlyEvmErc4337._rpcTarget(config.bundlerUrl, config.bundlerHeaders)
926
964
  const result = await erc7677.createPaymasterUserOperation(
927
965
  smartAccount,
928
966
  userOp,
929
- config.bundlerUrl,
967
+ bundlerRpc,
930
968
  context,
931
969
  paymasterOverrides
932
970
  )
@@ -230,6 +230,18 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
230
230
  * @returns {Promise<SafeAccountV0_3_0>} The safe account instance.
231
231
  */
232
232
  protected _getSmartAccount(config?: Omit<EvmErc4337WalletConfig, "transferMaxFee" | "transactionMaxFee">): Promise<import('abstractionkit').SafeAccountV0_3_0>;
233
+ /**
234
+ * Builds the RPC transport for an AbstractionKit client (Bundler / Erc7677Paymaster).
235
+ *
236
+ * When `headers` are provided, the transport injects them on every request (e.g.
237
+ * `{ Authorization: 'Bearer <key>' }` for authenticated bundlers/paymasters).
238
+ *
239
+ * @protected
240
+ * @param {string} url - The bundler or paymaster RPC url.
241
+ * @param {Record<string, string>} [headers] - Optional HTTP headers to inject on every request.
242
+ * @returns {HttpTransport} An HttpTransport for the url, carrying the headers when set.
243
+ */
244
+ protected static _rpcTarget(url: string, headers?: Record<string, string>): HttpTransport;
233
245
  /**
234
246
  * Returns an AbstractionKit Bundler for querying UserOperations.
235
247
  *
@@ -459,6 +471,10 @@ export type EvmErc4337WalletCommonConfig = {
459
471
  * - The url of the bundler service.
460
472
  */
461
473
  bundlerUrl: string;
474
+ /**
475
+ * - Optional HTTP headers sent on every request to the bundler (e.g. `{ Authorization: 'Bearer <key>' }`). Use for bundlers that require authentication.
476
+ */
477
+ bundlerHeaders?: Record<string, string>;
462
478
  /**
463
479
  * - Version of the Safe 4337 module set to deploy with the account (e.g. "0.3.0"). Determines the module addresses used in init code.
464
480
  */
@@ -489,6 +505,10 @@ export type EvmErc4337WalletPaymasterTokenConfig = {
489
505
  * - The url of the paymaster service.
490
506
  */
491
507
  paymasterUrl: string;
508
+ /**
509
+ * - Optional HTTP headers sent on every request to the paymaster (e.g. `{ Authorization: 'Bearer <key>' }`). Use for paymasters that require authentication.
510
+ */
511
+ paymasterHeaders?: Record<string, string>;
492
512
  /**
493
513
  * - The address of the paymaster smart contract.
494
514
  */
@@ -521,6 +541,10 @@ export type EvmErc4337WalletSponsorshipPolicyConfig = {
521
541
  * - The url of the paymaster service.
522
542
  */
523
543
  paymasterUrl: string;
544
+ /**
545
+ * - Optional HTTP headers sent on every request to the paymaster (e.g. `{ Authorization: 'Bearer <key>' }`). Use for paymasters that require authentication.
546
+ */
547
+ paymasterHeaders?: Record<string, string>;
524
548
  /**
525
549
  * - Identifier of the paymaster sponsorship policy to apply (provider-specific). Optional; some paymasters infer the policy from the project key.
526
550
  */
@@ -547,3 +571,4 @@ export type EvmErc4337WalletNativeCoinsConfig = {
547
571
  export type EvmErc4337WalletConfig = EvmErc4337WalletCommonConfig & (EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig);
548
572
  import { WalletAccountReadOnly } from '@tetherto/wdk-wallet';
549
573
  import { Bundler } from 'abstractionkit';
574
+ import { HttpTransport } from 'abstractionkit';