@metamask-previews/transaction-controller 24.0.0-preview.d78968a2 → 24.0.0-preview.eb2135e

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 (275) hide show
  1. package/dist/TransactionController.js +38 -1908
  2. package/dist/TransactionController.js.map +1 -1
  3. package/dist/TransactionController.mjs +39 -0
  4. package/dist/TransactionController.mjs.map +1 -0
  5. package/dist/chunk-2K7J3EY3.mjs +170 -0
  6. package/dist/chunk-2K7J3EY3.mjs.map +1 -0
  7. package/dist/chunk-5XBULBP2.js +399 -0
  8. package/dist/chunk-5XBULBP2.js.map +1 -0
  9. package/dist/chunk-6MYNWYJK.mjs +158 -0
  10. package/dist/chunk-6MYNWYJK.mjs.map +1 -0
  11. package/dist/chunk-7APMBUKB.js +158 -0
  12. package/dist/chunk-7APMBUKB.js.map +1 -0
  13. package/dist/chunk-7LXE4KHV.js +40 -0
  14. package/dist/chunk-7LXE4KHV.js.map +1 -0
  15. package/dist/chunk-7MZ57ILQ.mjs +62 -0
  16. package/dist/chunk-7MZ57ILQ.mjs.map +1 -0
  17. package/dist/chunk-BJEESIBE.js +2313 -0
  18. package/dist/chunk-BJEESIBE.js.map +1 -0
  19. package/dist/chunk-C67QD5PV.mjs +320 -0
  20. package/dist/chunk-C67QD5PV.mjs.map +1 -0
  21. package/dist/chunk-DE3MZYVY.mjs +2313 -0
  22. package/dist/chunk-DE3MZYVY.mjs.map +1 -0
  23. package/dist/chunk-DEKM6PVG.mjs +46 -0
  24. package/dist/chunk-DEKM6PVG.mjs.map +1 -0
  25. package/dist/chunk-DQP6X25N.mjs +208 -0
  26. package/dist/chunk-DQP6X25N.mjs.map +1 -0
  27. package/dist/chunk-DTDTOMTB.js +238 -0
  28. package/dist/chunk-DTDTOMTB.js.map +1 -0
  29. package/dist/chunk-DTEDYRTL.js +242 -0
  30. package/dist/chunk-DTEDYRTL.js.map +1 -0
  31. package/dist/chunk-EQ3RRHB7.mjs +211 -0
  32. package/dist/chunk-EQ3RRHB7.mjs.map +1 -0
  33. package/dist/chunk-FDJPXQTF.js +46 -0
  34. package/dist/chunk-FDJPXQTF.js.map +1 -0
  35. package/dist/chunk-FRKQ3Z2L.mjs +40 -0
  36. package/dist/chunk-FRKQ3Z2L.mjs.map +1 -0
  37. package/dist/chunk-FS7FRO7B.mjs +90 -0
  38. package/dist/chunk-FS7FRO7B.mjs.map +1 -0
  39. package/dist/chunk-GKTIFXPN.js +170 -0
  40. package/dist/chunk-GKTIFXPN.js.map +1 -0
  41. package/dist/chunk-H4M66BA3.js +62 -0
  42. package/dist/chunk-H4M66BA3.js.map +1 -0
  43. package/dist/chunk-HPNXIKFY.js +76 -0
  44. package/dist/chunk-HPNXIKFY.js.map +1 -0
  45. package/dist/chunk-HS277C77.js +75 -0
  46. package/dist/chunk-HS277C77.js.map +1 -0
  47. package/dist/chunk-I5YZ7QUK.js +121 -0
  48. package/dist/chunk-I5YZ7QUK.js.map +1 -0
  49. package/dist/chunk-IC233ZQS.js +211 -0
  50. package/dist/chunk-IC233ZQS.js.map +1 -0
  51. package/dist/chunk-IUBAETUH.js +137 -0
  52. package/dist/chunk-IUBAETUH.js.map +1 -0
  53. package/dist/chunk-J56A7UCK.mjs +123 -0
  54. package/dist/chunk-J56A7UCK.mjs.map +1 -0
  55. package/dist/chunk-JR6HDRNV.mjs +242 -0
  56. package/dist/chunk-JR6HDRNV.mjs.map +1 -0
  57. package/dist/chunk-JRBREX22.mjs +75 -0
  58. package/dist/chunk-JRBREX22.mjs.map +1 -0
  59. package/dist/chunk-JRQHIBG5.mjs +399 -0
  60. package/dist/chunk-JRQHIBG5.mjs.map +1 -0
  61. package/dist/chunk-LM4NUNMT.mjs +76 -0
  62. package/dist/chunk-LM4NUNMT.mjs.map +1 -0
  63. package/dist/chunk-M7455RU7.js +320 -0
  64. package/dist/chunk-M7455RU7.js.map +1 -0
  65. package/dist/chunk-MHM5LRRF.mjs +122 -0
  66. package/dist/chunk-MHM5LRRF.mjs.map +1 -0
  67. package/dist/chunk-NHRBO3LU.mjs +50 -0
  68. package/dist/chunk-NHRBO3LU.mjs.map +1 -0
  69. package/dist/chunk-NM6OYEPP.mjs +182 -0
  70. package/dist/chunk-NM6OYEPP.mjs.map +1 -0
  71. package/dist/chunk-NUOBUW7C.js +85 -0
  72. package/dist/chunk-NUOBUW7C.js.map +1 -0
  73. package/dist/chunk-QP75SWIQ.js +53 -0
  74. package/dist/chunk-QP75SWIQ.js.map +1 -0
  75. package/dist/chunk-RI6MVJJN.js +122 -0
  76. package/dist/chunk-RI6MVJJN.js.map +1 -0
  77. package/dist/chunk-S6VGOPUY.js +14 -0
  78. package/dist/chunk-S6VGOPUY.js.map +1 -0
  79. package/dist/chunk-UGFBA4GV.js +123 -0
  80. package/dist/chunk-UGFBA4GV.js.map +1 -0
  81. package/dist/chunk-UKYY2RVS.mjs +137 -0
  82. package/dist/chunk-UKYY2RVS.mjs.map +1 -0
  83. package/dist/chunk-UM4ORJ5B.mjs +121 -0
  84. package/dist/chunk-UM4ORJ5B.mjs.map +1 -0
  85. package/dist/chunk-UQQWZT6C.mjs +14 -0
  86. package/dist/chunk-UQQWZT6C.mjs.map +1 -0
  87. package/dist/chunk-VH47Q6TS.js +182 -0
  88. package/dist/chunk-VH47Q6TS.js.map +1 -0
  89. package/dist/chunk-XGRAHX6T.mjs +53 -0
  90. package/dist/chunk-XGRAHX6T.mjs.map +1 -0
  91. package/dist/chunk-XUI43LEZ.mjs +30 -0
  92. package/dist/chunk-XUI43LEZ.mjs.map +1 -0
  93. package/dist/chunk-Y734U4V6.mjs +85 -0
  94. package/dist/chunk-Y734U4V6.mjs.map +1 -0
  95. package/dist/chunk-Y7ENNK7L.mjs +238 -0
  96. package/dist/chunk-Y7ENNK7L.mjs.map +1 -0
  97. package/dist/chunk-Z4BLTVTB.js +30 -0
  98. package/dist/chunk-Z4BLTVTB.js.map +1 -0
  99. package/dist/chunk-ZCQRDZ36.js +208 -0
  100. package/dist/chunk-ZCQRDZ36.js.map +1 -0
  101. package/dist/chunk-ZJLZSFOZ.js +90 -0
  102. package/dist/chunk-ZJLZSFOZ.js.map +1 -0
  103. package/dist/chunk-ZNZEJDOE.js +50 -0
  104. package/dist/chunk-ZNZEJDOE.js.map +1 -0
  105. package/dist/constants.js +15 -110
  106. package/dist/constants.js.map +1 -1
  107. package/dist/constants.mjs +16 -0
  108. package/dist/constants.mjs.map +1 -0
  109. package/dist/gas-flows/DefaultGasFeeFlow.js +14 -77
  110. package/dist/gas-flows/DefaultGasFeeFlow.js.map +1 -1
  111. package/dist/gas-flows/DefaultGasFeeFlow.mjs +15 -0
  112. package/dist/gas-flows/DefaultGasFeeFlow.mjs.map +1 -0
  113. package/dist/gas-flows/LineaGasFeeFlow.js +15 -110
  114. package/dist/gas-flows/LineaGasFeeFlow.js.map +1 -1
  115. package/dist/gas-flows/LineaGasFeeFlow.mjs +16 -0
  116. package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -0
  117. package/dist/helpers/EtherscanRemoteTransactionSource.js +11 -145
  118. package/dist/helpers/EtherscanRemoteTransactionSource.js.map +1 -1
  119. package/dist/helpers/EtherscanRemoteTransactionSource.mjs +12 -0
  120. package/dist/helpers/EtherscanRemoteTransactionSource.mjs.map +1 -0
  121. package/dist/helpers/GasFeePoller.js +10 -142
  122. package/dist/helpers/GasFeePoller.js.map +1 -1
  123. package/dist/helpers/GasFeePoller.mjs +11 -0
  124. package/dist/helpers/GasFeePoller.mjs.map +1 -0
  125. package/dist/helpers/IncomingTransactionHelper.js +8 -204
  126. package/dist/helpers/IncomingTransactionHelper.js.map +1 -1
  127. package/dist/helpers/IncomingTransactionHelper.mjs +9 -0
  128. package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -0
  129. package/dist/helpers/MultichainTrackingHelper.js +12 -291
  130. package/dist/helpers/MultichainTrackingHelper.js.map +1 -1
  131. package/dist/helpers/MultichainTrackingHelper.mjs +13 -0
  132. package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -0
  133. package/dist/helpers/PendingTransactionTracker.js +9 -357
  134. package/dist/helpers/PendingTransactionTracker.js.map +1 -1
  135. package/dist/helpers/PendingTransactionTracker.mjs +10 -0
  136. package/dist/helpers/PendingTransactionTracker.mjs.map +1 -0
  137. package/dist/index.js +56 -20
  138. package/dist/index.js.map +1 -1
  139. package/dist/index.mjs +57 -0
  140. package/dist/index.mjs.map +1 -0
  141. package/dist/logger.js +11 -8
  142. package/dist/logger.js.map +1 -1
  143. package/dist/logger.mjs +12 -0
  144. package/dist/logger.mjs.map +1 -0
  145. package/dist/tsconfig.build.tsbuildinfo +1 -0
  146. package/dist/{TransactionController.d.ts → types/TransactionController.d.ts} +4 -1
  147. package/dist/types/TransactionController.d.ts.map +1 -0
  148. package/dist/{constants.d.ts → types/constants.d.ts} +5 -0
  149. package/dist/types/constants.d.ts.map +1 -0
  150. package/dist/types/gas-flows/DefaultGasFeeFlow.d.ts.map +1 -0
  151. package/dist/types/gas-flows/LineaGasFeeFlow.d.ts.map +1 -0
  152. package/dist/types/helpers/EtherscanRemoteTransactionSource.d.ts.map +1 -0
  153. package/dist/types/helpers/GasFeePoller.d.ts.map +1 -0
  154. package/dist/types/helpers/IncomingTransactionHelper.d.ts.map +1 -0
  155. package/dist/types/helpers/MultichainTrackingHelper.d.ts.map +1 -0
  156. package/dist/types/helpers/PendingTransactionTracker.d.ts.map +1 -0
  157. package/dist/types/index.d.ts.map +1 -0
  158. package/dist/types/logger.d.ts.map +1 -0
  159. package/dist/{types.d.ts → types/types.d.ts} +39 -0
  160. package/dist/types/types.d.ts.map +1 -0
  161. package/dist/types/utils/etherscan.d.ts.map +1 -0
  162. package/dist/types/utils/external-transactions.d.ts.map +1 -0
  163. package/dist/types/utils/gas-fees.d.ts.map +1 -0
  164. package/dist/types/utils/gas-flow.d.ts.map +1 -0
  165. package/dist/types/utils/gas.d.ts.map +1 -0
  166. package/dist/types/utils/history.d.ts.map +1 -0
  167. package/dist/types/utils/nonce.d.ts.map +1 -0
  168. package/dist/types/utils/simulation-api.d.ts +99 -0
  169. package/dist/types/utils/simulation-api.d.ts.map +1 -0
  170. package/dist/types/utils/simulation.d.ts +21 -0
  171. package/dist/types/utils/simulation.d.ts.map +1 -0
  172. package/dist/types/utils/swaps.d.ts.map +1 -0
  173. package/dist/types/utils/transaction-type.d.ts.map +1 -0
  174. package/dist/types/utils/utils.d.ts.map +1 -0
  175. package/dist/types/utils/validation.d.ts.map +1 -0
  176. package/dist/types.js +19 -170
  177. package/dist/types.js.map +1 -1
  178. package/dist/types.mjs +20 -0
  179. package/dist/types.mjs.map +1 -0
  180. package/dist/utils/etherscan.js +13 -118
  181. package/dist/utils/etherscan.js.map +1 -1
  182. package/dist/utils/etherscan.mjs +14 -0
  183. package/dist/utils/etherscan.mjs.map +1 -0
  184. package/dist/utils/external-transactions.js +8 -35
  185. package/dist/utils/external-transactions.js.map +1 -1
  186. package/dist/utils/external-transactions.mjs +9 -0
  187. package/dist/utils/external-transactions.mjs.map +1 -0
  188. package/dist/utils/gas-fees.js +15 -200
  189. package/dist/utils/gas-fees.js.map +1 -1
  190. package/dist/utils/gas-fees.mjs +16 -0
  191. package/dist/utils/gas-fees.mjs.map +1 -0
  192. package/dist/utils/gas-flow.js +10 -52
  193. package/dist/utils/gas-flow.js.map +1 -1
  194. package/dist/utils/gas-flow.mjs +11 -0
  195. package/dist/utils/gas-flow.mjs.map +1 -0
  196. package/dist/utils/gas.js +19 -133
  197. package/dist/utils/gas.js.map +1 -1
  198. package/dist/utils/gas.mjs +20 -0
  199. package/dist/utils/gas.mjs.map +1 -0
  200. package/dist/utils/history.js +9 -90
  201. package/dist/utils/history.js.map +1 -1
  202. package/dist/utils/history.mjs +10 -0
  203. package/dist/utils/history.mjs.map +1 -0
  204. package/dist/utils/nonce.js +10 -76
  205. package/dist/utils/nonce.js.map +1 -1
  206. package/dist/utils/nonce.mjs +11 -0
  207. package/dist/utils/nonce.mjs.map +1 -0
  208. package/dist/utils/simulation-api.js +10 -0
  209. package/dist/utils/simulation-api.js.map +1 -0
  210. package/dist/utils/simulation-api.mjs +10 -0
  211. package/dist/utils/simulation-api.mjs.map +1 -0
  212. package/dist/utils/simulation.js +12 -0
  213. package/dist/utils/simulation.js.map +1 -0
  214. package/dist/utils/simulation.mjs +12 -0
  215. package/dist/utils/simulation.mjs.map +1 -0
  216. package/dist/utils/swaps.js +23 -262
  217. package/dist/utils/swaps.js.map +1 -1
  218. package/dist/utils/swaps.mjs +24 -0
  219. package/dist/utils/swaps.mjs.map +1 -0
  220. package/dist/utils/transaction-type.js +10 -120
  221. package/dist/utils/transaction-type.js.map +1 -1
  222. package/dist/utils/transaction-type.mjs +11 -0
  223. package/dist/utils/transaction-type.mjs.map +1 -0
  224. package/dist/utils/utils.js +32 -175
  225. package/dist/utils/utils.js.map +1 -1
  226. package/dist/utils/utils.mjs +33 -0
  227. package/dist/utils/utils.mjs.map +1 -0
  228. package/dist/utils/validation.js +11 -258
  229. package/dist/utils/validation.js.map +1 -1
  230. package/dist/utils/validation.mjs +12 -0
  231. package/dist/utils/validation.mjs.map +1 -0
  232. package/package.json +12 -1
  233. package/dist/TransactionController.d.ts.map +0 -1
  234. package/dist/constants.d.ts.map +0 -1
  235. package/dist/gas-flows/DefaultGasFeeFlow.d.ts.map +0 -1
  236. package/dist/gas-flows/LineaGasFeeFlow.d.ts.map +0 -1
  237. package/dist/helpers/EtherscanRemoteTransactionSource.d.ts.map +0 -1
  238. package/dist/helpers/GasFeePoller.d.ts.map +0 -1
  239. package/dist/helpers/IncomingTransactionHelper.d.ts.map +0 -1
  240. package/dist/helpers/MultichainTrackingHelper.d.ts.map +0 -1
  241. package/dist/helpers/PendingTransactionTracker.d.ts.map +0 -1
  242. package/dist/index.d.ts.map +0 -1
  243. package/dist/logger.d.ts.map +0 -1
  244. package/dist/types.d.ts.map +0 -1
  245. package/dist/utils/etherscan.d.ts.map +0 -1
  246. package/dist/utils/external-transactions.d.ts.map +0 -1
  247. package/dist/utils/gas-fees.d.ts.map +0 -1
  248. package/dist/utils/gas-flow.d.ts.map +0 -1
  249. package/dist/utils/gas.d.ts.map +0 -1
  250. package/dist/utils/history.d.ts.map +0 -1
  251. package/dist/utils/nonce.d.ts.map +0 -1
  252. package/dist/utils/swaps.d.ts.map +0 -1
  253. package/dist/utils/transaction-type.d.ts.map +0 -1
  254. package/dist/utils/utils.d.ts.map +0 -1
  255. package/dist/utils/validation.d.ts.map +0 -1
  256. /package/dist/{gas-flows → types/gas-flows}/DefaultGasFeeFlow.d.ts +0 -0
  257. /package/dist/{gas-flows → types/gas-flows}/LineaGasFeeFlow.d.ts +0 -0
  258. /package/dist/{helpers → types/helpers}/EtherscanRemoteTransactionSource.d.ts +0 -0
  259. /package/dist/{helpers → types/helpers}/GasFeePoller.d.ts +0 -0
  260. /package/dist/{helpers → types/helpers}/IncomingTransactionHelper.d.ts +0 -0
  261. /package/dist/{helpers → types/helpers}/MultichainTrackingHelper.d.ts +0 -0
  262. /package/dist/{helpers → types/helpers}/PendingTransactionTracker.d.ts +0 -0
  263. /package/dist/{index.d.ts → types/index.d.ts} +0 -0
  264. /package/dist/{logger.d.ts → types/logger.d.ts} +0 -0
  265. /package/dist/{utils → types/utils}/etherscan.d.ts +0 -0
  266. /package/dist/{utils → types/utils}/external-transactions.d.ts +0 -0
  267. /package/dist/{utils → types/utils}/gas-fees.d.ts +0 -0
  268. /package/dist/{utils → types/utils}/gas-flow.d.ts +0 -0
  269. /package/dist/{utils → types/utils}/gas.d.ts +0 -0
  270. /package/dist/{utils → types/utils}/history.d.ts +0 -0
  271. /package/dist/{utils → types/utils}/nonce.d.ts +0 -0
  272. /package/dist/{utils → types/utils}/swaps.d.ts +0 -0
  273. /package/dist/{utils → types/utils}/transaction-type.d.ts +0 -0
  274. /package/dist/{utils → types/utils}/utils.d.ts +0 -0
  275. /package/dist/{utils → types/utils}/validation.d.ts +0 -0
@@ -1,1909 +1,39 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
12
- if (kind === "m") throw new TypeError("Private method is not writable");
13
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
14
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
15
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
16
- };
17
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
18
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
19
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
20
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
21
- };
22
- var __importDefault = (this && this.__importDefault) || function (mod) {
23
- return (mod && mod.__esModule) ? mod : { "default": mod };
24
- };
25
- var _TransactionController_instances, _TransactionController_internalEvents, _TransactionController_incomingTransactionOptions, _TransactionController_pendingTransactionOptions, _TransactionController_transactionHistoryLimit, _TransactionController_multichainTrackingHelper, _TransactionController_createNonceTracker, _TransactionController_createIncomingTransactionHelper, _TransactionController_createPendingTransactionTracker, _TransactionController_checkForPendingTransactionAndStartPolling, _TransactionController_stopAllTracking, _TransactionController_removeIncomingTransactionHelperListeners, _TransactionController_addIncomingTransactionHelperListeners, _TransactionController_removePendingTransactionTrackerListeners, _TransactionController_addPendingTransactionTrackerListeners, _TransactionController_getNonceTrackerPendingTransactions, _TransactionController_getGasFeeFlows, _TransactionController_updateTransactionInternal;
26
- Object.defineProperty(exports, "__esModule", { value: true });
27
- exports.TransactionController = exports.ApprovalState = exports.SPEED_UP_RATE = exports.CANCEL_RATE = exports.HARDFORK = void 0;
28
- const common_1 = require("@ethereumjs/common");
29
- const tx_1 = require("@ethereumjs/tx");
30
- const util_1 = require("@ethereumjs/util");
31
- const base_controller_1 = require("@metamask/base-controller");
32
- const controller_utils_1 = require("@metamask/controller-utils");
33
- const eth_query_1 = __importDefault(require("@metamask/eth-query"));
34
- const network_controller_1 = require("@metamask/network-controller");
35
- const rpc_errors_1 = require("@metamask/rpc-errors");
36
- const utils_1 = require("@metamask/utils");
37
- const async_mutex_1 = require("async-mutex");
38
- const eth_method_registry_1 = require("eth-method-registry");
39
- const events_1 = require("events");
40
- const lodash_1 = require("lodash");
41
- const nonce_tracker_1 = require("nonce-tracker");
42
- const uuid_1 = require("uuid");
43
- const DefaultGasFeeFlow_1 = require("./gas-flows/DefaultGasFeeFlow");
44
- const LineaGasFeeFlow_1 = require("./gas-flows/LineaGasFeeFlow");
45
- const EtherscanRemoteTransactionSource_1 = require("./helpers/EtherscanRemoteTransactionSource");
46
- const GasFeePoller_1 = require("./helpers/GasFeePoller");
47
- const IncomingTransactionHelper_1 = require("./helpers/IncomingTransactionHelper");
48
- const MultichainTrackingHelper_1 = require("./helpers/MultichainTrackingHelper");
49
- const PendingTransactionTracker_1 = require("./helpers/PendingTransactionTracker");
50
- const logger_1 = require("./logger");
51
- const types_1 = require("./types");
52
- const external_transactions_1 = require("./utils/external-transactions");
53
- const gas_1 = require("./utils/gas");
54
- const gas_fees_1 = require("./utils/gas-fees");
55
- const history_1 = require("./utils/history");
56
- const nonce_1 = require("./utils/nonce");
57
- const swaps_1 = require("./utils/swaps");
58
- const transaction_type_1 = require("./utils/transaction-type");
59
- const utils_2 = require("./utils/utils");
60
- const validation_1 = require("./utils/validation");
61
- /**
62
- * Metadata for the TransactionController state, describing how to "anonymize"
63
- * the state and which parts should be persisted.
64
- */
65
- const metadata = {
66
- transactions: {
67
- persist: true,
68
- anonymous: false,
69
- },
70
- methodData: {
71
- persist: true,
72
- anonymous: false,
73
- },
74
- lastFetchedBlockNumbers: {
75
- persist: true,
76
- anonymous: false,
77
- },
78
- };
79
- exports.HARDFORK = common_1.Hardfork.London;
80
- /**
81
- * Multiplier used to determine a transaction's increased gas fee during cancellation
82
- */
83
- exports.CANCEL_RATE = 1.1;
84
- /**
85
- * Multiplier used to determine a transaction's increased gas fee during speed up
86
- */
87
- exports.SPEED_UP_RATE = 1.1;
88
- /**
89
- * The name of the {@link TransactionController}.
90
- */
91
- const controllerName = 'TransactionController';
92
- /**
93
- * Possible states of the approve transaction step.
94
- */
95
- var ApprovalState;
96
- (function (ApprovalState) {
97
- ApprovalState["Approved"] = "approved";
98
- ApprovalState["NotApproved"] = "not-approved";
99
- ApprovalState["SkippedViaBeforePublishHook"] = "skipped-via-before-publish-hook";
100
- })(ApprovalState = exports.ApprovalState || (exports.ApprovalState = {}));
101
- /**
102
- * Get the default TransactionsController state.
103
- *
104
- * @returns The default TransactionsController state.
105
- */
106
- function getDefaultTransactionControllerState() {
107
- return {
108
- methodData: {},
109
- transactions: [],
110
- lastFetchedBlockNumbers: {},
111
- };
112
- }
113
- /**
114
- * Controller responsible for submitting and managing transactions.
115
- */
116
- class TransactionController extends base_controller_1.BaseController {
117
- /**
118
- * Constructs a TransactionController.
119
- *
120
- * @param options - The controller options.
121
- * @param options.blockTracker - The block tracker used to poll for new blocks data.
122
- * @param options.disableHistory - Whether to disable storing history in transaction metadata.
123
- * @param options.disableSendFlowHistory - Explicitly disable transaction metadata history.
124
- * @param options.disableSwaps - Whether to disable additional processing on swaps transactions.
125
- * @param options.getCurrentAccountEIP1559Compatibility - Whether or not the account supports EIP-1559.
126
- * @param options.getCurrentNetworkEIP1559Compatibility - Whether or not the network supports EIP-1559.
127
- * @param options.getExternalPendingTransactions - Callback to retrieve pending transactions from external sources.
128
- * @param options.getGasFeeEstimates - Callback to retrieve gas fee estimates.
129
- * @param options.getNetworkClientRegistry - Gets the network client registry.
130
- * @param options.getNetworkState - Gets the state of the network controller.
131
- * @param options.getPermittedAccounts - Get accounts that a given origin has permissions for.
132
- * @param options.getSavedGasFees - Gets the saved gas fee config.
133
- * @param options.getSelectedAddress - Gets the address of the currently selected account.
134
- * @param options.incomingTransactions - Configuration options for incoming transaction support.
135
- * @param options.isMultichainEnabled - Enable multichain support.
136
- * @param options.messenger - The controller messenger.
137
- * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
138
- * @param options.pendingTransactions - Configuration options for pending transaction support.
139
- * @param options.provider - The provider used to create the underlying EthQuery instance.
140
- * @param options.securityProviderRequest - A function for verifying a transaction, whether it is malicious or not.
141
- * @param options.sign - Function used to sign transactions.
142
- * @param options.state - Initial state to set on this controller.
143
- * @param options.transactionHistoryLimit - Transaction history limit.
144
- * @param options.hooks - The controller hooks.
145
- */
146
- constructor({ blockTracker, disableHistory, disableSendFlowHistory, disableSwaps, getCurrentAccountEIP1559Compatibility, getCurrentNetworkEIP1559Compatibility, getExternalPendingTransactions, getGasFeeEstimates, getNetworkClientRegistry, getNetworkState, getPermittedAccounts, getSavedGasFees, getSelectedAddress, incomingTransactions = {}, isMultichainEnabled = false, messenger, onNetworkStateChange, pendingTransactions = {}, provider, securityProviderRequest, sign, state, transactionHistoryLimit = 40, hooks, }) {
147
- var _a, _b, _c, _d, _e, _f;
148
- super({
149
- name: controllerName,
150
- metadata,
151
- messenger,
152
- state: Object.assign(Object.assign({}, getDefaultTransactionControllerState()), state),
153
- });
154
- _TransactionController_instances.add(this);
155
- _TransactionController_internalEvents.set(this, new events_1.EventEmitter());
156
- this.inProcessOfSigning = new Set();
157
- this.mutex = new async_mutex_1.Mutex();
158
- _TransactionController_incomingTransactionOptions.set(this, void 0);
159
- _TransactionController_pendingTransactionOptions.set(this, void 0);
160
- this.signAbortCallbacks = new Map();
161
- _TransactionController_transactionHistoryLimit.set(this, void 0);
162
- _TransactionController_multichainTrackingHelper.set(this, void 0);
163
- _TransactionController_checkForPendingTransactionAndStartPolling.set(this, () => {
164
- // PendingTransactionTracker reads state through its getTransactions hook
165
- this.pendingTransactionTracker.startIfPendingTransactions();
166
- __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").checkForPendingTransactionAndStartPolling();
167
- });
168
- this.messagingSystem = messenger;
169
- this.getNetworkState = getNetworkState;
170
- this.isSendFlowHistoryDisabled = disableSendFlowHistory !== null && disableSendFlowHistory !== void 0 ? disableSendFlowHistory : false;
171
- this.isHistoryDisabled = disableHistory !== null && disableHistory !== void 0 ? disableHistory : false;
172
- this.isSwapsDisabled = disableSwaps !== null && disableSwaps !== void 0 ? disableSwaps : false;
173
- // @ts-expect-error the type in eth-method-registry is inappropriate and should be changed
174
- this.registry = new eth_method_registry_1.MethodRegistry({ provider });
175
- this.getSavedGasFees = getSavedGasFees !== null && getSavedGasFees !== void 0 ? getSavedGasFees : ((_chainId) => undefined);
176
- this.getCurrentAccountEIP1559Compatibility =
177
- getCurrentAccountEIP1559Compatibility !== null && getCurrentAccountEIP1559Compatibility !== void 0 ? getCurrentAccountEIP1559Compatibility : (() => Promise.resolve(true));
178
- this.getCurrentNetworkEIP1559Compatibility =
179
- getCurrentNetworkEIP1559Compatibility;
180
- this.getGasFeeEstimates =
181
- getGasFeeEstimates || (() => Promise.resolve({}));
182
- this.getPermittedAccounts = getPermittedAccounts;
183
- this.getSelectedAddress = getSelectedAddress;
184
- this.getExternalPendingTransactions =
185
- getExternalPendingTransactions !== null && getExternalPendingTransactions !== void 0 ? getExternalPendingTransactions : (() => []);
186
- this.securityProviderRequest = securityProviderRequest;
187
- __classPrivateFieldSet(this, _TransactionController_incomingTransactionOptions, incomingTransactions, "f");
188
- __classPrivateFieldSet(this, _TransactionController_pendingTransactionOptions, pendingTransactions, "f");
189
- __classPrivateFieldSet(this, _TransactionController_transactionHistoryLimit, transactionHistoryLimit, "f");
190
- this.sign = sign;
191
- this.afterSign = (_a = hooks === null || hooks === void 0 ? void 0 : hooks.afterSign) !== null && _a !== void 0 ? _a : (() => true);
192
- this.beforeApproveOnInit = (_b = hooks === null || hooks === void 0 ? void 0 : hooks.beforeApproveOnInit) !== null && _b !== void 0 ? _b : (() => true);
193
- this.beforeCheckPendingTransaction =
194
- (_c = hooks === null || hooks === void 0 ? void 0 : hooks.beforeCheckPendingTransaction) !== null && _c !== void 0 ? _c :
195
- /* istanbul ignore next */
196
- (() => true);
197
- this.beforePublish = (_d = hooks === null || hooks === void 0 ? void 0 : hooks.beforePublish) !== null && _d !== void 0 ? _d : (() => true);
198
- this.getAdditionalSignArguments =
199
- (_e = hooks === null || hooks === void 0 ? void 0 : hooks.getAdditionalSignArguments) !== null && _e !== void 0 ? _e : (() => []);
200
- this.publish =
201
- (_f = hooks === null || hooks === void 0 ? void 0 : hooks.publish) !== null && _f !== void 0 ? _f : (() => Promise.resolve({ transactionHash: undefined }));
202
- this.nonceTracker = __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_createNonceTracker).call(this, {
203
- provider,
204
- blockTracker,
205
- });
206
- __classPrivateFieldSet(this, _TransactionController_multichainTrackingHelper, new MultichainTrackingHelper_1.MultichainTrackingHelper({
207
- isMultichainEnabled,
208
- provider,
209
- nonceTracker: this.nonceTracker,
210
- incomingTransactionOptions: incomingTransactions,
211
- findNetworkClientIdByChainId: (chainId) => {
212
- return this.messagingSystem.call(`NetworkController:findNetworkClientIdByChainId`, chainId);
213
- },
214
- getNetworkClientById: ((networkClientId) => {
215
- return this.messagingSystem.call(`NetworkController:getNetworkClientById`, networkClientId);
216
- }),
217
- getNetworkClientRegistry,
218
- removeIncomingTransactionHelperListeners: __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_removeIncomingTransactionHelperListeners).bind(this),
219
- removePendingTransactionTrackerListeners: __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_removePendingTransactionTrackerListeners).bind(this),
220
- createNonceTracker: __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_createNonceTracker).bind(this),
221
- createIncomingTransactionHelper: __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_createIncomingTransactionHelper).bind(this),
222
- createPendingTransactionTracker: __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_createPendingTransactionTracker).bind(this),
223
- onNetworkStateChange: (listener) => {
224
- this.messagingSystem.subscribe('NetworkController:stateChange', listener);
225
- },
226
- }), "f");
227
- __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").initialize();
228
- const etherscanRemoteTransactionSource = new EtherscanRemoteTransactionSource_1.EtherscanRemoteTransactionSource({
229
- includeTokenTransfers: incomingTransactions.includeTokenTransfers,
230
- });
231
- this.incomingTransactionHelper = __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_createIncomingTransactionHelper).call(this, {
232
- blockTracker,
233
- etherscanRemoteTransactionSource,
234
- });
235
- this.pendingTransactionTracker = __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_createPendingTransactionTracker).call(this, {
236
- provider,
237
- blockTracker,
238
- });
239
- this.gasFeeFlows = __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_getGasFeeFlows).call(this);
240
- const gasFeePoller = new GasFeePoller_1.GasFeePoller({
241
- // Default gas fee polling is not yet supported by the clients
242
- gasFeeFlows: this.gasFeeFlows.slice(0, -1),
243
- getEthQuery: (chainId, networkClientId) => __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
244
- networkClientId,
245
- chainId,
246
- }),
247
- getGasFeeControllerEstimates: this.getGasFeeEstimates,
248
- getTransactions: () => this.state.transactions,
249
- onStateChange: (listener) => {
250
- this.messagingSystem.subscribe('TransactionController:stateChange', listener);
251
- },
252
- });
253
- gasFeePoller.hub.on('transaction-updated', (transactionMeta) => __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_updateTransactionInternal).call(this, transactionMeta, { skipHistory: true }));
254
- // when transactionsController state changes
255
- // check for pending transactions and start polling if there are any
256
- this.messagingSystem.subscribe('TransactionController:stateChange', __classPrivateFieldGet(this, _TransactionController_checkForPendingTransactionAndStartPolling, "f"));
257
- // TODO once v2 is merged make sure this only runs when
258
- // selectedNetworkClientId changes
259
- onNetworkStateChange(() => {
260
- (0, logger_1.projectLogger)('Detected network change', this.getChainId());
261
- this.pendingTransactionTracker.startIfPendingTransactions();
262
- this.onBootCleanup();
263
- });
264
- this.onBootCleanup();
265
- }
266
- failTransaction(transactionMeta, error, actionId) {
267
- const newTransactionMeta = (0, lodash_1.merge)({}, transactionMeta, {
268
- error: (0, utils_2.normalizeTxError)(error),
269
- status: types_1.TransactionStatus.failed,
270
- });
271
- this.messagingSystem.publish(`${controllerName}:transactionFailed`, {
272
- actionId,
273
- error: error.message,
274
- transactionMeta: newTransactionMeta,
275
- });
276
- this.updateTransaction(newTransactionMeta, 'TransactionController#failTransaction - Add error message and set status to failed');
277
- this.onTransactionStatusChange(newTransactionMeta);
278
- this.messagingSystem.publish(`${controllerName}:transactionFinished`, newTransactionMeta);
279
- __classPrivateFieldGet(this, _TransactionController_internalEvents, "f").emit(`${transactionMeta.id}:finished`, newTransactionMeta);
280
- }
281
- registryLookup(fourBytePrefix) {
282
- return __awaiter(this, void 0, void 0, function* () {
283
- const registryMethod = yield this.registry.lookup(fourBytePrefix);
284
- if (!registryMethod) {
285
- return {
286
- registryMethod: '',
287
- parsedRegistryMethod: { name: undefined, args: undefined },
288
- };
289
- }
290
- const parsedRegistryMethod = this.registry.parse(registryMethod);
291
- return { registryMethod, parsedRegistryMethod };
292
- });
293
- }
294
- /**
295
- * Stops polling and removes listeners to prepare the controller for garbage collection.
296
- */
297
- destroy() {
298
- __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_stopAllTracking).call(this);
299
- }
300
- /**
301
- * Handle new method data request.
302
- *
303
- * @param fourBytePrefix - The method prefix.
304
- * @returns The method data object corresponding to the given signature prefix.
305
- */
306
- handleMethodData(fourBytePrefix) {
307
- return __awaiter(this, void 0, void 0, function* () {
308
- const releaseLock = yield this.mutex.acquire();
309
- try {
310
- const { methodData } = this.state;
311
- const knownMethod = Object.keys(methodData).find((knownFourBytePrefix) => fourBytePrefix === knownFourBytePrefix);
312
- if (knownMethod) {
313
- return methodData[fourBytePrefix];
314
- }
315
- const registry = yield this.registryLookup(fourBytePrefix);
316
- this.update((state) => {
317
- state.methodData[fourBytePrefix] = registry;
318
- });
319
- return registry;
320
- }
321
- finally {
322
- releaseLock();
323
- }
324
- });
325
- }
326
- /**
327
- * Add a new unapproved transaction to state. Parameters will be validated, a
328
- * unique transaction id will be generated, and gas and gasPrice will be calculated
329
- * if not provided. If A `<tx.id>:unapproved` hub event will be emitted once added.
330
- *
331
- * @param txParams - Standard parameters for an Ethereum transaction.
332
- * @param opts - Additional options to control how the transaction is added.
333
- * @param opts.actionId - Unique ID to prevent duplicate requests.
334
- * @param opts.deviceConfirmedOn - An enum to indicate what device confirmed the transaction.
335
- * @param opts.method - RPC method that requested the transaction.
336
- * @param opts.origin - The origin of the transaction request, such as a dApp hostname.
337
- * @param opts.requireApproval - Whether the transaction requires approval by the user, defaults to true unless explicitly disabled.
338
- * @param opts.securityAlertResponse - Response from security validator.
339
- * @param opts.sendFlowHistory - The sendFlowHistory entries to add.
340
- * @param opts.type - Type of transaction to add, such as 'cancel' or 'swap'.
341
- * @param opts.swaps - Options for swaps transactions.
342
- * @param opts.swaps.hasApproveTx - Whether the transaction has an approval transaction.
343
- * @param opts.swaps.meta - Metadata for swap transaction.
344
- * @param opts.networkClientId - The id of the network client for this transaction.
345
- * @returns Object containing a promise resolving to the transaction hash if approved.
346
- */
347
- addTransaction(txParams, { actionId, deviceConfirmedOn, method, origin, requireApproval, securityAlertResponse, sendFlowHistory, swaps = {}, type, networkClientId, } = {}) {
348
- return __awaiter(this, void 0, void 0, function* () {
349
- (0, logger_1.projectLogger)('Adding transaction', txParams);
350
- txParams = (0, utils_2.normalizeTransactionParams)(txParams);
351
- if (networkClientId &&
352
- !__classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").has(networkClientId)) {
353
- throw new Error('The networkClientId for this transaction could not be found');
354
- }
355
- const isEIP1559Compatible = yield this.getEIP1559Compatibility(networkClientId);
356
- (0, validation_1.validateTxParams)(txParams, isEIP1559Compatible);
357
- if (origin) {
358
- yield (0, validation_1.validateTransactionOrigin)(yield this.getPermittedAccounts(origin), this.getSelectedAddress(), txParams.from, origin);
359
- }
360
- const dappSuggestedGasFees = this.generateDappSuggestedGasFees(txParams, origin);
361
- const chainId = this.getChainId(networkClientId);
362
- const ethQuery = __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
363
- networkClientId,
364
- chainId,
365
- });
366
- const transactionType = type !== null && type !== void 0 ? type : (yield (0, transaction_type_1.determineTransactionType)(txParams, ethQuery)).type;
367
- const existingTransactionMeta = this.getTransactionWithActionId(actionId);
368
- // If a request to add a transaction with the same actionId is submitted again, a new transaction will not be created for it.
369
- let addedTransactionMeta = existingTransactionMeta
370
- ? (0, lodash_1.cloneDeep)(existingTransactionMeta)
371
- : {
372
- // Add actionId to txMeta to check if same actionId is seen again
373
- actionId,
374
- chainId,
375
- dappSuggestedGasFees,
376
- deviceConfirmedOn,
377
- id: (0, uuid_1.v1)(),
378
- origin,
379
- securityAlertResponse,
380
- status: types_1.TransactionStatus.unapproved,
381
- time: Date.now(),
382
- txParams,
383
- userEditedGasLimit: false,
384
- verifiedOnBlockchain: false,
385
- type: transactionType,
386
- networkClientId,
387
- };
388
- yield this.updateGasProperties(addedTransactionMeta);
389
- // Checks if a transaction already exists with a given actionId
390
- if (!existingTransactionMeta) {
391
- // Set security provider response
392
- if (method && this.securityProviderRequest) {
393
- const securityProviderResponse = yield this.securityProviderRequest(addedTransactionMeta, method);
394
- addedTransactionMeta.securityProviderResponse =
395
- securityProviderResponse;
396
- }
397
- if (!this.isSendFlowHistoryDisabled) {
398
- addedTransactionMeta.sendFlowHistory = sendFlowHistory !== null && sendFlowHistory !== void 0 ? sendFlowHistory : [];
399
- }
400
- // Initial history push
401
- if (!this.isHistoryDisabled) {
402
- addedTransactionMeta = (0, history_1.addInitialHistorySnapshot)(addedTransactionMeta);
403
- }
404
- addedTransactionMeta = (0, swaps_1.updateSwapsTransaction)(addedTransactionMeta, transactionType, swaps, {
405
- isSwapsDisabled: this.isSwapsDisabled,
406
- cancelTransaction: this.cancelTransaction.bind(this),
407
- messenger: this.messagingSystem,
408
- });
409
- this.addMetadata(addedTransactionMeta);
410
- this.messagingSystem.publish(`${controllerName}:unapprovedTransactionAdded`, addedTransactionMeta);
411
- }
412
- return {
413
- result: this.processApproval(addedTransactionMeta, {
414
- isExisting: Boolean(existingTransactionMeta),
415
- requireApproval,
416
- actionId,
417
- }),
418
- transactionMeta: addedTransactionMeta,
419
- };
420
- });
421
- }
422
- startIncomingTransactionPolling(networkClientIds = []) {
423
- if (networkClientIds.length === 0) {
424
- this.incomingTransactionHelper.start();
425
- return;
426
- }
427
- __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").startIncomingTransactionPolling(networkClientIds);
428
- }
429
- stopIncomingTransactionPolling(networkClientIds = []) {
430
- if (networkClientIds.length === 0) {
431
- this.incomingTransactionHelper.stop();
432
- return;
433
- }
434
- __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").stopIncomingTransactionPolling(networkClientIds);
435
- }
436
- stopAllIncomingTransactionPolling() {
437
- this.incomingTransactionHelper.stop();
438
- __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").stopAllIncomingTransactionPolling();
439
- }
440
- updateIncomingTransactions(networkClientIds = []) {
441
- return __awaiter(this, void 0, void 0, function* () {
442
- if (networkClientIds.length === 0) {
443
- yield this.incomingTransactionHelper.update();
444
- return;
445
- }
446
- yield __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").updateIncomingTransactions(networkClientIds);
447
- });
448
- }
449
- /**
450
- * Attempts to cancel a transaction based on its ID by setting its status to "rejected"
451
- * and emitting a `<tx.id>:finished` hub event.
452
- *
453
- * @param transactionId - The ID of the transaction to cancel.
454
- * @param gasValues - The gas values to use for the cancellation transaction.
455
- * @param options - The options for the cancellation transaction.
456
- * @param options.actionId - Unique ID to prevent duplicate requests.
457
- * @param options.estimatedBaseFee - The estimated base fee of the transaction.
458
- */
459
- stopTransaction(transactionId, gasValues, { estimatedBaseFee, actionId, } = {}) {
460
- var _a, _b, _c;
461
- return __awaiter(this, void 0, void 0, function* () {
462
- // If transaction is found for same action id, do not create a cancel transaction.
463
- if (this.getTransactionWithActionId(actionId)) {
464
- return;
465
- }
466
- if (gasValues) {
467
- // Not good practice to reassign a parameter but temporarily avoiding a larger refactor.
468
- gasValues = (0, utils_2.normalizeGasFeeValues)(gasValues);
469
- (0, utils_2.validateGasValues)(gasValues);
470
- }
471
- (0, logger_1.projectLogger)('Creating cancel transaction', transactionId, gasValues);
472
- const transactionMeta = this.getTransaction(transactionId);
473
- if (!transactionMeta) {
474
- return;
475
- }
476
- if (!this.sign) {
477
- throw new Error('No sign method defined.');
478
- }
479
- // gasPrice (legacy non EIP1559)
480
- const minGasPrice = (0, utils_2.getIncreasedPriceFromExisting)(transactionMeta.txParams.gasPrice, exports.CANCEL_RATE);
481
- const gasPriceFromValues = (0, utils_2.isGasPriceValue)(gasValues) && gasValues.gasPrice;
482
- const newGasPrice = (gasPriceFromValues &&
483
- (0, utils_2.validateMinimumIncrease)(gasPriceFromValues, minGasPrice)) ||
484
- minGasPrice;
485
- // maxFeePerGas (EIP1559)
486
- const existingMaxFeePerGas = (_a = transactionMeta.txParams) === null || _a === void 0 ? void 0 : _a.maxFeePerGas;
487
- const minMaxFeePerGas = (0, utils_2.getIncreasedPriceFromExisting)(existingMaxFeePerGas, exports.CANCEL_RATE);
488
- const maxFeePerGasValues = (0, utils_2.isFeeMarketEIP1559Values)(gasValues) && gasValues.maxFeePerGas;
489
- const newMaxFeePerGas = (maxFeePerGasValues &&
490
- (0, utils_2.validateMinimumIncrease)(maxFeePerGasValues, minMaxFeePerGas)) ||
491
- (existingMaxFeePerGas && minMaxFeePerGas);
492
- // maxPriorityFeePerGas (EIP1559)
493
- const existingMaxPriorityFeePerGas = (_b = transactionMeta.txParams) === null || _b === void 0 ? void 0 : _b.maxPriorityFeePerGas;
494
- const minMaxPriorityFeePerGas = (0, utils_2.getIncreasedPriceFromExisting)(existingMaxPriorityFeePerGas, exports.CANCEL_RATE);
495
- const maxPriorityFeePerGasValues = (0, utils_2.isFeeMarketEIP1559Values)(gasValues) && gasValues.maxPriorityFeePerGas;
496
- const newMaxPriorityFeePerGas = (maxPriorityFeePerGasValues &&
497
- (0, utils_2.validateMinimumIncrease)(maxPriorityFeePerGasValues, minMaxPriorityFeePerGas)) ||
498
- (existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);
499
- const newTxParams = newMaxFeePerGas && newMaxPriorityFeePerGas
500
- ? {
501
- from: transactionMeta.txParams.from,
502
- gasLimit: transactionMeta.txParams.gas,
503
- maxFeePerGas: newMaxFeePerGas,
504
- maxPriorityFeePerGas: newMaxPriorityFeePerGas,
505
- type: types_1.TransactionEnvelopeType.feeMarket,
506
- nonce: transactionMeta.txParams.nonce,
507
- to: transactionMeta.txParams.from,
508
- value: '0x0',
509
- }
510
- : {
511
- from: transactionMeta.txParams.from,
512
- gasLimit: transactionMeta.txParams.gas,
513
- gasPrice: newGasPrice,
514
- nonce: transactionMeta.txParams.nonce,
515
- to: transactionMeta.txParams.from,
516
- value: '0x0',
517
- };
518
- const unsignedEthTx = this.prepareUnsignedEthTx(transactionMeta.chainId, newTxParams);
519
- const signedTx = yield this.sign(unsignedEthTx, transactionMeta.txParams.from);
520
- const rawTx = (0, util_1.bufferToHex)(signedTx.serialize());
521
- const newFee = (_c = newTxParams.maxFeePerGas) !== null && _c !== void 0 ? _c : newTxParams.gasPrice;
522
- const oldFee = newTxParams.maxFeePerGas
523
- ? transactionMeta.txParams.maxFeePerGas
524
- : transactionMeta.txParams.gasPrice;
525
- (0, logger_1.projectLogger)('Submitting cancel transaction', {
526
- oldFee,
527
- newFee,
528
- txParams: newTxParams,
529
- });
530
- const ethQuery = __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
531
- networkClientId: transactionMeta.networkClientId,
532
- chainId: transactionMeta.chainId,
533
- });
534
- const hash = yield this.publishTransactionForRetry(ethQuery, rawTx, transactionMeta);
535
- const cancelTransactionMeta = {
536
- actionId,
537
- chainId: transactionMeta.chainId,
538
- networkClientId: transactionMeta.networkClientId,
539
- estimatedBaseFee,
540
- hash,
541
- id: (0, uuid_1.v1)(),
542
- originalGasEstimate: transactionMeta.txParams.gas,
543
- status: types_1.TransactionStatus.submitted,
544
- time: Date.now(),
545
- type: types_1.TransactionType.cancel,
546
- txParams: newTxParams,
547
- };
548
- this.addMetadata(cancelTransactionMeta);
549
- // stopTransaction has no approval request, so we assume the user has already approved the transaction
550
- this.messagingSystem.publish(`${controllerName}:transactionApproved`, {
551
- transactionMeta: cancelTransactionMeta,
552
- actionId,
553
- });
554
- this.messagingSystem.publish(`${controllerName}:transactionSubmitted`, {
555
- transactionMeta: cancelTransactionMeta,
556
- actionId,
557
- });
558
- this.messagingSystem.publish(`${controllerName}:transactionFinished`, cancelTransactionMeta);
559
- __classPrivateFieldGet(this, _TransactionController_internalEvents, "f").emit(`${transactionMeta.id}:finished`, cancelTransactionMeta);
560
- });
561
- }
562
- /**
563
- * Attempts to speed up a transaction increasing transaction gasPrice by ten percent.
564
- *
565
- * @param transactionId - The ID of the transaction to speed up.
566
- * @param gasValues - The gas values to use for the speed up transaction.
567
- * @param options - The options for the speed up transaction.
568
- * @param options.actionId - Unique ID to prevent duplicate requests
569
- * @param options.estimatedBaseFee - The estimated base fee of the transaction.
570
- */
571
- speedUpTransaction(transactionId, gasValues, { actionId, estimatedBaseFee, } = {}) {
572
- var _a, _b, _c;
573
- return __awaiter(this, void 0, void 0, function* () {
574
- // If transaction is found for same action id, do not create a new speed up transaction.
575
- if (this.getTransactionWithActionId(actionId)) {
576
- return;
577
- }
578
- if (gasValues) {
579
- // Not good practice to reassign a parameter but temporarily avoiding a larger refactor.
580
- gasValues = (0, utils_2.normalizeGasFeeValues)(gasValues);
581
- (0, utils_2.validateGasValues)(gasValues);
582
- }
583
- (0, logger_1.projectLogger)('Creating speed up transaction', transactionId, gasValues);
584
- const transactionMeta = this.state.transactions.find(({ id }) => id === transactionId);
585
- /* istanbul ignore next */
586
- if (!transactionMeta) {
587
- return;
588
- }
589
- /* istanbul ignore next */
590
- if (!this.sign) {
591
- throw new Error('No sign method defined.');
592
- }
593
- // gasPrice (legacy non EIP1559)
594
- const minGasPrice = (0, utils_2.getIncreasedPriceFromExisting)(transactionMeta.txParams.gasPrice, exports.SPEED_UP_RATE);
595
- const gasPriceFromValues = (0, utils_2.isGasPriceValue)(gasValues) && gasValues.gasPrice;
596
- const newGasPrice = (gasPriceFromValues &&
597
- (0, utils_2.validateMinimumIncrease)(gasPriceFromValues, minGasPrice)) ||
598
- minGasPrice;
599
- // maxFeePerGas (EIP1559)
600
- const existingMaxFeePerGas = (_a = transactionMeta.txParams) === null || _a === void 0 ? void 0 : _a.maxFeePerGas;
601
- const minMaxFeePerGas = (0, utils_2.getIncreasedPriceFromExisting)(existingMaxFeePerGas, exports.SPEED_UP_RATE);
602
- const maxFeePerGasValues = (0, utils_2.isFeeMarketEIP1559Values)(gasValues) && gasValues.maxFeePerGas;
603
- const newMaxFeePerGas = (maxFeePerGasValues &&
604
- (0, utils_2.validateMinimumIncrease)(maxFeePerGasValues, minMaxFeePerGas)) ||
605
- (existingMaxFeePerGas && minMaxFeePerGas);
606
- // maxPriorityFeePerGas (EIP1559)
607
- const existingMaxPriorityFeePerGas = (_b = transactionMeta.txParams) === null || _b === void 0 ? void 0 : _b.maxPriorityFeePerGas;
608
- const minMaxPriorityFeePerGas = (0, utils_2.getIncreasedPriceFromExisting)(existingMaxPriorityFeePerGas, exports.SPEED_UP_RATE);
609
- const maxPriorityFeePerGasValues = (0, utils_2.isFeeMarketEIP1559Values)(gasValues) && gasValues.maxPriorityFeePerGas;
610
- const newMaxPriorityFeePerGas = (maxPriorityFeePerGasValues &&
611
- (0, utils_2.validateMinimumIncrease)(maxPriorityFeePerGasValues, minMaxPriorityFeePerGas)) ||
612
- (existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas);
613
- const txParams = newMaxFeePerGas && newMaxPriorityFeePerGas
614
- ? Object.assign(Object.assign({}, transactionMeta.txParams), { gasLimit: transactionMeta.txParams.gas, maxFeePerGas: newMaxFeePerGas, maxPriorityFeePerGas: newMaxPriorityFeePerGas, type: types_1.TransactionEnvelopeType.feeMarket }) : Object.assign(Object.assign({}, transactionMeta.txParams), { gasLimit: transactionMeta.txParams.gas, gasPrice: newGasPrice });
615
- const unsignedEthTx = this.prepareUnsignedEthTx(transactionMeta.chainId, txParams);
616
- const signedTx = yield this.sign(unsignedEthTx, transactionMeta.txParams.from);
617
- const transactionMetaWithRsv = yield this.updateTransactionMetaRSV(transactionMeta, signedTx);
618
- const rawTx = (0, util_1.bufferToHex)(signedTx.serialize());
619
- const newFee = (_c = txParams.maxFeePerGas) !== null && _c !== void 0 ? _c : txParams.gasPrice;
620
- const oldFee = txParams.maxFeePerGas
621
- ? transactionMetaWithRsv.txParams.maxFeePerGas
622
- : transactionMetaWithRsv.txParams.gasPrice;
623
- (0, logger_1.projectLogger)('Submitting speed up transaction', { oldFee, newFee, txParams });
624
- const ethQuery = __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
625
- networkClientId: transactionMeta.networkClientId,
626
- chainId: transactionMeta.chainId,
627
- });
628
- const hash = yield this.publishTransactionForRetry(ethQuery, rawTx, transactionMeta);
629
- const baseTransactionMeta = Object.assign(Object.assign({}, transactionMetaWithRsv), { estimatedBaseFee, id: (0, uuid_1.v1)(), time: Date.now(), hash,
630
- actionId, originalGasEstimate: transactionMeta.txParams.gas, type: types_1.TransactionType.retry, originalType: transactionMeta.type });
631
- const newTransactionMeta = newMaxFeePerGas && newMaxPriorityFeePerGas
632
- ? Object.assign(Object.assign({}, baseTransactionMeta), { txParams: Object.assign(Object.assign({}, transactionMeta.txParams), { maxFeePerGas: newMaxFeePerGas, maxPriorityFeePerGas: newMaxPriorityFeePerGas }) }) : Object.assign(Object.assign({}, baseTransactionMeta), { txParams: Object.assign(Object.assign({}, transactionMeta.txParams), { gasPrice: newGasPrice }) });
633
- this.addMetadata(newTransactionMeta);
634
- // speedUpTransaction has no approval request, so we assume the user has already approved the transaction
635
- this.messagingSystem.publish(`${controllerName}:transactionApproved`, {
636
- transactionMeta: newTransactionMeta,
637
- actionId,
638
- });
639
- this.messagingSystem.publish(`${controllerName}:transactionSubmitted`, {
640
- transactionMeta: newTransactionMeta,
641
- actionId,
642
- });
643
- this.messagingSystem.publish(`${controllerName}:speedupTransactionAdded`, newTransactionMeta);
644
- });
645
- }
646
- /**
647
- * Estimates required gas for a given transaction.
648
- *
649
- * @param transaction - The transaction to estimate gas for.
650
- * @param networkClientId - The network client id to use for the estimate.
651
- * @returns The gas and gas price.
652
- */
653
- estimateGas(transaction, networkClientId) {
654
- return __awaiter(this, void 0, void 0, function* () {
655
- const ethQuery = __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
656
- networkClientId,
657
- });
658
- const { estimatedGas, simulationFails } = yield (0, gas_1.estimateGas)(transaction, ethQuery);
659
- return { gas: estimatedGas, simulationFails };
660
- });
661
- }
662
- /**
663
- * Estimates required gas for a given transaction and add additional gas buffer with the given multiplier.
664
- *
665
- * @param transaction - The transaction params to estimate gas for.
666
- * @param multiplier - The multiplier to use for the gas buffer.
667
- * @param networkClientId - The network client id to use for the estimate.
668
- */
669
- estimateGasBuffered(transaction, multiplier, networkClientId) {
670
- return __awaiter(this, void 0, void 0, function* () {
671
- const ethQuery = __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
672
- networkClientId,
673
- });
674
- const { blockGasLimit, estimatedGas, simulationFails } = yield (0, gas_1.estimateGas)(transaction, ethQuery);
675
- const gas = (0, gas_1.addGasBuffer)(estimatedGas, blockGasLimit, multiplier);
676
- return {
677
- gas,
678
- simulationFails,
679
- };
680
- });
681
- }
682
- /**
683
- * Updates an existing transaction in state.
684
- *
685
- * @param transactionMeta - The new transaction to store in state.
686
- * @param note - A note or update reason to include in the transaction history.
687
- */
688
- updateTransaction(transactionMeta, note) {
689
- __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_updateTransactionInternal).call(this, transactionMeta, {
690
- note,
691
- skipHistory: this.isHistoryDisabled,
692
- });
693
- }
694
- /**
695
- * Update the security alert response for a transaction.
696
- *
697
- * @param transactionId - ID of the transaction.
698
- * @param securityAlertResponse - The new security alert response for the transaction.
699
- */
700
- updateSecurityAlertResponse(transactionId, securityAlertResponse) {
701
- if (!securityAlertResponse) {
702
- throw new Error('updateSecurityAlertResponse: securityAlertResponse should not be null');
703
- }
704
- const transactionMeta = this.getTransaction(transactionId);
705
- if (!transactionMeta) {
706
- throw new Error(`Cannot update security alert response as no transaction metadata found`);
707
- }
708
- const updatedTransactionMeta = Object.assign(Object.assign({}, transactionMeta), { securityAlertResponse });
709
- this.updateTransaction(updatedTransactionMeta, `${controllerName}:updatesecurityAlertResponse - securityAlertResponse updated`);
710
- }
711
- /**
712
- * Removes all transactions from state, optionally based on the current network.
713
- *
714
- * @param ignoreNetwork - Determines whether to wipe all transactions, or just those on the
715
- * current network. If `true`, all transactions are wiped.
716
- * @param address - If specified, only transactions originating from this address will be
717
- * wiped on current network.
718
- */
719
- wipeTransactions(ignoreNetwork, address) {
720
- /* istanbul ignore next */
721
- if (ignoreNetwork && !address) {
722
- this.update((state) => {
723
- state.transactions = [];
724
- });
725
- return;
726
- }
727
- const currentChainId = this.getChainId();
728
- const newTransactions = this.state.transactions.filter(({ chainId, txParams }) => {
729
- var _a;
730
- const isMatchingNetwork = ignoreNetwork || chainId === currentChainId;
731
- if (!isMatchingNetwork) {
732
- return true;
733
- }
734
- const isMatchingAddress = !address || ((_a = txParams.from) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === address.toLowerCase();
735
- return !isMatchingAddress;
736
- });
737
- this.update((state) => {
738
- state.transactions = this.trimTransactionsForState(newTransactions);
739
- });
740
- }
741
- /**
742
- * Adds external provided transaction to state as confirmed transaction.
743
- *
744
- * @param transactionMeta - TransactionMeta to add transactions.
745
- * @param transactionReceipt - TransactionReceipt of the external transaction.
746
- * @param baseFeePerGas - Base fee per gas of the external transaction.
747
- */
748
- confirmExternalTransaction(transactionMeta, transactionReceipt, baseFeePerGas) {
749
- return __awaiter(this, void 0, void 0, function* () {
750
- // Run validation and add external transaction to state.
751
- const newTransactionMeta = this.addExternalTransaction(transactionMeta);
752
- try {
753
- const transactionId = newTransactionMeta.id;
754
- // Make sure status is confirmed and define gasUsed as in receipt.
755
- const updatedTransactionMeta = Object.assign(Object.assign({}, newTransactionMeta), { status: types_1.TransactionStatus.confirmed, txReceipt: transactionReceipt });
756
- if (baseFeePerGas) {
757
- updatedTransactionMeta.baseFeePerGas = baseFeePerGas;
758
- }
759
- // Update same nonce local transactions as dropped and define replacedBy properties.
760
- this.markNonceDuplicatesDropped(transactionId);
761
- // Update external provided transaction with updated gas values and confirmed status.
762
- this.updateTransaction(updatedTransactionMeta, `${controllerName}:confirmExternalTransaction - Add external transaction`);
763
- this.onTransactionStatusChange(updatedTransactionMeta);
764
- // Intentional given potential duration of process.
765
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
766
- this.updatePostBalance(updatedTransactionMeta);
767
- this.messagingSystem.publish(`${controllerName}:transactionConfirmed`, updatedTransactionMeta);
768
- }
769
- catch (error) {
770
- console.error('Failed to confirm external transaction', error);
771
- }
772
- });
773
- }
774
- /**
775
- * Append new send flow history to a transaction.
776
- *
777
- * @param transactionID - The ID of the transaction to update.
778
- * @param currentSendFlowHistoryLength - The length of the current sendFlowHistory array.
779
- * @param sendFlowHistoryToAdd - The sendFlowHistory entries to add.
780
- * @returns The updated transactionMeta.
781
- */
782
- updateTransactionSendFlowHistory(transactionID, currentSendFlowHistoryLength, sendFlowHistoryToAdd) {
783
- var _a;
784
- if (this.isSendFlowHistoryDisabled) {
785
- throw new Error('Send flow history is disabled for the current transaction controller');
786
- }
787
- const transactionMeta = this.getTransaction(transactionID);
788
- if (!transactionMeta) {
789
- throw new Error(`Cannot update send flow history as no transaction metadata found`);
790
- }
791
- (0, utils_2.validateIfTransactionUnapproved)(transactionMeta, 'updateTransactionSendFlowHistory');
792
- const sendFlowHistory = (_a = transactionMeta.sendFlowHistory) !== null && _a !== void 0 ? _a : [];
793
- if (currentSendFlowHistoryLength === sendFlowHistory.length) {
794
- const updatedTransactionMeta = Object.assign(Object.assign({}, transactionMeta), { sendFlowHistory: [...sendFlowHistory, ...sendFlowHistoryToAdd] });
795
- this.updateTransaction(updatedTransactionMeta, `${controllerName}:updateTransactionSendFlowHistory - sendFlowHistory updated`);
796
- }
797
- return this.getTransaction(transactionID);
798
- }
799
- /**
800
- * Update the gas values of a transaction.
801
- *
802
- * @param transactionId - The ID of the transaction to update.
803
- * @param gasValues - Gas values to update.
804
- * @param gasValues.gas - Same as transaction.gasLimit.
805
- * @param gasValues.gasLimit - Maxmimum number of units of gas to use for this transaction.
806
- * @param gasValues.gasPrice - Price per gas for legacy transactions.
807
- * @param gasValues.maxPriorityFeePerGas - Maximum amount per gas to give to validator as incentive.
808
- * @param gasValues.maxFeePerGas - Maximum amount per gas to pay for the transaction, including the priority fee.
809
- * @param gasValues.estimateUsed - Which estimate level was used.
810
- * @param gasValues.estimateSuggested - Which estimate level that the API suggested.
811
- * @param gasValues.defaultGasEstimates - The default estimate for gas.
812
- * @param gasValues.originalGasEstimate - Original estimate for gas.
813
- * @param gasValues.userEditedGasLimit - The gas limit supplied by user.
814
- * @param gasValues.userFeeLevel - Estimate level user selected.
815
- * @returns The updated transactionMeta.
816
- */
817
- updateTransactionGasFees(transactionId, { defaultGasEstimates, estimateUsed, estimateSuggested, gas, gasLimit, gasPrice, maxPriorityFeePerGas, maxFeePerGas, originalGasEstimate, userEditedGasLimit, userFeeLevel, }) {
818
- const transactionMeta = this.getTransaction(transactionId);
819
- if (!transactionMeta) {
820
- throw new Error(`Cannot update transaction as no transaction metadata found`);
821
- }
822
- (0, utils_2.validateIfTransactionUnapproved)(transactionMeta, 'updateTransactionGasFees');
823
- let transactionGasFees = {
824
- txParams: {
825
- gas,
826
- gasLimit,
827
- gasPrice,
828
- maxPriorityFeePerGas,
829
- maxFeePerGas,
830
- },
831
- defaultGasEstimates,
832
- estimateUsed,
833
- estimateSuggested,
834
- originalGasEstimate,
835
- userEditedGasLimit,
836
- userFeeLevel,
837
- // TODO: Replace `any` with type
838
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
839
- };
840
- // only update what is defined
841
- transactionGasFees.txParams = (0, lodash_1.pickBy)(transactionGasFees.txParams);
842
- transactionGasFees = (0, lodash_1.pickBy)(transactionGasFees);
843
- // merge updated gas values with existing transaction meta
844
- const updatedMeta = (0, lodash_1.merge)({}, transactionMeta, transactionGasFees);
845
- this.updateTransaction(updatedMeta, `${controllerName}:updateTransactionGasFees - gas values updated`);
846
- return this.getTransaction(transactionId);
847
- }
848
- /**
849
- * Update the previous gas values of a transaction.
850
- *
851
- * @param transactionId - The ID of the transaction to update.
852
- * @param previousGas - Previous gas values to update.
853
- * @param previousGas.gasLimit - Maxmimum number of units of gas to use for this transaction.
854
- * @param previousGas.maxFeePerGas - Maximum amount per gas to pay for the transaction, including the priority fee.
855
- * @param previousGas.maxPriorityFeePerGas - Maximum amount per gas to give to validator as incentive.
856
- * @returns The updated transactionMeta.
857
- */
858
- updatePreviousGasParams(transactionId, { gasLimit, maxFeePerGas, maxPriorityFeePerGas, }) {
859
- const transactionMeta = this.getTransaction(transactionId);
860
- if (!transactionMeta) {
861
- throw new Error(`Cannot update transaction as no transaction metadata found`);
862
- }
863
- (0, utils_2.validateIfTransactionUnapproved)(transactionMeta, 'updatePreviousGasParams');
864
- const transactionPreviousGas = {
865
- previousGas: {
866
- gasLimit,
867
- maxFeePerGas,
868
- maxPriorityFeePerGas,
869
- },
870
- // TODO: Replace `any` with type
871
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
872
- };
873
- // only update what is defined
874
- transactionPreviousGas.previousGas = (0, lodash_1.pickBy)(transactionPreviousGas.previousGas);
875
- // merge updated previous gas values with existing transaction meta
876
- const updatedMeta = (0, lodash_1.merge)({}, transactionMeta, transactionPreviousGas);
877
- this.updateTransaction(updatedMeta, `${controllerName}:updatePreviousGasParams - Previous gas values updated`);
878
- return this.getTransaction(transactionId);
879
- }
880
- getNonceLock(address, networkClientId) {
881
- return __awaiter(this, void 0, void 0, function* () {
882
- return __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getNonceLock(address, networkClientId);
883
- });
884
- }
885
- /**
886
- * Updates the editable parameters of a transaction.
887
- *
888
- * @param txId - The ID of the transaction to update.
889
- * @param params - The editable parameters to update.
890
- * @param params.data - Data to pass with the transaction.
891
- * @param params.gas - Maximum number of units of gas to use for the transaction.
892
- * @param params.gasPrice - Price per gas for legacy transactions.
893
- * @param params.from - Address to send the transaction from.
894
- * @param params.to - Address to send the transaction to.
895
- * @param params.value - Value associated with the transaction.
896
- * @returns The updated transaction metadata.
897
- */
898
- updateEditableParams(txId, { data, gas, gasPrice, from, to, value, }) {
899
- return __awaiter(this, void 0, void 0, function* () {
900
- const transactionMeta = this.getTransaction(txId);
901
- if (!transactionMeta) {
902
- throw new Error(`Cannot update editable params as no transaction metadata found`);
903
- }
904
- (0, utils_2.validateIfTransactionUnapproved)(transactionMeta, 'updateEditableParams');
905
- const editableParams = {
906
- txParams: {
907
- data,
908
- from,
909
- to,
910
- value,
911
- gas,
912
- gasPrice,
913
- },
914
- };
915
- editableParams.txParams = (0, lodash_1.pickBy)(editableParams.txParams);
916
- const updatedTransaction = (0, lodash_1.merge)({}, transactionMeta, editableParams);
917
- const { type } = yield (0, transaction_type_1.determineTransactionType)(updatedTransaction.txParams, __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
918
- networkClientId: transactionMeta.networkClientId,
919
- chainId: transactionMeta.chainId,
920
- }));
921
- updatedTransaction.type = type;
922
- this.updateTransaction(updatedTransaction, `Update Editable Params for ${txId}`);
923
- return this.getTransaction(txId);
924
- });
925
- }
926
- /**
927
- * Signs and returns the raw transaction data for provided transaction params list.
928
- *
929
- * @param listOfTxParams - The list of transaction params to approve.
930
- * @param opts - Options bag.
931
- * @param opts.hasNonce - Whether the transactions already have a nonce.
932
- * @returns The raw transactions.
933
- */
934
- approveTransactionsWithSameNonce(listOfTxParams = [], { hasNonce } = {}) {
935
- return __awaiter(this, void 0, void 0, function* () {
936
- (0, logger_1.projectLogger)('Approving transactions with same nonce', {
937
- transactions: listOfTxParams,
938
- });
939
- if (listOfTxParams.length === 0) {
940
- return '';
941
- }
942
- const initialTx = listOfTxParams[0];
943
- const common = this.getCommonConfiguration(initialTx.chainId);
944
- // We need to ensure we get the nonce using the the NonceTracker on the chain matching
945
- // the txParams. In this context we only have chainId available to us, but the
946
- // NonceTrackers are keyed by networkClientId. To workaround this, we attempt to find
947
- // a networkClientId that matches the chainId. As a fallback, the globally selected
948
- // network's NonceTracker will be used instead.
949
- let networkClientId;
950
- try {
951
- networkClientId = this.messagingSystem.call(`NetworkController:findNetworkClientIdByChainId`, initialTx.chainId);
952
- }
953
- catch (err) {
954
- (0, logger_1.projectLogger)('failed to find networkClientId from chainId', err);
955
- }
956
- const initialTxAsEthTx = tx_1.TransactionFactory.fromTxData(initialTx, {
957
- common,
958
- });
959
- const initialTxAsSerializedHex = (0, util_1.bufferToHex)(initialTxAsEthTx.serialize());
960
- if (this.inProcessOfSigning.has(initialTxAsSerializedHex)) {
961
- return '';
962
- }
963
- this.inProcessOfSigning.add(initialTxAsSerializedHex);
964
- let rawTransactions, nonceLock;
965
- try {
966
- // TODO: we should add a check to verify that all transactions have the same from address
967
- const fromAddress = initialTx.from;
968
- const requiresNonce = hasNonce !== true;
969
- nonceLock = requiresNonce
970
- ? yield this.getNonceLock(fromAddress, networkClientId)
971
- : undefined;
972
- const nonce = nonceLock
973
- ? (0, utils_1.add0x)(nonceLock.nextNonce.toString(16))
974
- : initialTx.nonce;
975
- if (nonceLock) {
976
- (0, logger_1.projectLogger)('Using nonce from nonce tracker', nonce, nonceLock.nonceDetails);
977
- }
978
- rawTransactions = yield Promise.all(listOfTxParams.map((txParams) => {
979
- txParams.nonce = nonce;
980
- return this.signExternalTransaction(txParams.chainId, txParams);
981
- }));
982
- }
983
- catch (err) {
984
- (0, logger_1.projectLogger)('Error while signing transactions with same nonce', err);
985
- // Must set transaction to submitted/failed before releasing lock
986
- // continue with error chain
987
- throw err;
988
- }
989
- finally {
990
- nonceLock === null || nonceLock === void 0 ? void 0 : nonceLock.releaseLock();
991
- this.inProcessOfSigning.delete(initialTxAsSerializedHex);
992
- }
993
- return rawTransactions;
994
- });
995
- }
996
- /**
997
- * Update a custodial transaction.
998
- *
999
- * @param transactionId - The ID of the transaction to update.
1000
- * @param options - The custodial transaction options to update.
1001
- * @param options.errorMessage - The error message to be assigned in case transaction status update to failed.
1002
- * @param options.hash - The new hash value to be assigned.
1003
- * @param options.status - The new status value to be assigned.
1004
- */
1005
- updateCustodialTransaction(transactionId, { errorMessage, hash, status, }) {
1006
- const transactionMeta = this.getTransaction(transactionId);
1007
- if (!transactionMeta) {
1008
- throw new Error(`Cannot update custodial transaction as no transaction metadata found`);
1009
- }
1010
- if (!transactionMeta.custodyId) {
1011
- throw new Error('Transaction must be a custodian transaction');
1012
- }
1013
- if (status &&
1014
- ![
1015
- types_1.TransactionStatus.submitted,
1016
- types_1.TransactionStatus.signed,
1017
- types_1.TransactionStatus.failed,
1018
- ].includes(status)) {
1019
- throw new Error(`Cannot update custodial transaction with status: ${status}`);
1020
- }
1021
- const updatedTransactionMeta = (0, lodash_1.merge)({}, transactionMeta, (0, lodash_1.pickBy)({ hash, status }));
1022
- if (status === types_1.TransactionStatus.submitted) {
1023
- updatedTransactionMeta.submittedTime = new Date().getTime();
1024
- }
1025
- if (status === types_1.TransactionStatus.failed) {
1026
- updatedTransactionMeta.error = (0, utils_2.normalizeTxError)(new Error(errorMessage));
1027
- }
1028
- this.updateTransaction(updatedTransactionMeta, `${controllerName}:updateCustodialTransaction - Custodial transaction updated`);
1029
- if ([types_1.TransactionStatus.submitted, types_1.TransactionStatus.failed].includes(status)) {
1030
- this.messagingSystem.publish(`${controllerName}:transactionFinished`, updatedTransactionMeta);
1031
- }
1032
- }
1033
- /**
1034
- * Creates approvals for all unapproved transactions persisted.
1035
- */
1036
- initApprovals() {
1037
- const chainId = this.getChainId();
1038
- const unapprovedTxs = this.state.transactions.filter((transaction) => transaction.status === types_1.TransactionStatus.unapproved &&
1039
- transaction.chainId === chainId &&
1040
- !transaction.isUserOperation);
1041
- for (const txMeta of unapprovedTxs) {
1042
- this.processApproval(txMeta, {
1043
- shouldShowRequest: false,
1044
- }).catch((error) => {
1045
- if ((error === null || error === void 0 ? void 0 : error.code) === rpc_errors_1.errorCodes.provider.userRejectedRequest) {
1046
- return;
1047
- }
1048
- console.error('Error during persisted transaction approval', error);
1049
- });
1050
- }
1051
- }
1052
- /**
1053
- * Search transaction metadata for matching entries.
1054
- *
1055
- * @param opts - Options bag.
1056
- * @param opts.searchCriteria - An object containing values or functions for transaction properties to filter transactions with.
1057
- * @param opts.initialList - The transactions to search. Defaults to the current state.
1058
- * @param opts.filterToCurrentNetwork - Whether to filter the results to the current network. Defaults to true.
1059
- * @param opts.limit - The maximum number of transactions to return. No limit by default.
1060
- * @returns An array of transactions matching the provided options.
1061
- */
1062
- getTransactions({ searchCriteria = {}, initialList, filterToCurrentNetwork = true, limit, } = {}) {
1063
- const chainId = this.getChainId();
1064
- // searchCriteria is an object that might have values that aren't predicate
1065
- // methods. When providing any other value type (string, number, etc), we
1066
- // consider this shorthand for "check the value at key for strict equality
1067
- // with the provided value". To conform this object to be only methods, we
1068
- // mapValues (lodash) such that every value on the object is a method that
1069
- // returns a boolean.
1070
- const predicateMethods = (0, lodash_1.mapValues)(searchCriteria, (predicate) => {
1071
- return typeof predicate === 'function'
1072
- ? predicate
1073
- : // TODO: Replace `any` with type
1074
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1075
- (v) => v === predicate;
1076
- });
1077
- const transactionsToFilter = initialList !== null && initialList !== void 0 ? initialList : this.state.transactions;
1078
- // Combine sortBy and pickBy to transform our state object into an array of
1079
- // matching transactions that are sorted by time.
1080
- const filteredTransactions = (0, lodash_1.sortBy)((0, lodash_1.pickBy)(transactionsToFilter, (transaction) => {
1081
- if (filterToCurrentNetwork && transaction.chainId !== chainId) {
1082
- return false;
1083
- }
1084
- // iterate over the predicateMethods keys to check if the transaction
1085
- // matches the searchCriteria
1086
- for (const [key, predicate] of Object.entries(predicateMethods)) {
1087
- // We return false early as soon as we know that one of the specified
1088
- // search criteria do not match the transaction. This prevents
1089
- // needlessly checking all criteria when we already know the criteria
1090
- // are not fully satisfied. We check both txParams and the base
1091
- // object as predicate keys can be either.
1092
- if (key in transaction.txParams) {
1093
- // TODO: Replace `any` with type
1094
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1095
- if (predicate(transaction.txParams[key]) === false) {
1096
- return false;
1097
- }
1098
- // TODO: Replace `any` with type
1099
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1100
- }
1101
- else if (predicate(transaction[key]) === false) {
1102
- return false;
1103
- }
1104
- }
1105
- return true;
1106
- }), 'time');
1107
- if (limit !== undefined) {
1108
- // We need to have all transactions of a given nonce in order to display
1109
- // necessary details in the UI. We use the size of this set to determine
1110
- // whether we have reached the limit provided, thus ensuring that all
1111
- // transactions of nonces we include will be sent to the UI.
1112
- const nonces = new Set();
1113
- const txs = [];
1114
- // By default, the transaction list we filter from is sorted by time ASC.
1115
- // To ensure that filtered results prefers the newest transactions we
1116
- // iterate from right to left, inserting transactions into front of a new
1117
- // array. The original order is preserved, but we ensure that newest txs
1118
- // are preferred.
1119
- for (let i = filteredTransactions.length - 1; i > -1; i--) {
1120
- const txMeta = filteredTransactions[i];
1121
- const { nonce } = txMeta.txParams;
1122
- if (!nonces.has(nonce)) {
1123
- if (nonces.size < limit) {
1124
- nonces.add(nonce);
1125
- }
1126
- else {
1127
- continue;
1128
- }
1129
- }
1130
- // Push transaction into the beginning of our array to ensure the
1131
- // original order is preserved.
1132
- txs.unshift(txMeta);
1133
- }
1134
- return txs;
1135
- }
1136
- return filteredTransactions;
1137
- }
1138
- signExternalTransaction(chainId, transactionParams) {
1139
- return __awaiter(this, void 0, void 0, function* () {
1140
- if (!this.sign) {
1141
- throw new Error('No sign method defined.');
1142
- }
1143
- const normalizedTransactionParams = (0, utils_2.normalizeTransactionParams)(transactionParams);
1144
- const type = (0, utils_2.isEIP1559Transaction)(normalizedTransactionParams)
1145
- ? types_1.TransactionEnvelopeType.feeMarket
1146
- : types_1.TransactionEnvelopeType.legacy;
1147
- const updatedTransactionParams = Object.assign(Object.assign({}, normalizedTransactionParams), { type, gasLimit: normalizedTransactionParams.gas, chainId });
1148
- const { from } = updatedTransactionParams;
1149
- const common = this.getCommonConfiguration(chainId);
1150
- const unsignedTransaction = tx_1.TransactionFactory.fromTxData(updatedTransactionParams, { common });
1151
- const signedTransaction = yield this.sign(unsignedTransaction, from);
1152
- const rawTransaction = (0, util_1.bufferToHex)(signedTransaction.serialize());
1153
- return rawTransaction;
1154
- });
1155
- }
1156
- /**
1157
- * Removes unapproved transactions from state.
1158
- */
1159
- clearUnapprovedTransactions() {
1160
- const transactions = this.state.transactions.filter(({ status }) => status !== types_1.TransactionStatus.unapproved);
1161
- this.update((state) => {
1162
- state.transactions = this.trimTransactionsForState(transactions);
1163
- });
1164
- }
1165
- /**
1166
- * Stop the signing process for a specific transaction.
1167
- * Throws an error causing the transaction status to be set to failed.
1168
- * @param transactionId - The ID of the transaction to stop signing.
1169
- */
1170
- abortTransactionSigning(transactionId) {
1171
- const transactionMeta = this.getTransaction(transactionId);
1172
- if (!transactionMeta) {
1173
- throw new Error(`Cannot abort signing as no transaction metadata found`);
1174
- }
1175
- const abortCallback = this.signAbortCallbacks.get(transactionId);
1176
- if (!abortCallback) {
1177
- throw new Error(`Cannot abort signing as transaction is not waiting for signing`);
1178
- }
1179
- abortCallback();
1180
- this.signAbortCallbacks.delete(transactionId);
1181
- }
1182
- addMetadata(transactionMeta) {
1183
- this.update((state) => {
1184
- state.transactions = this.trimTransactionsForState([
1185
- ...state.transactions,
1186
- transactionMeta,
1187
- ]);
1188
- });
1189
- }
1190
- updateGasProperties(transactionMeta) {
1191
- return __awaiter(this, void 0, void 0, function* () {
1192
- const isEIP1559Compatible = (yield this.getEIP1559Compatibility(transactionMeta.networkClientId)) &&
1193
- transactionMeta.txParams.type !== types_1.TransactionEnvelopeType.legacy;
1194
- const { networkClientId, chainId } = transactionMeta;
1195
- const isCustomNetwork = networkClientId
1196
- ? this.messagingSystem.call(`NetworkController:getNetworkClientById`, networkClientId).configuration.type === network_controller_1.NetworkClientType.Custom
1197
- : this.getNetworkState().providerConfig.type === controller_utils_1.NetworkType.rpc;
1198
- yield (0, gas_1.updateGas)({
1199
- ethQuery: __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
1200
- networkClientId,
1201
- chainId,
1202
- }),
1203
- chainId,
1204
- isCustomNetwork,
1205
- txMeta: transactionMeta,
1206
- });
1207
- yield (0, gas_fees_1.updateGasFees)({
1208
- eip1559: isEIP1559Compatible,
1209
- ethQuery: __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
1210
- networkClientId,
1211
- chainId,
1212
- }),
1213
- gasFeeFlows: this.gasFeeFlows,
1214
- getGasFeeEstimates: this.getGasFeeEstimates,
1215
- getSavedGasFees: this.getSavedGasFees.bind(this),
1216
- txMeta: transactionMeta,
1217
- });
1218
- });
1219
- }
1220
- onBootCleanup() {
1221
- this.submitApprovedTransactions();
1222
- }
1223
- /**
1224
- * Force submit approved transactions for all chains.
1225
- */
1226
- submitApprovedTransactions() {
1227
- const approvedTransactions = this.state.transactions.filter((transaction) => transaction.status === types_1.TransactionStatus.approved);
1228
- for (const transactionMeta of approvedTransactions) {
1229
- if (this.beforeApproveOnInit(transactionMeta)) {
1230
- this.approveTransaction(transactionMeta.id).catch((error) => {
1231
- /* istanbul ignore next */
1232
- console.error('Error while submitting persisted transaction', error);
1233
- });
1234
- }
1235
- }
1236
- }
1237
- processApproval(transactionMeta, { isExisting = false, requireApproval, shouldShowRequest = true, actionId, }) {
1238
- return __awaiter(this, void 0, void 0, function* () {
1239
- const transactionId = transactionMeta.id;
1240
- let resultCallbacks;
1241
- const { meta, isCompleted } = this.isTransactionCompleted(transactionId);
1242
- const finishedPromise = isCompleted
1243
- ? Promise.resolve(meta)
1244
- : this.waitForTransactionFinished(transactionId);
1245
- if (meta && !isExisting && !isCompleted) {
1246
- try {
1247
- if (requireApproval !== false) {
1248
- const acceptResult = yield this.requestApproval(transactionMeta, {
1249
- shouldShowRequest,
1250
- });
1251
- resultCallbacks = acceptResult.resultCallbacks;
1252
- const approvalValue = acceptResult.value;
1253
- const updatedTransaction = approvalValue === null || approvalValue === void 0 ? void 0 : approvalValue.txMeta;
1254
- if (updatedTransaction) {
1255
- (0, logger_1.projectLogger)('Updating transaction with approval data', {
1256
- customNonce: updatedTransaction.customNonceValue,
1257
- params: updatedTransaction.txParams,
1258
- });
1259
- this.updateTransaction(updatedTransaction, 'TransactionController#processApproval - Updated with approval data');
1260
- }
1261
- }
1262
- const { isCompleted: isTxCompleted } = this.isTransactionCompleted(transactionId);
1263
- if (!isTxCompleted) {
1264
- const approvalResult = yield this.approveTransaction(transactionId);
1265
- if (approvalResult === ApprovalState.SkippedViaBeforePublishHook &&
1266
- resultCallbacks) {
1267
- resultCallbacks.success();
1268
- }
1269
- const updatedTransactionMeta = this.getTransaction(transactionId);
1270
- this.messagingSystem.publish(`${controllerName}:transactionApproved`, {
1271
- transactionMeta: updatedTransactionMeta,
1272
- actionId,
1273
- });
1274
- }
1275
- // TODO: Replace `any` with type
1276
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1277
- }
1278
- catch (error) {
1279
- const { isCompleted: isTxCompleted } = this.isTransactionCompleted(transactionId);
1280
- if (!isTxCompleted) {
1281
- if ((error === null || error === void 0 ? void 0 : error.code) === rpc_errors_1.errorCodes.provider.userRejectedRequest) {
1282
- this.cancelTransaction(transactionId, actionId);
1283
- throw rpc_errors_1.providerErrors.userRejectedRequest('MetaMask Tx Signature: User denied transaction signature.');
1284
- }
1285
- else {
1286
- this.failTransaction(meta, error, actionId);
1287
- }
1288
- }
1289
- }
1290
- }
1291
- const finalMeta = yield finishedPromise;
1292
- switch (finalMeta === null || finalMeta === void 0 ? void 0 : finalMeta.status) {
1293
- case types_1.TransactionStatus.failed:
1294
- resultCallbacks === null || resultCallbacks === void 0 ? void 0 : resultCallbacks.error(finalMeta.error);
1295
- throw rpc_errors_1.rpcErrors.internal(finalMeta.error.message);
1296
- case types_1.TransactionStatus.submitted:
1297
- resultCallbacks === null || resultCallbacks === void 0 ? void 0 : resultCallbacks.success();
1298
- return finalMeta.hash;
1299
- default:
1300
- const internalError = rpc_errors_1.rpcErrors.internal(`MetaMask Tx Signature: Unknown problem: ${JSON.stringify(finalMeta || transactionId)}`);
1301
- resultCallbacks === null || resultCallbacks === void 0 ? void 0 : resultCallbacks.error(internalError);
1302
- throw internalError;
1303
- }
1304
- });
1305
- }
1306
- /**
1307
- * Approves a transaction and updates it's status in state. If this is not a
1308
- * retry transaction, a nonce will be generated. The transaction is signed
1309
- * using the sign configuration property, then published to the blockchain.
1310
- * A `<tx.id>:finished` hub event is fired after success or failure.
1311
- *
1312
- * @param transactionId - The ID of the transaction to approve.
1313
- */
1314
- approveTransaction(transactionId) {
1315
- return __awaiter(this, void 0, void 0, function* () {
1316
- const { transactions } = this.state;
1317
- const releaseLock = yield this.mutex.acquire();
1318
- const index = transactions.findIndex(({ id }) => transactionId === id);
1319
- const transactionMeta = transactions[index];
1320
- const updatedTransactionMeta = (0, lodash_1.cloneDeep)(transactionMeta);
1321
- const { txParams: { from }, networkClientId, } = transactionMeta;
1322
- let releaseNonceLock;
1323
- try {
1324
- if (!this.sign) {
1325
- releaseLock();
1326
- this.failTransaction(transactionMeta, new Error('No sign method defined.'));
1327
- return ApprovalState.NotApproved;
1328
- }
1329
- else if (!transactionMeta.chainId) {
1330
- releaseLock();
1331
- this.failTransaction(transactionMeta, new Error('No chainId defined.'));
1332
- return ApprovalState.NotApproved;
1333
- }
1334
- if (this.inProcessOfSigning.has(transactionId)) {
1335
- (0, logger_1.projectLogger)('Skipping approval as signing in progress', transactionId);
1336
- return ApprovalState.NotApproved;
1337
- }
1338
- const [nonce, releaseNonce] = yield (0, nonce_1.getNextNonce)(transactionMeta, (address) => __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getNonceLock(address, networkClientId));
1339
- releaseNonceLock = releaseNonce;
1340
- updatedTransactionMeta.status = types_1.TransactionStatus.approved;
1341
- updatedTransactionMeta.txParams = Object.assign(Object.assign({}, updatedTransactionMeta.txParams), { nonce, chainId: transactionMeta.chainId });
1342
- const baseTxParams = Object.assign(Object.assign({}, updatedTransactionMeta.txParams), { gasLimit: updatedTransactionMeta.txParams.gas });
1343
- this.updateTransaction(updatedTransactionMeta, 'TransactionController#approveTransaction - Transaction approved');
1344
- this.onTransactionStatusChange(updatedTransactionMeta);
1345
- const isEIP1559 = (0, utils_2.isEIP1559Transaction)(updatedTransactionMeta.txParams);
1346
- const txParams = isEIP1559
1347
- ? Object.assign(Object.assign({}, baseTxParams), { estimatedBaseFee: updatedTransactionMeta.txParams.estimatedBaseFee, type: types_1.TransactionEnvelopeType.feeMarket }) : baseTxParams;
1348
- const rawTx = yield this.signTransaction(updatedTransactionMeta, txParams);
1349
- if (!this.beforePublish(updatedTransactionMeta)) {
1350
- (0, logger_1.projectLogger)('Skipping publishing transaction based on hook');
1351
- this.messagingSystem.publish(`${controllerName}:transactionPublishingSkipped`, updatedTransactionMeta);
1352
- return ApprovalState.SkippedViaBeforePublishHook;
1353
- }
1354
- if (!rawTx) {
1355
- return ApprovalState.NotApproved;
1356
- }
1357
- const ethQuery = __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
1358
- networkClientId: transactionMeta.networkClientId,
1359
- chainId: transactionMeta.chainId,
1360
- });
1361
- if (transactionMeta.type === types_1.TransactionType.swap) {
1362
- (0, logger_1.projectLogger)('Determining pre-transaction balance');
1363
- const preTxBalance = yield (0, controller_utils_1.query)(ethQuery, 'getBalance', [from]);
1364
- updatedTransactionMeta.preTxBalance = preTxBalance;
1365
- (0, logger_1.projectLogger)('Updated pre-transaction balance', updatedTransactionMeta.preTxBalance);
1366
- }
1367
- (0, logger_1.projectLogger)('Publishing transaction', txParams);
1368
- let { transactionHash: hash } = yield this.publish(transactionMeta, rawTx);
1369
- if (hash === undefined) {
1370
- hash = yield this.publishTransaction(ethQuery, rawTx);
1371
- }
1372
- (0, logger_1.projectLogger)('Publish successful', hash);
1373
- updatedTransactionMeta.hash = hash;
1374
- updatedTransactionMeta.status = types_1.TransactionStatus.submitted;
1375
- updatedTransactionMeta.submittedTime = new Date().getTime();
1376
- this.updateTransaction(updatedTransactionMeta, 'TransactionController#approveTransaction - Transaction submitted');
1377
- this.messagingSystem.publish(`${controllerName}:transactionSubmitted`, {
1378
- transactionMeta: updatedTransactionMeta,
1379
- });
1380
- this.messagingSystem.publish(`${controllerName}:transactionFinished`, updatedTransactionMeta);
1381
- __classPrivateFieldGet(this, _TransactionController_internalEvents, "f").emit(`${updatedTransactionMeta.id}:finished`, updatedTransactionMeta);
1382
- this.onTransactionStatusChange(updatedTransactionMeta);
1383
- return ApprovalState.Approved;
1384
- // TODO: Replace `any` with type
1385
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1386
- }
1387
- catch (error) {
1388
- this.failTransaction(transactionMeta, error);
1389
- return ApprovalState.NotApproved;
1390
- }
1391
- finally {
1392
- this.inProcessOfSigning.delete(transactionId);
1393
- // must set transaction to submitted/failed before releasing lock
1394
- releaseNonceLock === null || releaseNonceLock === void 0 ? void 0 : releaseNonceLock();
1395
- releaseLock();
1396
- }
1397
- });
1398
- }
1399
- publishTransaction(ethQuery, rawTransaction) {
1400
- return __awaiter(this, void 0, void 0, function* () {
1401
- return yield (0, controller_utils_1.query)(ethQuery, 'sendRawTransaction', [rawTransaction]);
1402
- });
1403
- }
1404
- /**
1405
- * Cancels a transaction based on its ID by setting its status to "rejected"
1406
- * and emitting a `<tx.id>:finished` hub event.
1407
- *
1408
- * @param transactionId - The ID of the transaction to cancel.
1409
- * @param actionId - The actionId passed from UI
1410
- */
1411
- cancelTransaction(transactionId, actionId) {
1412
- const transactionMeta = this.state.transactions.find(({ id }) => id === transactionId);
1413
- if (!transactionMeta) {
1414
- return;
1415
- }
1416
- this.update((state) => {
1417
- const transactions = state.transactions.filter(({ id }) => id !== transactionId);
1418
- state.transactions = this.trimTransactionsForState(transactions);
1419
- });
1420
- const updatedTransactionMeta = Object.assign(Object.assign({}, transactionMeta), { status: types_1.TransactionStatus.rejected });
1421
- this.messagingSystem.publish(`${controllerName}:transactionFinished`, updatedTransactionMeta);
1422
- __classPrivateFieldGet(this, _TransactionController_internalEvents, "f").emit(`${transactionMeta.id}:finished`, updatedTransactionMeta);
1423
- this.messagingSystem.publish(`${controllerName}:transactionRejected`, {
1424
- transactionMeta: updatedTransactionMeta,
1425
- actionId,
1426
- });
1427
- this.onTransactionStatusChange(updatedTransactionMeta);
1428
- }
1429
- /**
1430
- * Trim the amount of transactions that are set on the state. Checks
1431
- * if the length of the tx history is longer then desired persistence
1432
- * limit and then if it is removes the oldest confirmed or rejected tx.
1433
- * Pending or unapproved transactions will not be removed by this
1434
- * operation. For safety of presenting a fully functional transaction UI
1435
- * representation, this function will not break apart transactions with the
1436
- * same nonce, created on the same day, per network. Not accounting for
1437
- * transactions of the same nonce, same day and network combo can result in
1438
- * confusing or broken experiences in the UI.
1439
- *
1440
- * @param transactions - The transactions to be applied to the state.
1441
- * @returns The trimmed list of transactions.
1442
- */
1443
- trimTransactionsForState(transactions) {
1444
- const nonceNetworkSet = new Set();
1445
- const txsToKeep = [...transactions]
1446
- .sort((a, b) => (a.time > b.time ? -1 : 1)) // Descending time order
1447
- .filter((tx) => {
1448
- const { chainId, status, txParams, time } = tx;
1449
- if (txParams) {
1450
- const key = `${String(txParams.nonce)}-${(0, controller_utils_1.convertHexToDecimal)(chainId)}-${new Date(time).toDateString()}`;
1451
- if (nonceNetworkSet.has(key)) {
1452
- return true;
1453
- }
1454
- else if (nonceNetworkSet.size < __classPrivateFieldGet(this, _TransactionController_transactionHistoryLimit, "f") ||
1455
- !this.isFinalState(status)) {
1456
- nonceNetworkSet.add(key);
1457
- return true;
1458
- }
1459
- }
1460
- return false;
1461
- });
1462
- txsToKeep.reverse(); // Ascending time order
1463
- return txsToKeep;
1464
- }
1465
- /**
1466
- * Determines if the transaction is in a final state.
1467
- *
1468
- * @param status - The transaction status.
1469
- * @returns Whether the transaction is in a final state.
1470
- */
1471
- isFinalState(status) {
1472
- return (status === types_1.TransactionStatus.rejected ||
1473
- status === types_1.TransactionStatus.confirmed ||
1474
- status === types_1.TransactionStatus.failed);
1475
- }
1476
- /**
1477
- * Whether the transaction has at least completed all local processing.
1478
- *
1479
- * @param status - The transaction status.
1480
- * @returns Whether the transaction is in a final state.
1481
- */
1482
- isLocalFinalState(status) {
1483
- return [
1484
- types_1.TransactionStatus.confirmed,
1485
- types_1.TransactionStatus.failed,
1486
- types_1.TransactionStatus.rejected,
1487
- types_1.TransactionStatus.submitted,
1488
- ].includes(status);
1489
- }
1490
- requestApproval(txMeta, { shouldShowRequest }) {
1491
- return __awaiter(this, void 0, void 0, function* () {
1492
- const id = this.getApprovalId(txMeta);
1493
- const { origin } = txMeta;
1494
- const type = controller_utils_1.ApprovalType.Transaction;
1495
- const requestData = { txId: txMeta.id };
1496
- return (yield this.messagingSystem.call('ApprovalController:addRequest', {
1497
- id,
1498
- origin: origin || controller_utils_1.ORIGIN_METAMASK,
1499
- type,
1500
- requestData,
1501
- expectsResult: true,
1502
- }, shouldShowRequest));
1503
- });
1504
- }
1505
- getTransaction(transactionId) {
1506
- const { transactions } = this.state;
1507
- return transactions.find(({ id }) => id === transactionId);
1508
- }
1509
- getApprovalId(txMeta) {
1510
- return String(txMeta.id);
1511
- }
1512
- isTransactionCompleted(transactionId) {
1513
- const transaction = this.getTransaction(transactionId);
1514
- if (!transaction) {
1515
- return { meta: undefined, isCompleted: false };
1516
- }
1517
- const isCompleted = this.isLocalFinalState(transaction.status);
1518
- return { meta: transaction, isCompleted };
1519
- }
1520
- getChainId(networkClientId) {
1521
- if (networkClientId) {
1522
- return this.messagingSystem.call(`NetworkController:getNetworkClientById`, networkClientId).configuration.chainId;
1523
- }
1524
- const { providerConfig } = this.getNetworkState();
1525
- return providerConfig.chainId;
1526
- }
1527
- prepareUnsignedEthTx(chainId, txParams) {
1528
- return tx_1.TransactionFactory.fromTxData(txParams, {
1529
- freeze: false,
1530
- common: this.getCommonConfiguration(chainId),
1531
- });
1532
- }
1533
- /**
1534
- * `@ethereumjs/tx` uses `@ethereumjs/common` as a configuration tool for
1535
- * specifying which chain, network, hardfork and EIPs to support for
1536
- * a transaction. By referencing this configuration, and analyzing the fields
1537
- * specified in txParams, @ethereumjs/tx is able to determine which EIP-2718
1538
- * transaction type to use.
1539
- *
1540
- * @param chainId - The chainId to use for the configuration.
1541
- * @returns common configuration object
1542
- */
1543
- getCommonConfiguration(chainId) {
1544
- const customChainParams = {
1545
- chainId: parseInt(chainId, 16),
1546
- defaultHardfork: exports.HARDFORK,
1547
- };
1548
- return common_1.Common.custom(customChainParams);
1549
- }
1550
- onIncomingTransactions({ added, updated, }) {
1551
- this.update((state) => {
1552
- const { transactions: currentTransactions } = state;
1553
- const updatedTransactions = [
1554
- ...added,
1555
- ...currentTransactions.map((originalTransaction) => {
1556
- const updatedTransaction = updated.find(({ hash }) => hash === originalTransaction.hash);
1557
- return updatedTransaction !== null && updatedTransaction !== void 0 ? updatedTransaction : originalTransaction;
1558
- }),
1559
- ];
1560
- state.transactions = this.trimTransactionsForState(updatedTransactions);
1561
- });
1562
- }
1563
- onUpdatedLastFetchedBlockNumbers({ lastFetchedBlockNumbers, blockNumber, }) {
1564
- this.update((state) => {
1565
- state.lastFetchedBlockNumbers = lastFetchedBlockNumbers;
1566
- });
1567
- this.messagingSystem.publish(`${controllerName}:incomingTransactionBlockReceived`, blockNumber);
1568
- }
1569
- generateDappSuggestedGasFees(txParams, origin) {
1570
- if (!origin || origin === controller_utils_1.ORIGIN_METAMASK) {
1571
- return undefined;
1572
- }
1573
- const { gasPrice, maxFeePerGas, maxPriorityFeePerGas, gas } = txParams;
1574
- if (gasPrice === undefined &&
1575
- maxFeePerGas === undefined &&
1576
- maxPriorityFeePerGas === undefined &&
1577
- gas === undefined) {
1578
- return undefined;
1579
- }
1580
- const dappSuggestedGasFees = {};
1581
- if (gasPrice !== undefined) {
1582
- dappSuggestedGasFees.gasPrice = gasPrice;
1583
- }
1584
- else if (maxFeePerGas !== undefined ||
1585
- maxPriorityFeePerGas !== undefined) {
1586
- dappSuggestedGasFees.maxFeePerGas = maxFeePerGas;
1587
- dappSuggestedGasFees.maxPriorityFeePerGas = maxPriorityFeePerGas;
1588
- }
1589
- if (gas !== undefined) {
1590
- dappSuggestedGasFees.gas = gas;
1591
- }
1592
- return dappSuggestedGasFees;
1593
- }
1594
- /**
1595
- * Validates and adds external provided transaction to state.
1596
- *
1597
- * @param transactionMeta - Nominated external transaction to be added to state.
1598
- * @returns The new transaction.
1599
- */
1600
- addExternalTransaction(transactionMeta) {
1601
- var _a, _b;
1602
- const { chainId } = transactionMeta;
1603
- const { transactions } = this.state;
1604
- const fromAddress = (_a = transactionMeta === null || transactionMeta === void 0 ? void 0 : transactionMeta.txParams) === null || _a === void 0 ? void 0 : _a.from;
1605
- const sameFromAndNetworkTransactions = transactions.filter((transaction) => transaction.txParams.from === fromAddress &&
1606
- transaction.chainId === chainId);
1607
- const confirmedTxs = sameFromAndNetworkTransactions.filter((transaction) => transaction.status === types_1.TransactionStatus.confirmed);
1608
- const pendingTxs = sameFromAndNetworkTransactions.filter((transaction) => transaction.status === types_1.TransactionStatus.submitted);
1609
- (0, external_transactions_1.validateConfirmedExternalTransaction)(transactionMeta, confirmedTxs, pendingTxs);
1610
- // Make sure provided external transaction has non empty history array
1611
- const newTransactionMeta = ((_b = transactionMeta.history) !== null && _b !== void 0 ? _b : []).length === 0 && !this.isHistoryDisabled
1612
- ? (0, history_1.addInitialHistorySnapshot)(transactionMeta)
1613
- : transactionMeta;
1614
- this.update((state) => {
1615
- state.transactions = this.trimTransactionsForState([
1616
- ...state.transactions,
1617
- newTransactionMeta,
1618
- ]);
1619
- });
1620
- return newTransactionMeta;
1621
- }
1622
- /**
1623
- * Sets other txMeta statuses to dropped if the txMeta that has been confirmed has other transactions
1624
- * in the transactions have the same nonce.
1625
- *
1626
- * @param transactionId - Used to identify original transaction.
1627
- */
1628
- markNonceDuplicatesDropped(transactionId) {
1629
- var _a, _b;
1630
- const transactionMeta = this.getTransaction(transactionId);
1631
- if (!transactionMeta) {
1632
- return;
1633
- }
1634
- const nonce = (_a = transactionMeta.txParams) === null || _a === void 0 ? void 0 : _a.nonce;
1635
- const from = (_b = transactionMeta.txParams) === null || _b === void 0 ? void 0 : _b.from;
1636
- const { chainId } = transactionMeta;
1637
- const sameNonceTransactions = this.state.transactions.filter((transaction) => transaction.id !== transactionId &&
1638
- transaction.txParams.from === from &&
1639
- transaction.txParams.nonce === nonce &&
1640
- transaction.chainId === chainId &&
1641
- transaction.type !== types_1.TransactionType.incoming);
1642
- const sameNonceTransactionIds = sameNonceTransactions.map((transaction) => transaction.id);
1643
- if (sameNonceTransactions.length === 0) {
1644
- return;
1645
- }
1646
- this.update((state) => {
1647
- for (const transaction of state.transactions) {
1648
- if (sameNonceTransactionIds.includes(transaction.id)) {
1649
- transaction.replacedBy = transactionMeta === null || transactionMeta === void 0 ? void 0 : transactionMeta.hash;
1650
- transaction.replacedById = transactionMeta === null || transactionMeta === void 0 ? void 0 : transactionMeta.id;
1651
- }
1652
- }
1653
- });
1654
- for (const transaction of this.state.transactions) {
1655
- if (sameNonceTransactionIds.includes(transaction.id) &&
1656
- transaction.status !== types_1.TransactionStatus.failed) {
1657
- this.setTransactionStatusDropped(transaction);
1658
- }
1659
- }
1660
- }
1661
- /**
1662
- * Method to set transaction status to dropped.
1663
- *
1664
- * @param transactionMeta - TransactionMeta of transaction to be marked as dropped.
1665
- */
1666
- setTransactionStatusDropped(transactionMeta) {
1667
- const updatedTransactionMeta = Object.assign(Object.assign({}, transactionMeta), { status: types_1.TransactionStatus.dropped });
1668
- this.messagingSystem.publish(`${controllerName}:transactionDropped`, {
1669
- transactionMeta: updatedTransactionMeta,
1670
- });
1671
- this.updateTransaction(updatedTransactionMeta, 'TransactionController#setTransactionStatusDropped - Transaction dropped');
1672
- this.onTransactionStatusChange(updatedTransactionMeta);
1673
- }
1674
- /**
1675
- * Get transaction with provided actionId.
1676
- *
1677
- * @param actionId - Unique ID to prevent duplicate requests
1678
- * @returns the filtered transaction
1679
- */
1680
- getTransactionWithActionId(actionId) {
1681
- return this.state.transactions.find((transaction) => actionId && transaction.actionId === actionId);
1682
- }
1683
- waitForTransactionFinished(transactionId) {
1684
- return __awaiter(this, void 0, void 0, function* () {
1685
- return new Promise((resolve) => {
1686
- __classPrivateFieldGet(this, _TransactionController_internalEvents, "f").once(`${transactionId}:finished`, (txMeta) => {
1687
- resolve(txMeta);
1688
- });
1689
- });
1690
- });
1691
- }
1692
- /**
1693
- * Updates the r, s, and v properties of a TransactionMeta object
1694
- * with values from a signed transaction.
1695
- *
1696
- * @param transactionMeta - The TransactionMeta object to update.
1697
- * @param signedTx - The encompassing type for all transaction types containing r, s, and v values.
1698
- */
1699
- updateTransactionMetaRSV(transactionMeta, signedTx) {
1700
- return __awaiter(this, void 0, void 0, function* () {
1701
- const transactionMetaWithRsv = (0, lodash_1.cloneDeep)(transactionMeta);
1702
- for (const key of ['r', 's', 'v']) {
1703
- const value = signedTx[key];
1704
- if (value === undefined || value === null) {
1705
- continue;
1706
- }
1707
- transactionMetaWithRsv[key] = (0, utils_1.add0x)(value.toString(16));
1708
- }
1709
- return transactionMetaWithRsv;
1710
- });
1711
- }
1712
- getEIP1559Compatibility(networkClientId) {
1713
- return __awaiter(this, void 0, void 0, function* () {
1714
- const currentNetworkIsEIP1559Compatible = yield this.getCurrentNetworkEIP1559Compatibility(networkClientId);
1715
- const currentAccountIsEIP1559Compatible = yield this.getCurrentAccountEIP1559Compatibility();
1716
- return (currentNetworkIsEIP1559Compatible && currentAccountIsEIP1559Compatible);
1717
- });
1718
- }
1719
- signTransaction(transactionMeta, txParams) {
1720
- return __awaiter(this, void 0, void 0, function* () {
1721
- (0, logger_1.projectLogger)('Signing transaction', txParams);
1722
- const unsignedEthTx = this.prepareUnsignedEthTx(transactionMeta.chainId, txParams);
1723
- this.inProcessOfSigning.add(transactionMeta.id);
1724
- const signedTx = yield new Promise((resolve, reject) => {
1725
- var _a;
1726
- (_a = this.sign) === null || _a === void 0 ? void 0 : _a.call(this, unsignedEthTx, txParams.from, ...this.getAdditionalSignArguments(transactionMeta)).then(resolve, reject);
1727
- this.signAbortCallbacks.set(transactionMeta.id, () => reject(new Error('Signing aborted by user')));
1728
- });
1729
- this.signAbortCallbacks.delete(transactionMeta.id);
1730
- if (!signedTx) {
1731
- (0, logger_1.projectLogger)('Skipping signed status as no signed transaction');
1732
- return undefined;
1733
- }
1734
- if (!this.afterSign(transactionMeta, signedTx)) {
1735
- this.updateTransaction(transactionMeta, 'TransactionController#signTransaction - Update after sign');
1736
- (0, logger_1.projectLogger)('Skipping signed status based on hook');
1737
- return undefined;
1738
- }
1739
- const transactionMetaWithRsv = Object.assign(Object.assign({}, (yield this.updateTransactionMetaRSV(transactionMeta, signedTx))), { status: types_1.TransactionStatus.signed });
1740
- this.updateTransaction(transactionMetaWithRsv, 'TransactionController#approveTransaction - Transaction signed');
1741
- this.onTransactionStatusChange(transactionMetaWithRsv);
1742
- const rawTx = (0, util_1.bufferToHex)(signedTx.serialize());
1743
- const transactionMetaWithRawTx = (0, lodash_1.merge)({}, transactionMetaWithRsv, {
1744
- rawTx,
1745
- });
1746
- this.updateTransaction(transactionMetaWithRawTx, 'TransactionController#approveTransaction - RawTransaction added');
1747
- return rawTx;
1748
- });
1749
- }
1750
- onTransactionStatusChange(transactionMeta) {
1751
- this.messagingSystem.publish(`${controllerName}:transactionStatusUpdated`, {
1752
- transactionMeta,
1753
- });
1754
- }
1755
- getNonceTrackerTransactions(status, address, chainId = this.getChainId()) {
1756
- return (0, nonce_1.getAndFormatTransactionsForNonceTracker)(chainId, address, status, this.state.transactions);
1757
- }
1758
- onConfirmedTransaction(transactionMeta) {
1759
- (0, logger_1.projectLogger)('Processing confirmed transaction', transactionMeta.id);
1760
- this.markNonceDuplicatesDropped(transactionMeta.id);
1761
- this.messagingSystem.publish(`${controllerName}:transactionConfirmed`, transactionMeta);
1762
- this.onTransactionStatusChange(transactionMeta);
1763
- // Intentional given potential duration of process.
1764
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
1765
- this.updatePostBalance(transactionMeta);
1766
- }
1767
- updatePostBalance(transactionMeta) {
1768
- return __awaiter(this, void 0, void 0, function* () {
1769
- try {
1770
- if (transactionMeta.type !== types_1.TransactionType.swap) {
1771
- return;
1772
- }
1773
- const ethQuery = __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").getEthQuery({
1774
- networkClientId: transactionMeta.networkClientId,
1775
- chainId: transactionMeta.chainId,
1776
- });
1777
- const { updatedTransactionMeta, approvalTransactionMeta } = yield (0, swaps_1.updatePostTransactionBalance)(transactionMeta, {
1778
- ethQuery,
1779
- getTransaction: this.getTransaction.bind(this),
1780
- updateTransaction: this.updateTransaction.bind(this),
1781
- });
1782
- this.messagingSystem.publish(`${controllerName}:postTransactionBalanceUpdated`, {
1783
- transactionMeta: updatedTransactionMeta,
1784
- approvalTransactionMeta,
1785
- });
1786
- }
1787
- catch (error) {
1788
- /* istanbul ignore next */
1789
- (0, logger_1.projectLogger)('Error while updating post transaction balance', error);
1790
- }
1791
- });
1792
- }
1793
- publishTransactionForRetry(ethQuery, rawTx, transactionMeta) {
1794
- return __awaiter(this, void 0, void 0, function* () {
1795
- try {
1796
- const hash = yield this.publishTransaction(ethQuery, rawTx);
1797
- return hash;
1798
- }
1799
- catch (error) {
1800
- if (this.isTransactionAlreadyConfirmedError(error)) {
1801
- yield this.pendingTransactionTracker.forceCheckTransaction(transactionMeta);
1802
- throw new Error('Previous transaction is already confirmed');
1803
- }
1804
- throw error;
1805
- }
1806
- });
1807
- }
1808
- /**
1809
- * Ensures that error is a nonce issue
1810
- *
1811
- * @param error - The error to check
1812
- * @returns Whether or not the error is a nonce issue
1813
- */
1814
- // TODO: Replace `any` with type
1815
- // Some networks are returning original error in the data field
1816
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1817
- isTransactionAlreadyConfirmedError(error) {
1818
- var _a, _b, _c;
1819
- return (((_a = error === null || error === void 0 ? void 0 : error.message) === null || _a === void 0 ? void 0 : _a.includes('nonce too low')) ||
1820
- ((_c = (_b = error === null || error === void 0 ? void 0 : error.data) === null || _b === void 0 ? void 0 : _b.message) === null || _c === void 0 ? void 0 : _c.includes('nonce too low')));
1821
- }
1822
- }
1823
- exports.TransactionController = TransactionController;
1824
- _TransactionController_internalEvents = new WeakMap(), _TransactionController_incomingTransactionOptions = new WeakMap(), _TransactionController_pendingTransactionOptions = new WeakMap(), _TransactionController_transactionHistoryLimit = new WeakMap(), _TransactionController_multichainTrackingHelper = new WeakMap(), _TransactionController_checkForPendingTransactionAndStartPolling = new WeakMap(), _TransactionController_instances = new WeakSet(), _TransactionController_createNonceTracker = function _TransactionController_createNonceTracker({ provider, blockTracker, chainId, }) {
1825
- return new nonce_tracker_1.NonceTracker({
1826
- // TODO: Replace `any` with type
1827
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1828
- provider: provider,
1829
- blockTracker,
1830
- getPendingTransactions: __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_getNonceTrackerPendingTransactions).bind(this, chainId),
1831
- getConfirmedTransactions: this.getNonceTrackerTransactions.bind(this, types_1.TransactionStatus.confirmed),
1832
- });
1833
- }, _TransactionController_createIncomingTransactionHelper = function _TransactionController_createIncomingTransactionHelper({ blockTracker, etherscanRemoteTransactionSource, chainId, }) {
1834
- const incomingTransactionHelper = new IncomingTransactionHelper_1.IncomingTransactionHelper({
1835
- blockTracker,
1836
- getCurrentAccount: this.getSelectedAddress,
1837
- getLastFetchedBlockNumbers: () => this.state.lastFetchedBlockNumbers,
1838
- getChainId: chainId ? () => chainId : this.getChainId.bind(this),
1839
- isEnabled: __classPrivateFieldGet(this, _TransactionController_incomingTransactionOptions, "f").isEnabled,
1840
- queryEntireHistory: __classPrivateFieldGet(this, _TransactionController_incomingTransactionOptions, "f").queryEntireHistory,
1841
- remoteTransactionSource: etherscanRemoteTransactionSource,
1842
- transactionLimit: __classPrivateFieldGet(this, _TransactionController_transactionHistoryLimit, "f"),
1843
- updateTransactions: __classPrivateFieldGet(this, _TransactionController_incomingTransactionOptions, "f").updateTransactions,
1844
- });
1845
- __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_addIncomingTransactionHelperListeners).call(this, incomingTransactionHelper);
1846
- return incomingTransactionHelper;
1847
- }, _TransactionController_createPendingTransactionTracker = function _TransactionController_createPendingTransactionTracker({ provider, blockTracker, chainId, }) {
1848
- const ethQuery = new eth_query_1.default(provider);
1849
- const getChainId = chainId ? () => chainId : this.getChainId.bind(this);
1850
- const pendingTransactionTracker = new PendingTransactionTracker_1.PendingTransactionTracker({
1851
- approveTransaction: (transactionId) => __awaiter(this, void 0, void 0, function* () {
1852
- yield this.approveTransaction(transactionId);
1853
- }),
1854
- blockTracker,
1855
- getChainId,
1856
- getEthQuery: () => ethQuery,
1857
- getTransactions: () => this.state.transactions,
1858
- isResubmitEnabled: __classPrivateFieldGet(this, _TransactionController_pendingTransactionOptions, "f").isResubmitEnabled,
1859
- getGlobalLock: () => __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").acquireNonceLockForChainIdKey({
1860
- chainId: getChainId(),
1861
- }),
1862
- publishTransaction: this.publishTransaction.bind(this),
1863
- hooks: {
1864
- beforeCheckPendingTransaction: this.beforeCheckPendingTransaction.bind(this),
1865
- beforePublish: this.beforePublish.bind(this),
1866
- },
1867
- });
1868
- __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_addPendingTransactionTrackerListeners).call(this, pendingTransactionTracker);
1869
- return pendingTransactionTracker;
1870
- }, _TransactionController_stopAllTracking = function _TransactionController_stopAllTracking() {
1871
- this.pendingTransactionTracker.stop();
1872
- __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_removePendingTransactionTrackerListeners).call(this, this.pendingTransactionTracker);
1873
- this.incomingTransactionHelper.stop();
1874
- __classPrivateFieldGet(this, _TransactionController_instances, "m", _TransactionController_removeIncomingTransactionHelperListeners).call(this, this.incomingTransactionHelper);
1875
- __classPrivateFieldGet(this, _TransactionController_multichainTrackingHelper, "f").stopAllTracking();
1876
- }, _TransactionController_removeIncomingTransactionHelperListeners = function _TransactionController_removeIncomingTransactionHelperListeners(incomingTransactionHelper) {
1877
- incomingTransactionHelper.hub.removeAllListeners('transactions');
1878
- incomingTransactionHelper.hub.removeAllListeners('updatedLastFetchedBlockNumbers');
1879
- }, _TransactionController_addIncomingTransactionHelperListeners = function _TransactionController_addIncomingTransactionHelperListeners(incomingTransactionHelper) {
1880
- incomingTransactionHelper.hub.on('transactions', this.onIncomingTransactions.bind(this));
1881
- incomingTransactionHelper.hub.on('updatedLastFetchedBlockNumbers', this.onUpdatedLastFetchedBlockNumbers.bind(this));
1882
- }, _TransactionController_removePendingTransactionTrackerListeners = function _TransactionController_removePendingTransactionTrackerListeners(pendingTransactionTracker) {
1883
- pendingTransactionTracker.hub.removeAllListeners('transaction-confirmed');
1884
- pendingTransactionTracker.hub.removeAllListeners('transaction-dropped');
1885
- pendingTransactionTracker.hub.removeAllListeners('transaction-failed');
1886
- pendingTransactionTracker.hub.removeAllListeners('transaction-updated');
1887
- }, _TransactionController_addPendingTransactionTrackerListeners = function _TransactionController_addPendingTransactionTrackerListeners(pendingTransactionTracker) {
1888
- pendingTransactionTracker.hub.on('transaction-confirmed', this.onConfirmedTransaction.bind(this));
1889
- pendingTransactionTracker.hub.on('transaction-dropped', this.setTransactionStatusDropped.bind(this));
1890
- pendingTransactionTracker.hub.on('transaction-failed', this.failTransaction.bind(this));
1891
- pendingTransactionTracker.hub.on('transaction-updated', this.updateTransaction.bind(this));
1892
- }, _TransactionController_getNonceTrackerPendingTransactions = function _TransactionController_getNonceTrackerPendingTransactions(chainId, address) {
1893
- const standardPendingTransactions = this.getNonceTrackerTransactions(types_1.TransactionStatus.submitted, address, chainId);
1894
- const externalPendingTransactions = this.getExternalPendingTransactions(address, chainId);
1895
- return [...standardPendingTransactions, ...externalPendingTransactions];
1896
- }, _TransactionController_getGasFeeFlows = function _TransactionController_getGasFeeFlows() {
1897
- return [new LineaGasFeeFlow_1.LineaGasFeeFlow(), new DefaultGasFeeFlow_1.DefaultGasFeeFlow()];
1898
- }, _TransactionController_updateTransactionInternal = function _TransactionController_updateTransactionInternal(transactionMeta, { note, skipHistory }) {
1899
- const normalizedTransaction = Object.assign(Object.assign({}, transactionMeta), { txParams: (0, utils_2.normalizeTransactionParams)(transactionMeta.txParams) });
1900
- (0, validation_1.validateTxParams)(normalizedTransaction.txParams);
1901
- const transactionWithUpdatedHistory = skipHistory === true
1902
- ? normalizedTransaction
1903
- : (0, history_1.updateTransactionHistory)(normalizedTransaction, note !== null && note !== void 0 ? note : 'Transaction updated');
1904
- this.update((state) => {
1905
- const index = state.transactions.findIndex(({ id }) => transactionMeta.id === id);
1906
- state.transactions[index] = transactionWithUpdatedHistory;
1907
- });
1908
- };
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
+
3
+
4
+
5
+
6
+
7
+ var _chunkBJEESIBEjs = require('./chunk-BJEESIBE.js');
8
+ require('./chunk-VH47Q6TS.js');
9
+ require('./chunk-IUBAETUH.js');
10
+ require('./chunk-QP75SWIQ.js');
11
+ require('./chunk-ZNZEJDOE.js');
12
+ require('./chunk-DTEDYRTL.js');
13
+ require('./chunk-FDJPXQTF.js');
14
+ require('./chunk-HS277C77.js');
15
+ require('./chunk-7APMBUKB.js');
16
+ require('./chunk-DTDTOMTB.js');
17
+ require('./chunk-M7455RU7.js');
18
+ require('./chunk-5XBULBP2.js');
19
+ require('./chunk-7LXE4KHV.js');
20
+ require('./chunk-I5YZ7QUK.js');
21
+ require('./chunk-ZJLZSFOZ.js');
22
+ require('./chunk-ZCQRDZ36.js');
23
+ require('./chunk-IC233ZQS.js');
24
+ require('./chunk-UGFBA4GV.js');
25
+ require('./chunk-H4M66BA3.js');
26
+ require('./chunk-GKTIFXPN.js');
27
+ require('./chunk-NUOBUW7C.js');
28
+ require('./chunk-RI6MVJJN.js');
29
+ require('./chunk-S6VGOPUY.js');
30
+ require('./chunk-HPNXIKFY.js');
31
+ require('./chunk-Z4BLTVTB.js');
32
+
33
+
34
+
35
+
36
+
37
+
38
+ exports.ApprovalState = _chunkBJEESIBEjs.ApprovalState; exports.CANCEL_RATE = _chunkBJEESIBEjs.CANCEL_RATE; exports.HARDFORK = _chunkBJEESIBEjs.HARDFORK; exports.SPEED_UP_RATE = _chunkBJEESIBEjs.SPEED_UP_RATE; exports.TransactionController = _chunkBJEESIBEjs.TransactionController;
1909
39
  //# sourceMappingURL=TransactionController.js.map