@tetherto/wdk-wallet-evm-erc-4337 1.0.0-beta.26 → 1.0.0-beta.27

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
@@ -73,7 +73,7 @@ that authenticate via the URL (e.g. an `apikey` query parameter) keep working un
73
73
  - **BIP-44 Derivation Paths**: Standard Ethereum derivation (m/44'/60')
74
74
  - **Multi-Account Management**: Derive multiple smart accounts from a single seed phrase
75
75
  - **ERC-20 Token Support**: Query balances and transfer tokens via UserOperations
76
- - **Message Signing**: Sign messages and typed data as the Safe (ERC-1271 / SafeMessage), and verify them against the Safe
76
+ - **Message Signing**: Sign messages and typed data as the Safe (ERC-1271 / SafeMessage, wrapped in ERC-6492 until the Safe is deployed), and verify them against the Safe
77
77
  - **Per-Call Config Overrides**: Switch gas payment modes on a per-transaction basis
78
78
  - **Parallel Nonce Lanes**: Send independent operations concurrently via ERC-4337 two-dimensional nonces (`parallel: true` or a reusable `nonceKey`)
79
79
  - **Secure Memory Disposal**: Clear private keys from memory when done
@@ -103,6 +103,52 @@ const account = WalletAccountEvmErc4337.fromPrivateKey(privateKey, config)
103
103
  - The safe's address is predicted from the signer's `getAddress()` on first use, so signers that only provide their address asynchronously (e.g. hardware signers) are supported.
104
104
  - `account.path` and `account.keyPair` are `null` for signers without a derivation path or key material.
105
105
 
106
+ ## Signature Formats
107
+
108
+ `sign()` and `signTypedData()` sign as the Safe, so the Safe's ERC-1271 `isValidSignature` accepts the signature:
109
+
110
+ - **Deployed Safe:** a plain ERC-1271 (SafeMessage) signature.
111
+ - **Safe not deployed yet:** the same signature wrapped in an [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) signature, which also carries the call that deploys the Safe. ERC-6492-aware verifiers (e.g. viem's `verifyMessage` / `verifyTypedData`) simulate the deployment and check it, so third parties can verify signatures from a Safe that has no code yet.
112
+
113
+ `verify()` and `verifyTypedData()` accept both formats.
114
+
115
+ A verifier that doesn't support ERC-6492 can't check a wrapped signature. This matters when a contract checks the signature through the Safe's `isValidSignature` after the Safe is deployed, e.g. a Permit2 permit or an order (CoW, Seaport, UniswapX) signed before the Safe's first transaction and settled later. Unwrap the signature for those:
116
+
117
+ ```javascript
118
+ import { WalletAccountReadOnlyEvmErc4337 } from '@tetherto/wdk-wallet-evm-erc-4337'
119
+
120
+ const signature = await account.signTypedData(permit)
121
+
122
+ // The ERC-1271 signature; signatures that are not wrapped are returned unchanged.
123
+ const erc1271Signature = WalletAccountReadOnlyEvmErc4337.unwrapErc6492Signature(signature)
124
+ ```
125
+
126
+ ## Binding to an Existing Safe
127
+
128
+ A safe's address is derived from its owners, so after an owner change (key rotation, a recovery module) the new owner's key predicts a different, undeployed safe. Bind the account to the existing safe instead:
129
+
130
+ ```javascript
131
+ // Through the wallet manager (and WDK's registerWallet)
132
+ const wallet = new WalletManagerEvmErc4337(newSeedPhrase, {
133
+ ...config,
134
+ safeAddresses: {
135
+ // The account derived at this path from the default signer (getAccount(0))
136
+ "0'/0/0": '0xYourSafe...',
137
+ // The account derived at this path from the signer named 'seed-signer-1'
138
+ "seed-signer-1:0'/0/0": '0xYourOtherSafe...',
139
+ // The account bound to the signer named 'private-key-signer-1'
140
+ 'private-key-signer-1': '0xYourThirdSafe...'
141
+ }
142
+ })
143
+
144
+ // Or on a single account
145
+ const account = new WalletAccountEvmErc4337(signer, { ...config, safeAddress: '0xYourSafe...' })
146
+ ```
147
+
148
+ **Notes:**
149
+ - `safeAddresses` keys are the manager's account cache keys: the path as given to `getAccountByPath` (`"0'/0/0"`, which `getAccount(0)` also uses), prefixed with `"<signerName>:"` for a named signer, or just `"<signerName>"` for the account bound to a named signer.
150
+ - Unless the address is the signer's own predicted safe, the first sign or send checks that a safe is deployed there and counts the signer among its owners, and throws a `ConfigurationError` otherwise. Quotes skip this check.
151
+
106
152
  ## Concurrent / Parallel Sends (nonce lanes)
107
153
 
108
154
  By default every send uses the account's key-0 nonce, so it is sequential — a second send fired before the first is mined would collide on the nonce. To send independent operations concurrently, put each in its own **nonce lane** (an ERC-4337 two-dimensional nonce: a 192-bit `key` with its own sequence). Ops in different keys have no ordering constraint and validate independently, so they can be submitted at the same time.
package/index.js CHANGED
@@ -31,6 +31,8 @@
31
31
  /** @typedef {import('./src/wallet-account-read-only-evm-erc-4337.js').EvmErc4337GasOverrides} EvmErc4337GasOverrides */
32
32
  /** @typedef {import('./src/wallet-account-read-only-evm-erc-4337.js').EvmErc4337TransferOptions} EvmErc4337TransferOptions */
33
33
  /** @typedef {import('./src/wallet-account-evm-erc-4337.js').EvmErc4337ApproveOptions} EvmErc4337ApproveOptions */
34
+ /** @typedef {import('./src/wallet-account-evm-erc-4337.js').EvmErc4337SafeOptions} EvmErc4337SafeOptions */
35
+ /** @typedef {import('./src/wallet-manager-evm-erc-4337.js').EvmErc4337WalletManagerSafeOptions} EvmErc4337WalletManagerSafeOptions */
34
36
  /** @typedef {import('./src/wallet-account-read-only-evm-erc-4337.js').Nonce} Nonce */
35
37
  /** @typedef {import('@tetherto/wdk-wallet-evm').TransactionResult} TransactionResult */
36
38
  /** @typedef {import('@tetherto/wdk-wallet-evm').TransferOptions} TransferOptions */
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.26",
3
+ "version": "1.0.0-beta.27",
4
4
  "description": "ERC-4337 wallet module for EVM-compatible blockchains in WDK (Wallet Development Kit) by Tether.",
5
5
  "homepage": "https://docs.wdk.tether.io/sdk/wallet-modules/wallet-evm-erc-4337/",
6
6
  "keywords": [
@@ -32,8 +32,8 @@
32
32
  },
33
33
  "dependencies": {
34
34
  "@tetherto/wdk-failover-provider": "1.0.0-beta.2",
35
- "@tetherto/wdk-wallet": "1.0.0-beta.25",
36
- "@tetherto/wdk-wallet-evm": "1.0.0-beta.26",
35
+ "@tetherto/wdk-wallet": "1.0.0-beta.26",
36
+ "@tetherto/wdk-wallet-evm": "1.0.0-beta.27",
37
37
  "abstractionkit": "0.4.3",
38
38
  "bare-node-runtime": "^1.5.2",
39
39
  "ethers": "6.17.0"
@@ -48,6 +48,7 @@
48
48
  "prool": "0.0.23",
49
49
  "standard": "17.1.2",
50
50
  "typescript": "5.8.3",
51
+ "viem": "2.55.2",
51
52
  "wait-on": "8.0.4"
52
53
  },
53
54
  "devEngines": {
@@ -58,8 +59,8 @@
58
59
  }
59
60
  },
60
61
  "overrides": {
61
- "fast-uri": "3.1.2",
62
- "tar": "7.5.16",
62
+ "fast-uri": "3.1.9",
63
+ "tar": "7.5.23",
63
64
  "uuid": "11.1.1"
64
65
  },
65
66
  "exports": {
@@ -14,16 +14,19 @@
14
14
 
15
15
  'use strict'
16
16
 
17
- import { Contract, TypedDataEncoder, hashMessage, hexlify, keccak256, randomBytes, toUtf8Bytes } from 'ethers'
17
+ import { Contract, TypedDataEncoder, getAddress, hashMessage, hexlify, isAddress, keccak256, randomBytes, toUtf8Bytes } from 'ethers'
18
18
 
19
19
  import { DisposalError, MaximumFeeExceededError, ProviderRequiredError, TransactionError, TransactionErrorReason, UnsupportedOperationError, ValueError } from '@tetherto/wdk-wallet'
20
20
 
21
21
  import { PrivateKeySignerEvm, SeedSignerEvm } from '@tetherto/wdk-wallet-evm/signers'
22
22
 
23
- import { ENTRYPOINT_V7, calculateUserOperationMaxGasCost, fetchAccountNonce } from 'abstractionkit'
23
+ // eslint-disable-next-line camelcase
24
+ import { SafeAccountV0_3_0 as SafeAccount030, ENTRYPOINT_V7, calculateUserOperationMaxGasCost, fetchAccountNonce } from 'abstractionkit'
24
25
 
25
26
  import WalletAccountReadOnlyEvmErc4337, { FEE_TOLERANCE_COEFFICIENT } from './wallet-account-read-only-evm-erc-4337.js'
26
27
 
28
+ import { ConfigurationError } from './errors.js'
29
+
27
30
  /** @typedef {import('abstractionkit').UserOperationV7} UserOperationV7 */
28
31
  /** @typedef {import('abstractionkit').SafeAccountV0_3_0} SafeAccountV0_3_0 */
29
32
 
@@ -62,6 +65,13 @@ import WalletAccountReadOnlyEvmErc4337, { FEE_TOLERANCE_COEFFICIENT } from './wa
62
65
  * @typedef {ApproveOptions & EvmErc4337GasOverrides} EvmErc4337ApproveOptions
63
66
  */
64
67
 
68
+ /**
69
+ * @typedef {Object} EvmErc4337SafeOptions
70
+ * @property {string} [safeAddress] - The address of an existing safe to operate, instead of the safe predicted from the signer's address (e.g. after the safe's owner was changed). Unless it is the signer's own predicted safe, it must be a deployed safe that counts the signer among its owners; this is checked on the first operation that signs or sends.
71
+ */
72
+
73
+ const SAFE_ABI = ['function isOwner(address owner) view returns (bool)']
74
+
65
75
  const QUOTE_MAX_AGE_MS = 2 * 60 * 1_000
66
76
 
67
77
  const NONCE_KEY_SHIFT = 64n
@@ -82,8 +92,9 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
82
92
  * @overload
83
93
  * @param {string | Uint8Array} seed - A [BIP-39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes).
84
94
  * @param {string} path - The BIP-44 derivation path, relative to "m/44'/60'" (e.g. "0'/0/0").
85
- * @param {EvmErc4337WalletConfig} config - The configuration object.
95
+ * @param {EvmErc4337WalletConfig & EvmErc4337SafeOptions} config - The configuration object.
86
96
  * @throws {ValueError} If the given seed phrase is invalid.
97
+ * @throws {ValueError} If `config.safeAddress` is set and is not a well-formed evm address.
87
98
  */
88
99
 
89
100
  /**
@@ -91,19 +102,21 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
91
102
  *
92
103
  * @overload
93
104
  * @param {string | Uint8Array} seed - A [BIP-39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes).
94
- * @param {EvmErc4337WalletConfig} config - The configuration object.
105
+ * @param {EvmErc4337WalletConfig & EvmErc4337SafeOptions} config - The configuration object.
95
106
  * @throws {ValueError} If the given seed phrase is invalid.
107
+ * @throws {ValueError} If `config.safeAddress` is set and is not a well-formed evm address.
96
108
  */
97
109
 
98
110
  /**
99
111
  * Creates a new evm [erc-4337](https://www.erc4337.io/docs) wallet account using a signer as the safe's owner.
100
112
  *
101
- * The signer is wiped on {@link dispose} only if `shouldWipeSignerOnDisposal` is set. The safe's address is
102
- * predicted from the signer's address on the first call to {@link getAddress}.
113
+ * The signer is wiped on {@link dispose} only if `shouldWipeSignerOnDisposal` is set. Unless `safeAddress` is set,
114
+ * the safe's address is predicted from the signer's address on the first call to {@link getAddress}.
103
115
  *
104
116
  * @overload
105
117
  * @param {ISignerEvm} signer - A signer implementing the EVM signer interface.
106
- * @param {EvmErc4337WalletConfig & SignerOptions} config - The configuration object.
118
+ * @param {EvmErc4337WalletConfig & SignerOptions & EvmErc4337SafeOptions} config - The configuration object.
119
+ * @throws {ValueError} If `config.safeAddress` is set and is not a well-formed evm address.
107
120
  */
108
121
 
109
122
  constructor (seedOrSigner, pathOrConfig, config) {
@@ -116,7 +129,19 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
116
129
  ]
117
130
  : [seedOrSigner, pathOrConfig]
118
131
 
132
+ let pinnedSafeAddress
133
+
119
134
  try {
135
+ const safeAddress = configuration?.safeAddress
136
+
137
+ if (safeAddress !== undefined && safeAddress !== null) {
138
+ if (!isAddress(safeAddress)) {
139
+ throw new ValueError(`Invalid safe address: '${safeAddress}'.`)
140
+ }
141
+
142
+ pinnedSafeAddress = getAddress(safeAddress)
143
+ }
144
+
120
145
  super(undefined, configuration)
121
146
  } catch (error) {
122
147
  if (isSeed) signer.dispose()
@@ -143,8 +168,24 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
143
168
  /** @private */
144
169
  this._signer = signer
145
170
 
171
+ /**
172
+ * The safe address given in the configuration, or `undefined` if the safe is predicted from the signer.
173
+ *
174
+ * @private
175
+ * @type {string | undefined}
176
+ */
177
+ this._pinnedSafeAddress = pinnedSafeAddress
178
+
146
179
  /** @private */
147
- this._safeAddress = undefined
180
+ this._safeAddress = pinnedSafeAddress
181
+
182
+ /**
183
+ * True once the pinned safe has been checked against the signer.
184
+ *
185
+ * @private
186
+ * @type {boolean}
187
+ */
188
+ this._pinnedSafeChecked = false
148
189
 
149
190
  /**
150
191
  * Cached quotes from fee estimations, keyed by serialized transaction and paymaster configuration.
@@ -191,7 +232,8 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
191
232
  * The account owns the key and wipes it on {@link dispose}.
192
233
  *
193
234
  * @param {string | Uint8Array} privateKey - The raw private key (hex string with or without 0x, or 32 bytes).
194
- * @param {EvmErc4337WalletConfig} config - The configuration object.
235
+ * @param {EvmErc4337WalletConfig & EvmErc4337SafeOptions} config - The configuration object.
236
+ * @throws {ValueError} If `config.safeAddress` is set and is not a well-formed evm address.
195
237
  * @returns {WalletAccountEvmErc4337} The wallet account.
196
238
  */
197
239
  static fromPrivateKey (privateKey, config) {
@@ -230,7 +272,8 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
230
272
  }
231
273
 
232
274
  /**
233
- * Returns the account's address, which is the safe's address predicted from the signer's address.
275
+ * Returns the account's address: the `safeAddress` given in the configuration if set, otherwise the safe's
276
+ * address predicted from the signer's address.
234
277
  *
235
278
  * @returns {Promise<string>} The account's address.
236
279
  * @throws {ValueError} If the signer's address is not a well-formed evm address.
@@ -244,27 +287,41 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
244
287
  /**
245
288
  * Signs a message as the safe (ERC-1271 / SafeMessage), so the safe's `isValidSignature` accepts it.
246
289
  *
290
+ * While the safe is not deployed, the signature is wrapped in an [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492)
291
+ * signature, so that verifiers can simulate the safe's deployment to check it. Use
292
+ * {@link WalletAccountReadOnlyEvmErc4337.unwrapErc6492Signature} to get the ERC-1271 signature it wraps.
293
+ *
247
294
  * @param {string} message - The message to sign.
248
295
  * @returns {Promise<string>} The message's signature.
296
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
249
297
  * @throws {DisposalError} If the account, or the externally supplied signer it uses, has been disposed.
250
298
  */
251
299
  async sign (message) {
252
300
  this._guardDisposed()
253
301
 
254
- return await this._signer.signTypedData(await this._getSafeMessageTypedData(hashMessage(message)))
302
+ await this._checkPinnedSafe()
303
+
304
+ return await this._signSafeMessage(hashMessage(message))
255
305
  }
256
306
 
257
307
  /**
258
308
  * Signs typed data according to EIP-712 as the safe (ERC-1271 / SafeMessage), so the safe's `isValidSignature` accepts it.
259
309
  *
310
+ * While the safe is not deployed, the signature is wrapped in an [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492)
311
+ * signature, so that verifiers can simulate the safe's deployment to check it. Use
312
+ * {@link WalletAccountReadOnlyEvmErc4337.unwrapErc6492Signature} to get the ERC-1271 signature it wraps.
313
+ *
260
314
  * @param {TypedData} typedData - The typed data to sign.
261
315
  * @returns {Promise<string>} The typed data signature.
316
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
262
317
  * @throws {DisposalError} If the account, or the externally supplied signer it uses, has been disposed.
263
318
  */
264
319
  async signTypedData ({ domain, types, message }) {
265
320
  this._guardDisposed()
266
321
 
267
- return await this._signer.signTypedData(await this._getSafeMessageTypedData(TypedDataEncoder.hash(domain, types, message)))
322
+ await this._checkPinnedSafe()
323
+
324
+ return await this._signSafeMessage(TypedDataEncoder.hash(domain, types, message))
268
325
  }
269
326
 
270
327
  /**
@@ -276,6 +333,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
276
333
  * @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
277
334
  * @returns {Promise<UserOperationV7>} The signed user operation.
278
335
  * @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
336
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
279
337
  * @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
280
338
  * @throws {MaximumFeeExceededError} If the transaction is not sponsored, and the transaction's cost surpasses the transaction max. fee option.
281
339
  * @throws {TransactionError} If the paymaster reports AA50 (the account cannot repay the paymaster).
@@ -290,6 +348,8 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
290
348
  this._validateConfig(mergedConfig)
291
349
  }
292
350
 
351
+ await this._checkPinnedSafe()
352
+
293
353
  const prepared = await this._prepareForSend(tx, [tx], mergedConfig)
294
354
 
295
355
  const fee = prepared.fee
@@ -420,6 +480,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
420
480
  * @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
421
481
  * @returns {Promise<TransactionResult>} The transaction's result.
422
482
  * @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
483
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
423
484
  * @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
424
485
  * @throws {MaximumFeeExceededError} If the transaction is not sponsored, and the transaction's cost surpasses the transaction max. fee option.
425
486
  * @throws {ValueError} If `nonceKey` is a bigint outside the uint192 range (0 to 2^192 - 1).
@@ -435,6 +496,8 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
435
496
  this._validateConfig(mergedConfig)
436
497
  }
437
498
 
499
+ await this._checkPinnedSafe()
500
+
438
501
  if (WalletAccountEvmErc4337._isSignedUserOperation(tx)) {
439
502
  const fee = mergedConfig.isSponsored ? 0n : WalletAccountEvmErc4337._getSignedUserOperationFee(tx)
440
503
 
@@ -464,6 +527,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
464
527
  * @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
465
528
  * @returns {Promise<TransferResult>} The transfer's result.
466
529
  * @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
530
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
467
531
  * @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
468
532
  * @throws {MaximumFeeExceededError} If the transaction is not sponsored, and the transfer's cost surpasses the transfer max. fee option.
469
533
  * @throws {ValueError} If `nonceKey` is a bigint outside the uint192 range (0 to 2^192 - 1).
@@ -481,6 +545,8 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
481
545
 
482
546
  const { isSponsored, transferMaxFee } = mergedConfig
483
547
 
548
+ await this._checkPinnedSafe()
549
+
484
550
  const tx = await WalletAccountReadOnlyEvmErc4337._getTransferTransaction(options)
485
551
 
486
552
  const txs = [tx]
@@ -500,11 +566,38 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
500
566
  * @returns {Promise<WalletAccountReadOnlyEvmErc4337>} The read-only account.
501
567
  */
502
568
  async toReadOnlyAccount () {
503
- const address = await this._getOwnerAddress()
569
+ const { safeAddress, ...config } = this._config
570
+ const ownerAddress = await this._getOwnerAddress()
571
+
572
+ if (this._pinnedSafeAddress !== undefined &&
573
+ this._pinnedSafeAddress !== WalletAccountReadOnlyEvmErc4337.predictSafeAddress(ownerAddress, config)) {
574
+ return WalletAccountReadOnlyEvmErc4337.fromSafeAddress(this._pinnedSafeAddress, config)
575
+ }
576
+
577
+ return new WalletAccountReadOnlyEvmErc4337(ownerAddress, config)
578
+ }
579
+
580
+ /**
581
+ * Signs a hash as the safe (ERC-1271 / SafeMessage). While the safe is not deployed, wraps the signature in an
582
+ * ERC-6492 signature that deploys the safe predicted from the signer's address.
583
+ *
584
+ * @private
585
+ * @param {string} hash - The hash of the message or typed data (EIP-191 / EIP-712).
586
+ * @returns {Promise<string>} The signature.
587
+ */
588
+ async _signSafeMessage (hash) {
589
+ const isDeployed = await this._isSafeDeployed()
504
590
 
505
- const readOnlyAccount = new WalletAccountReadOnlyEvmErc4337(address, this._config)
591
+ const signature = await this._signer.signTypedData(await this._getSafeMessageTypedData(hash))
506
592
 
507
- return readOnlyAccount
593
+ if (isDeployed) {
594
+ return signature
595
+ }
596
+
597
+ const overrides = WalletAccountReadOnlyEvmErc4337._getInitCodeOverrides(this._config)
598
+ const [factory, factoryData] = SafeAccount030.createFactoryAddressAndData([await this._getOwnerAddress()], overrides)
599
+
600
+ return WalletAccountReadOnlyEvmErc4337._wrapErc6492Signature(factory, factoryData, signature)
508
601
  }
509
602
 
510
603
  /**
@@ -518,7 +611,41 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
518
611
  }
519
612
 
520
613
  /**
521
- * Disposes the wallet account, erasing the private key from the memory.
614
+ * Checks that the signer can operate the safe pinned through `safeAddress`. Nothing to check if no safe is pinned or
615
+ * if it is the signer's own predicted safe; otherwise, it must be a deployed safe that counts the signer among its
616
+ * owners. A successful check is cached.
617
+ *
618
+ * @private
619
+ * @throws {ConfigurationError} If the signer cannot operate the pinned safe.
620
+ * @returns {Promise<void>}
621
+ */
622
+ async _checkPinnedSafe () {
623
+ if (this._pinnedSafeAddress === undefined || this._pinnedSafeChecked) return
624
+
625
+ const safeAddress = this._pinnedSafeAddress
626
+ const ownerAddress = await this._getOwnerAddress()
627
+
628
+ if (safeAddress !== WalletAccountReadOnlyEvmErc4337.predictSafeAddress(ownerAddress, this._config)) {
629
+ const safe = new Contract(safeAddress, SAFE_ABI, this._provider)
630
+
631
+ // No code at the address (undeployed safe, eoa) returns no data; a non-safe contract reverts.
632
+ const isOwner = await safe.isOwner(ownerAddress).catch((error) => {
633
+ if (WalletAccountReadOnlyEvmErc4337._isRejectedCallError(error)) return false
634
+
635
+ throw error
636
+ })
637
+
638
+ if (!isOwner) {
639
+ throw new ConfigurationError(`The signer '${ownerAddress}' is not an owner of a safe deployed at '${safeAddress}'.`)
640
+ }
641
+ }
642
+
643
+ this._pinnedSafeChecked = true
644
+ }
645
+
646
+ /**
647
+ * Disposes the wallet account. The signer's private key is erased only if the account owns the signer (created from a
648
+ * seed or private key, or with `shouldWipeSignerOnDisposal`); otherwise a signer you supplied is left untouched.
522
649
  */
523
650
  dispose () {
524
651
  if (this._disposed) return
@@ -14,7 +14,7 @@
14
14
 
15
15
  'use strict'
16
16
 
17
- import { Contract, TypedDataEncoder, getAddress, hashMessage, isAddress, isError, isHexString, verifyTypedData } from 'ethers'
17
+ import { AbiCoder, Contract, TypedDataEncoder, concat, dataLength, dataSlice, getAddress, hashMessage, isAddress, isError, isHexString, verifyTypedData } from 'ethers'
18
18
 
19
19
  import { WalletAccountReadOnly, NoSuchElementError, TransactionError, TransactionErrorReason, UnsupportedOperationError, ValueError } from '@tetherto/wdk-wallet'
20
20
 
@@ -44,6 +44,10 @@ const ERC1271_ABI = [
44
44
  'function isValidSignature(bytes32 _dataHash, bytes _signature) view returns (bytes4)'
45
45
  ]
46
46
 
47
+ const ERC6492_MAGIC_BYTES = '0x' + '6492'.repeat(16)
48
+
49
+ const ERC6492_WRAPPER_TYPES = ['address', 'bytes', 'bytes']
50
+
47
51
  const PaymasterMode = {
48
52
  NATIVE: 'native',
49
53
  SPONSORED: 'sponsored',
@@ -221,7 +225,7 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
221
225
  ? [config, address]
222
226
  : [unpinnedConfig, undefined]
223
227
 
224
- super(pinnedSafeAddress ?? (address ? WalletAccountReadOnlyEvmErc4337.predictSafeAddress(address, config) : undefined))
228
+ super(pinnedSafeAddress ?? (address ? WalletAccountReadOnlyEvmErc4337.predictSafeAddress(address, config) : undefined), accountConfig)
225
229
 
226
230
  /**
227
231
  * The read-only evm erc-4337 wallet account configuration.
@@ -331,6 +335,37 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
331
335
  return new WalletAccountReadOnlyEvmErc4337(undefined, { ...config, [PINNED_SAFE_ADDRESS]: getAddress(safeAddress) })
332
336
  }
333
337
 
338
+ /**
339
+ * Returns the ERC-1271 signature inside an [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) signature, as
340
+ * returned by the account's `sign` and `signTypedData` methods while the safe is not deployed. Signatures that are
341
+ * not ERC-6492 signatures are returned unchanged.
342
+ *
343
+ * Useful for verifiers that do not support ERC-6492 and check the signature through the safe's
344
+ * `isValidSignature` once the safe is deployed (e.g. permits or orders settled on-chain after the deployment).
345
+ *
346
+ * @param {string} signature - The signature.
347
+ * @throws {ValueError} If the signature ends with the ERC-6492 magic bytes, but is not a well-formed ERC-6492 signature.
348
+ * @returns {string} The ERC-1271 signature.
349
+ */
350
+ static unwrapErc6492Signature (signature) {
351
+ if (!isHexString(signature) || !signature.toLowerCase().endsWith(ERC6492_MAGIC_BYTES.slice(2))) {
352
+ return signature
353
+ }
354
+
355
+ try {
356
+ const wrapper = dataSlice(signature, 0, dataLength(signature) - dataLength(ERC6492_MAGIC_BYTES))
357
+ const [, , innerSignature] = AbiCoder.defaultAbiCoder().decode(ERC6492_WRAPPER_TYPES, wrapper)
358
+
359
+ return innerSignature
360
+ } catch (error) {
361
+ if (isError(error, 'BUFFER_OVERRUN') || isError(error, 'INVALID_ARGUMENT')) {
362
+ throw new ValueError('Invalid ERC-6492 signature.')
363
+ }
364
+
365
+ throw error
366
+ }
367
+ }
368
+
334
369
  /**
335
370
  * Returns the account's eth balance.
336
371
  *
@@ -549,7 +584,8 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
549
584
  }
550
585
 
551
586
  /**
552
- * Verifies a message's signature, as produced by the safe (ERC-1271 / SafeMessage).
587
+ * Verifies a message's signature, as produced by the safe (ERC-1271 / SafeMessage). ERC-6492 signatures are
588
+ * accepted too, and checked through the ERC-1271 signature they wrap.
553
589
  *
554
590
  * If the safe is deployed, the signature is checked on-chain through the safe's `isValidSignature`. Otherwise,
555
591
  * it is checked offline against the safe's owner.
@@ -564,7 +600,8 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
564
600
  }
565
601
 
566
602
  /**
567
- * Verifies a typed data signature, as produced by the safe (ERC-1271 / SafeMessage).
603
+ * Verifies a typed data signature, as produced by the safe (ERC-1271 / SafeMessage). ERC-6492 signatures are
604
+ * accepted too, and checked through the ERC-1271 signature they wrap.
568
605
  *
569
606
  * If the safe is deployed, the signature is checked on-chain through the safe's `isValidSignature`. Otherwise,
570
607
  * it is checked offline against the safe's owner.
@@ -678,6 +715,16 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
678
715
  * @returns {Promise<boolean>} True if the signature is valid.
679
716
  */
680
717
  async _verifySafeMessage (hash, signature, methodName) {
718
+ try {
719
+ signature = WalletAccountReadOnlyEvmErc4337.unwrapErc6492Signature(signature)
720
+ } catch (error) {
721
+ if (error instanceof ValueError) {
722
+ return false
723
+ }
724
+
725
+ throw error
726
+ }
727
+
681
728
  if (await this._isSafeDeployed()) {
682
729
  const safe = new Contract(await this.getAddress(), ERC1271_ABI, this._provider)
683
730
 
@@ -686,7 +733,7 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
686
733
 
687
734
  return result.toLowerCase() === ERC1271_MAGIC_VALUE
688
735
  } catch (error) {
689
- if (WalletAccountReadOnlyEvmErc4337._isInvalidSignatureError(error)) {
736
+ if (WalletAccountReadOnlyEvmErc4337._isRejectedCallError(error)) {
690
737
  return false
691
738
  }
692
739
 
@@ -716,14 +763,14 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
716
763
  }
717
764
 
718
765
  /**
719
- * Returns whether an `isValidSignature` error means the signature is invalid (revert, bad input or output),
720
- * rather than a failed check (e.g. a network error). ethers reports any EIP-1193 `eth_call` error as a CALL_EXCEPTION.
766
+ * Returns whether a contract call error means the contract rejected the call (revert, bad input or output),
767
+ * rather than the call failing (e.g. a network error). ethers reports any EIP-1193 `eth_call` error as a CALL_EXCEPTION.
721
768
  *
722
769
  * @protected
723
770
  * @param {unknown} error - The error.
724
- * @returns {boolean} True if the error means that the signature is invalid.
771
+ * @returns {boolean} True if the contract rejected the call.
725
772
  */
726
- static _isInvalidSignatureError (error) {
773
+ static _isRejectedCallError (error) {
727
774
  if (isError(error, 'INVALID_ARGUMENT') || isError(error, 'BAD_DATA')) {
728
775
  return true
729
776
  }
@@ -741,6 +788,22 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
741
788
  return rpcError?.code === 3 || /revert/i.test(rpcError?.message ?? '')
742
789
  }
743
790
 
791
+ /**
792
+ * Wraps an ERC-1271 signature of a safe that is not deployed yet in an [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492)
793
+ * signature, so that verifiers can simulate the safe's deployment before calling its `isValidSignature`.
794
+ *
795
+ * @protected
796
+ * @param {string} factory - The address of the factory that deploys the safe.
797
+ * @param {string} factoryData - The calldata that deploys the safe through the factory.
798
+ * @param {string} signature - The ERC-1271 signature.
799
+ * @returns {string} The ERC-6492 signature.
800
+ */
801
+ static _wrapErc6492Signature (factory, factoryData, signature) {
802
+ const wrapper = AbiCoder.defaultAbiCoder().encode(ERC6492_WRAPPER_TYPES, [factory, factoryData, signature])
803
+
804
+ return concat([wrapper, ERC6492_MAGIC_BYTES])
805
+ }
806
+
744
807
  /**
745
808
  * Returns whether the safe is deployed. A safe cannot be undeployed, so a positive result is cached.
746
809
  *
@@ -14,6 +14,8 @@
14
14
 
15
15
  'use strict'
16
16
 
17
+ import { isAddress } from 'ethers'
18
+
17
19
  import WalletManager, { DisposalError, InvalidSignerError, ProviderRequiredError, ValueError } from '@tetherto/wdk-wallet'
18
20
 
19
21
  import WalletManagerEvm, { WalletAccountReadOnlyEvm } from '@tetherto/wdk-wallet-evm'
@@ -31,6 +33,11 @@ import WalletAccountEvmErc4337 from './wallet-account-evm-erc-4337.js'
31
33
 
32
34
  /** @typedef {import('./wallet-account-evm-erc-4337.js').EvmErc4337WalletConfig} EvmErc4337WalletConfig */
33
35
 
36
+ /**
37
+ * @typedef {Object} EvmErc4337WalletManagerSafeOptions
38
+ * @property {Record<string, string>} [safeAddresses] - Binds accounts to existing safes, instead of the safes predicted from their owners (e.g. after an owner change). Maps an account key to the safe's address. The keys are the manager's account cache keys, with derivation paths as given to {@link WalletManagerEvmErc4337#getAccountByPath}: "0'/0/0" binds the account derived at that path from the default signer (also returned by `getAccount(0)`), "<signerName>:0'/0/0" the account derived at that path from a named signer, and "<signerName>" the account bound to a named signer (see {@link WalletManagerEvmErc4337#getAccount}). Each bound account checks its safe as described for the account's `safeAddress` option.
39
+ */
40
+
34
41
  const BIP_44_ETH_DERIVATION_PATH_PREFIX = "m/44'/60'"
35
42
 
36
43
  /** @extends {WalletManager<ISignerEvm>} */
@@ -48,9 +55,10 @@ export default class WalletManagerEvmErc4337 extends WalletManager {
48
55
  *
49
56
  * @overload
50
57
  * @param {string | Uint8Array} seed - A [BIP-39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes).
51
- * @param {EvmErc4337WalletConfig} config - The configuration object.
58
+ * @param {EvmErc4337WalletConfig & EvmErc4337WalletManagerSafeOptions} config - The configuration object.
52
59
  * @throws {ValueError} If the seed phrase is invalid.
53
60
  * @throws {ValueError} If the `provider` option is set to an empty list.
61
+ * @throws {ValueError} If a `safeAddresses` value is not a well-formed evm address.
54
62
  */
55
63
 
56
64
  /**
@@ -61,9 +69,10 @@ export default class WalletManagerEvmErc4337 extends WalletManager {
61
69
  *
62
70
  * @overload
63
71
  * @param {ISignerEvm} signer - The default signer.
64
- * @param {EvmErc4337WalletConfig} config - The configuration object.
72
+ * @param {EvmErc4337WalletConfig & EvmErc4337WalletManagerSafeOptions} config - The configuration object.
65
73
  * @throws {InvalidSignerError} If the default signer does not support account derivation.
66
74
  * @throws {ValueError} If the `provider` option is set to an empty list.
75
+ * @throws {ValueError} If a `safeAddresses` value is not a well-formed evm address.
67
76
  */
68
77
 
69
78
  constructor (seedOrSigner, config) {
@@ -71,6 +80,12 @@ export default class WalletManagerEvmErc4337 extends WalletManager {
71
80
  throw new ValueError("The 'provider' option cannot be set to an empty list.")
72
81
  }
73
82
 
83
+ for (const safeAddress of Object.values(config.safeAddresses ?? {})) {
84
+ if (!isAddress(safeAddress)) {
85
+ throw new ValueError(`Invalid safe address: '${safeAddress}'.`)
86
+ }
87
+ }
88
+
74
89
  const isSeed = typeof seedOrSigner === 'string' || seedOrSigner instanceof Uint8Array
75
90
 
76
91
  super(isSeed ? new SeedSignerEvm(seedOrSigner, BIP_44_ETH_DERIVATION_PATH_PREFIX) : seedOrSigner, config)
@@ -87,7 +102,7 @@ export default class WalletManagerEvmErc4337 extends WalletManager {
87
102
  * The evm erc-4337 wallet configuration.
88
103
  *
89
104
  * @protected
90
- * @type {EvmErc4337WalletConfig}
105
+ * @type {EvmErc4337WalletConfig & EvmErc4337WalletManagerSafeOptions}
91
106
  */
92
107
  this._config = config
93
108
 
@@ -134,7 +149,9 @@ export default class WalletManagerEvmErc4337 extends WalletManager {
134
149
  throw new DisposalError('The given signer has been disposed.')
135
150
  }
136
151
 
137
- this._accounts[key] = new WalletAccountEvmErc4337(signer, this._accountConfig())
152
+ const safeAddress = this._config.safeAddresses?.[key]
153
+
154
+ this._accounts[key] = new WalletAccountEvmErc4337(signer, { ...this._accountConfig(), safeAddress })
138
155
  }
139
156
 
140
157
  return this._accounts[key]
@@ -186,7 +203,9 @@ export default class WalletManagerEvmErc4337 extends WalletManager {
186
203
  childSigner.dispose()
187
204
  } else {
188
205
  try {
189
- this._accounts[key] = new WalletAccountEvmErc4337(childSigner, { ...this._accountConfig(), shouldWipeSignerOnDisposal: true })
206
+ const safeAddress = this._config.safeAddresses?.[key]
207
+
208
+ this._accounts[key] = new WalletAccountEvmErc4337(childSigner, { ...this._accountConfig(), safeAddress, shouldWipeSignerOnDisposal: true })
190
209
  } catch (error) {
191
210
  childSigner.dispose()
192
211
 
@@ -200,13 +219,16 @@ export default class WalletManagerEvmErc4337 extends WalletManager {
200
219
 
201
220
  /**
202
221
  * Builds the account config, injecting the manager's shared provider so accounts reuse the
203
- * single ethers provider instance instead of opening their own.
222
+ * single ethers provider instance instead of opening their own. The `safeAddresses` option is
223
+ * dropped, since it is resolved per account.
204
224
  *
205
225
  * @private
206
226
  * @returns {EvmErc4337WalletConfig} The account configuration.
207
227
  */
208
228
  _accountConfig () {
209
- return { ...this._config, provider: this._provider }
229
+ const { safeAddresses, ...config } = this._config
230
+
231
+ return { ...config, provider: this._provider }
210
232
  }
211
233
 
212
234
  /**
@@ -231,7 +253,10 @@ export default class WalletManagerEvmErc4337 extends WalletManager {
231
253
  }
232
254
 
233
255
  /**
234
- * Disposes all the wallet accounts, erasing their private keys from the memory.
256
+ * Disposes the wallet accounts, erasing their private keys from memory, and the default signer if the manager created
257
+ * it from a seed. Signers you supplied are never disposed, so an account created directly on one with
258
+ * getAccount(signerName) keeps its key. The seed you passed in is never wiped (a seed phrase string stays in memory
259
+ * until it is garbage collected).
235
260
  */
236
261
  dispose () {
237
262
  if (this._shouldWipeDefaultSignerOnDisposal) {
package/types/index.d.ts CHANGED
@@ -16,6 +16,8 @@ export type EvmErc4337Transaction = import("./src/wallet-account-read-only-evm-e
16
16
  export type EvmErc4337GasOverrides = import("./src/wallet-account-read-only-evm-erc-4337.js").EvmErc4337GasOverrides;
17
17
  export type EvmErc4337TransferOptions = import("./src/wallet-account-read-only-evm-erc-4337.js").EvmErc4337TransferOptions;
18
18
  export type EvmErc4337ApproveOptions = import("./src/wallet-account-evm-erc-4337.js").EvmErc4337ApproveOptions;
19
+ export type EvmErc4337SafeOptions = import("./src/wallet-account-evm-erc-4337.js").EvmErc4337SafeOptions;
20
+ export type EvmErc4337WalletManagerSafeOptions = import("./src/wallet-manager-evm-erc-4337.js").EvmErc4337WalletManagerSafeOptions;
19
21
  export type Nonce = import("./src/wallet-account-read-only-evm-erc-4337.js").Nonce;
20
22
  export type TransactionResult = import("@tetherto/wdk-wallet-evm").TransactionResult;
21
23
  export type TransferOptions = import("@tetherto/wdk-wallet-evm").TransferOptions;
@@ -6,40 +6,44 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
6
6
  * The account owns the key and wipes it on {@link dispose}.
7
7
  *
8
8
  * @param {string | Uint8Array} privateKey - The raw private key (hex string with or without 0x, or 32 bytes).
9
- * @param {EvmErc4337WalletConfig} config - The configuration object.
9
+ * @param {EvmErc4337WalletConfig & EvmErc4337SafeOptions} config - The configuration object.
10
+ * @throws {ValueError} If `config.safeAddress` is set and is not a well-formed evm address.
10
11
  * @returns {WalletAccountEvmErc4337} The wallet account.
11
12
  */
12
- static fromPrivateKey(privateKey: string | Uint8Array, config: EvmErc4337WalletConfig): WalletAccountEvmErc4337;
13
+ static fromPrivateKey(privateKey: string | Uint8Array, config: EvmErc4337WalletConfig & EvmErc4337SafeOptions): WalletAccountEvmErc4337;
13
14
  /**
14
15
  * Creates a new evm [erc-4337](https://www.erc4337.io/docs) wallet account from a BIP-39 seed.
15
16
  *
16
17
  * @overload
17
18
  * @param {string | Uint8Array} seed - A [BIP-39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes).
18
19
  * @param {string} path - The BIP-44 derivation path, relative to "m/44'/60'" (e.g. "0'/0/0").
19
- * @param {EvmErc4337WalletConfig} config - The configuration object.
20
+ * @param {EvmErc4337WalletConfig & EvmErc4337SafeOptions} config - The configuration object.
20
21
  * @throws {ValueError} If the given seed phrase is invalid.
22
+ * @throws {ValueError} If `config.safeAddress` is set and is not a well-formed evm address.
21
23
  */
22
- constructor(seed: string | Uint8Array, path: string, config: EvmErc4337WalletConfig);
24
+ constructor(seed: string | Uint8Array, path: string, config: EvmErc4337WalletConfig & EvmErc4337SafeOptions);
23
25
  /**
24
26
  * Creates a new evm [erc-4337](https://www.erc4337.io/docs) wallet account from a BIP-39 seed at path m/44'/60'/0'/0/0.
25
27
  *
26
28
  * @overload
27
29
  * @param {string | Uint8Array} seed - A [BIP-39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes).
28
- * @param {EvmErc4337WalletConfig} config - The configuration object.
30
+ * @param {EvmErc4337WalletConfig & EvmErc4337SafeOptions} config - The configuration object.
29
31
  * @throws {ValueError} If the given seed phrase is invalid.
32
+ * @throws {ValueError} If `config.safeAddress` is set and is not a well-formed evm address.
30
33
  */
31
- constructor(seed: string | Uint8Array, config: EvmErc4337WalletConfig);
34
+ constructor(seed: string | Uint8Array, config: EvmErc4337WalletConfig & EvmErc4337SafeOptions);
32
35
  /**
33
36
  * Creates a new evm [erc-4337](https://www.erc4337.io/docs) wallet account using a signer as the safe's owner.
34
37
  *
35
- * The signer is wiped on {@link dispose} only if `shouldWipeSignerOnDisposal` is set. The safe's address is
36
- * predicted from the signer's address on the first call to {@link getAddress}.
38
+ * The signer is wiped on {@link dispose} only if `shouldWipeSignerOnDisposal` is set. Unless `safeAddress` is set,
39
+ * the safe's address is predicted from the signer's address on the first call to {@link getAddress}.
37
40
  *
38
41
  * @overload
39
42
  * @param {ISignerEvm} signer - A signer implementing the EVM signer interface.
40
- * @param {EvmErc4337WalletConfig & SignerOptions} config - The configuration object.
43
+ * @param {EvmErc4337WalletConfig & SignerOptions & EvmErc4337SafeOptions} config - The configuration object.
44
+ * @throws {ValueError} If `config.safeAddress` is set and is not a well-formed evm address.
41
45
  */
42
- constructor(signer: ISignerEvm, config: EvmErc4337WalletConfig & SignerOptions);
46
+ constructor(signer: ISignerEvm, config: EvmErc4337WalletConfig & SignerOptions & EvmErc4337SafeOptions);
43
47
  /**
44
48
  * Creates a read-only account for a safe whose address is already known. Not supported on the writable
45
49
  * account: a safe address cannot produce a signer. Use {@link WalletAccountReadOnlyEvmErc4337.fromSafeAddress}.
@@ -66,8 +70,22 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
66
70
  protected _shouldWipeSignerOnDisposal: boolean;
67
71
  /** @private */
68
72
  private _signer;
73
+ /**
74
+ * The safe address given in the configuration, or `undefined` if the safe is predicted from the signer.
75
+ *
76
+ * @private
77
+ * @type {string | undefined}
78
+ */
79
+ private _pinnedSafeAddress;
69
80
  /** @private */
70
81
  private _safeAddress;
82
+ /**
83
+ * True once the pinned safe has been checked against the signer.
84
+ *
85
+ * @private
86
+ * @type {boolean}
87
+ */
88
+ private _pinnedSafeChecked;
71
89
  /** @private */
72
90
  private _quoteCache;
73
91
  /** @private */
@@ -101,7 +119,8 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
101
119
  */
102
120
  get keyPair(): KeyPair | null;
103
121
  /**
104
- * Returns the account's address, which is the safe's address predicted from the signer's address.
122
+ * Returns the account's address: the `safeAddress` given in the configuration if set, otherwise the safe's
123
+ * address predicted from the signer's address.
105
124
  *
106
125
  * @returns {Promise<string>} The account's address.
107
126
  * @throws {ValueError} If the signer's address is not a well-formed evm address.
@@ -110,16 +129,26 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
110
129
  /**
111
130
  * Signs a message as the safe (ERC-1271 / SafeMessage), so the safe's `isValidSignature` accepts it.
112
131
  *
132
+ * While the safe is not deployed, the signature is wrapped in an [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492)
133
+ * signature, so that verifiers can simulate the safe's deployment to check it. Use
134
+ * {@link WalletAccountReadOnlyEvmErc4337.unwrapErc6492Signature} to get the ERC-1271 signature it wraps.
135
+ *
113
136
  * @param {string} message - The message to sign.
114
137
  * @returns {Promise<string>} The message's signature.
138
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
115
139
  * @throws {DisposalError} If the account, or the externally supplied signer it uses, has been disposed.
116
140
  */
117
141
  sign(message: string): Promise<string>;
118
142
  /**
119
143
  * Signs typed data according to EIP-712 as the safe (ERC-1271 / SafeMessage), so the safe's `isValidSignature` accepts it.
120
144
  *
145
+ * While the safe is not deployed, the signature is wrapped in an [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492)
146
+ * signature, so that verifiers can simulate the safe's deployment to check it. Use
147
+ * {@link WalletAccountReadOnlyEvmErc4337.unwrapErc6492Signature} to get the ERC-1271 signature it wraps.
148
+ *
121
149
  * @param {TypedData} typedData - The typed data to sign.
122
150
  * @returns {Promise<string>} The typed data signature.
151
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
123
152
  * @throws {DisposalError} If the account, or the externally supplied signer it uses, has been disposed.
124
153
  */
125
154
  signTypedData({ domain, types, message }: TypedData): Promise<string>;
@@ -132,6 +161,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
132
161
  * @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
133
162
  * @returns {Promise<UserOperationV7>} The signed user operation.
134
163
  * @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
164
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
135
165
  * @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
136
166
  * @throws {MaximumFeeExceededError} If the transaction is not sponsored, and the transaction's cost surpasses the transaction max. fee option.
137
167
  * @throws {TransactionError} If the paymaster reports AA50 (the account cannot repay the paymaster).
@@ -179,6 +209,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
179
209
  * @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
180
210
  * @returns {Promise<TransactionResult>} The transaction's result.
181
211
  * @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
212
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
182
213
  * @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
183
214
  * @throws {MaximumFeeExceededError} If the transaction is not sponsored, and the transaction's cost surpasses the transaction max. fee option.
184
215
  * @throws {ValueError} If `nonceKey` is a bigint outside the uint192 range (0 to 2^192 - 1).
@@ -195,6 +226,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
195
226
  * @param {Partial<EvmErc4337WalletPaymasterTokenConfig | EvmErc4337WalletSponsorshipPolicyConfig | EvmErc4337WalletNativeCoinsConfig>} [config] - If set, overrides the given configuration options.
196
227
  * @returns {Promise<TransferResult>} The transfer's result.
197
228
  * @throws {ConfigurationError} If the override `config` is invalid or has missing required fields.
229
+ * @throws {ConfigurationError} If `safeAddress` is set and the signer cannot operate that safe.
198
230
  * @throws {ConfigurationError} If, in token mode, the configured `paymasterAddress` does not match the paymaster address returned by the paymaster RPC. This guards against the auto-generated ERC-20 approval targeting an unexpected paymaster contract.
199
231
  * @throws {MaximumFeeExceededError} If the transaction is not sponsored, and the transfer's cost surpasses the transfer max. fee option.
200
232
  * @throws {ValueError} If `nonceKey` is a bigint outside the uint192 range (0 to 2^192 - 1).
@@ -208,6 +240,15 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
208
240
  * @returns {Promise<WalletAccountReadOnlyEvmErc4337>} The read-only account.
209
241
  */
210
242
  toReadOnlyAccount(): Promise<WalletAccountReadOnlyEvmErc4337>;
243
+ /**
244
+ * Signs a hash as the safe (ERC-1271 / SafeMessage). While the safe is not deployed, wraps the signature in an
245
+ * ERC-6492 signature that deploys the safe predicted from the signer's address.
246
+ *
247
+ * @private
248
+ * @param {string} hash - The hash of the message or typed data (EIP-191 / EIP-712).
249
+ * @returns {Promise<string>} The signature.
250
+ */
251
+ private _signSafeMessage;
211
252
  /**
212
253
  * Returns the safe owner's address, as given by the signer.
213
254
  *
@@ -216,7 +257,18 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
216
257
  */
217
258
  protected _getOwnerAddress(): Promise<string>;
218
259
  /**
219
- * Disposes the wallet account, erasing the private key from the memory.
260
+ * Checks that the signer can operate the safe pinned through `safeAddress`. Nothing to check if no safe is pinned or
261
+ * if it is the signer's own predicted safe; otherwise, it must be a deployed safe that counts the signer among its
262
+ * owners. A successful check is cached.
263
+ *
264
+ * @private
265
+ * @throws {ConfigurationError} If the signer cannot operate the pinned safe.
266
+ * @returns {Promise<void>}
267
+ */
268
+ private _checkPinnedSafe;
269
+ /**
270
+ * Disposes the wallet account. The signer's private key is erased only if the account owns the signer (created from
271
+ * a seed or private key, or with `shouldWipeSignerOnDisposal`); otherwise a signer you supplied is left untouched.
220
272
  */
221
273
  dispose(): void;
222
274
  /** @private */
@@ -259,6 +311,12 @@ export type EvmErc4337WalletNativeCoinsConfig = import("./wallet-account-read-on
259
311
  * The options of a token approval, extended with the optional UserOperationV7 gas overrides.
260
312
  */
261
313
  export type EvmErc4337ApproveOptions = ApproveOptions & EvmErc4337GasOverrides;
314
+ export type EvmErc4337SafeOptions = {
315
+ /**
316
+ * - The address of an existing safe to operate, instead of the safe predicted from the signer's address (e.g. after the safe's owner was changed). Unless it is the signer's own predicted safe, it must be a deployed safe that counts the signer among its owners; this is checked on the first operation that signs or sends.
317
+ */
318
+ safeAddress?: string;
319
+ };
262
320
  export type UserOperationV7 = import("abstractionkit").UserOperationV7;
263
321
  export type SafeAccountV0_3_0 = import("abstractionkit").SafeAccountV0_3_0;
264
322
  import WalletAccountReadOnlyEvmErc4337 from './wallet-account-read-only-evm-erc-4337.js';
@@ -25,6 +25,19 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
25
25
  * @returns {WalletAccountReadOnlyEvmErc4337} A read-only account whose address is `safeAddress`.
26
26
  */
27
27
  static fromSafeAddress(safeAddress: string, config: Omit<EvmErc4337WalletConfig, "transferMaxFee" | "transactionMaxFee">): WalletAccountReadOnlyEvmErc4337;
28
+ /**
29
+ * Returns the ERC-1271 signature inside an [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492) signature, as
30
+ * returned by the account's `sign` and `signTypedData` methods while the safe is not deployed. Signatures that are
31
+ * not ERC-6492 signatures are returned unchanged.
32
+ *
33
+ * Useful for verifiers that do not support ERC-6492 and check the signature through the safe's
34
+ * `isValidSignature` once the safe is deployed (e.g. permits or orders settled on-chain after the deployment).
35
+ *
36
+ * @param {string} signature - The signature.
37
+ * @throws {ValueError} If the signature ends with the ERC-6492 magic bytes, but is not a well-formed ERC-6492 signature.
38
+ * @returns {string} The ERC-1271 signature.
39
+ */
40
+ static unwrapErc6492Signature(signature: string): string;
28
41
  /**
29
42
  * Builds the init code overrides from the wallet configuration.
30
43
  *
@@ -199,7 +212,8 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
199
212
  */
200
213
  getAllowance(token: string, spender: string): Promise<bigint>;
201
214
  /**
202
- * Verifies a message's signature, as produced by the safe (ERC-1271 / SafeMessage).
215
+ * Verifies a message's signature, as produced by the safe (ERC-1271 / SafeMessage). ERC-6492 signatures are
216
+ * accepted too, and checked through the ERC-1271 signature they wrap.
203
217
  *
204
218
  * If the safe is deployed, the signature is checked on-chain through the safe's `isValidSignature`. Otherwise,
205
219
  * it is checked offline against the safe's owner.
@@ -211,7 +225,8 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
211
225
  */
212
226
  verify(message: string, signature: string): Promise<boolean>;
213
227
  /**
214
- * Verifies a typed data signature, as produced by the safe (ERC-1271 / SafeMessage).
228
+ * Verifies a typed data signature, as produced by the safe (ERC-1271 / SafeMessage). ERC-6492 signatures are
229
+ * accepted too, and checked through the ERC-1271 signature they wrap.
215
230
  *
216
231
  * If the safe is deployed, the signature is checked on-chain through the safe's `isValidSignature`. Otherwise,
217
232
  * it is checked offline against the safe's owner.
@@ -261,14 +276,25 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
261
276
  */
262
277
  protected _verifySafeMessage(hash: string, signature: string, methodName: string): Promise<boolean>;
263
278
  /**
264
- * Returns whether an `isValidSignature` error means the signature is invalid (revert, bad input or output),
265
- * rather than a failed check (e.g. a network error). ethers reports any EIP-1193 `eth_call` error as a CALL_EXCEPTION.
279
+ * Returns whether a contract call error means the contract rejected the call (revert, bad input or output),
280
+ * rather than the call failing (e.g. a network error). ethers reports any EIP-1193 `eth_call` error as a CALL_EXCEPTION.
266
281
  *
267
282
  * @protected
268
283
  * @param {unknown} error - The error.
269
- * @returns {boolean} True if the error means that the signature is invalid.
284
+ * @returns {boolean} True if the contract rejected the call.
285
+ */
286
+ protected static _isRejectedCallError(error: unknown): boolean;
287
+ /**
288
+ * Wraps an ERC-1271 signature of a safe that is not deployed yet in an [ERC-6492](https://eips.ethereum.org/EIPS/eip-6492)
289
+ * signature, so that verifiers can simulate the safe's deployment before calling its `isValidSignature`.
290
+ *
291
+ * @protected
292
+ * @param {string} factory - The address of the factory that deploys the safe.
293
+ * @param {string} factoryData - The calldata that deploys the safe through the factory.
294
+ * @param {string} signature - The ERC-1271 signature.
295
+ * @returns {string} The ERC-6492 signature.
270
296
  */
271
- protected static _isInvalidSignatureError(error: unknown): boolean;
297
+ protected static _wrapErc6492Signature(factory: string, factoryData: string, signature: string): string;
272
298
  /**
273
299
  * Returns whether the safe is deployed. A safe cannot be undeployed, so a positive result is cached.
274
300
  *
@@ -5,11 +5,12 @@ export default class WalletManagerEvmErc4337 extends WalletManager<ISignerEvm> {
5
5
  *
6
6
  * @overload
7
7
  * @param {string | Uint8Array} seed - A [BIP-39](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic seed phrase, or a raw BIP-32 master seed (16-64 bytes).
8
- * @param {EvmErc4337WalletConfig} config - The configuration object.
8
+ * @param {EvmErc4337WalletConfig & EvmErc4337WalletManagerSafeOptions} config - The configuration object.
9
9
  * @throws {ValueError} If the seed phrase is invalid.
10
10
  * @throws {ValueError} If the `provider` option is set to an empty list.
11
+ * @throws {ValueError} If a `safeAddresses` value is not a well-formed evm address.
11
12
  */
12
- constructor(seed: string | Uint8Array, config: EvmErc4337WalletConfig);
13
+ constructor(seed: string | Uint8Array, config: EvmErc4337WalletConfig & EvmErc4337WalletManagerSafeOptions);
13
14
  /**
14
15
  * Creates a new wallet manager for evm blockchains that implements the [erc-4337](https://www.erc4337.io/docs) standard from a default signer.
15
16
  *
@@ -18,11 +19,12 @@ export default class WalletManagerEvmErc4337 extends WalletManager<ISignerEvm> {
18
19
  *
19
20
  * @overload
20
21
  * @param {ISignerEvm} signer - The default signer.
21
- * @param {EvmErc4337WalletConfig} config - The configuration object.
22
+ * @param {EvmErc4337WalletConfig & EvmErc4337WalletManagerSafeOptions} config - The configuration object.
22
23
  * @throws {InvalidSignerError} If the default signer does not support account derivation.
23
24
  * @throws {ValueError} If the `provider` option is set to an empty list.
25
+ * @throws {ValueError} If a `safeAddresses` value is not a well-formed evm address.
24
26
  */
25
- constructor(signer: ISignerEvm, config: EvmErc4337WalletConfig);
27
+ constructor(signer: ISignerEvm, config: EvmErc4337WalletConfig & EvmErc4337WalletManagerSafeOptions);
26
28
  /**
27
29
  * An ethers provider to interact with a node of the blockchain.
28
30
  *
@@ -83,7 +85,8 @@ export default class WalletManagerEvmErc4337 extends WalletManager<ISignerEvm> {
83
85
  }): Promise<WalletAccountEvmErc4337>;
84
86
  /**
85
87
  * Builds the account config, injecting the manager's shared provider so accounts reuse the
86
- * single ethers provider instance instead of opening their own.
88
+ * single ethers provider instance instead of opening their own. The `safeAddresses` option is
89
+ * dropped, since it is resolved per account.
87
90
  *
88
91
  * @private
89
92
  * @returns {EvmErc4337WalletConfig} The account configuration.
@@ -97,7 +100,10 @@ export default class WalletManagerEvmErc4337 extends WalletManager<ISignerEvm> {
97
100
  */
98
101
  getFeeRates(): Promise<FeeRates>;
99
102
  /**
100
- * Disposes all the wallet accounts, erasing their private keys from the memory.
103
+ * Disposes the wallet accounts, erasing their private keys from memory, and the default signer if the manager
104
+ * created it from a seed. Signers you supplied are never disposed, so an account created directly on one with
105
+ * getAccount(signerName) keeps its key. The seed you passed in is never wiped (a seed phrase string stays in memory
106
+ * until it is garbage collected).
101
107
  */
102
108
  dispose(): void;
103
109
  }
@@ -106,5 +112,11 @@ export type FeeRates = import("@tetherto/wdk-wallet-evm").FeeRates;
106
112
  export type ISignerEvm = import("@tetherto/wdk-wallet-evm/signers").ISignerEvm;
107
113
  export type NoSuchElementError = import("@tetherto/wdk-wallet").NoSuchElementError;
108
114
  export type EvmErc4337WalletConfig = import("./wallet-account-evm-erc-4337.js").EvmErc4337WalletConfig;
115
+ export type EvmErc4337WalletManagerSafeOptions = {
116
+ /**
117
+ * - Binds accounts to existing safes, instead of the safes predicted from their owners (e.g. after an owner change). Maps an account key to the safe's address. The keys are the manager's account cache keys, with derivation paths as given to {@link WalletManagerEvmErc4337#getAccountByPath}: "0'/0/0" binds the account derived at that path from the default signer (also returned by `getAccount(0)`), "<signerName>:0'/0/0" the account derived at that path from a named signer, and "<signerName>" the account bound to a named signer (see {@link WalletManagerEvmErc4337#getAccount}). Each bound account checks its safe as described for the account's `safeAddress` option.
118
+ */
119
+ safeAddresses?: Record<string, string>;
120
+ };
109
121
  import WalletManager from '@tetherto/wdk-wallet';
110
122
  import WalletAccountEvmErc4337 from './wallet-account-evm-erc-4337.js';