@toruslabs/ethereum-controllers 8.17.1 → 9.0.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 (61) hide show
  1. package/dist/lib.cjs/Account/AccountTrackerController.js +15 -7
  2. package/dist/lib.cjs/AccountAbstraction/AccountAbstractionController.js +4 -6
  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 +3 -2
  7. package/dist/lib.cjs/Keyring/KeyringController.js +69 -40
  8. package/dist/lib.cjs/Message/utils.js +15 -14
  9. package/dist/lib.cjs/Nfts/NftHandler.js +54 -12
  10. package/dist/lib.cjs/Nfts/NftsController.js +1 -4
  11. package/dist/lib.cjs/Preferences/PreferencesController.js +2 -2
  12. package/dist/lib.cjs/Tokens/TokenHandler.js +39 -7
  13. package/dist/lib.cjs/Tokens/TokensController.js +15 -7
  14. package/dist/lib.cjs/Transaction/TransactionController.js +17 -20
  15. package/dist/lib.cjs/Transaction/TransactionGasUtil.js +11 -12
  16. package/dist/lib.cjs/Transaction/TransactionUtils.js +44 -39
  17. package/dist/lib.cjs/types/Account/AccountTrackerController.d.ts +1 -1
  18. package/dist/lib.cjs/types/AccountAbstraction/AccountAbstractionController.d.ts +1 -3
  19. package/dist/lib.cjs/types/Keyring/KeyringController.d.ts +4 -4
  20. package/dist/lib.cjs/types/Nfts/NftHandler.d.ts +4 -3
  21. package/dist/lib.cjs/types/Nfts/NftsController.d.ts +0 -1
  22. package/dist/lib.cjs/types/Tokens/TokenHandler.d.ts +4 -3
  23. package/dist/lib.cjs/types/Tokens/TokensController.d.ts +1 -1
  24. package/dist/lib.cjs/types/Transaction/TransactionUtils.d.ts +11 -3
  25. package/dist/lib.cjs/types/utils/abis.d.ts +544 -99
  26. package/dist/lib.cjs/types/utils/hex.d.ts +9 -0
  27. package/dist/lib.cjs/types/utils/interfaces.d.ts +205 -2
  28. package/dist/lib.cjs/types/utils/transaction.d.ts +1 -1
  29. package/dist/lib.cjs/types/utils/viem.d.ts +8 -0
  30. package/dist/lib.cjs/utils/abis.js +12 -0
  31. package/dist/lib.cjs/utils/conversionUtils.js +3 -4
  32. package/dist/lib.cjs/utils/helpers.js +9 -8
  33. package/dist/lib.cjs/utils/hex.js +23 -0
  34. package/dist/lib.cjs/utils/transaction.js +7 -11
  35. package/dist/lib.cjs/utils/viem.js +214 -0
  36. package/dist/lib.esm/Account/AccountTrackerController.js +15 -7
  37. package/dist/lib.esm/AccountAbstraction/AccountAbstractionController.js +5 -7
  38. package/dist/lib.esm/Eip5792/walletGetCallsStatus.js +1 -1
  39. package/dist/lib.esm/Eip5792/walletSendCalls.js +6 -7
  40. package/dist/lib.esm/Eip7702/eip7702Utils.js +1 -1
  41. package/dist/lib.esm/Gas/GasFeeController.js +3 -2
  42. package/dist/lib.esm/Keyring/KeyringController.js +68 -40
  43. package/dist/lib.esm/Message/utils.js +13 -12
  44. package/dist/lib.esm/Nfts/NftHandler.js +54 -12
  45. package/dist/lib.esm/Nfts/NftsController.js +1 -4
  46. package/dist/lib.esm/Preferences/PreferencesController.js +1 -1
  47. package/dist/lib.esm/Tokens/TokenHandler.js +39 -7
  48. package/dist/lib.esm/Tokens/TokensController.js +15 -7
  49. package/dist/lib.esm/Transaction/TransactionController.js +6 -9
  50. package/dist/lib.esm/Transaction/TransactionGasUtil.js +11 -12
  51. package/dist/lib.esm/Transaction/TransactionUtils.js +28 -24
  52. package/dist/lib.esm/utils/abis.js +12 -0
  53. package/dist/lib.esm/utils/conversionUtils.js +2 -3
  54. package/dist/lib.esm/utils/helpers.js +6 -5
  55. package/dist/lib.esm/utils/hex.js +21 -0
  56. package/dist/lib.esm/utils/interfaces.js +64 -0
  57. package/dist/lib.esm/utils/transaction.js +7 -11
  58. package/dist/lib.esm/utils/viem.js +214 -0
  59. package/package.json +13 -18
  60. package/dist/ethereumControllers.umd.min.js +0 -2
  61. 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,10 +2,8 @@
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');
@@ -125,7 +123,7 @@ class AccountAbstractionController extends baseControllers.BaseController {
125
123
  });
126
124
  }
127
125
  async sendTransaction(id, tx, address) {
128
- var _txParams$chainId, _txReceipt$receipt, _txReceipt$nonce, _txReceipt$receipt2, _txReceipt$receipt3, _txReceipt$receipt4;
126
+ var _txParams$chainId, _txReceipt$receipt, _txReceipt$nonce, _txReceipt$receipt$ga, _txReceipt$receipt2, _txReceipt$receipt$ef, _txReceipt$receipt3, _txReceipt$receipt4;
129
127
  if (address.toLowerCase() !== this.smartAccount.address.toLowerCase()) {
130
128
  throw new Error("Invalid address");
131
129
  }
@@ -165,8 +163,8 @@ class AccountAbstractionController extends baseControllers.BaseController {
165
163
  receipt: {
166
164
  transactionHash: (_txReceipt$receipt = txReceipt.receipt) === null || _txReceipt$receipt === void 0 ? void 0 : _txReceipt$receipt.transactionHash,
167
165
  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)),
166
+ 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),
167
+ 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
168
  type: (_txReceipt$receipt4 = txReceipt.receipt) === null || _txReceipt$receipt4 === void 0 ? void 0 : _txReceipt$receipt4.type,
171
169
  reason: txReceipt.reason
172
170
  },
@@ -277,7 +275,7 @@ class AccountAbstractionController extends baseControllers.BaseController {
277
275
  throw new Error("Invalid address");
278
276
  }
279
277
  return (_this$smartAccount = this.smartAccount) === null || _this$smartAccount === void 0 ? void 0 : _this$smartAccount.signMessage({
280
- message: ethers.isHexString(message) ? {
278
+ message: viem.isHex(message) ? {
281
279
  raw: message
282
280
  } : message
283
281
  });
@@ -1,9 +1,9 @@
1
1
  'use strict';
2
2
 
3
- var util = require('@ethereumjs/util');
4
3
  var baseControllers = require('@toruslabs/base-controllers');
5
4
  var auth = require('@web3auth/auth');
6
5
  var eip5792Types = require('../utils/eip5792Types.js');
6
+ var hex = require('../utils/hex.js');
7
7
 
8
8
  /**
9
9
  * Maps a TransactionStatus to an EIP-5792 GetCallsStatusCode.
@@ -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: hex.addHexPrefix(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,10 +1,10 @@
1
1
  'use strict';
2
2
 
3
- var util = require('@ethereumjs/util');
4
3
  var viem = require('viem');
5
4
  var abis = require('../utils/abis.js');
6
5
  var constants = require('../utils/constants.js');
7
6
  var eip7702Types = require('../utils/eip7702Types.js');
7
+ var hex = require('../utils/hex.js');
8
8
 
9
9
  /**
10
10
  * The MetaMask EIP-7702 Stateless Delegator contract address.
@@ -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 ? hex.addHexPrefix(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 = hex.addHexPrefix(normalizedCode.slice(eip7702Types.EIP_7702_PREFIX.length));
21
21
  return delegationAddress;
22
22
  }
23
23
  return null;
@@ -1,10 +1,11 @@
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');
6
5
  var log = require('loglevel');
6
+ var viem = require('viem');
7
7
  var constants = require('../utils/constants.js');
8
+ var hex = require('../utils/hex.js');
8
9
  var gasUtil = require('./gasUtil.js');
9
10
 
10
11
  const GAS_FEE_API = "https://mock-gas-server.herokuapp.com/";
@@ -119,7 +120,7 @@ class GasFeeController extends baseControllers.BaseController {
119
120
  const chainId = this.getNetworkIdentifier();
120
121
  if (chainId === "loading") return;
121
122
  let chainIdInt;
122
- if (typeof chainId === "string" && util.isHexString(util.addHexPrefix(chainId))) {
123
+ if (typeof chainId === "string" && viem.isHex(hex.addHexPrefix(chainId))) {
123
124
  chainIdInt = Number.parseInt(chainId, 16);
124
125
  }
125
126
  try {
@@ -1,10 +1,12 @@
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 hex = require('../utils/hex.js');
9
+ var viem = require('../utils/viem.js');
8
10
 
9
11
  class KeyringController extends baseControllers.BaseKeyringController {
10
12
  constructor({
@@ -22,47 +24,54 @@ class KeyringController extends baseControllers.BaseKeyringController {
22
24
  }
23
25
  async signTransaction(tx, address) {
24
26
  const wallet = this._getWalletForAccount(address);
25
- const privKey = new ethers.SigningKey(util.addHexPrefix(wallet.privateKey));
27
+ const account = accounts.privateKeyToAccount(hex.addHexPrefix(wallet.privateKey));
26
28
  const localTx = tx;
27
- localTx.signature = privKey.sign(localTx.unsignedHash);
28
- return localTx;
29
+ const txToSign = viem.prepareViemTx(localTx);
30
+ // NOTE: don't use account.signTransaction directly because it only return signed serialized transaction
31
+ // we don't want to compute unsigned hash and signature again
32
+ const serializedUnsigned = viem$1.serializeTransaction(txToSign);
33
+ const unsignedHash = viem$1.keccak256(serializedUnsigned);
34
+ const rawSig = await account.sign({
35
+ hash: unsignedHash
36
+ });
37
+ const signature = viem$1.parseSignature(rawSig);
38
+ const serialized = viem$1.serializeTransaction(txToSign, signature);
39
+ return _objectSpread(_objectSpread({}, txToSign), {}, {
40
+ unsignedHash,
41
+ serialized,
42
+ signature
43
+ });
29
44
  }
30
45
  async signEip7702Authorization(authorization, address) {
31
46
  const wallet = this._getWalletForAccount(address);
32
- const privKey = new ethers.SigningKey(util.addHexPrefix(wallet.privateKey));
47
+ const account = accounts.privateKeyToAccount(hex.addHexPrefix(wallet.privateKey));
33
48
  // Convert hex strings to proper types for RLP encoding
34
49
  // EIP-7702 authorization tuple: [chain_id_decimal, address, nonce_decimal]
35
50
  const chainIdDecimal = parseInt(authorization.chainId, 16);
36
51
  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 = {
52
+ const signedAuthorization = await account.signAuthorization({
53
+ contractAddress: authorization.address,
54
+ chainId: chainIdDecimal,
55
+ nonce: nonceDecimal
56
+ });
57
+ return {
48
58
  address: authorization.address,
49
59
  chainId: authorization.chainId,
50
60
  nonce: authorization.nonce,
51
- r: util.addHexPrefix(r),
52
- s: util.addHexPrefix(s),
53
- yParity: viem.toHex(v - 27 === 0 ? 0 : 1)
61
+ r: signedAuthorization.r,
62
+ s: signedAuthorization.s,
63
+ yParity: viem$1.toHex(signedAuthorization.yParity)
54
64
  };
55
- return signedAuthorization;
56
65
  }
57
66
  getAccounts() {
58
67
  return this.state.wallets.map(w => w.publicKey);
59
68
  }
60
- importAccount(accountPrivateKey) {
69
+ async importAccount(accountPrivateKey) {
61
70
  try {
62
71
  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)));
72
+ const account = accounts.privateKeyToAccount(hex.addHexPrefix(hexPrivateKey));
73
+ const publicKey = account.publicKey;
74
+ const address = account.address;
66
75
  const existingWallet = this.state.wallets.find(w => w.address === address);
67
76
  if (existingWallet) return existingWallet.address;
68
77
  this.update({
@@ -90,35 +99,55 @@ class KeyringController extends baseControllers.BaseKeyringController {
90
99
  });
91
100
  }
92
101
  }
93
- getBufferPrivateKey(privateKey) {
94
- const stripped = util.stripHexPrefix(privateKey);
95
- return Buffer.from(stripped, "hex");
102
+ getPrivateKeyBytes(privateKey) {
103
+ const stripped = hex.stripHexPrefix(privateKey);
104
+ return metadataHelpers.hexToBytes(stripped);
96
105
  }
97
106
  // For eth_sign, we need to sign arbitrary data:
98
107
  async signMessage(data, address) {
108
+ if (typeof data !== "string") {
109
+ throw new Error("Torus Keyring - signMessage data must be type 'string'");
110
+ }
99
111
  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));
112
+ const privKey = this.getPrivateKeyBytes(wallet.privateKey);
113
+ const payload = metadataHelpers.hexToBytes(hex.stripHexPrefix(data));
114
+ const messageSig = baseControllers.ecsignature(payload, privKey);
115
+ const sig = baseControllers.concatSig(messageSig.v, messageSig.r, messageSig.s);
103
116
  return sig;
104
117
  }
105
118
  async signPersonalMessage(data, address) {
106
119
  const wallet = this._getWalletForAccount(address);
107
- const privKey = new ethers.SigningKey(util.addHexPrefix(wallet.privateKey));
120
+ const account = accounts.privateKeyToAccount(hex.addHexPrefix(wallet.privateKey));
108
121
  // we need to check if the data is hex or not
109
122
  // For historical reasons, you must submit the message to sign in hex-encoded UTF-8.
110
123
  // 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;
124
+ const message = viem$1.isHex(data) ? {
125
+ raw: data
126
+ } : data;
127
+ return account.signMessage({
128
+ message
129
+ });
114
130
  }
115
131
  // personal_signTypedData, signs data along with the schema
116
132
  async signTypedData(typedData, address) {
117
133
  const wallet = this._getWalletForAccount(address);
118
- const privKey = new ethers.SigningKey(util.addHexPrefix(wallet.privateKey));
134
+ const account = accounts.privateKeyToAccount(hex.addHexPrefix(wallet.privateKey));
119
135
  delete typedData.types.EIP712Domain;
120
- const signature = privKey.sign(ethers.TypedDataEncoder.hash(typedData.domain, typedData.types, typedData.message)).serialized;
121
- return signature;
136
+ const primaryType = typedData.primaryType;
137
+ if (!primaryType) {
138
+ throw new Error("Torus Keyring - primaryType is required");
139
+ }
140
+ const rawSig = await account.signTypedData({
141
+ domain: _objectSpread(_objectSpread({}, typedData.domain), {}, {
142
+ chainId: typeof typedData.domain.chainId === "string" ? parseInt(typedData.domain.chainId, 16) : typedData.domain.chainId,
143
+ salt: typedData.domain.salt,
144
+ verifyingContract: typedData.domain.verifyingContract
145
+ }),
146
+ types: typedData.types,
147
+ primaryType,
148
+ message: typedData.message
149
+ });
150
+ return rawSig;
122
151
  }
123
152
  _getWalletForAccount(account) {
124
153
  const address = account.toLowerCase();
@@ -1,12 +1,13 @@
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
+ var hex = require('../utils/hex.js');
6
7
 
7
8
  const hexRe = /^[0-9A-Fa-f]+$/gu;
8
9
  function validateAddress(address, propertyName) {
9
- if (!address || typeof address !== "string" || !util.isValidAddress(address)) {
10
+ if (!address || typeof address !== "string" || !viem.isAddress(address)) {
10
11
  throw new Error(`Invalid "${propertyName}" address: ${address} must be a valid string.`);
11
12
  }
12
13
  }
@@ -22,14 +23,14 @@ function validateSignMessageData(messageData) {
22
23
  }
23
24
  function normalizeMessageData(data) {
24
25
  try {
25
- const stripped = util.stripHexPrefix(data);
26
+ const stripped = hex.stripHexPrefix(data);
26
27
  if (stripped.match(hexRe)) {
27
- return util.addHexPrefix(stripped);
28
+ return hex.addHexPrefix(stripped);
28
29
  }
29
30
  } catch {
30
31
  // do nothing
31
32
  }
32
- return util.bytesToHex(Buffer.from(data, "utf8"));
33
+ return hex.addHexPrefix(metadataHelpers.bytesToHex(metadataHelpers.utf8ToBytes(data)));
33
34
  }
34
35
  async function validateTypedSignMessageDataV4(messageData, currentChainId) {
35
36
  validateAddress(messageData.from, "from");
@@ -74,7 +75,7 @@ async function validateAddChainData(data) {
74
75
  if (!chainId) {
75
76
  throw new Error("Invalid add chain params: please pass chainId in params");
76
77
  }
77
- if (!ethers.isHexString(chainId)) {
78
+ if (!viem.isHex(chainId)) {
78
79
  throw new Error("Invalid add chain params: please pass a valid hex chainId in params, for: ex: 0x1");
79
80
  }
80
81
  if (!rpcUrls || rpcUrls.length === 0) throw new Error("params.rpcUrls not provided");
@@ -87,12 +88,12 @@ async function validateAddChainData(data) {
87
88
  if (!name) throw new Error("params.nativeCurrency.name not provided");
88
89
  if (!symbol) throw new Error("params.nativeCurrency.symbol not provided");
89
90
  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}`);
91
+ const client = viem.createPublicClient({
92
+ transport: viem.http(rpcUrls[0])
93
+ });
94
+ const networkChainID = await client.getChainId();
95
+ if (networkChainID !== Number.parseInt(chainId, 16)) {
96
+ throw new Error(`Provided rpc url's chainId version is not matching with provided chainId, expected: ${viem.toHex(networkChainID)}, received: ${chainId}`);
96
97
  }
97
98
  }
98
99
  function validateSwitchChainData(data) {
@@ -102,7 +103,7 @@ function validateSwitchChainData(data) {
102
103
  if (!fullChainId) {
103
104
  throw new Error("Invalid switch chain params: please pass chainId in params");
104
105
  }
105
- if (!ethers.isHexString(fullChainId)) {
106
+ if (!viem.isHex(fullChainId)) {
106
107
  const [namespace, chainId] = fullChainId.split(":");
107
108
  if (namespace !== baseControllers.CHAIN_NAMESPACES.SOLANA && namespace !== baseControllers.CHAIN_NAMESPACES.EIP155) {
108
109
  throw new Error("Invalid switch chain params: invalid namespace");
@@ -3,8 +3,8 @@
3
3
  var _objectSpread = require('@babel/runtime/helpers/objectSpread2');
4
4
  var _defineProperty = require('@babel/runtime/helpers/defineProperty');
5
5
  var httpHelpers = require('@toruslabs/http-helpers');
6
- var ethers = require('ethers');
7
6
  var log = require('loglevel');
7
+ var viem = require('viem');
8
8
  var abis = require('../utils/abis.js');
9
9
  var constants = require('../utils/constants.js');
10
10
  var helpers = require('../utils/helpers.js');
@@ -33,6 +33,7 @@ class NftHandler {
33
33
  _defineProperty(this, "chainId", void 0);
34
34
  _defineProperty(this, "provider", void 0);
35
35
  _defineProperty(this, "isSpecial", void 0);
36
+ _defineProperty(this, "publicClient", void 0);
36
37
  this.chainId = chainId;
37
38
  this.contractAddress = contractAddress;
38
39
  this.contractImage = contractImage;
@@ -40,6 +41,9 @@ class NftHandler {
40
41
  this.contractSymbol = contractSymbol;
41
42
  this.nftStandard = nftStandard;
42
43
  this.provider = provider;
44
+ this.publicClient = viem.createPublicClient({
45
+ transport: viem.custom(this.provider)
46
+ });
43
47
  this.contractDescription = contractDescription;
44
48
  this.contractFallbackLogo = contractFallbackLogo;
45
49
  this.contractSupply = contractSupply;
@@ -103,8 +107,17 @@ class NftHandler {
103
107
  }
104
108
  if (!this.contractName || !this.contractSymbol || !this.contractDescription) {
105
109
  const abi = this.nftStandard === constants.CONTRACT_TYPE_ERC721 ? abis.erc721Abi : abis.erc1155Abi;
106
- const contract = new ethers.Contract(this.contractAddress, abi, this.provider);
107
- const [name, symbol] = await Promise.all([contract.name(), contract.symbol()]);
110
+ const [name, symbol] = await Promise.all([this.publicClient.readContract({
111
+ address: this.contractAddress,
112
+ abi,
113
+ functionName: "name",
114
+ authorizationList: undefined
115
+ }), this.publicClient.readContract({
116
+ address: this.contractAddress,
117
+ abi,
118
+ functionName: "symbol",
119
+ authorizationList: undefined
120
+ })]);
108
121
  returnNft.contractName = name;
109
122
  returnNft.contractSymbol = symbol;
110
123
  if (!this.contractName) this.contractName = name;
@@ -117,14 +130,25 @@ class NftHandler {
117
130
  standard
118
131
  } = await this.checkNftStandard();
119
132
  const abi = standard === constants.CONTRACT_TYPE_ERC721 ? abis.erc721Abi : abis.erc1155Abi;
120
- const contract = new ethers.Contract(this.contractAddress, abi, this.provider);
121
133
  if (standard === constants.CONTRACT_TYPE_ERC1155) {
122
- const balance = await contract.balanceOf(userAddress, tokenId);
123
- return balance;
134
+ const balance = await this.publicClient.readContract({
135
+ address: this.contractAddress,
136
+ abi,
137
+ functionName: "balanceOf",
138
+ args: [userAddress, BigInt(tokenId)],
139
+ authorizationList: undefined
140
+ });
141
+ return String(balance);
124
142
  }
125
143
  let owner = "";
126
144
  try {
127
- owner = await contract.ownerOf(tokenId);
145
+ owner = await this.publicClient.readContract({
146
+ address: this.contractAddress,
147
+ abi,
148
+ functionName: "ownerOf",
149
+ args: [BigInt(tokenId)],
150
+ authorizationList: undefined
151
+ });
128
152
  } catch {
129
153
  throw new Error("Token id doesn't exists");
130
154
  }
@@ -166,14 +190,32 @@ class NftHandler {
166
190
  }
167
191
  async contractSupportsInterface(standard, interfaceId) {
168
192
  const abi = standard === constants.CONTRACT_TYPE_ERC721 ? abis.erc721Abi : abis.erc1155Abi;
169
- const contract = new ethers.Contract(this.contractAddress, abi, this.provider);
170
- return contract.supportsInterface(interfaceId);
193
+ return await this.publicClient.readContract({
194
+ address: this.contractAddress,
195
+ abi,
196
+ functionName: "supportsInterface",
197
+ args: [interfaceId],
198
+ authorizationList: undefined
199
+ });
171
200
  }
172
201
  async getCollectibleTokenURI(tokenId, standard = constants.CONTRACT_TYPE_ERC721) {
173
- const method = standard === constants.CONTRACT_TYPE_ERC721 ? "tokenURI" : "uri";
174
202
  const abi = standard === constants.CONTRACT_TYPE_ERC721 ? abis.erc721Abi : abis.erc1155Abi;
175
- const contract = new ethers.Contract(this.contractAddress, abi, this.provider);
176
- return contract[method](tokenId);
203
+ if (standard === constants.CONTRACT_TYPE_ERC721) {
204
+ return await this.publicClient.readContract({
205
+ address: this.contractAddress,
206
+ abi,
207
+ functionName: "tokenURI",
208
+ args: [BigInt(tokenId)],
209
+ authorizationList: undefined
210
+ });
211
+ }
212
+ return await this.publicClient.readContract({
213
+ address: this.contractAddress,
214
+ abi,
215
+ functionName: "uri",
216
+ args: [BigInt(tokenId)],
217
+ authorizationList: undefined
218
+ });
177
219
  }
178
220
  }
179
221
 
@@ -4,7 +4,6 @@ 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 deepmerge = require('deepmerge');
7
- var ethers = require('ethers');
8
7
  var log = require('loglevel');
9
8
  var constants = require('../utils/constants.js');
10
9
  var NftHandler = require('./NftHandler.js');
@@ -27,12 +26,10 @@ class NftsController extends baseControllers.BaseController {
27
26
  });
28
27
  _defineProperty(this, "name", "NftsController");
29
28
  _defineProperty(this, "provider", void 0);
30
- _defineProperty(this, "ethersProvider", void 0);
31
29
  _defineProperty(this, "getCustomNfts", void 0);
32
30
  _defineProperty(this, "getSimpleHashNfts", void 0);
33
31
  _defineProperty(this, "pollingManager", void 0);
34
32
  this.provider = provider;
35
- this.ethersProvider = new ethers.BrowserProvider(this.provider, "any");
36
33
  this.getCustomNfts = getCustomNfts;
37
34
  this.getSimpleHashNfts = getSimpleHashNfts;
38
35
  this.defaultConfig = {
@@ -175,7 +172,7 @@ class NftsController extends baseControllers.BaseController {
175
172
  const promiseSettledResult = await Promise.allSettled(currentNetworkNfts.map(async x => {
176
173
  try {
177
174
  const tokenInstance = new NftHandler.NftHandler(_objectSpread(_objectSpread({}, x), {}, {
178
- provider: this.ethersProvider
175
+ provider: this.provider
179
176
  }));
180
177
  const contractData = await tokenInstance.getContractMetadata();
181
178
  const assetData = await Promise.allSettled(x.assets.map(y => tokenInstance.getNftMetadata(userAddress, y)));
@@ -1,12 +1,12 @@
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');
6
5
  var asyncMutex = require('async-mutex');
7
6
  var log = require('loglevel');
8
7
  var constants = require('../utils/constants.js');
9
8
  var helpers = require('../utils/helpers.js');
9
+ var hex = require('../utils/hex.js');
10
10
 
11
11
  class PreferencesController extends baseControllers.BasePreferencesController {
12
12
  constructor({
@@ -302,7 +302,7 @@ class PreferencesController extends baseControllers.BasePreferencesController {
302
302
  }
303
303
  isChainIdSupported(address, chainId) {
304
304
  const approveChainOptions = this.getChainOptions(address);
305
- const providerConfig = approveChainOptions.find(x => util.stripHexPrefix(x.chainId) === chainId);
305
+ const providerConfig = approveChainOptions.find(x => hex.stripHexPrefix(x.chainId) === chainId);
306
306
  return !!providerConfig;
307
307
  }
308
308
  async addChain(network) {