@toruslabs/ethereum-controllers 8.17.1 → 9.1.0

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.
Files changed (76) hide show
  1. package/dist/lib.cjs/Account/AccountTrackerController.js +15 -7
  2. package/dist/lib.cjs/AccountAbstraction/AccountAbstractionController.js +22 -26
  3. package/dist/lib.cjs/Eip5792/walletGetCallsStatus.js +2 -2
  4. package/dist/lib.cjs/Eip5792/walletSendCalls.js +6 -7
  5. package/dist/lib.cjs/Eip7702/eip7702Utils.js +3 -3
  6. package/dist/lib.cjs/Gas/GasFeeController.js +2 -2
  7. package/dist/lib.cjs/Keyring/KeyringController.js +68 -41
  8. package/dist/lib.cjs/Message/utils.js +14 -16
  9. package/dist/lib.cjs/Network/NetworkController.js +7 -9
  10. package/dist/lib.cjs/Network/createEthereumMiddleware.js +373 -285
  11. package/dist/lib.cjs/Network/createJsonRpcClient.js +21 -21
  12. package/dist/lib.cjs/Nfts/NftHandler.js +54 -12
  13. package/dist/lib.cjs/Nfts/NftsController.js +1 -4
  14. package/dist/lib.cjs/Preferences/PreferencesController.js +2 -2
  15. package/dist/lib.cjs/Tokens/TokenHandler.js +39 -7
  16. package/dist/lib.cjs/Tokens/TokensController.js +15 -7
  17. package/dist/lib.cjs/Transaction/TransactionController.js +17 -20
  18. package/dist/lib.cjs/Transaction/TransactionGasUtil.js +11 -12
  19. package/dist/lib.cjs/Transaction/TransactionUtils.js +44 -39
  20. package/dist/lib.cjs/index.js +9 -0
  21. package/dist/lib.cjs/types/Account/AccountTrackerController.d.ts +1 -1
  22. package/dist/lib.cjs/types/AccountAbstraction/AccountAbstractionController.d.ts +4 -6
  23. package/dist/lib.cjs/types/Eip5792/walletSendCalls.d.ts +1 -1
  24. package/dist/lib.cjs/types/Eip7702/walletUpgradeAccount.d.ts +1 -1
  25. package/dist/lib.cjs/types/Keyring/KeyringController.d.ts +4 -4
  26. package/dist/lib.cjs/types/Network/NetworkController.d.ts +1 -1
  27. package/dist/lib.cjs/types/Network/createEthereumMiddleware.d.ts +28 -90
  28. package/dist/lib.cjs/types/Network/createJsonRpcClient.d.ts +4 -4
  29. package/dist/lib.cjs/types/Network/index.d.ts +5 -0
  30. package/dist/lib.cjs/types/Network/interfaces.d.ts +58 -0
  31. package/dist/lib.cjs/types/Nfts/NftHandler.d.ts +4 -3
  32. package/dist/lib.cjs/types/Nfts/NftsController.d.ts +0 -1
  33. package/dist/lib.cjs/types/Tokens/TokenHandler.d.ts +4 -3
  34. package/dist/lib.cjs/types/Tokens/TokensController.d.ts +1 -1
  35. package/dist/lib.cjs/types/Transaction/TransactionUtils.d.ts +11 -3
  36. package/dist/lib.cjs/types/index.d.ts +1 -3
  37. package/dist/lib.cjs/types/utils/abis.d.ts +544 -99
  38. package/dist/lib.cjs/types/utils/eip5792Types.d.ts +1 -1
  39. package/dist/lib.cjs/types/utils/eip7702Types.d.ts +1 -1
  40. package/dist/lib.cjs/types/utils/interfaces.d.ts +207 -4
  41. package/dist/lib.cjs/types/utils/transaction.d.ts +1 -1
  42. package/dist/lib.cjs/types/utils/viem.d.ts +8 -0
  43. package/dist/lib.cjs/utils/abis.js +12 -0
  44. package/dist/lib.cjs/utils/conversionUtils.js +3 -4
  45. package/dist/lib.cjs/utils/helpers.js +8 -7
  46. package/dist/lib.cjs/utils/transaction.js +7 -11
  47. package/dist/lib.cjs/utils/viem.js +214 -0
  48. package/dist/lib.esm/Account/AccountTrackerController.js +15 -7
  49. package/dist/lib.esm/AccountAbstraction/AccountAbstractionController.js +24 -28
  50. package/dist/lib.esm/Eip5792/walletGetCallsStatus.js +2 -2
  51. package/dist/lib.esm/Eip5792/walletSendCalls.js +6 -7
  52. package/dist/lib.esm/Eip7702/eip7702Utils.js +3 -3
  53. package/dist/lib.esm/Gas/GasFeeController.js +2 -2
  54. package/dist/lib.esm/Keyring/KeyringController.js +68 -42
  55. package/dist/lib.esm/Message/utils.js +14 -16
  56. package/dist/lib.esm/Network/NetworkController.js +8 -10
  57. package/dist/lib.esm/Network/createEthereumMiddleware.js +387 -290
  58. package/dist/lib.esm/Network/createJsonRpcClient.js +22 -22
  59. package/dist/lib.esm/Nfts/NftHandler.js +54 -12
  60. package/dist/lib.esm/Nfts/NftsController.js +1 -4
  61. package/dist/lib.esm/Preferences/PreferencesController.js +2 -2
  62. package/dist/lib.esm/Tokens/TokenHandler.js +39 -7
  63. package/dist/lib.esm/Tokens/TokensController.js +15 -7
  64. package/dist/lib.esm/Transaction/TransactionController.js +18 -21
  65. package/dist/lib.esm/Transaction/TransactionGasUtil.js +11 -12
  66. package/dist/lib.esm/Transaction/TransactionUtils.js +44 -40
  67. package/dist/lib.esm/index.js +4 -3
  68. package/dist/lib.esm/utils/abis.js +12 -0
  69. package/dist/lib.esm/utils/conversionUtils.js +3 -4
  70. package/dist/lib.esm/utils/helpers.js +8 -7
  71. package/dist/lib.esm/utils/interfaces.js +64 -0
  72. package/dist/lib.esm/utils/transaction.js +7 -11
  73. package/dist/lib.esm/utils/viem.js +214 -0
  74. package/package.json +14 -19
  75. package/dist/ethereumControllers.umd.min.js +0 -2
  76. package/dist/ethereumControllers.umd.min.js.LICENSE.txt +0 -50
@@ -4,8 +4,8 @@ var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
4
4
  var _defineProperty = require('@babel/runtime/helpers/defineProperty');
5
5
  var baseControllers = require('@toruslabs/base-controllers');
6
6
  var asyncMutex = require('async-mutex');
7
- var ethers = require('ethers');
8
7
  var log = require('loglevel');
8
+ var viem = require('viem');
9
9
  var abis = require('../utils/abis.js');
10
10
  var contractAddresses = require('../utils/contractAddresses.js');
11
11
 
@@ -33,7 +33,7 @@ class AccountTrackerController extends baseControllers.BaseController {
33
33
  _defineProperty(this, "provider", void 0);
34
34
  _defineProperty(this, "blockTracker", void 0);
35
35
  _defineProperty(this, "mutex", new asyncMutex.Mutex());
36
- _defineProperty(this, "ethersProvider", void 0);
36
+ _defineProperty(this, "publicClient", void 0);
37
37
  _defineProperty(this, "getIdentities", void 0);
38
38
  _defineProperty(this, "getCurrentChainId", void 0);
39
39
  this.defaultState = {
@@ -42,7 +42,9 @@ class AccountTrackerController extends baseControllers.BaseController {
42
42
  this.initialize();
43
43
  this.provider = provider;
44
44
  this.blockTracker = blockTracker;
45
- this.ethersProvider = new ethers.BrowserProvider(this.provider, "any");
45
+ this.publicClient = viem.createPublicClient({
46
+ transport: viem.custom(this.provider)
47
+ });
46
48
  this.getIdentities = getIdentities;
47
49
  this.getCurrentChainId = getCurrentChainId;
48
50
  onPreferencesStateChange(() => {
@@ -128,21 +130,27 @@ class AccountTrackerController extends baseControllers.BaseController {
128
130
  } = this.state;
129
131
  if (!accounts[address]) return;
130
132
  accounts[address] = {
131
- balance: ethers.toQuantity(balance)
133
+ balance: viem.toHex(BigInt(balance))
132
134
  };
133
135
  this.update({
134
136
  accounts
135
137
  });
136
138
  }
137
139
  async _updateAccountsViaBalanceChecker(addresses, deployedContractAddress) {
138
- const ethContract = new ethers.Contract(deployedContractAddress, abis.singleBalanceCheckerAbi, this.ethersProvider);
139
140
  try {
140
- const result = await ethContract.balances(addresses, [ZERO_ADDRESS]);
141
+ const result = await this.publicClient.readContract({
142
+ address: deployedContractAddress,
143
+ abi: abis.singleBalanceCheckerAbi,
144
+ functionName: "balances",
145
+ args: [addresses, [ZERO_ADDRESS]],
146
+ authorizationList: undefined // required when public client has no chain specified
147
+ });
141
148
  const {
142
149
  accounts
143
150
  } = this.state;
144
151
  addresses.forEach((address, index) => {
145
- const balance = ethers.toQuantity(result[index]);
152
+ var _result$index;
153
+ const balance = viem.toHex((_result$index = result[index]) !== null && _result$index !== void 0 ? _result$index : 0n);
146
154
  if (!accounts[address]) return;
147
155
  accounts[address] = {
148
156
  balance
@@ -2,33 +2,29 @@
2
2
 
3
3
  var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
4
4
  var _defineProperty = require('@babel/runtime/helpers/defineProperty');
5
- var util = require('@ethereumjs/util');
6
5
  var baseControllers = require('@toruslabs/base-controllers');
7
6
  var auth = require('@web3auth/auth');
8
- var ethers = require('ethers');
9
7
  var log = require('loglevel');
10
8
  var viem = require('viem');
11
9
  var accountAbstraction = require('viem/account-abstraction');
12
10
 
13
- const eoaInterceptorMiddleware = eoaAddress => (req, res, next, end) => {
14
- req.isAAProviderRequest = true;
15
- if (req.method === "eth_accounts" || req.method === "eth_requestAccounts") {
16
- res.result = [eoaAddress];
17
- end();
18
- return;
11
+ const eoaInterceptorMiddleware = eoaAddress => async ({
12
+ request,
13
+ next,
14
+ context
15
+ }) => {
16
+ context.set("isAAProviderRequest", true);
17
+ if (request.method === "eth_accounts" || request.method === "eth_requestAccounts") {
18
+ return [eoaAddress];
19
19
  }
20
- next();
20
+ return next();
21
21
  };
22
22
  function eoaProviderAsMiddleware(provider) {
23
- return async (req, res, _next, end) => {
24
- // send request to provider
25
- try {
26
- const providerRes = await provider.request(req);
27
- res.result = providerRes;
28
- return end();
29
- } catch (error) {
30
- return end(error);
31
- }
23
+ return async ({
24
+ request
25
+ }) => {
26
+ const result = await provider.request(request);
27
+ return result;
32
28
  };
33
29
  }
34
30
  class AccountAbstractionController extends baseControllers.BaseController {
@@ -94,10 +90,10 @@ class AccountAbstractionController extends baseControllers.BaseController {
94
90
  transport: viem.http(providerConfig.rpcTarget)
95
91
  });
96
92
  // viem wallet client using json-rpc account from eoaProvider
97
- const aaEngine = new auth.JRPCEngine();
98
- aaEngine.push(eoaInterceptorMiddleware(eoaAddress));
99
- aaEngine.push(eoaProviderAsMiddleware(eoaProvider));
100
- const provider = auth.providerFromEngine(aaEngine);
93
+ const aaEngine = auth.JRPCEngineV2.create({
94
+ middleware: [eoaInterceptorMiddleware(eoaAddress), eoaProviderAsMiddleware(eoaProvider)]
95
+ });
96
+ const provider = auth.providerFromEngineV2(aaEngine);
101
97
  // need to hoist the account address https://viem.sh/docs/clients/wallet#optional-hoist-the-account
102
98
  const eoaWalletClient = viem.createWalletClient({
103
99
  account: eoaAddress,
@@ -125,7 +121,7 @@ class AccountAbstractionController extends baseControllers.BaseController {
125
121
  });
126
122
  }
127
123
  async sendTransaction(id, tx, address) {
128
- var _txParams$chainId, _txReceipt$receipt, _txReceipt$nonce, _txReceipt$receipt2, _txReceipt$receipt3, _txReceipt$receipt4;
124
+ var _txParams$chainId, _txReceipt$receipt, _txReceipt$nonce, _txReceipt$receipt$ga, _txReceipt$receipt2, _txReceipt$receipt$ef, _txReceipt$receipt3, _txReceipt$receipt4;
129
125
  if (address.toLowerCase() !== this.smartAccount.address.toLowerCase()) {
130
126
  throw new Error("Invalid address");
131
127
  }
@@ -165,8 +161,8 @@ class AccountAbstractionController extends baseControllers.BaseController {
165
161
  receipt: {
166
162
  transactionHash: (_txReceipt$receipt = txReceipt.receipt) === null || _txReceipt$receipt === void 0 ? void 0 : _txReceipt$receipt.transactionHash,
167
163
  nonce: (_txReceipt$nonce = txReceipt.nonce) === null || _txReceipt$nonce === void 0 ? void 0 : _txReceipt$nonce.toString(),
168
- gasUsed: util.addHexPrefix((_txReceipt$receipt2 = txReceipt.receipt) === null || _txReceipt$receipt2 === void 0 || (_txReceipt$receipt2 = _txReceipt$receipt2.gasUsed) === null || _txReceipt$receipt2 === void 0 ? void 0 : _txReceipt$receipt2.toString(16)),
169
- effectiveGasPrice: util.addHexPrefix((_txReceipt$receipt3 = txReceipt.receipt) === null || _txReceipt$receipt3 === void 0 || (_txReceipt$receipt3 = _txReceipt$receipt3.effectiveGasPrice) === null || _txReceipt$receipt3 === void 0 ? void 0 : _txReceipt$receipt3.toString(16)),
164
+ gasUsed: viem.toHex((_txReceipt$receipt$ga = (_txReceipt$receipt2 = txReceipt.receipt) === null || _txReceipt$receipt2 === void 0 ? void 0 : _txReceipt$receipt2.gasUsed) !== null && _txReceipt$receipt$ga !== void 0 ? _txReceipt$receipt$ga : 0n),
165
+ effectiveGasPrice: viem.toHex((_txReceipt$receipt$ef = (_txReceipt$receipt3 = txReceipt.receipt) === null || _txReceipt$receipt3 === void 0 ? void 0 : _txReceipt$receipt3.effectiveGasPrice) !== null && _txReceipt$receipt$ef !== void 0 ? _txReceipt$receipt$ef : 0n),
170
166
  type: (_txReceipt$receipt4 = txReceipt.receipt) === null || _txReceipt$receipt4 === void 0 ? void 0 : _txReceipt$receipt4.type,
171
167
  reason: txReceipt.reason
172
168
  },
@@ -277,7 +273,7 @@ class AccountAbstractionController extends baseControllers.BaseController {
277
273
  throw new Error("Invalid address");
278
274
  }
279
275
  return (_this$smartAccount = this.smartAccount) === null || _this$smartAccount === void 0 ? void 0 : _this$smartAccount.signMessage({
280
- message: ethers.isHexString(message) ? {
276
+ message: viem.isHex(message) ? {
281
277
  raw: message
282
278
  } : message
283
279
  });
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var util = require('@ethereumjs/util');
4
3
  var baseControllers = require('@toruslabs/base-controllers');
4
+ var metadataHelpers = require('@toruslabs/metadata-helpers');
5
5
  var auth = require('@web3auth/auth');
6
6
  var eip5792Types = require('../utils/eip5792Types.js');
7
7
 
@@ -65,7 +65,7 @@ function walletGetCallsStatus(request, getTransactionByBatchId) {
65
65
  return {
66
66
  status: mapTransactionStatusToEip5792Status(batchTx.status),
67
67
  id: batchId,
68
- chainId: util.addHexPrefix(batchTx.chainId),
68
+ chainId: metadataHelpers.add0x(batchTx.chainId),
69
69
  atomic: true,
70
70
  receipts: batchTx.txReceipt ? [batchTx.txReceipt] : []
71
71
  };
@@ -1,9 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var util = require('@ethereumjs/util');
4
3
  var auth = require('@web3auth/auth');
5
- var ethers = require('ethers');
6
4
  var uuid = require('uuid');
5
+ var viem = require('viem');
7
6
  var eip7702Utils = require('../Eip7702/eip7702Utils.js');
8
7
  var eip5792Types = require('../utils/eip5792Types.js');
9
8
 
@@ -24,18 +23,18 @@ function generateBatchId() {
24
23
  */
25
24
  function validateCall(call, index) {
26
25
  // Validate 'to' address
27
- if (!call.to || !ethers.isHexString(call.to) || !util.isValidAddress(call.to)) {
26
+ if (!call.to || !viem.isHex(call.to) || !viem.isAddress(call.to)) {
28
27
  throw auth.rpcErrors.invalidParams(`Invalid 'to' address in call at index ${index}`);
29
28
  }
30
29
  // Validate 'value' if present
31
30
  if (call.value !== undefined) {
32
- if (!ethers.isHexString(call.value)) {
31
+ if (!viem.isHex(call.value)) {
33
32
  throw auth.rpcErrors.invalidParams(`Invalid 'value' in call at index ${index}: must be a valid non-negative hex string`);
34
33
  }
35
34
  }
36
35
  // Validate 'data' if present
37
36
  if (call.data !== undefined) {
38
- if (!ethers.isHexString(call.data)) {
37
+ if (!viem.isHex(call.data)) {
39
38
  throw auth.rpcErrors.invalidParams(`Invalid 'data' in call at index ${index}: must be a valid hex string`);
40
39
  }
41
40
  }
@@ -54,14 +53,14 @@ function validateSendCallsParams(sendCallsParams) {
54
53
  throw auth.rpcErrors.invalidParams(`Invalid version: expected a string, got "${sendCallsParams.version || "undefined"}"`);
55
54
  }
56
55
  // Validate chainId format
57
- if (!sendCallsParams.chainId || !ethers.isHexString(sendCallsParams.chainId)) {
56
+ if (!sendCallsParams.chainId || !viem.isHex(sendCallsParams.chainId)) {
58
57
  throw auth.rpcErrors.invalidParams("Invalid chainId: must be a valid hex string");
59
58
  }
60
59
  // Validate 'from' address
61
60
  if (!sendCallsParams.from) {
62
61
  throw auth.rpcErrors.invalidParams("Missing 'from' address");
63
62
  }
64
- if (!ethers.isHexString(sendCallsParams.from) || !util.isValidAddress(sendCallsParams.from)) {
63
+ if (!viem.isHex(sendCallsParams.from) || !viem.isAddress(sendCallsParams.from)) {
65
64
  throw auth.rpcErrors.invalidParams("Invalid 'from' address: must be a valid hex address");
66
65
  }
67
66
  // Validate calls array
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var util = require('@ethereumjs/util');
3
+ var metadataHelpers = require('@toruslabs/metadata-helpers');
4
4
  var viem = require('viem');
5
5
  var abis = require('../utils/abis.js');
6
6
  var constants = require('../utils/constants.js');
@@ -14,10 +14,10 @@ const MetaMask_EIP7702_Stateless_Delegator = "0x63c0c19a282a1B52b07dD5a65b58948A
14
14
  async function getDelegationAddress(walletAddress, chainId, getEthCode) {
15
15
  // query eth_getCode
16
16
  const code = await getEthCode(walletAddress, chainId);
17
- const normalizedCode = code ? util.addHexPrefix(code).toLowerCase() : "0x0";
17
+ const normalizedCode = code ? metadataHelpers.add0x(code).toLowerCase() : "0x0";
18
18
  const hasDelegation = normalizedCode.length === 48 && normalizedCode.startsWith(eip7702Types.EIP_7702_PREFIX);
19
19
  if (hasDelegation) {
20
- const delegationAddress = util.addHexPrefix(normalizedCode.slice(eip7702Types.EIP_7702_PREFIX.length));
20
+ const delegationAddress = metadataHelpers.add0x(normalizedCode.slice(eip7702Types.EIP_7702_PREFIX.length));
21
21
  return delegationAddress;
22
22
  }
23
23
  return null;
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var _defineProperty = require('@babel/runtime/helpers/defineProperty');
4
- var util = require('@ethereumjs/util');
5
4
  var baseControllers = require('@toruslabs/base-controllers');
5
+ var metadataHelpers = require('@toruslabs/metadata-helpers');
6
6
  var log = require('loglevel');
7
7
  var constants = require('../utils/constants.js');
8
8
  var gasUtil = require('./gasUtil.js');
@@ -119,7 +119,7 @@ class GasFeeController extends baseControllers.BaseController {
119
119
  const chainId = this.getNetworkIdentifier();
120
120
  if (chainId === "loading") return;
121
121
  let chainIdInt;
122
- if (typeof chainId === "string" && util.isHexString(util.addHexPrefix(chainId))) {
122
+ if (metadataHelpers.isHexString(chainId)) {
123
123
  chainIdInt = Number.parseInt(chainId, 16);
124
124
  }
125
125
  try {
@@ -1,10 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var rlp = require('@ethereumjs/rlp');
4
- var util = require('@ethereumjs/util');
3
+ var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
5
4
  var baseControllers = require('@toruslabs/base-controllers');
6
- var ethers = require('ethers');
7
- var viem = require('viem');
5
+ var metadataHelpers = require('@toruslabs/metadata-helpers');
6
+ var viem$1 = require('viem');
7
+ var accounts = require('viem/accounts');
8
+ var viem = require('../utils/viem.js');
8
9
 
9
10
  class KeyringController extends baseControllers.BaseKeyringController {
10
11
  constructor({
@@ -22,47 +23,54 @@ class KeyringController extends baseControllers.BaseKeyringController {
22
23
  }
23
24
  async signTransaction(tx, address) {
24
25
  const wallet = this._getWalletForAccount(address);
25
- const privKey = new ethers.SigningKey(util.addHexPrefix(wallet.privateKey));
26
+ const account = accounts.privateKeyToAccount(metadataHelpers.add0x(wallet.privateKey));
26
27
  const localTx = tx;
27
- localTx.signature = privKey.sign(localTx.unsignedHash);
28
- return localTx;
28
+ const txToSign = viem.prepareViemTx(localTx);
29
+ // NOTE: don't use account.signTransaction directly because it only return signed serialized transaction
30
+ // we don't want to compute unsigned hash and signature again
31
+ const serializedUnsigned = viem$1.serializeTransaction(txToSign);
32
+ const unsignedHash = viem$1.keccak256(serializedUnsigned);
33
+ const rawSig = await account.sign({
34
+ hash: unsignedHash
35
+ });
36
+ const signature = viem$1.parseSignature(rawSig);
37
+ const serialized = viem$1.serializeTransaction(txToSign, signature);
38
+ return _objectSpread(_objectSpread({}, txToSign), {}, {
39
+ unsignedHash,
40
+ serialized,
41
+ signature
42
+ });
29
43
  }
30
44
  async signEip7702Authorization(authorization, address) {
31
45
  const wallet = this._getWalletForAccount(address);
32
- const privKey = new ethers.SigningKey(util.addHexPrefix(wallet.privateKey));
46
+ const account = accounts.privateKeyToAccount(metadataHelpers.add0x(wallet.privateKey));
33
47
  // Convert hex strings to proper types for RLP encoding
34
48
  // EIP-7702 authorization tuple: [chain_id_decimal, address, nonce_decimal]
35
49
  const chainIdDecimal = parseInt(authorization.chainId, 16);
36
50
  const nonceDecimal = parseInt(authorization.nonce, 16);
37
- // RLP encode the eip7702 authorization
38
- const encodedAuthorization = rlp.encode([chainIdDecimal, authorization.address, nonceDecimal]);
39
- // Prefixed with EIP7702 Domain Separator (0x05)
40
- const prefixedAuthorization = ethers.concat(["0x05", encodedAuthorization]);
41
- const authorizationHash = ethers.keccak256(prefixedAuthorization);
42
- const {
43
- r,
44
- s,
45
- v
46
- } = privKey.sign(authorizationHash);
47
- const signedAuthorization = {
51
+ const signedAuthorization = await account.signAuthorization({
52
+ contractAddress: authorization.address,
53
+ chainId: chainIdDecimal,
54
+ nonce: nonceDecimal
55
+ });
56
+ return {
48
57
  address: authorization.address,
49
58
  chainId: authorization.chainId,
50
59
  nonce: authorization.nonce,
51
- r: util.addHexPrefix(r),
52
- s: util.addHexPrefix(s),
53
- yParity: viem.toHex(v - 27 === 0 ? 0 : 1)
60
+ r: signedAuthorization.r,
61
+ s: signedAuthorization.s,
62
+ yParity: viem$1.toHex(signedAuthorization.yParity)
54
63
  };
55
- return signedAuthorization;
56
64
  }
57
65
  getAccounts() {
58
66
  return this.state.wallets.map(w => w.publicKey);
59
67
  }
60
- importAccount(accountPrivateKey) {
68
+ async importAccount(accountPrivateKey) {
61
69
  try {
62
- const hexPrivateKey = accountPrivateKey.padStart(64, "0");
63
- const bufferPrivKey = Buffer.from(hexPrivateKey, "hex");
64
- const publicKey = util.bytesToHex(util.privateToPublic(bufferPrivKey));
65
- const address = util.toChecksumAddress(util.bytesToHex(util.privateToAddress(bufferPrivKey)));
70
+ const hexPrivateKey = metadataHelpers.remove0x(accountPrivateKey).padStart(64, "0");
71
+ const account = accounts.privateKeyToAccount(metadataHelpers.add0x(hexPrivateKey));
72
+ const publicKey = account.publicKey;
73
+ const address = account.address;
66
74
  const existingWallet = this.state.wallets.find(w => w.address === address);
67
75
  if (existingWallet) return existingWallet.address;
68
76
  this.update({
@@ -90,35 +98,54 @@ class KeyringController extends baseControllers.BaseKeyringController {
90
98
  });
91
99
  }
92
100
  }
93
- getBufferPrivateKey(privateKey) {
94
- const stripped = util.stripHexPrefix(privateKey);
95
- return Buffer.from(stripped, "hex");
101
+ getPrivateKeyBytes(privateKey) {
102
+ return metadataHelpers.hexToBytes(privateKey);
96
103
  }
97
104
  // For eth_sign, we need to sign arbitrary data:
98
105
  async signMessage(data, address) {
106
+ if (typeof data !== "string") {
107
+ throw new Error("Torus Keyring - signMessage data must be type 'string'");
108
+ }
99
109
  const wallet = this._getWalletForAccount(address);
100
- const privKey = this.getBufferPrivateKey(wallet.privateKey);
101
- const messageSig = baseControllers.ecsignature(Buffer.from(util.stripHexPrefix(data), "hex"), privKey);
102
- const sig = baseControllers.concatSig(Buffer.from(util.bigIntToBytes(messageSig.v)), Buffer.from(messageSig.r), Buffer.from(messageSig.s));
110
+ const privKey = this.getPrivateKeyBytes(wallet.privateKey);
111
+ const payload = metadataHelpers.hexToBytes(data);
112
+ const messageSig = baseControllers.ecsignature(payload, privKey);
113
+ const sig = baseControllers.concatSig(messageSig.v, messageSig.r, messageSig.s);
103
114
  return sig;
104
115
  }
105
116
  async signPersonalMessage(data, address) {
106
117
  const wallet = this._getWalletForAccount(address);
107
- const privKey = new ethers.SigningKey(util.addHexPrefix(wallet.privateKey));
118
+ const account = accounts.privateKeyToAccount(metadataHelpers.add0x(wallet.privateKey));
108
119
  // we need to check if the data is hex or not
109
120
  // For historical reasons, you must submit the message to sign in hex-encoded UTF-8.
110
121
  // https://docs.metamask.io/wallet/how-to/sign-data/#use-personal_sign
111
- const message = util.isHexString(data) ? Buffer.from(util.stripHexPrefix(data), "hex") : Buffer.from(data);
112
- const signature = privKey.sign(ethers.hashMessage(message)).serialized;
113
- return signature;
122
+ const message = viem$1.isHex(data) ? {
123
+ raw: data
124
+ } : data;
125
+ return account.signMessage({
126
+ message
127
+ });
114
128
  }
115
129
  // personal_signTypedData, signs data along with the schema
116
130
  async signTypedData(typedData, address) {
117
131
  const wallet = this._getWalletForAccount(address);
118
- const privKey = new ethers.SigningKey(util.addHexPrefix(wallet.privateKey));
132
+ const account = accounts.privateKeyToAccount(metadataHelpers.add0x(wallet.privateKey));
119
133
  delete typedData.types.EIP712Domain;
120
- const signature = privKey.sign(ethers.TypedDataEncoder.hash(typedData.domain, typedData.types, typedData.message)).serialized;
121
- return signature;
134
+ const primaryType = typedData.primaryType;
135
+ if (!primaryType) {
136
+ throw new Error("Torus Keyring - primaryType is required");
137
+ }
138
+ const rawSig = await account.signTypedData({
139
+ domain: _objectSpread(_objectSpread({}, typedData.domain), {}, {
140
+ chainId: typeof typedData.domain.chainId === "string" ? parseInt(typedData.domain.chainId, 16) : typedData.domain.chainId,
141
+ salt: typedData.domain.salt,
142
+ verifyingContract: typedData.domain.verifyingContract
143
+ }),
144
+ types: typedData.types,
145
+ primaryType,
146
+ message: typedData.message
147
+ });
148
+ return rawSig;
122
149
  }
123
150
  _getWalletForAccount(account) {
124
151
  const address = account.toLowerCase();
@@ -1,12 +1,11 @@
1
1
  'use strict';
2
2
 
3
- var util = require('@ethereumjs/util');
4
3
  var baseControllers = require('@toruslabs/base-controllers');
5
- var ethers = require('ethers');
4
+ var metadataHelpers = require('@toruslabs/metadata-helpers');
5
+ var viem = require('viem');
6
6
 
7
- const hexRe = /^[0-9A-Fa-f]+$/gu;
8
7
  function validateAddress(address, propertyName) {
9
- if (!address || typeof address !== "string" || !util.isValidAddress(address)) {
8
+ if (!address || typeof address !== "string" || !viem.isAddress(address)) {
10
9
  throw new Error(`Invalid "${propertyName}" address: ${address} must be a valid string.`);
11
10
  }
12
11
  }
@@ -22,14 +21,13 @@ function validateSignMessageData(messageData) {
22
21
  }
23
22
  function normalizeMessageData(data) {
24
23
  try {
25
- const stripped = util.stripHexPrefix(data);
26
- if (stripped.match(hexRe)) {
27
- return util.addHexPrefix(stripped);
24
+ if (metadataHelpers.isHexString(data)) {
25
+ return metadataHelpers.add0x(data);
28
26
  }
29
27
  } catch {
30
28
  // do nothing
31
29
  }
32
- return util.bytesToHex(Buffer.from(data, "utf8"));
30
+ return metadataHelpers.add0x(metadataHelpers.bytesToHex(metadataHelpers.utf8ToBytes(data)));
33
31
  }
34
32
  async function validateTypedSignMessageDataV4(messageData, currentChainId) {
35
33
  validateAddress(messageData.from, "from");
@@ -74,7 +72,7 @@ async function validateAddChainData(data) {
74
72
  if (!chainId) {
75
73
  throw new Error("Invalid add chain params: please pass chainId in params");
76
74
  }
77
- if (!ethers.isHexString(chainId)) {
75
+ if (!viem.isHex(chainId)) {
78
76
  throw new Error("Invalid add chain params: please pass a valid hex chainId in params, for: ex: 0x1");
79
77
  }
80
78
  if (!rpcUrls || rpcUrls.length === 0) throw new Error("params.rpcUrls not provided");
@@ -87,12 +85,12 @@ async function validateAddChainData(data) {
87
85
  if (!name) throw new Error("params.nativeCurrency.name not provided");
88
86
  if (!symbol) throw new Error("params.nativeCurrency.symbol not provided");
89
87
  if (decimals === undefined) throw new Error("params.nativeCurrency.decimals not provided");
90
- const _web3 = new ethers.JsonRpcProvider(rpcUrls[0], "any");
91
- const {
92
- chainId: networkChainID
93
- } = await _web3.getNetwork();
94
- if (Number.parseInt(networkChainID.toString()) !== Number.parseInt(chainId, 16)) {
95
- throw new Error(`Provided rpc url's chainId version is not matching with provided chainId, expected: ${ethers.toQuantity(networkChainID)}, received: ${chainId}`);
88
+ const client = viem.createPublicClient({
89
+ transport: viem.http(rpcUrls[0])
90
+ });
91
+ const networkChainID = await client.getChainId();
92
+ if (networkChainID !== Number.parseInt(chainId, 16)) {
93
+ throw new Error(`Provided rpc url's chainId version is not matching with provided chainId, expected: ${viem.toHex(networkChainID)}, received: ${chainId}`);
96
94
  }
97
95
  }
98
96
  function validateSwitchChainData(data) {
@@ -102,7 +100,7 @@ function validateSwitchChainData(data) {
102
100
  if (!fullChainId) {
103
101
  throw new Error("Invalid switch chain params: please pass chainId in params");
104
102
  }
105
- if (!ethers.isHexString(fullChainId)) {
103
+ if (!viem.isHex(fullChainId)) {
106
104
  const [namespace, chainId] = fullChainId.split(":");
107
105
  if (namespace !== baseControllers.CHAIN_NAMESPACES.SOLANA && namespace !== baseControllers.CHAIN_NAMESPACES.EIP155) {
108
106
  throw new Error("Invalid switch chain params: invalid namespace");
@@ -150,15 +150,13 @@ class NetworkController extends baseControllers.BaseController {
150
150
  networkMiddleware,
151
151
  blockTracker
152
152
  }) {
153
- const ethereumMiddleware = createEthereumMiddleware.createEthereumMiddleware(this.baseProviderHandlers, this.getProviderConfig(), this.analytics);
154
- const engine = new auth.JRPCEngine();
155
- engine.push(baseControllers.createAnalyticsMiddleware({
156
- providerConfig: this.getProviderConfig(),
157
- analytics: this.analytics
158
- }));
159
- engine.push(ethereumMiddleware);
160
- engine.push(networkMiddleware);
161
- const provider = auth.providerFromEngine(engine);
153
+ const engine = auth.JRPCEngineV2.create({
154
+ middleware: [baseControllers.createAnalyticsMiddleware({
155
+ providerConfig: this.getProviderConfig(),
156
+ analytics: this.analytics
157
+ }), createEthereumMiddleware.createEthereumMiddleware(this.baseProviderHandlers, this.getProviderConfig(), this.analytics), networkMiddleware]
158
+ });
159
+ const provider = auth.providerFromEngineV2(engine);
162
160
  this.setProvider({
163
161
  provider,
164
162
  blockTracker