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

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 and verify messages with the underlying EOA key
76
+ - **Message Signing**: Sign messages and typed data as the Safe (ERC-1271 / SafeMessage), 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
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.25",
3
+ "version": "1.0.0-beta.26",
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": [
@@ -14,7 +14,7 @@
14
14
 
15
15
  'use strict'
16
16
 
17
- import { Contract, hexlify, keccak256, randomBytes, toUtf8Bytes } from 'ethers'
17
+ import { Contract, TypedDataEncoder, hashMessage, hexlify, keccak256, randomBytes, toUtf8Bytes } from 'ethers'
18
18
 
19
19
  import { DisposalError, MaximumFeeExceededError, ProviderRequiredError, TransactionError, TransactionErrorReason, UnsupportedOperationError, ValueError } from '@tetherto/wdk-wallet'
20
20
 
@@ -242,7 +242,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
242
242
  }
243
243
 
244
244
  /**
245
- * Signs a message.
245
+ * Signs a message as the safe (ERC-1271 / SafeMessage), so the safe's `isValidSignature` accepts it.
246
246
  *
247
247
  * @param {string} message - The message to sign.
248
248
  * @returns {Promise<string>} The message's signature.
@@ -251,11 +251,11 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
251
251
  async sign (message) {
252
252
  this._guardDisposed()
253
253
 
254
- return await this._signer.sign(message)
254
+ return await this._signer.signTypedData(await this._getSafeMessageTypedData(hashMessage(message)))
255
255
  }
256
256
 
257
257
  /**
258
- * Signs typed data according to EIP-712.
258
+ * Signs typed data according to EIP-712 as the safe (ERC-1271 / SafeMessage), so the safe's `isValidSignature` accepts it.
259
259
  *
260
260
  * @param {TypedData} typedData - The typed data to sign.
261
261
  * @returns {Promise<string>} The typed data signature.
@@ -264,7 +264,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
264
264
  async signTypedData ({ domain, types, message }) {
265
265
  this._guardDisposed()
266
266
 
267
- return await this._signer.signTypedData({ domain, types, message })
267
+ return await this._signer.signTypedData(await this._getSafeMessageTypedData(TypedDataEncoder.hash(domain, types, message)))
268
268
  }
269
269
 
270
270
  /**
@@ -14,7 +14,7 @@
14
14
 
15
15
  'use strict'
16
16
 
17
- import { getAddress, isAddress, isHexString } from 'ethers'
17
+ import { Contract, TypedDataEncoder, 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
 
@@ -28,6 +28,7 @@ import {
28
28
  Erc7677Paymaster,
29
29
  HttpTransport,
30
30
  ENTRYPOINT_V7,
31
+ SAFE_MESSAGE_MODULE_TYPE,
31
32
  calculateUserOperationMaxGasCost
32
33
  } from 'abstractionkit'
33
34
 
@@ -37,6 +38,12 @@ import {
37
38
 
38
39
  import { ConfigurationError } from './errors.js'
39
40
 
41
+ const ERC1271_MAGIC_VALUE = '0x1626ba7e'
42
+
43
+ const ERC1271_ABI = [
44
+ 'function isValidSignature(bytes32 _dataHash, bytes _signature) view returns (bytes4)'
45
+ ]
46
+
40
47
  const PaymasterMode = {
41
48
  NATIVE: 'native',
42
49
  SPONSORED: 'sponsored',
@@ -278,6 +285,9 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
278
285
  /** @private */
279
286
  this._deployedSmartAccount = undefined
280
287
 
288
+ /** @private */
289
+ this._safeDeployed = false
290
+
281
291
  /** @private */
282
292
  this._evmReadOnlyAccount = undefined
283
293
  }
@@ -303,8 +313,8 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
303
313
  * Creates a read-only account for a safe whose address is already known.
304
314
  *
305
315
  * The address is used as the account's own address, so balances, allowances and quotes resolve against that
306
- * safe. Its owner is unknown to the account: {@link verify} and {@link verifyTypedData} throw, and the safe must
307
- * already be deployed for {@link quoteSendTransaction} and {@link quoteTransfer}.
316
+ * safe. Its owner is unknown to the account, so the safe must already be deployed for {@link verify},
317
+ * {@link verifyTypedData}, {@link quoteSendTransaction} and {@link quoteTransfer}.
308
318
  *
309
319
  * @param {string} safeAddress - The safe's evm address. Normalized to its checksummed form.
310
320
  * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} config - The configuration object.
@@ -539,48 +549,35 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
539
549
  }
540
550
 
541
551
  /**
542
- * Verifies a message's signature.
552
+ * Verifies a message's signature, as produced by the safe (ERC-1271 / SafeMessage).
553
+ *
554
+ * If the safe is deployed, the signature is checked on-chain through the safe's `isValidSignature`. Otherwise,
555
+ * it is checked offline against the safe's owner.
543
556
  *
544
557
  * @param {string} message - The original message.
545
558
  * @param {string} signature - The signature to verify.
546
- * @throws {UnsupportedOperationError} If the account was created from a safe address, whose owner is unknown.
559
+ * @throws {UnsupportedOperationError} If the account was created from a safe address whose safe is not deployed.
547
560
  * @returns {Promise<boolean>} True if the signature is valid.
548
561
  */
549
562
  async verify (message, signature) {
550
- const ownerAddress = await this._getOwnerAddress()
551
-
552
- if (ownerAddress === undefined) {
553
- throw new UnsupportedOperationError('verify(message, signature)')
554
- }
555
-
556
- const evmReadOnlyAccount = new WalletAccountReadOnlyEvm(ownerAddress, {
557
- ...this._config,
558
- provider: this._provider
559
- })
560
- return await evmReadOnlyAccount.verify(message, signature)
563
+ return await this._verifySafeMessage(hashMessage(message), signature, 'verify(message, signature)')
561
564
  }
562
565
 
563
566
  /**
564
- * Verifies a typed data signature.
567
+ * Verifies a typed data signature, as produced by the safe (ERC-1271 / SafeMessage).
568
+ *
569
+ * If the safe is deployed, the signature is checked on-chain through the safe's `isValidSignature`. Otherwise,
570
+ * it is checked offline against the safe's owner.
565
571
  *
566
572
  * @param {TypedData} typedData - The typed data to verify.
567
573
  * @param {string} signature - The signature to verify.
568
- * @throws {UnsupportedOperationError} If the account was created from a safe address, whose owner is unknown.
574
+ * @throws {UnsupportedOperationError} If the account was created from a safe address whose safe is not deployed.
569
575
  * @returns {Promise<boolean>} True if the signature is valid.
570
576
  */
571
577
  async verifyTypedData (typedData, signature) {
572
- const ownerAddress = await this._getOwnerAddress()
578
+ const hash = TypedDataEncoder.hash(typedData.domain, typedData.types, typedData.message)
573
579
 
574
- if (ownerAddress === undefined) {
575
- throw new UnsupportedOperationError('verifyTypedData(typedData, signature)')
576
- }
577
-
578
- const evmReadOnlyAccount = new WalletAccountReadOnlyEvm(ownerAddress, {
579
- ...this._config,
580
- provider: this._provider
581
- })
582
-
583
- return await evmReadOnlyAccount.verifyTypedData(typedData, signature)
580
+ return await this._verifySafeMessage(hash, signature, 'verifyTypedData(typedData, signature)')
584
581
  }
585
582
 
586
583
  /**
@@ -638,7 +635,7 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
638
635
  const overrides = WalletAccountReadOnlyEvmErc4337._getInitCodeOverrides(config)
639
636
  const safeAddress = await this.getAddress()
640
637
 
641
- if (await SafeAccount030.isDeployed(safeAddress, this._eip1193Provider)) {
638
+ if (await this._isSafeDeployed()) {
642
639
  this._deployedSmartAccount = new SafeAccount030(safeAddress, overrides)
643
640
  return this._deployedSmartAccount
644
641
  }
@@ -652,6 +649,112 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
652
649
  return SafeAccount030.initializeNewAccount([ownerAddress], overrides)
653
650
  }
654
651
 
652
+ /**
653
+ * Wraps a hash in the safe's SafeMessage EIP-712 typed data, which is what the safe's ERC-1271
654
+ * `isValidSignature` expects its owners to have signed.
655
+ *
656
+ * @protected
657
+ * @param {string} hash - The hash of the message or typed data (EIP-191 / EIP-712).
658
+ * @returns {Promise<TypedData>} The SafeMessage typed data.
659
+ */
660
+ async _getSafeMessageTypedData (hash) {
661
+ const [safeAddress, chainId] = await Promise.all([this.getAddress(), this._getChainId()])
662
+
663
+ return {
664
+ domain: { chainId: Number(chainId), verifyingContract: safeAddress },
665
+ types: SAFE_MESSAGE_MODULE_TYPE,
666
+ message: { message: hash }
667
+ }
668
+ }
669
+
670
+ /**
671
+ * Verifies a SafeMessage signature over a hash.
672
+ *
673
+ * @protected
674
+ * @param {string} hash - The hash of the message or typed data (EIP-191 / EIP-712).
675
+ * @param {string} signature - The signature to verify.
676
+ * @param {string} methodName - The calling method's name, used in the error if verification is unsupported.
677
+ * @throws {UnsupportedOperationError} If the safe is not deployed and its owner is unknown.
678
+ * @returns {Promise<boolean>} True if the signature is valid.
679
+ */
680
+ async _verifySafeMessage (hash, signature, methodName) {
681
+ if (await this._isSafeDeployed()) {
682
+ const safe = new Contract(await this.getAddress(), ERC1271_ABI, this._provider)
683
+
684
+ try {
685
+ const result = await safe.isValidSignature(hash, signature)
686
+
687
+ return result.toLowerCase() === ERC1271_MAGIC_VALUE
688
+ } catch (error) {
689
+ if (WalletAccountReadOnlyEvmErc4337._isInvalidSignatureError(error)) {
690
+ return false
691
+ }
692
+
693
+ throw error
694
+ }
695
+ }
696
+
697
+ const ownerAddress = await this._getOwnerAddress()
698
+
699
+ if (ownerAddress === undefined) {
700
+ throw new UnsupportedOperationError(methodName)
701
+ }
702
+
703
+ const { domain, types, message } = await this._getSafeMessageTypedData(hash)
704
+
705
+ try {
706
+ const signer = verifyTypedData(domain, types, message, signature)
707
+
708
+ return signer.toLowerCase() === ownerAddress.toLowerCase()
709
+ } catch (error) {
710
+ if (isError(error, 'INVALID_ARGUMENT')) {
711
+ return false
712
+ }
713
+
714
+ throw error
715
+ }
716
+ }
717
+
718
+ /**
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.
721
+ *
722
+ * @protected
723
+ * @param {unknown} error - The error.
724
+ * @returns {boolean} True if the error means that the signature is invalid.
725
+ */
726
+ static _isInvalidSignatureError (error) {
727
+ if (isError(error, 'INVALID_ARGUMENT') || isError(error, 'BAD_DATA')) {
728
+ return true
729
+ }
730
+
731
+ if (!isError(error, 'CALL_EXCEPTION')) {
732
+ return false
733
+ }
734
+
735
+ if (error.data && error.data !== '0x') {
736
+ return true
737
+ }
738
+
739
+ const rpcError = error.info?.error
740
+
741
+ return rpcError?.code === 3 || /revert/i.test(rpcError?.message ?? '')
742
+ }
743
+
744
+ /**
745
+ * Returns whether the safe is deployed. A safe cannot be undeployed, so a positive result is cached.
746
+ *
747
+ * @protected
748
+ * @returns {Promise<boolean>} True if the safe is deployed.
749
+ */
750
+ async _isSafeDeployed () {
751
+ if (!this._safeDeployed) {
752
+ this._safeDeployed = await SafeAccount030.isDeployed(await this.getAddress(), this._eip1193Provider)
753
+ }
754
+
755
+ return this._safeDeployed
756
+ }
757
+
655
758
  /**
656
759
  * Returns the safe owner's address.
657
760
  *
@@ -108,7 +108,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
108
108
  */
109
109
  getAddress(): Promise<string>;
110
110
  /**
111
- * Signs a message.
111
+ * Signs a message as the safe (ERC-1271 / SafeMessage), so the safe's `isValidSignature` accepts it.
112
112
  *
113
113
  * @param {string} message - The message to sign.
114
114
  * @returns {Promise<string>} The message's signature.
@@ -116,7 +116,7 @@ export default class WalletAccountEvmErc4337 extends WalletAccountReadOnlyEvmErc
116
116
  */
117
117
  sign(message: string): Promise<string>;
118
118
  /**
119
- * Signs typed data according to EIP-712.
119
+ * Signs typed data according to EIP-712 as the safe (ERC-1271 / SafeMessage), so the safe's `isValidSignature` accepts it.
120
120
  *
121
121
  * @param {TypedData} typedData - The typed data to sign.
122
122
  * @returns {Promise<string>} The typed data signature.
@@ -14,8 +14,8 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
14
14
  * Creates a read-only account for a safe whose address is already known.
15
15
  *
16
16
  * The address is used as the account's own address, so balances, allowances and quotes resolve against that
17
- * safe. Its owner is unknown to the account: {@link verify} and {@link verifyTypedData} throw, and the safe must
18
- * already be deployed for {@link quoteSendTransaction} and {@link quoteTransfer}.
17
+ * safe. Its owner is unknown to the account, so the safe must already be deployed for {@link verify},
18
+ * {@link verifyTypedData}, {@link quoteSendTransaction} and {@link quoteTransfer}.
19
19
  *
20
20
  * @param {string} safeAddress - The safe's evm address. Normalized to its checksummed form.
21
21
  * @param {Omit<EvmErc4337WalletConfig, 'transferMaxFee' | 'transactionMaxFee'>} config - The configuration object.
@@ -199,20 +199,26 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
199
199
  */
200
200
  getAllowance(token: string, spender: string): Promise<bigint>;
201
201
  /**
202
- * Verifies a message's signature.
202
+ * Verifies a message's signature, as produced by the safe (ERC-1271 / SafeMessage).
203
+ *
204
+ * If the safe is deployed, the signature is checked on-chain through the safe's `isValidSignature`. Otherwise,
205
+ * it is checked offline against the safe's owner.
203
206
  *
204
207
  * @param {string} message - The original message.
205
208
  * @param {string} signature - The signature to verify.
206
- * @throws {UnsupportedOperationError} If the account was created from a safe address, whose owner is unknown.
209
+ * @throws {UnsupportedOperationError} If the account was created from a safe address whose safe is not deployed.
207
210
  * @returns {Promise<boolean>} True if the signature is valid.
208
211
  */
209
212
  verify(message: string, signature: string): Promise<boolean>;
210
213
  /**
211
- * Verifies a typed data signature.
214
+ * Verifies a typed data signature, as produced by the safe (ERC-1271 / SafeMessage).
215
+ *
216
+ * If the safe is deployed, the signature is checked on-chain through the safe's `isValidSignature`. Otherwise,
217
+ * it is checked offline against the safe's owner.
212
218
  *
213
219
  * @param {TypedData} typedData - The typed data to verify.
214
220
  * @param {string} signature - The signature to verify.
215
- * @throws {UnsupportedOperationError} If the account was created from a safe address, whose owner is unknown.
221
+ * @throws {UnsupportedOperationError} If the account was created from a safe address whose safe is not deployed.
216
222
  * @returns {Promise<boolean>} True if the signature is valid.
217
223
  */
218
224
  verifyTypedData(typedData: TypedData, signature: string): Promise<boolean>;
@@ -234,6 +240,42 @@ export default class WalletAccountReadOnlyEvmErc4337 extends WalletAccountReadOn
234
240
  * @returns {Promise<SafeAccountV0_3_0>} The safe account instance.
235
241
  */
236
242
  protected _getSmartAccount(config?: Omit<EvmErc4337WalletConfig, "transferMaxFee" | "transactionMaxFee">): Promise<import('abstractionkit').SafeAccountV0_3_0>;
243
+ /**
244
+ * Wraps a hash in the safe's SafeMessage EIP-712 typed data, which is what the safe's ERC-1271
245
+ * `isValidSignature` expects its owners to have signed.
246
+ *
247
+ * @protected
248
+ * @param {string} hash - The hash of the message or typed data (EIP-191 / EIP-712).
249
+ * @returns {Promise<TypedData>} The SafeMessage typed data.
250
+ */
251
+ protected _getSafeMessageTypedData(hash: string): Promise<TypedData>;
252
+ /**
253
+ * Verifies a SafeMessage signature over a hash.
254
+ *
255
+ * @protected
256
+ * @param {string} hash - The hash of the message or typed data (EIP-191 / EIP-712).
257
+ * @param {string} signature - The signature to verify.
258
+ * @param {string} methodName - The calling method's name, used in the error if verification is unsupported.
259
+ * @throws {UnsupportedOperationError} If the safe is not deployed and its owner is unknown.
260
+ * @returns {Promise<boolean>} True if the signature is valid.
261
+ */
262
+ protected _verifySafeMessage(hash: string, signature: string, methodName: string): Promise<boolean>;
263
+ /**
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.
266
+ *
267
+ * @protected
268
+ * @param {unknown} error - The error.
269
+ * @returns {boolean} True if the error means that the signature is invalid.
270
+ */
271
+ protected static _isInvalidSignatureError(error: unknown): boolean;
272
+ /**
273
+ * Returns whether the safe is deployed. A safe cannot be undeployed, so a positive result is cached.
274
+ *
275
+ * @protected
276
+ * @returns {Promise<boolean>} True if the safe is deployed.
277
+ */
278
+ protected _isSafeDeployed(): Promise<boolean>;
237
279
  /**
238
280
  * Returns the safe owner's address.
239
281
  *