@toruslabs/ethereum-controllers 7.2.1 → 8.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 (95) hide show
  1. package/dist/ethereumControllers.umd.min.js +1 -1
  2. package/dist/lib.cjs/Account/AccountTrackerController.js +3 -2
  3. package/dist/lib.cjs/AccountAbstraction/AccountAbstractionController.js +0 -2
  4. package/dist/lib.cjs/Block/PollingBlockTracker.js +1 -3
  5. package/dist/lib.cjs/Currency/CurrencyController.js +0 -2
  6. package/dist/lib.cjs/Gas/GasFeeController.js +1 -3
  7. package/dist/lib.cjs/Gas/gasUtil.js +0 -1
  8. package/dist/lib.cjs/Keyring/KeyringController.js +0 -2
  9. package/dist/lib.cjs/Message/utils.js +4 -2
  10. package/dist/lib.cjs/Network/NetworkController.js +0 -4
  11. package/dist/lib.cjs/Network/cacheIdentifier.js +20 -14
  12. package/dist/lib.cjs/Nfts/NftsController.js +0 -1
  13. package/dist/lib.cjs/Preferences/PreferencesController.js +7 -10
  14. package/dist/lib.cjs/Tokens/TokenRatesController.js +0 -1
  15. package/dist/lib.cjs/Tokens/TokensController.js +24 -34
  16. package/dist/lib.cjs/Transaction/NonceTracker.js +2 -4
  17. package/dist/lib.cjs/Transaction/PendingTransactionTracker.js +3 -10
  18. package/dist/lib.cjs/Transaction/TransactionController.js +0 -6
  19. package/dist/lib.cjs/Transaction/TransactionGasUtil.js +0 -4
  20. package/dist/lib.cjs/Transaction/TransactionStateHistoryHelper.js +0 -1
  21. package/dist/lib.cjs/Transaction/TransactionStateManager.js +3 -11
  22. package/dist/lib.cjs/Transaction/TransactionUtils.js +1 -14
  23. package/dist/lib.cjs/index.js +10 -10
  24. package/dist/{types → lib.cjs/types}/Keyring/KeyringController.d.ts +1 -1
  25. package/dist/{types → lib.cjs/types}/Tokens/TokensController.d.ts +1 -1
  26. package/dist/lib.cjs/utils/constants.js +0 -1
  27. package/dist/lib.cjs/utils/conversionUtils.js +0 -4
  28. package/dist/lib.cjs/utils/helpers.js +0 -1
  29. package/dist/lib.esm/Account/AccountTrackerController.js +3 -1
  30. package/dist/lib.esm/Block/PollingBlockTracker.js +1 -1
  31. package/dist/lib.esm/Gas/GasFeeController.js +1 -1
  32. package/dist/lib.esm/Message/utils.js +4 -2
  33. package/dist/lib.esm/Network/cacheIdentifier.js +12 -0
  34. package/dist/lib.esm/Preferences/PreferencesController.js +7 -7
  35. package/dist/lib.esm/Tokens/TokenRatesController.js +3 -0
  36. package/dist/lib.esm/Tokens/TokensController.js +25 -33
  37. package/dist/lib.esm/Transaction/TransactionStateManager.js +1 -2
  38. package/dist/lib.esm/Transaction/TransactionUtils.js +2 -2
  39. package/dist/lib.esm/utils/contractAddresses.js +1 -1
  40. package/dist/lib.esm/utils/helpers.js +2 -2
  41. package/package.json +20 -18
  42. package/dist/757.ethereumControllers.cjs.js +0 -226
  43. package/dist/ethereumControllers.cjs.js +0 -24043
  44. package/dist/ethereumControllers.esm.js +0 -6314
  45. package/dist/lib.cjs/utils/lodashUtils.js +0 -25
  46. package/dist/lib.esm/utils/lodashUtils.js +0 -21
  47. package/dist/types/utils/lodashUtils.d.ts +0 -5
  48. /package/dist/{types → lib.cjs/types}/Account/AccountTrackerController.d.ts +0 -0
  49. /package/dist/{types → lib.cjs/types}/AccountAbstraction/AccountAbstractionController.d.ts +0 -0
  50. /package/dist/{types → lib.cjs/types}/AccountAbstraction/smartAccounts/BiconomySmartAccount.d.ts +0 -0
  51. /package/dist/{types → lib.cjs/types}/AccountAbstraction/smartAccounts/KernelSmartAccount.d.ts +0 -0
  52. /package/dist/{types → lib.cjs/types}/AccountAbstraction/smartAccounts/LightSmartAccount.d.ts +0 -0
  53. /package/dist/{types → lib.cjs/types}/AccountAbstraction/smartAccounts/NexusSmartAccount.d.ts +0 -0
  54. /package/dist/{types → lib.cjs/types}/AccountAbstraction/smartAccounts/SafeSmartAccount.d.ts +0 -0
  55. /package/dist/{types → lib.cjs/types}/AccountAbstraction/smartAccounts/SimpleSmartAccount.d.ts +0 -0
  56. /package/dist/{types → lib.cjs/types}/AccountAbstraction/smartAccounts/TrustSmartAccount.d.ts +0 -0
  57. /package/dist/{types → lib.cjs/types}/AccountAbstraction/smartAccounts/index.d.ts +0 -0
  58. /package/dist/{types → lib.cjs/types}/Block/PollingBlockTracker.d.ts +0 -0
  59. /package/dist/{types → lib.cjs/types}/Currency/CurrencyController.d.ts +0 -0
  60. /package/dist/{types → lib.cjs/types}/Gas/GasFeeController.d.ts +0 -0
  61. /package/dist/{types → lib.cjs/types}/Gas/IGasFeeController.d.ts +0 -0
  62. /package/dist/{types → lib.cjs/types}/Gas/gasUtil.d.ts +0 -0
  63. /package/dist/{types → lib.cjs/types}/Message/AddChainController.d.ts +0 -0
  64. /package/dist/{types → lib.cjs/types}/Message/MessageController.d.ts +0 -0
  65. /package/dist/{types → lib.cjs/types}/Message/PersonalMessageController.d.ts +0 -0
  66. /package/dist/{types → lib.cjs/types}/Message/SwitchChainController.d.ts +0 -0
  67. /package/dist/{types → lib.cjs/types}/Message/TypedMessageController.d.ts +0 -0
  68. /package/dist/{types → lib.cjs/types}/Message/types.d.ts +0 -0
  69. /package/dist/{types → lib.cjs/types}/Message/utils.d.ts +0 -0
  70. /package/dist/{types → lib.cjs/types}/Network/NetworkController.d.ts +0 -0
  71. /package/dist/{types → lib.cjs/types}/Network/cacheIdentifier.d.ts +0 -0
  72. /package/dist/{types → lib.cjs/types}/Network/createEthereumMiddleware.d.ts +0 -0
  73. /package/dist/{types → lib.cjs/types}/Network/createJsonRpcClient.d.ts +0 -0
  74. /package/dist/{types → lib.cjs/types}/Nfts/INftsController.d.ts +0 -0
  75. /package/dist/{types → lib.cjs/types}/Nfts/NftHandler.d.ts +0 -0
  76. /package/dist/{types → lib.cjs/types}/Nfts/NftsController.d.ts +0 -0
  77. /package/dist/{types → lib.cjs/types}/Preferences/IPreferencesController.d.ts +0 -0
  78. /package/dist/{types → lib.cjs/types}/Preferences/PreferencesController.d.ts +0 -0
  79. /package/dist/{types → lib.cjs/types}/Tokens/ITokensController.d.ts +0 -0
  80. /package/dist/{types → lib.cjs/types}/Tokens/TokenHandler.d.ts +0 -0
  81. /package/dist/{types → lib.cjs/types}/Tokens/TokenRatesController.d.ts +0 -0
  82. /package/dist/{types → lib.cjs/types}/Transaction/NonceTracker.d.ts +0 -0
  83. /package/dist/{types → lib.cjs/types}/Transaction/PendingTransactionTracker.d.ts +0 -0
  84. /package/dist/{types → lib.cjs/types}/Transaction/TransactionController.d.ts +0 -0
  85. /package/dist/{types → lib.cjs/types}/Transaction/TransactionGasUtil.d.ts +0 -0
  86. /package/dist/{types → lib.cjs/types}/Transaction/TransactionStateHistoryHelper.d.ts +0 -0
  87. /package/dist/{types → lib.cjs/types}/Transaction/TransactionStateManager.d.ts +0 -0
  88. /package/dist/{types → lib.cjs/types}/Transaction/TransactionUtils.d.ts +0 -0
  89. /package/dist/{types → lib.cjs/types}/index.d.ts +0 -0
  90. /package/dist/{types → lib.cjs/types}/utils/abis.d.ts +0 -0
  91. /package/dist/{types → lib.cjs/types}/utils/constants.d.ts +0 -0
  92. /package/dist/{types → lib.cjs/types}/utils/contractAddresses.d.ts +0 -0
  93. /package/dist/{types → lib.cjs/types}/utils/conversionUtils.d.ts +0 -0
  94. /package/dist/{types → lib.cjs/types}/utils/helpers.d.ts +0 -0
  95. /package/dist/{types → lib.cjs/types}/utils/interfaces.d.ts +0 -0
@@ -10,7 +10,6 @@ var abis = require('../utils/abis.js');
10
10
  var contractAddresses = require('../utils/contractAddresses.js');
11
11
 
12
12
  const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
13
-
14
13
  /**
15
14
  * Tracks accounts based on blocks.
16
15
  * If block tracker provides latest block, we query accounts from it.
@@ -97,7 +96,9 @@ class AccountTrackerController extends baseControllers.BaseController {
97
96
  const releaseLock = await this.mutex.acquire();
98
97
  try {
99
98
  this._updateAccounts();
100
- } catch (error) {} finally {
99
+ } catch {
100
+ // do nothing
101
+ } finally {
101
102
  releaseLock();
102
103
  }
103
104
  }
@@ -188,7 +188,6 @@ class AccountAbstractionController extends baseControllers.BaseController {
188
188
  }];
189
189
  const maxFeePerGas = txParams.maxFeePerGas ? BigInt(txParams.maxFeePerGas) : undefined;
190
190
  const maxPriorityFeePerGas = txParams.maxPriorityFeePerGas ? BigInt(txParams.maxPriorityFeePerGas) : undefined;
191
-
192
191
  // estimate gas: maxFeePerGas and maxPriorityFeePerGas are not required
193
192
  const estimateGasParams = {
194
193
  account: this.smartAccount,
@@ -203,7 +202,6 @@ class AccountAbstractionController extends baseControllers.BaseController {
203
202
  balance: viem.parseEther("1")
204
203
  }]
205
204
  };
206
-
207
205
  // bundler only support factoryArgs for estimate user operation gas in entryPoint v0.7
208
206
  let factoryArgs;
209
207
  if (this.smartAccount.entryPoint.version !== "0.6") {
@@ -20,7 +20,6 @@ class PollingBlockTracker extends baseControllers.BaseBlockTracker {
20
20
  });
21
21
  const pollingInterval = config.pollingInterval || DEFAULT_POLLING_INTERVAL;
22
22
  const retryTimeout = config.retryTimeout || DEFAULT_RETRY_TIMEOUT;
23
-
24
23
  // merge default + provided config.
25
24
  this.defaultConfig = {
26
25
  provider: config.provider,
@@ -34,7 +33,6 @@ class PollingBlockTracker extends baseControllers.BaseBlockTracker {
34
33
  await this._updateLatestBlock();
35
34
  return this.getLatestBlock();
36
35
  }
37
-
38
36
  // overrides the BaseBlockTracker._start method.
39
37
  _start() {
40
38
  this._synchronize().catch(err => this.emit("error", err));
@@ -49,7 +47,7 @@ class PollingBlockTracker extends baseControllers.BaseBlockTracker {
49
47
  const newErr = new Error(`PollingBlockTracker - encountered an error while attempting to update latest block:\n${err.stack}`);
50
48
  try {
51
49
  this.emit("error", newErr);
52
- } catch (emitErr) {
50
+ } catch {
53
51
  log.error(newErr);
54
52
  }
55
53
  await baseControllers.timeout(this.config.retryTimeout);
@@ -46,7 +46,6 @@ class CurrencyController extends baseControllers.BaseCurrencyController {
46
46
  getCommonDenominatorPrice() {
47
47
  return this.state.commonDenominatorPrice;
48
48
  }
49
-
50
49
  /**
51
50
  * Creates a new poll, using setInterval, to periodically call updateConversionRate. The id of the interval is
52
51
  * stored at the controller's conversionInterval property. If it is called and such an id already exists, the
@@ -62,7 +61,6 @@ class CurrencyController extends baseControllers.BaseCurrencyController {
62
61
  }
63
62
  }, this.config.pollInterval);
64
63
  }
65
-
66
64
  /**
67
65
  * Updates the conversionRate and conversionDate properties associated with the currentCurrency. Updated info is
68
66
  * fetched from an external API
@@ -95,7 +95,6 @@ class GasFeeController extends baseControllers.BaseController {
95
95
  disconnectPoller() {
96
96
  this.stopPolling();
97
97
  }
98
-
99
98
  /**
100
99
  * Prepare to discard this controller.
101
100
  *
@@ -110,7 +109,6 @@ class GasFeeController extends baseControllers.BaseController {
110
109
  }
111
110
  this.resetState();
112
111
  }
113
-
114
112
  /**
115
113
  * Gets and sets gasFeeEstimates in state
116
114
  *
@@ -142,7 +140,7 @@ class GasFeeController extends baseControllers.BaseController {
142
140
  } else {
143
141
  throw new Error("ChainId not supported by api");
144
142
  }
145
- } catch (error) {
143
+ } catch {
146
144
  estimates = await this.fetchGasEstimatesViaEthFeeHistory(this.provider);
147
145
  }
148
146
  const {
@@ -77,7 +77,6 @@ async function fetchGasEstimatesViaEthFeeHistory(provider) {
77
77
  }
78
78
  };
79
79
  }
80
-
81
80
  /**
82
81
  * Hit the legacy MetaSwaps gasPrices estimate api and return the low, medium
83
82
  * high values from that API.
@@ -58,7 +58,6 @@ class KeyringController extends baseControllers.BaseKeyringController {
58
58
  const stripped = util.stripHexPrefix(privateKey);
59
59
  return Buffer.from(stripped, "hex");
60
60
  }
61
-
62
61
  // For eth_sign, we need to sign arbitrary data:
63
62
  async signMessage(data, address) {
64
63
  const wallet = this._getWalletForAccount(address);
@@ -77,7 +76,6 @@ class KeyringController extends baseControllers.BaseKeyringController {
77
76
  const signature = privKey.sign(ethers.hashMessage(message)).serialized;
78
77
  return signature;
79
78
  }
80
-
81
79
  // personal_signTypedData, signs data along with the schema
82
80
  async signTypedData(typedData, address) {
83
81
  const wallet = this._getWalletForAccount(address);
@@ -26,7 +26,9 @@ function normalizeMessageData(data) {
26
26
  if (stripped.match(hexRe)) {
27
27
  return util.addHexPrefix(stripped);
28
28
  }
29
- } catch (e) {}
29
+ } catch {
30
+ // do nothing
31
+ }
30
32
  return util.bytesToHex(Buffer.from(data, "utf8"));
31
33
  }
32
34
  async function validateTypedSignMessageDataV4(messageData, currentChainId) {
@@ -40,7 +42,7 @@ async function validateTypedSignMessageDataV4(messageData, currentChainId) {
40
42
  } else {
41
43
  try {
42
44
  data = JSON.parse(messageData.data);
43
- } catch (e) {
45
+ } catch {
44
46
  throw new Error("Data must be passed as a valid JSON string.");
45
47
  }
46
48
  }
@@ -35,7 +35,6 @@ class NetworkController extends baseControllers.BaseController {
35
35
  },
36
36
  providerConfig: constants.SUPPORTED_NETWORKS[constants.MAINNET_CHAIN_ID]
37
37
  };
38
-
39
38
  // when a new network is set,
40
39
  // we set to loading first and
41
40
  // then when connection succeeds,
@@ -48,7 +47,6 @@ class NetworkController extends baseControllers.BaseController {
48
47
  getNetworkRPCUrl() {
49
48
  return this.state.providerConfig.rpcTarget;
50
49
  }
51
-
52
50
  /**
53
51
  * Called by orchestrator once while initializing the class
54
52
  * @param providerHandlers - JRPC handlers for provider
@@ -92,7 +90,6 @@ class NetworkController extends baseControllers.BaseController {
92
90
  });
93
91
  return supportsEIP1559;
94
92
  }
95
-
96
93
  /**
97
94
  * Refreshes the current network code
98
95
  */
@@ -177,7 +174,6 @@ class NetworkController extends baseControllers.BaseController {
177
174
  eventFilter: "skipInternal"
178
175
  });
179
176
  }
180
-
181
177
  // set new provider and blockTracker
182
178
  this.provider = provider;
183
179
  provider.setMaxListeners(10);
@@ -2,13 +2,25 @@
2
2
 
3
3
  var stringify = require('fast-safe-stringify');
4
4
 
5
- let CacheStrategy = /*#__PURE__*/function (CacheStrategy) {
5
+ exports.CacheStrategy = void 0;
6
+ (function (CacheStrategy) {
7
+ /**
8
+ * Cache per-block.
9
+ */
6
10
  CacheStrategy["Block"] = "block";
11
+ /**
12
+ * Cache until a chain reorganization occurs.
13
+ */
7
14
  CacheStrategy["Fork"] = "fork";
15
+ /**
16
+ * Never cache.
17
+ */
8
18
  CacheStrategy["Never"] = "never";
19
+ /**
20
+ * Permanently cache.
21
+ */
9
22
  CacheStrategy["Permanent"] = "perma";
10
- return CacheStrategy;
11
- }({});
23
+ })(exports.CacheStrategy || (exports.CacheStrategy = {}));
12
24
  function blockTagParamIndex(method) {
13
25
  switch (method) {
14
26
  // blockTag is at index 2
@@ -48,8 +60,7 @@ function cacheTypeForMethod(method) {
48
60
  case "eth_compileSerpent":
49
61
  case "shh_version":
50
62
  case "test_permaCache":
51
- return CacheStrategy.Permanent;
52
-
63
+ return exports.CacheStrategy.Permanent;
53
64
  // cache until fork
54
65
  case "eth_getBlockByNumber":
55
66
  case "eth_getBlockTransactionCountByNumber":
@@ -57,8 +68,7 @@ function cacheTypeForMethod(method) {
57
68
  case "eth_getTransactionByBlockNumberAndIndex":
58
69
  case "eth_getUncleByBlockNumberAndIndex":
59
70
  case "test_forkCache":
60
- return CacheStrategy.Fork;
61
-
71
+ return exports.CacheStrategy.Fork;
62
72
  // cache for block
63
73
  case "eth_gasPrice":
64
74
  case "eth_blockNumber":
@@ -70,27 +80,24 @@ function cacheTypeForMethod(method) {
70
80
  case "eth_getFilterLogs":
71
81
  case "eth_getLogs":
72
82
  case "test_blockCache":
73
- return CacheStrategy.Block;
74
-
83
+ return exports.CacheStrategy.Block;
75
84
  // never cache
76
85
  default:
77
- return CacheStrategy.Never;
86
+ return exports.CacheStrategy.Never;
78
87
  }
79
88
  }
80
89
  function canCache(method) {
81
- return cacheTypeForMethod(method) !== CacheStrategy.Never;
90
+ return cacheTypeForMethod(method) !== exports.CacheStrategy.Never;
82
91
  }
83
92
  function paramsWithoutBlockTag(request) {
84
93
  if (!request.params) {
85
94
  return [];
86
95
  }
87
96
  const index = blockTagParamIndex(request.method);
88
-
89
97
  // Block tag param not passed.
90
98
  if (index === undefined || !Array.isArray(request.params) || index >= request.params.length) {
91
99
  return request.params;
92
100
  }
93
-
94
101
  // eth_getBlockByNumber has the block tag first, then the optional includeTx? param
95
102
  if (request.method === "eth_getBlockByNumber") {
96
103
  return request.params.slice(1);
@@ -106,7 +113,6 @@ function cacheIdentifierForRequest(request, skipBlockRef) {
106
113
  return null;
107
114
  }
108
115
 
109
- exports.CacheStrategy = CacheStrategy;
110
116
  exports.blockTagParamIndex = blockTagParamIndex;
111
117
  exports.cacheIdentifierForRequest = cacheIdentifierForRequest;
112
118
  exports.cacheTypeForMethod = cacheTypeForMethod;
@@ -92,7 +92,6 @@ class NftsController extends baseControllers.BaseController {
92
92
  });
93
93
  this.restartNftDetection();
94
94
  }
95
-
96
95
  /**
97
96
  * Restart nft detection polling period and call detectNewNfts
98
97
  * in case of address change or user session initialization.
@@ -95,9 +95,9 @@ class PreferencesController extends baseControllers.BasePreferencesController {
95
95
  }
96
96
  });
97
97
  const {
98
- aggregateVerifier,
99
- verifier,
100
- verifierId
98
+ groupedAuthConnectionId,
99
+ authConnection,
100
+ userId
101
101
  } = userInfo || {};
102
102
  const userExists = await this.sync(address);
103
103
  if (!userExists) {
@@ -105,8 +105,8 @@ class PreferencesController extends baseControllers.BasePreferencesController {
105
105
  await this.createUser({
106
106
  selectedCurrency: accountState.selectedCurrency,
107
107
  theme: accountState.theme,
108
- verifier: aggregateVerifier || verifier,
109
- verifierId,
108
+ verifier: groupedAuthConnectionId || authConnection,
109
+ verifierId: userId,
110
110
  locale,
111
111
  address,
112
112
  type,
@@ -122,8 +122,8 @@ class PreferencesController extends baseControllers.BasePreferencesController {
122
122
  eoaAddress
123
123
  }, address);
124
124
  this.storeUserLogin({
125
- verifier: aggregateVerifier || verifier,
126
- verifierId,
125
+ verifier: groupedAuthConnectionId || authConnection,
126
+ verifierId: userId,
127
127
  options: {
128
128
  calledFromEmbed,
129
129
  rehydrate
@@ -154,7 +154,6 @@ class PreferencesController extends baseControllers.BasePreferencesController {
154
154
  customNfts,
155
155
  account_type: accountType
156
156
  } = user || {};
157
-
158
157
  // update latest data in state.
159
158
  this.updateState({
160
159
  contacts,
@@ -200,7 +199,6 @@ class PreferencesController extends baseControllers.BasePreferencesController {
200
199
  if (duplicateIndex === -1) {
201
200
  var _tx$to;
202
201
  // No duplicate found
203
-
204
202
  const finalTx = this.cancelTxCalculate([...storePastTx, formattedTx]);
205
203
  tx.is_cancel = formattedTx.is_cancel;
206
204
  tx.to = (_tx$to = tx.to) === null || _tx$to === void 0 ? void 0 : _tx$to.toLowerCase();
@@ -332,7 +330,6 @@ class PreferencesController extends baseControllers.BasePreferencesController {
332
330
  throw new Error(`chainId ${data.chainId} is not supported`);
333
331
  }
334
332
  }
335
-
336
333
  // Custom Network methods
337
334
  async addCustomNetwork({
338
335
  network
@@ -56,7 +56,6 @@ class TokenRatesController extends baseControllers.BaseController {
56
56
  }
57
57
  });
58
58
  }
59
-
60
59
  /**
61
60
  * Creates a new poll, using setInterval, to periodically call updateConversionRate. The id of the interval is
62
61
  * stored at the controller's conversionInterval property. If it is called and such an id already exists, the
@@ -10,23 +10,6 @@ var constants = require('../utils/constants.js');
10
10
  var contractAddresses = require('../utils/contractAddresses.js');
11
11
  var TokenHandler = require('./TokenHandler.js');
12
12
 
13
- function getObjectFromArrayBasedonKey(oldArray, key) {
14
- return oldArray.reduce((acc, x) => {
15
- const xkey = x[key];
16
- if (typeof xkey === "boolean") return acc;
17
- acc[xkey] = x;
18
- return acc;
19
- }, {});
20
- }
21
- const mergeTokenArrays = (oldArray, newArray) => {
22
- const oldMap = getObjectFromArrayBasedonKey(oldArray || [], "tokenAddress");
23
- const newMap = getObjectFromArrayBasedonKey(newArray || [], "tokenAddress");
24
- const finalArr = newArray;
25
- Object.keys(oldMap).forEach(x => {
26
- if (!newMap[x] && oldMap[x].isEtherScan) finalArr.push(oldMap[x]);
27
- });
28
- return finalArr;
29
- };
30
13
  const DEFAULT_INTERVAL = 180 * 1000;
31
14
  class TokensController extends baseControllers.BaseController {
32
15
  constructor({
@@ -113,7 +96,6 @@ class TokensController extends baseControllers.BaseController {
113
96
  });
114
97
  this.restartTokenDetection();
115
98
  }
116
-
117
99
  /**
118
100
  * Restart token detection polling period and call detectNewTokens
119
101
  * in case of address change or user session initialization.
@@ -179,45 +161,57 @@ class TokensController extends baseControllers.BaseController {
179
161
  const userAddress = this.userSelectedAddress;
180
162
  if (userAddress === "") return;
181
163
  const oldTokens = [...this.userTokens];
182
- const tokenAddresses = oldTokens.map(x => x.tokenAddress);
183
- const nonZeroTokens = [];
164
+ // - fetch from Etherscan, if failed then fetch from TokenHandler
165
+ // - if there are remaining tokens, fetch either from SingleAddressContract (if failed then use TokenHandler) or TokenHandler
184
166
  try {
167
+ const nonZeroTokens = [];
185
168
  const currentChainId = this.config.chainId;
186
169
  if (constants.ETHERSCAN_SUPPORTED_CHAINS.includes(currentChainId)) {
187
170
  const etherscanBalances = await this.getEtherScanTokens(userAddress, currentChainId, skipCache);
188
171
  nonZeroTokens.push(...etherscanBalances);
189
172
  }
190
- if (tokenAddresses.length > 0) {
173
+ // only fetch balances for tokens that are not already in the nonZeroTokens array
174
+ const remainingTokens = oldTokens.filter(x => !nonZeroTokens.find(y => {
175
+ var _y$tokenAddress, _x$tokenAddress;
176
+ return ((_y$tokenAddress = y.tokenAddress) === null || _y$tokenAddress === void 0 ? void 0 : _y$tokenAddress.toLocaleLowerCase()) === ((_x$tokenAddress = x.tokenAddress) === null || _x$tokenAddress === void 0 ? void 0 : _x$tokenAddress.toLocaleLowerCase());
177
+ }));
178
+ if (remainingTokens.length > 0) {
179
+ const remainingTokensAddresses = remainingTokens.map(x => x.tokenAddress);
191
180
  const currentSingleCallAddress = contractAddresses.SINGLE_CALL_BALANCES_ADDRESSES[currentChainId];
192
181
  if (currentSingleCallAddress) {
193
182
  const ethContract = new ethers.Contract(currentSingleCallAddress, abis.singleBalanceCheckerAbi, this.ethersProvider);
194
- const result = await ethContract.balances([userAddress], tokenAddresses);
195
- tokenAddresses.forEach((_, index) => {
183
+ const result = await ethContract.balances([userAddress], remainingTokensAddresses);
184
+ remainingTokensAddresses.forEach((_, index) => {
196
185
  const balance = ethers.toQuantity(result[index]);
197
186
  if (balance && balance !== "0x0") {
198
- nonZeroTokens.push(_objectSpread(_objectSpread({}, oldTokens[index]), {}, {
187
+ nonZeroTokens.push(_objectSpread(_objectSpread({}, remainingTokens[index]), {}, {
199
188
  balance,
200
189
  chainId: currentChainId
201
190
  }));
202
191
  }
203
192
  });
204
193
  } else {
205
- this.getTokenBalancesUsingHandler(oldTokens);
194
+ const fetchedRemainingTokens = await this.getTokenBalancesUsingHandler(remainingTokens);
195
+ nonZeroTokens.push(...fetchedRemainingTokens);
206
196
  }
207
197
  }
198
+ this.update({
199
+ tokens: {
200
+ [userAddress]: nonZeroTokens
201
+ }
202
+ });
208
203
  } catch (error) {
209
204
  log.error(error, "unable to fetch token balances using single call balance address");
210
- this.getTokenBalancesUsingHandler(oldTokens);
211
- } finally {
205
+ const fetchedTokens = await this.getTokenBalancesUsingHandler(oldTokens);
212
206
  this.update({
213
207
  tokens: {
214
- [userAddress]: nonZeroTokens
208
+ [userAddress]: fetchedTokens
215
209
  }
216
210
  });
217
211
  }
218
212
  }
219
213
  async getTokenBalancesUsingHandler(customTokens) {
220
- if (!this.userSelectedAddress) return;
214
+ if (!this.userSelectedAddress) return [];
221
215
  const currentNetworkTokens = customTokens;
222
216
  const promiseSettledResult = await Promise.allSettled(currentNetworkTokens.map(async x => {
223
217
  try {
@@ -250,11 +244,7 @@ class TokensController extends baseControllers.BaseController {
250
244
  if (x.status === "fulfilled" && x.value) acc.push(x.value);
251
245
  return acc;
252
246
  }, []);
253
- this.update({
254
- tokens: {
255
- [this.userSelectedAddress]: mergeTokenArrays(this.userTokens, nonZeroTokens)
256
- }
257
- });
247
+ return nonZeroTokens;
258
248
  }
259
249
  }
260
250
 
@@ -30,11 +30,10 @@ class NonceTracker {
30
30
  releaseLock
31
31
  };
32
32
  }
33
-
34
33
  /**
35
- this will return an object with the `nextNonce`
34
+ this will return an object with the `nextNonce`
36
35
  `nonceDetails`, and the releaseLock.
37
- Note: releaseLock must be called after adding a signed tx
36
+ Note: releaseLock must be called after adding a signed tx
38
37
  to pending transactions (or discarding).
39
38
  */
40
39
  async getNonceLock(address) {
@@ -59,7 +58,6 @@ class NonceTracker {
59
58
  nonceDetails.local = localNonceResult;
60
59
  nonceDetails.network = networkNonceResult;
61
60
  const nextNonce = Math.max(networkNonceResult.nonce, localNonceResult.nonce);
62
-
63
61
  // return nonce and release cb
64
62
  return {
65
63
  nextNonce,
@@ -32,7 +32,6 @@ class PendingTransactionTracker extends auth.SafeEventEmitter {
32
32
  this.getConfirmedTransactions = getConfirmedTransactions;
33
33
  this.droppedBlocksBufferByHash = new Map();
34
34
  }
35
-
36
35
  /**
37
36
  checks the network for signed txs and releases the nonce global lock if it is
38
37
  */
@@ -57,15 +56,15 @@ class PendingTransactionTracker extends auth.SafeEventEmitter {
57
56
  try {
58
57
  await this._resubmitTx(txMeta, block.idempotencyKey);
59
58
  } catch (error) {
60
- var _value;
59
+ var _error$value;
61
60
  /*
62
61
  Dont marked as failed if the error is a "known" transaction warning
63
62
  "there is already a transaction with the same sender-nonce
64
63
  but higher/same gas price"
65
- Also don't mark as failed if it has ever been broadcast successfully.
64
+ Also don't mark as failed if it has ever been broadcast successfully.
66
65
  A successful broadcast means it may still be mined.
67
66
  */
68
- const errorMessage = ((_value = error.value) === null || _value === void 0 || (_value = _value.message) === null || _value === void 0 ? void 0 : _value.toLowerCase()) || error.message.toLowerCase();
67
+ const errorMessage = ((_error$value = error.value) === null || _error$value === void 0 || (_error$value = _error$value.message) === null || _error$value === void 0 ? void 0 : _error$value.toLowerCase()) || error.message.toLowerCase();
69
68
  const isKnownTx =
70
69
  // geth
71
70
  errorMessage.includes("replacement transaction underpriced") || errorMessage.includes("known transaction") ||
@@ -99,17 +98,14 @@ class PendingTransactionTracker extends auth.SafeEventEmitter {
99
98
  const firstRetryBlockNumber = txMeta.firstRetryBlockNumber || latestBlockNumber;
100
99
  const txBlockDistance = Number.parseInt(latestBlockNumber, 16) - Number.parseInt(firstRetryBlockNumber, 16);
101
100
  const retryCount = txMeta.retryCount || 0;
102
-
103
101
  // Exponential backoff to limit retries at publishing (capped at last 15 mins)
104
102
  if (txBlockDistance <= Math.min(50, 2 ** retryCount)) return undefined;
105
-
106
103
  // Only auto-submit already-signed txs:
107
104
  if (!("rawTransaction" in txMeta)) return this.approveTransaction(txMeta.id);
108
105
  const {
109
106
  rawTransaction
110
107
  } = txMeta;
111
108
  const txHash = await this.publishTransaction(rawTransaction);
112
-
113
109
  // Increment successful tries:
114
110
  this.emit(baseControllers.TX_EVENTS.TX_RETRY, {
115
111
  txMeta,
@@ -121,10 +117,8 @@ class PendingTransactionTracker extends auth.SafeEventEmitter {
121
117
  const txMeta = foundTx;
122
118
  const txHash = txMeta.transactionHash;
123
119
  const txId = txMeta.id;
124
-
125
120
  // Only check submitted txs
126
121
  if (txMeta.status !== baseControllers.TransactionStatus.submitted || txMeta.isUserOperation) return;
127
-
128
122
  // extra check in case there was an uncaught error during the
129
123
  // signature and submission process
130
124
  if (!txHash) {
@@ -136,7 +130,6 @@ class PendingTransactionTracker extends auth.SafeEventEmitter {
136
130
  });
137
131
  return;
138
132
  }
139
-
140
133
  // If another tx with the same nonce is mined, set as failed.
141
134
  if (this._checkIfNonceIsTaken(txMeta)) {
142
135
  this.emit(baseControllers.TX_EVENTS.TX_DROPPED, {
@@ -259,7 +259,6 @@ class TransactionController extends TransactionStateManager.TransactionStateMana
259
259
  txMeta.transaction.maxFeePerGas = txMeta.transaction.gasPrice;
260
260
  // If the dapp has suggested a gas price, but no maxFeePerGas or maxPriorityFeePerGas
261
261
  // then we set maxFeePerGas to the suggested gasPrice.
262
-
263
262
  txMeta.transaction.maxPriorityFeePerGas = helpers.bnLessThan(typeof defaultMaxPriorityFeePerGas === "string" ? util.stripHexPrefix(defaultMaxPriorityFeePerGas) : defaultMaxPriorityFeePerGas, typeof txMeta.transaction.gasPrice === "string" ? util.stripHexPrefix(txMeta.transaction.gasPrice) : txMeta.transaction.gasPrice) ? defaultMaxPriorityFeePerGas : txMeta.transaction.gasPrice;
264
263
  } else {
265
264
  if (defaultMaxFeePerGas && !txMeta.transaction.maxFeePerGas) {
@@ -286,18 +285,14 @@ class TransactionController extends TransactionStateManager.TransactionStateMana
286
285
  txMeta.transaction.maxPriorityFeePerGas = txMeta.transaction.maxFeePerGas;
287
286
  }
288
287
  }
289
-
290
288
  // We remove the gasPrice param entirely when on an eip1559 compatible network
291
-
292
289
  delete txMeta.transaction.gasPrice;
293
290
  } else {
294
291
  // We ensure that maxFeePerGas and maxPriorityFeePerGas are not in the transaction params
295
292
  // when not on a EIP1559 compatible network
296
-
297
293
  delete txMeta.transaction.maxPriorityFeePerGas;
298
294
  delete txMeta.transaction.maxFeePerGas;
299
295
  }
300
-
301
296
  // If we have gotten to this point, and none of gasPrice, maxPriorityFeePerGas or maxFeePerGas are
302
297
  // set on transaction, it means that either we are on a non-EIP1559 network and the dapp didn't suggest
303
298
  // a gas price, or we are on an EIP1559 network, and none of gasPrice, maxPriorityFeePerGas or maxFeePerGas
@@ -387,7 +382,6 @@ class TransactionController extends TransactionStateManager.TransactionStateMana
387
382
  estimatedGasHex,
388
383
  simulationFails
389
384
  } = await this.txGasUtil.analyzeGasUsage(txMeta);
390
-
391
385
  // add additional gas buffer to our estimation for safety
392
386
  const gasLimit = this.txGasUtil.addGasBuffer(util.addHexPrefix(estimatedGasHex), blockGasLimit, customNetworkGasBuffer);
393
387
  return {
@@ -39,7 +39,6 @@ class TransactionGasUtil {
39
39
  simulationFails
40
40
  };
41
41
  }
42
-
43
42
  /**
44
43
  Adds a gas buffer with out exceeding the block gas limit
45
44
  */
@@ -48,7 +47,6 @@ class TransactionGasUtil {
48
47
  const blockGasLimitBn = new BN.BN(util.stripHexPrefix(blockGasLimitHex), 16);
49
48
  const upperGasLimitBn = blockGasLimitBn.muln(0.9);
50
49
  const bufferedGasLimitBn = initialGasLimitBn.muln(multiplier);
51
-
52
50
  // if initialGasLimit is above blockGasLimit, dont modify it
53
51
  if (initialGasLimitBn.gt(upperGasLimitBn)) return util.addHexPrefix(initialGasLimitBn.toString("hex"));
54
52
  // if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit
@@ -56,13 +54,11 @@ class TransactionGasUtil {
56
54
  // otherwise use blockGasLimit
57
55
  return util.addHexPrefix(upperGasLimitBn.toString("hex"));
58
56
  }
59
-
60
57
  /**
61
58
  Estimates the tx's gas usage
62
59
  */
63
60
  async estimateTxGas(txMeta) {
64
61
  const txParams = baseControllers.cloneDeep(txMeta.transaction);
65
-
66
62
  // `eth_estimateGas` can fail if the user has insufficient balance for the
67
63
  // value being sent, or for the gas cost. We don't want to check their
68
64
  // balance here, we just want the gas estimate. The gas price is removed
@@ -23,7 +23,6 @@ function generateHistoryEntry(previousState, newState, note) {
23
23
  }
24
24
  return entry;
25
25
  }
26
-
27
26
  /**
28
27
  Recovers previous txMeta state obj
29
28
  */