@metamask/transaction-controller 24.0.0 → 25.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. package/CHANGELOG.md +129 -1
  2. package/dist/TransactionController.js +39 -1816
  3. package/dist/TransactionController.js.map +1 -1
  4. package/dist/TransactionController.mjs +40 -0
  5. package/dist/TransactionController.mjs.map +1 -0
  6. package/dist/chunk-2YXA3K67.mjs +62 -0
  7. package/dist/chunk-2YXA3K67.mjs.map +1 -0
  8. package/dist/chunk-3D3SA6PY.mjs +211 -0
  9. package/dist/chunk-3D3SA6PY.mjs.map +1 -0
  10. package/dist/chunk-4S25HUCL.js +46 -0
  11. package/dist/chunk-4S25HUCL.js.map +1 -0
  12. package/dist/chunk-5OQ373JS.js +211 -0
  13. package/dist/chunk-5OQ373JS.js.map +1 -0
  14. package/dist/chunk-5XBULBP2.js +399 -0
  15. package/dist/chunk-5XBULBP2.js.map +1 -0
  16. package/dist/chunk-72OTU5ZW.mjs +2332 -0
  17. package/dist/chunk-72OTU5ZW.mjs.map +1 -0
  18. package/dist/chunk-7LXE4KHV.js +40 -0
  19. package/dist/chunk-7LXE4KHV.js.map +1 -0
  20. package/dist/chunk-7XPI7KU5.mjs +46 -0
  21. package/dist/chunk-7XPI7KU5.mjs.map +1 -0
  22. package/dist/chunk-BILEZLAT.js +182 -0
  23. package/dist/chunk-BILEZLAT.js.map +1 -0
  24. package/dist/chunk-CQBXHAYR.js +121 -0
  25. package/dist/chunk-CQBXHAYR.js.map +1 -0
  26. package/dist/chunk-CXXGL43K.js +85 -0
  27. package/dist/chunk-CXXGL43K.js.map +1 -0
  28. package/dist/chunk-DTDTOMTB.js +238 -0
  29. package/dist/chunk-DTDTOMTB.js.map +1 -0
  30. package/dist/chunk-DTONMSFW.mjs +208 -0
  31. package/dist/chunk-DTONMSFW.mjs.map +1 -0
  32. package/dist/chunk-EEMJC7S7.mjs +182 -0
  33. package/dist/chunk-EEMJC7S7.mjs.map +1 -0
  34. package/dist/chunk-F3CMU2DM.js +170 -0
  35. package/dist/chunk-F3CMU2DM.js.map +1 -0
  36. package/dist/chunk-FRKQ3Z2L.mjs +40 -0
  37. package/dist/chunk-FRKQ3Z2L.mjs.map +1 -0
  38. package/dist/chunk-HS277C77.js +75 -0
  39. package/dist/chunk-HS277C77.js.map +1 -0
  40. package/dist/chunk-ITDY6AIZ.js +127 -0
  41. package/dist/chunk-ITDY6AIZ.js.map +1 -0
  42. package/dist/chunk-IZI7FQIN.mjs +170 -0
  43. package/dist/chunk-IZI7FQIN.mjs.map +1 -0
  44. package/dist/chunk-J56A7UCK.mjs +123 -0
  45. package/dist/chunk-J56A7UCK.mjs.map +1 -0
  46. package/dist/chunk-JRBREX22.mjs +75 -0
  47. package/dist/chunk-JRBREX22.mjs.map +1 -0
  48. package/dist/chunk-JRQHIBG5.mjs +399 -0
  49. package/dist/chunk-JRQHIBG5.mjs.map +1 -0
  50. package/dist/chunk-K26EBMGI.mjs +121 -0
  51. package/dist/chunk-K26EBMGI.mjs.map +1 -0
  52. package/dist/chunk-KFL2GGZC.mjs +48 -0
  53. package/dist/chunk-KFL2GGZC.mjs.map +1 -0
  54. package/dist/chunk-NHRBO3LU.mjs +50 -0
  55. package/dist/chunk-NHRBO3LU.mjs.map +1 -0
  56. package/dist/chunk-NM4LTWRU.mjs +76 -0
  57. package/dist/chunk-NM4LTWRU.mjs.map +1 -0
  58. package/dist/chunk-NM6OYEPP.mjs +182 -0
  59. package/dist/chunk-NM6OYEPP.mjs.map +1 -0
  60. package/dist/chunk-NRWEI43Q.js +320 -0
  61. package/dist/chunk-NRWEI43Q.js.map +1 -0
  62. package/dist/chunk-O7H2MC7R.js +62 -0
  63. package/dist/chunk-O7H2MC7R.js.map +1 -0
  64. package/dist/chunk-OF6NSLXF.mjs +90 -0
  65. package/dist/chunk-OF6NSLXF.mjs.map +1 -0
  66. package/dist/chunk-QDIYZX5V.js +2332 -0
  67. package/dist/chunk-QDIYZX5V.js.map +1 -0
  68. package/dist/chunk-QP75SWIQ.js +53 -0
  69. package/dist/chunk-QP75SWIQ.js.map +1 -0
  70. package/dist/chunk-QPNEFZB3.js +208 -0
  71. package/dist/chunk-QPNEFZB3.js.map +1 -0
  72. package/dist/chunk-QSBIXUMB.mjs +242 -0
  73. package/dist/chunk-QSBIXUMB.mjs.map +1 -0
  74. package/dist/chunk-R7NJVDWN.js +48 -0
  75. package/dist/chunk-R7NJVDWN.js.map +1 -0
  76. package/dist/chunk-RQKICZYP.js +137 -0
  77. package/dist/chunk-RQKICZYP.js.map +1 -0
  78. package/dist/chunk-S6VGOPUY.js +14 -0
  79. package/dist/chunk-S6VGOPUY.js.map +1 -0
  80. package/dist/chunk-TXVH44HM.js +90 -0
  81. package/dist/chunk-TXVH44HM.js.map +1 -0
  82. package/dist/chunk-UGFBA4GV.js +123 -0
  83. package/dist/chunk-UGFBA4GV.js.map +1 -0
  84. package/dist/chunk-UQQWZT6C.mjs +14 -0
  85. package/dist/chunk-UQQWZT6C.mjs.map +1 -0
  86. package/dist/chunk-VEREDMI2.mjs +85 -0
  87. package/dist/chunk-VEREDMI2.mjs.map +1 -0
  88. package/dist/chunk-VH47Q6TS.js +182 -0
  89. package/dist/chunk-VH47Q6TS.js.map +1 -0
  90. package/dist/chunk-W3GAOR7Y.js +76 -0
  91. package/dist/chunk-W3GAOR7Y.js.map +1 -0
  92. package/dist/chunk-WXQZIUNW.js +242 -0
  93. package/dist/chunk-WXQZIUNW.js.map +1 -0
  94. package/dist/chunk-XGRAHX6T.mjs +53 -0
  95. package/dist/chunk-XGRAHX6T.mjs.map +1 -0
  96. package/dist/chunk-XKNFL657.mjs +137 -0
  97. package/dist/chunk-XKNFL657.mjs.map +1 -0
  98. package/dist/chunk-XUI43LEZ.mjs +30 -0
  99. package/dist/chunk-XUI43LEZ.mjs.map +1 -0
  100. package/dist/chunk-Y7ENNK7L.mjs +238 -0
  101. package/dist/chunk-Y7ENNK7L.mjs.map +1 -0
  102. package/dist/chunk-Z3HHSD5I.mjs +127 -0
  103. package/dist/chunk-Z3HHSD5I.mjs.map +1 -0
  104. package/dist/chunk-Z4BLTVTB.js +30 -0
  105. package/dist/chunk-Z4BLTVTB.js.map +1 -0
  106. package/dist/chunk-ZNZEJDOE.js +50 -0
  107. package/dist/chunk-ZNZEJDOE.js.map +1 -0
  108. package/dist/chunk-ZQFMTLZJ.mjs +320 -0
  109. package/dist/chunk-ZQFMTLZJ.mjs.map +1 -0
  110. package/dist/constants.js +15 -110
  111. package/dist/constants.js.map +1 -1
  112. package/dist/constants.mjs +16 -0
  113. package/dist/constants.mjs.map +1 -0
  114. package/dist/gas-flows/DefaultGasFeeFlow.js +14 -77
  115. package/dist/gas-flows/DefaultGasFeeFlow.js.map +1 -1
  116. package/dist/gas-flows/DefaultGasFeeFlow.mjs +15 -0
  117. package/dist/gas-flows/DefaultGasFeeFlow.mjs.map +1 -0
  118. package/dist/gas-flows/LineaGasFeeFlow.js +15 -110
  119. package/dist/gas-flows/LineaGasFeeFlow.js.map +1 -1
  120. package/dist/gas-flows/LineaGasFeeFlow.mjs +16 -0
  121. package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -0
  122. package/dist/helpers/EtherscanRemoteTransactionSource.js +11 -145
  123. package/dist/helpers/EtherscanRemoteTransactionSource.js.map +1 -1
  124. package/dist/helpers/EtherscanRemoteTransactionSource.mjs +12 -0
  125. package/dist/helpers/EtherscanRemoteTransactionSource.mjs.map +1 -0
  126. package/dist/helpers/GasFeePoller.js +11 -143
  127. package/dist/helpers/GasFeePoller.js.map +1 -1
  128. package/dist/helpers/GasFeePoller.mjs +12 -0
  129. package/dist/helpers/GasFeePoller.mjs.map +1 -0
  130. package/dist/helpers/IncomingTransactionHelper.js +8 -205
  131. package/dist/helpers/IncomingTransactionHelper.js.map +1 -1
  132. package/dist/helpers/IncomingTransactionHelper.mjs +9 -0
  133. package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -0
  134. package/dist/helpers/MultichainTrackingHelper.js +12 -291
  135. package/dist/helpers/MultichainTrackingHelper.js.map +1 -1
  136. package/dist/helpers/MultichainTrackingHelper.mjs +13 -0
  137. package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -0
  138. package/dist/helpers/PendingTransactionTracker.js +9 -360
  139. package/dist/helpers/PendingTransactionTracker.js.map +1 -1
  140. package/dist/helpers/PendingTransactionTracker.mjs +10 -0
  141. package/dist/helpers/PendingTransactionTracker.mjs.map +1 -0
  142. package/dist/index.js +57 -26
  143. package/dist/index.js.map +1 -1
  144. package/dist/index.mjs +58 -0
  145. package/dist/index.mjs.map +1 -0
  146. package/dist/logger.js +11 -8
  147. package/dist/logger.js.map +1 -1
  148. package/dist/logger.mjs +12 -0
  149. package/dist/logger.mjs.map +1 -0
  150. package/dist/tsconfig.build.tsbuildinfo +1 -0
  151. package/dist/{TransactionController.d.ts → types/TransactionController.d.ts} +236 -46
  152. package/dist/types/TransactionController.d.ts.map +1 -0
  153. package/dist/{constants.d.ts → types/constants.d.ts} +10 -0
  154. package/dist/types/constants.d.ts.map +1 -0
  155. package/dist/types/gas-flows/DefaultGasFeeFlow.d.ts.map +1 -0
  156. package/dist/types/gas-flows/LineaGasFeeFlow.d.ts.map +1 -0
  157. package/dist/types/helpers/EtherscanRemoteTransactionSource.d.ts.map +1 -0
  158. package/dist/{helpers → types/helpers}/GasFeePoller.d.ts +5 -3
  159. package/dist/types/helpers/GasFeePoller.d.ts.map +1 -0
  160. package/dist/types/helpers/IncomingTransactionHelper.d.ts.map +1 -0
  161. package/dist/types/helpers/MultichainTrackingHelper.d.ts.map +1 -0
  162. package/dist/types/helpers/PendingTransactionTracker.d.ts.map +1 -0
  163. package/dist/types/index.d.ts +9 -0
  164. package/dist/types/index.d.ts.map +1 -0
  165. package/dist/types/logger.d.ts.map +1 -0
  166. package/dist/{types.d.ts → types/types.d.ts} +94 -65
  167. package/dist/types/types.d.ts.map +1 -0
  168. package/dist/types/utils/etherscan.d.ts.map +1 -0
  169. package/dist/types/utils/external-transactions.d.ts.map +1 -0
  170. package/dist/types/utils/gas-fees.d.ts.map +1 -0
  171. package/dist/types/utils/gas-flow.d.ts.map +1 -0
  172. package/dist/types/utils/gas.d.ts.map +1 -0
  173. package/dist/types/utils/history.d.ts +20 -0
  174. package/dist/types/utils/history.d.ts.map +1 -0
  175. package/dist/types/utils/layer1-gas-fee-flow.d.ts +16 -0
  176. package/dist/types/utils/layer1-gas-fee-flow.d.ts.map +1 -0
  177. package/dist/types/utils/nonce.d.ts.map +1 -0
  178. package/dist/types/utils/simulation-api.d.ts +99 -0
  179. package/dist/types/utils/simulation-api.d.ts.map +1 -0
  180. package/dist/types/utils/simulation.d.ts +21 -0
  181. package/dist/types/utils/simulation.d.ts.map +1 -0
  182. package/dist/{utils → types/utils}/swaps.d.ts +8 -5
  183. package/dist/types/utils/swaps.d.ts.map +1 -0
  184. package/dist/types/utils/transaction-type.d.ts.map +1 -0
  185. package/dist/types/utils/utils.d.ts.map +1 -0
  186. package/dist/types/utils/validation.d.ts.map +1 -0
  187. package/dist/types.js +19 -170
  188. package/dist/types.js.map +1 -1
  189. package/dist/types.mjs +20 -0
  190. package/dist/types.mjs.map +1 -0
  191. package/dist/utils/etherscan.js +13 -118
  192. package/dist/utils/etherscan.js.map +1 -1
  193. package/dist/utils/etherscan.mjs +14 -0
  194. package/dist/utils/etherscan.mjs.map +1 -0
  195. package/dist/utils/external-transactions.js +8 -35
  196. package/dist/utils/external-transactions.js.map +1 -1
  197. package/dist/utils/external-transactions.mjs +9 -0
  198. package/dist/utils/external-transactions.mjs.map +1 -0
  199. package/dist/utils/gas-fees.js +15 -200
  200. package/dist/utils/gas-fees.js.map +1 -1
  201. package/dist/utils/gas-fees.mjs +16 -0
  202. package/dist/utils/gas-fees.mjs.map +1 -0
  203. package/dist/utils/gas-flow.js +10 -52
  204. package/dist/utils/gas-flow.js.map +1 -1
  205. package/dist/utils/gas-flow.mjs +11 -0
  206. package/dist/utils/gas-flow.mjs.map +1 -0
  207. package/dist/utils/gas.js +19 -133
  208. package/dist/utils/gas.js.map +1 -1
  209. package/dist/utils/gas.mjs +20 -0
  210. package/dist/utils/gas.mjs.map +1 -0
  211. package/dist/utils/history.js +9 -83
  212. package/dist/utils/history.js.map +1 -1
  213. package/dist/utils/history.mjs +10 -0
  214. package/dist/utils/history.mjs.map +1 -0
  215. package/dist/utils/layer1-gas-fee-flow.js +9 -0
  216. package/dist/utils/layer1-gas-fee-flow.js.map +1 -0
  217. package/dist/utils/layer1-gas-fee-flow.mjs +9 -0
  218. package/dist/utils/layer1-gas-fee-flow.mjs.map +1 -0
  219. package/dist/utils/nonce.js +10 -76
  220. package/dist/utils/nonce.js.map +1 -1
  221. package/dist/utils/nonce.mjs +11 -0
  222. package/dist/utils/nonce.mjs.map +1 -0
  223. package/dist/utils/simulation-api.js +10 -0
  224. package/dist/utils/simulation-api.js.map +1 -0
  225. package/dist/utils/simulation-api.mjs +10 -0
  226. package/dist/utils/simulation-api.mjs.map +1 -0
  227. package/dist/utils/simulation.js +12 -0
  228. package/dist/utils/simulation.js.map +1 -0
  229. package/dist/utils/simulation.mjs +12 -0
  230. package/dist/utils/simulation.mjs.map +1 -0
  231. package/dist/utils/swaps.js +23 -256
  232. package/dist/utils/swaps.js.map +1 -1
  233. package/dist/utils/swaps.mjs +24 -0
  234. package/dist/utils/swaps.mjs.map +1 -0
  235. package/dist/utils/transaction-type.js +10 -120
  236. package/dist/utils/transaction-type.js.map +1 -1
  237. package/dist/utils/transaction-type.mjs +11 -0
  238. package/dist/utils/transaction-type.mjs.map +1 -0
  239. package/dist/utils/utils.js +32 -160
  240. package/dist/utils/utils.js.map +1 -1
  241. package/dist/utils/utils.mjs +33 -0
  242. package/dist/utils/utils.mjs.map +1 -0
  243. package/dist/utils/validation.js +11 -258
  244. package/dist/utils/validation.js.map +1 -1
  245. package/dist/utils/validation.mjs +12 -0
  246. package/dist/utils/validation.mjs.map +1 -0
  247. package/package.json +22 -10
  248. package/dist/TransactionController.d.ts.map +0 -1
  249. package/dist/constants.d.ts.map +0 -1
  250. package/dist/gas-flows/DefaultGasFeeFlow.d.ts.map +0 -1
  251. package/dist/gas-flows/LineaGasFeeFlow.d.ts.map +0 -1
  252. package/dist/helpers/EtherscanRemoteTransactionSource.d.ts.map +0 -1
  253. package/dist/helpers/GasFeePoller.d.ts.map +0 -1
  254. package/dist/helpers/IncomingTransactionHelper.d.ts.map +0 -1
  255. package/dist/helpers/MultichainTrackingHelper.d.ts.map +0 -1
  256. package/dist/helpers/PendingTransactionTracker.d.ts.map +0 -1
  257. package/dist/index.d.ts +0 -7
  258. package/dist/index.d.ts.map +0 -1
  259. package/dist/logger.d.ts.map +0 -1
  260. package/dist/types.d.ts.map +0 -1
  261. package/dist/utils/etherscan.d.ts.map +0 -1
  262. package/dist/utils/external-transactions.d.ts.map +0 -1
  263. package/dist/utils/gas-fees.d.ts.map +0 -1
  264. package/dist/utils/gas-flow.d.ts.map +0 -1
  265. package/dist/utils/gas.d.ts.map +0 -1
  266. package/dist/utils/history.d.ts +0 -15
  267. package/dist/utils/history.d.ts.map +0 -1
  268. package/dist/utils/nonce.d.ts.map +0 -1
  269. package/dist/utils/swaps.d.ts.map +0 -1
  270. package/dist/utils/transaction-type.d.ts.map +0 -1
  271. package/dist/utils/utils.d.ts.map +0 -1
  272. package/dist/utils/validation.d.ts.map +0 -1
  273. /package/dist/{gas-flows → types/gas-flows}/DefaultGasFeeFlow.d.ts +0 -0
  274. /package/dist/{gas-flows → types/gas-flows}/LineaGasFeeFlow.d.ts +0 -0
  275. /package/dist/{helpers → types/helpers}/EtherscanRemoteTransactionSource.d.ts +0 -0
  276. /package/dist/{helpers → types/helpers}/IncomingTransactionHelper.d.ts +0 -0
  277. /package/dist/{helpers → types/helpers}/MultichainTrackingHelper.d.ts +0 -0
  278. /package/dist/{helpers → types/helpers}/PendingTransactionTracker.d.ts +0 -0
  279. /package/dist/{logger.d.ts → types/logger.d.ts} +0 -0
  280. /package/dist/{utils → types/utils}/etherscan.d.ts +0 -0
  281. /package/dist/{utils → types/utils}/external-transactions.d.ts +0 -0
  282. /package/dist/{utils → types/utils}/gas-fees.d.ts +0 -0
  283. /package/dist/{utils → types/utils}/gas-flow.d.ts +0 -0
  284. /package/dist/{utils → types/utils}/gas.d.ts +0 -0
  285. /package/dist/{utils → types/utils}/nonce.d.ts +0 -0
  286. /package/dist/{utils → types/utils}/transaction-type.d.ts +0 -0
  287. /package/dist/{utils → types/utils}/utils.d.ts +0 -0
  288. /package/dist/{utils → types/utils}/validation.d.ts +0 -0
@@ -0,0 +1,2332 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
2
+
3
+
4
+ var _chunkVH47Q6TSjs = require('./chunk-VH47Q6TS.js');
5
+
6
+
7
+
8
+
9
+ var _chunkRQKICZYPjs = require('./chunk-RQKICZYP.js');
10
+
11
+
12
+
13
+ var _chunkQP75SWIQjs = require('./chunk-QP75SWIQ.js');
14
+
15
+
16
+
17
+ var _chunkZNZEJDOEjs = require('./chunk-ZNZEJDOE.js');
18
+
19
+
20
+ var _chunkWXQZIUNWjs = require('./chunk-WXQZIUNW.js');
21
+
22
+
23
+ var _chunkHS277C77js = require('./chunk-HS277C77.js');
24
+
25
+
26
+ var _chunkBILEZLATjs = require('./chunk-BILEZLAT.js');
27
+
28
+
29
+ var _chunkR7NJVDWNjs = require('./chunk-R7NJVDWN.js');
30
+
31
+
32
+ var _chunkDTDTOMTBjs = require('./chunk-DTDTOMTB.js');
33
+
34
+
35
+ var _chunkNRWEI43Qjs = require('./chunk-NRWEI43Q.js');
36
+
37
+
38
+ var _chunk5XBULBP2js = require('./chunk-5XBULBP2.js');
39
+
40
+
41
+ var _chunk7LXE4KHVjs = require('./chunk-7LXE4KHV.js');
42
+
43
+
44
+ var _chunkCQBXHAYRjs = require('./chunk-CQBXHAYR.js');
45
+
46
+
47
+ var _chunkTXVH44HMjs = require('./chunk-TXVH44HM.js');
48
+
49
+
50
+ var _chunkQPNEFZB3js = require('./chunk-QPNEFZB3.js');
51
+
52
+
53
+
54
+ var _chunk5OQ373JSjs = require('./chunk-5OQ373JS.js');
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+ var _chunkUGFBA4GVjs = require('./chunk-UGFBA4GV.js');
67
+
68
+
69
+ var _chunkF3CMU2DMjs = require('./chunk-F3CMU2DM.js');
70
+
71
+
72
+ var _chunkS6VGOPUYjs = require('./chunk-S6VGOPUY.js');
73
+
74
+
75
+
76
+
77
+
78
+ var _chunkZ4BLTVTBjs = require('./chunk-Z4BLTVTB.js');
79
+
80
+ // src/TransactionController.ts
81
+ var _common = require('@ethereumjs/common');
82
+ var _tx = require('@ethereumjs/tx');
83
+ var _util = require('@ethereumjs/util');
84
+ var _basecontroller = require('@metamask/base-controller');
85
+
86
+
87
+
88
+
89
+
90
+
91
+ var _controllerutils = require('@metamask/controller-utils');
92
+ var _ethquery = require('@metamask/eth-query'); var _ethquery2 = _interopRequireDefault(_ethquery);
93
+ var _networkcontroller = require('@metamask/network-controller');
94
+ var _rpcerrors = require('@metamask/rpc-errors');
95
+ var _utils = require('@metamask/utils');
96
+ var _asyncmutex = require('async-mutex');
97
+ var _ethmethodregistry = require('eth-method-registry');
98
+ var _events = require('events');
99
+ var _lodash = require('lodash');
100
+ var _noncetracker = require('nonce-tracker');
101
+ var _uuid = require('uuid');
102
+ var metadata = {
103
+ transactions: {
104
+ persist: true,
105
+ anonymous: false
106
+ },
107
+ methodData: {
108
+ persist: true,
109
+ anonymous: false
110
+ },
111
+ lastFetchedBlockNumbers: {
112
+ persist: true,
113
+ anonymous: false
114
+ }
115
+ };
116
+ var HARDFORK = _common.Hardfork.London;
117
+ var CANCEL_RATE = 1.1;
118
+ var SPEED_UP_RATE = 1.1;
119
+ var controllerName = "TransactionController";
120
+ var ApprovalState = /* @__PURE__ */ ((ApprovalState2) => {
121
+ ApprovalState2["Approved"] = "approved";
122
+ ApprovalState2["NotApproved"] = "not-approved";
123
+ ApprovalState2["SkippedViaBeforePublishHook"] = "skipped-via-before-publish-hook";
124
+ return ApprovalState2;
125
+ })(ApprovalState || {});
126
+ function getDefaultTransactionControllerState() {
127
+ return {
128
+ methodData: {},
129
+ transactions: [],
130
+ lastFetchedBlockNumbers: {}
131
+ };
132
+ }
133
+ var _internalEvents, _incomingTransactionOptions, _pendingTransactionOptions, _transactionHistoryLimit, _isSimulationEnabled, _multichainTrackingHelper, _createNonceTracker, createNonceTracker_fn, _createIncomingTransactionHelper, createIncomingTransactionHelper_fn, _createPendingTransactionTracker, createPendingTransactionTracker_fn, _checkForPendingTransactionAndStartPolling, _stopAllTracking, stopAllTracking_fn, _removeIncomingTransactionHelperListeners, removeIncomingTransactionHelperListeners_fn, _addIncomingTransactionHelperListeners, addIncomingTransactionHelperListeners_fn, _removePendingTransactionTrackerListeners, removePendingTransactionTrackerListeners_fn, _addPendingTransactionTrackerListeners, addPendingTransactionTrackerListeners_fn, _getNonceTrackerPendingTransactions, getNonceTrackerPendingTransactions_fn, _getGasFeeFlows, getGasFeeFlows_fn, _getLayer1GasFeeFlows, getLayer1GasFeeFlows_fn, _updateTransactionInternal, updateTransactionInternal_fn, _simulateTransaction, simulateTransaction_fn;
134
+ var TransactionController = class extends _basecontroller.BaseController {
135
+ /**
136
+ * Constructs a TransactionController.
137
+ *
138
+ * @param options - The controller options.
139
+ * @param options.blockTracker - The block tracker used to poll for new blocks data.
140
+ * @param options.disableHistory - Whether to disable storing history in transaction metadata.
141
+ * @param options.disableSendFlowHistory - Explicitly disable transaction metadata history.
142
+ * @param options.disableSwaps - Whether to disable additional processing on swaps transactions.
143
+ * @param options.getCurrentAccountEIP1559Compatibility - Whether or not the account supports EIP-1559.
144
+ * @param options.getCurrentNetworkEIP1559Compatibility - Whether or not the network supports EIP-1559.
145
+ * @param options.getExternalPendingTransactions - Callback to retrieve pending transactions from external sources.
146
+ * @param options.getGasFeeEstimates - Callback to retrieve gas fee estimates.
147
+ * @param options.getNetworkClientRegistry - Gets the network client registry.
148
+ * @param options.getNetworkState - Gets the state of the network controller.
149
+ * @param options.getPermittedAccounts - Get accounts that a given origin has permissions for.
150
+ * @param options.getSavedGasFees - Gets the saved gas fee config.
151
+ * @param options.getSelectedAddress - Gets the address of the currently selected account.
152
+ * @param options.incomingTransactions - Configuration options for incoming transaction support.
153
+ * @param options.isMultichainEnabled - Enable multichain support.
154
+ * @param options.isSimulationEnabled - Whether new transactions will be automatically simulated.
155
+ * @param options.messenger - The controller messenger.
156
+ * @param options.onNetworkStateChange - Allows subscribing to network controller state changes.
157
+ * @param options.pendingTransactions - Configuration options for pending transaction support.
158
+ * @param options.provider - The provider used to create the underlying EthQuery instance.
159
+ * @param options.securityProviderRequest - A function for verifying a transaction, whether it is malicious or not.
160
+ * @param options.sign - Function used to sign transactions.
161
+ * @param options.state - Initial state to set on this controller.
162
+ * @param options.transactionHistoryLimit - Transaction history limit.
163
+ * @param options.hooks - The controller hooks.
164
+ */
165
+ constructor({
166
+ blockTracker,
167
+ disableHistory,
168
+ disableSendFlowHistory,
169
+ disableSwaps,
170
+ getCurrentAccountEIP1559Compatibility,
171
+ getCurrentNetworkEIP1559Compatibility,
172
+ getExternalPendingTransactions,
173
+ getGasFeeEstimates,
174
+ getNetworkClientRegistry,
175
+ getNetworkState,
176
+ getPermittedAccounts,
177
+ getSavedGasFees,
178
+ getSelectedAddress,
179
+ incomingTransactions = {},
180
+ isMultichainEnabled = false,
181
+ isSimulationEnabled,
182
+ messenger,
183
+ onNetworkStateChange,
184
+ pendingTransactions = {},
185
+ provider,
186
+ securityProviderRequest,
187
+ sign,
188
+ state,
189
+ transactionHistoryLimit = 40,
190
+ hooks
191
+ }) {
192
+ super({
193
+ name: controllerName,
194
+ metadata,
195
+ messenger,
196
+ state: {
197
+ ...getDefaultTransactionControllerState(),
198
+ ...state
199
+ }
200
+ });
201
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _createNonceTracker);
202
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _createIncomingTransactionHelper);
203
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _createPendingTransactionTracker);
204
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _stopAllTracking);
205
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _removeIncomingTransactionHelperListeners);
206
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _addIncomingTransactionHelperListeners);
207
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _removePendingTransactionTrackerListeners);
208
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _addPendingTransactionTrackerListeners);
209
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getNonceTrackerPendingTransactions);
210
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getGasFeeFlows);
211
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _getLayer1GasFeeFlows);
212
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _updateTransactionInternal);
213
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _simulateTransaction);
214
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _internalEvents, new (0, _events.EventEmitter)());
215
+ this.inProcessOfSigning = /* @__PURE__ */ new Set();
216
+ this.mutex = new (0, _asyncmutex.Mutex)();
217
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _incomingTransactionOptions, void 0);
218
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _pendingTransactionOptions, void 0);
219
+ this.signAbortCallbacks = /* @__PURE__ */ new Map();
220
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _transactionHistoryLimit, void 0);
221
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _isSimulationEnabled, void 0);
222
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _multichainTrackingHelper, void 0);
223
+ _chunkZ4BLTVTBjs.__privateAdd.call(void 0, this, _checkForPendingTransactionAndStartPolling, () => {
224
+ this.pendingTransactionTracker.startIfPendingTransactions();
225
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).checkForPendingTransactionAndStartPolling();
226
+ });
227
+ this.messagingSystem = messenger;
228
+ this.getNetworkState = getNetworkState;
229
+ this.isSendFlowHistoryDisabled = disableSendFlowHistory ?? false;
230
+ this.isHistoryDisabled = disableHistory ?? false;
231
+ this.isSwapsDisabled = disableSwaps ?? false;
232
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _isSimulationEnabled, isSimulationEnabled ?? (() => true));
233
+ this.registry = new (0, _ethmethodregistry.MethodRegistry)({ provider });
234
+ this.getSavedGasFees = getSavedGasFees ?? ((_chainId) => void 0);
235
+ this.getCurrentAccountEIP1559Compatibility = getCurrentAccountEIP1559Compatibility ?? (() => Promise.resolve(true));
236
+ this.getCurrentNetworkEIP1559Compatibility = getCurrentNetworkEIP1559Compatibility;
237
+ this.getGasFeeEstimates = getGasFeeEstimates || (() => Promise.resolve({}));
238
+ this.getPermittedAccounts = getPermittedAccounts;
239
+ this.getSelectedAddress = getSelectedAddress;
240
+ this.getExternalPendingTransactions = getExternalPendingTransactions ?? (() => []);
241
+ this.securityProviderRequest = securityProviderRequest;
242
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _incomingTransactionOptions, incomingTransactions);
243
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _pendingTransactionOptions, pendingTransactions);
244
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _transactionHistoryLimit, transactionHistoryLimit);
245
+ this.sign = sign;
246
+ this.afterSign = hooks?.afterSign ?? (() => true);
247
+ this.beforeApproveOnInit = hooks?.beforeApproveOnInit ?? (() => true);
248
+ this.beforeCheckPendingTransaction = hooks?.beforeCheckPendingTransaction ?? /* istanbul ignore next */
249
+ (() => true);
250
+ this.beforePublish = hooks?.beforePublish ?? (() => true);
251
+ this.getAdditionalSignArguments = hooks?.getAdditionalSignArguments ?? (() => []);
252
+ this.publish = hooks?.publish ?? (() => Promise.resolve({ transactionHash: void 0 }));
253
+ this.nonceTracker = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _createNonceTracker, createNonceTracker_fn).call(this, {
254
+ provider,
255
+ blockTracker
256
+ });
257
+ _chunkZ4BLTVTBjs.__privateSet.call(void 0, this, _multichainTrackingHelper, new (0, _chunkNRWEI43Qjs.MultichainTrackingHelper)({
258
+ isMultichainEnabled,
259
+ provider,
260
+ nonceTracker: this.nonceTracker,
261
+ incomingTransactionOptions: incomingTransactions,
262
+ findNetworkClientIdByChainId: (chainId) => {
263
+ return this.messagingSystem.call(
264
+ `NetworkController:findNetworkClientIdByChainId`,
265
+ chainId
266
+ );
267
+ },
268
+ getNetworkClientById: (networkClientId) => {
269
+ return this.messagingSystem.call(
270
+ `NetworkController:getNetworkClientById`,
271
+ networkClientId
272
+ );
273
+ },
274
+ getNetworkClientRegistry,
275
+ removeIncomingTransactionHelperListeners: _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _removeIncomingTransactionHelperListeners, removeIncomingTransactionHelperListeners_fn).bind(this),
276
+ removePendingTransactionTrackerListeners: _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _removePendingTransactionTrackerListeners, removePendingTransactionTrackerListeners_fn).bind(this),
277
+ createNonceTracker: _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _createNonceTracker, createNonceTracker_fn).bind(this),
278
+ createIncomingTransactionHelper: _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _createIncomingTransactionHelper, createIncomingTransactionHelper_fn).bind(this),
279
+ createPendingTransactionTracker: _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _createPendingTransactionTracker, createPendingTransactionTracker_fn).bind(this),
280
+ onNetworkStateChange: (listener) => {
281
+ this.messagingSystem.subscribe(
282
+ "NetworkController:stateChange",
283
+ listener
284
+ );
285
+ }
286
+ }));
287
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).initialize();
288
+ const etherscanRemoteTransactionSource = new (0, _chunkF3CMU2DMjs.EtherscanRemoteTransactionSource)({
289
+ includeTokenTransfers: incomingTransactions.includeTokenTransfers
290
+ });
291
+ this.incomingTransactionHelper = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _createIncomingTransactionHelper, createIncomingTransactionHelper_fn).call(this, {
292
+ blockTracker,
293
+ etherscanRemoteTransactionSource
294
+ });
295
+ this.pendingTransactionTracker = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _createPendingTransactionTracker, createPendingTransactionTracker_fn).call(this, {
296
+ provider,
297
+ blockTracker
298
+ });
299
+ this.gasFeeFlows = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getGasFeeFlows, getGasFeeFlows_fn).call(this);
300
+ this.layer1GasFeeFlows = _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getLayer1GasFeeFlows, getLayer1GasFeeFlows_fn).call(this);
301
+ const gasFeePoller = new (0, _chunkBILEZLATjs.GasFeePoller)({
302
+ // Default gas fee polling is not yet supported by the clients
303
+ gasFeeFlows: this.gasFeeFlows.slice(0, -1),
304
+ getEthQuery: (chainId, networkClientId) => _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
305
+ networkClientId,
306
+ chainId
307
+ }),
308
+ getGasFeeControllerEstimates: this.getGasFeeEstimates,
309
+ getTransactions: () => this.state.transactions,
310
+ layer1GasFeeFlows: this.layer1GasFeeFlows,
311
+ onStateChange: (listener) => {
312
+ this.messagingSystem.subscribe(
313
+ "TransactionController:stateChange",
314
+ listener
315
+ );
316
+ }
317
+ });
318
+ gasFeePoller.hub.on(
319
+ "transaction-updated",
320
+ (transactionMeta) => _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _updateTransactionInternal, updateTransactionInternal_fn).call(this, transactionMeta, { skipHistory: true })
321
+ );
322
+ this.messagingSystem.subscribe(
323
+ "TransactionController:stateChange",
324
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _checkForPendingTransactionAndStartPolling)
325
+ );
326
+ onNetworkStateChange(() => {
327
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Detected network change", this.getChainId());
328
+ this.pendingTransactionTracker.startIfPendingTransactions();
329
+ this.onBootCleanup();
330
+ });
331
+ this.onBootCleanup();
332
+ }
333
+ failTransaction(transactionMeta, error, actionId) {
334
+ const newTransactionMeta = _lodash.merge.call(void 0, {}, transactionMeta, {
335
+ error: _chunkUGFBA4GVjs.normalizeTxError.call(void 0, error),
336
+ status: "failed" /* failed */
337
+ });
338
+ this.messagingSystem.publish(`${controllerName}:transactionFailed`, {
339
+ actionId,
340
+ error: error.message,
341
+ transactionMeta: newTransactionMeta
342
+ });
343
+ this.updateTransaction(
344
+ newTransactionMeta,
345
+ "TransactionController#failTransaction - Add error message and set status to failed"
346
+ );
347
+ this.onTransactionStatusChange(newTransactionMeta);
348
+ this.messagingSystem.publish(
349
+ `${controllerName}:transactionFinished`,
350
+ newTransactionMeta
351
+ );
352
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _internalEvents).emit(
353
+ `${transactionMeta.id}:finished`,
354
+ newTransactionMeta
355
+ );
356
+ }
357
+ async registryLookup(fourBytePrefix) {
358
+ const registryMethod = await this.registry.lookup(fourBytePrefix);
359
+ if (!registryMethod) {
360
+ return {
361
+ registryMethod: "",
362
+ parsedRegistryMethod: { name: void 0, args: void 0 }
363
+ };
364
+ }
365
+ const parsedRegistryMethod = this.registry.parse(registryMethod);
366
+ return { registryMethod, parsedRegistryMethod };
367
+ }
368
+ /**
369
+ * Stops polling and removes listeners to prepare the controller for garbage collection.
370
+ */
371
+ destroy() {
372
+ _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _stopAllTracking, stopAllTracking_fn).call(this);
373
+ }
374
+ /**
375
+ * Handle new method data request.
376
+ *
377
+ * @param fourBytePrefix - The method prefix.
378
+ * @returns The method data object corresponding to the given signature prefix.
379
+ */
380
+ async handleMethodData(fourBytePrefix) {
381
+ const releaseLock = await this.mutex.acquire();
382
+ try {
383
+ const { methodData } = this.state;
384
+ const knownMethod = Object.keys(methodData).find(
385
+ (knownFourBytePrefix) => fourBytePrefix === knownFourBytePrefix
386
+ );
387
+ if (knownMethod) {
388
+ return methodData[fourBytePrefix];
389
+ }
390
+ const registry = await this.registryLookup(fourBytePrefix);
391
+ this.update((state) => {
392
+ state.methodData[fourBytePrefix] = registry;
393
+ });
394
+ return registry;
395
+ } finally {
396
+ releaseLock();
397
+ }
398
+ }
399
+ /**
400
+ * Add a new unapproved transaction to state. Parameters will be validated, a
401
+ * unique transaction id will be generated, and gas and gasPrice will be calculated
402
+ * if not provided. If A `<tx.id>:unapproved` hub event will be emitted once added.
403
+ *
404
+ * @param txParams - Standard parameters for an Ethereum transaction.
405
+ * @param opts - Additional options to control how the transaction is added.
406
+ * @param opts.actionId - Unique ID to prevent duplicate requests.
407
+ * @param opts.deviceConfirmedOn - An enum to indicate what device confirmed the transaction.
408
+ * @param opts.method - RPC method that requested the transaction.
409
+ * @param opts.origin - The origin of the transaction request, such as a dApp hostname.
410
+ * @param opts.requireApproval - Whether the transaction requires approval by the user, defaults to true unless explicitly disabled.
411
+ * @param opts.securityAlertResponse - Response from security validator.
412
+ * @param opts.sendFlowHistory - The sendFlowHistory entries to add.
413
+ * @param opts.type - Type of transaction to add, such as 'cancel' or 'swap'.
414
+ * @param opts.swaps - Options for swaps transactions.
415
+ * @param opts.swaps.hasApproveTx - Whether the transaction has an approval transaction.
416
+ * @param opts.swaps.meta - Metadata for swap transaction.
417
+ * @param opts.networkClientId - The id of the network client for this transaction.
418
+ * @returns Object containing a promise resolving to the transaction hash if approved.
419
+ */
420
+ async addTransaction(txParams, {
421
+ actionId,
422
+ deviceConfirmedOn,
423
+ method,
424
+ origin,
425
+ requireApproval,
426
+ securityAlertResponse,
427
+ sendFlowHistory,
428
+ swaps = {},
429
+ type,
430
+ networkClientId
431
+ } = {}) {
432
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Adding transaction", txParams);
433
+ txParams = _chunkUGFBA4GVjs.normalizeTransactionParams.call(void 0, txParams);
434
+ if (networkClientId && !_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).has(networkClientId)) {
435
+ throw new Error(
436
+ "The networkClientId for this transaction could not be found"
437
+ );
438
+ }
439
+ const isEIP1559Compatible = await this.getEIP1559Compatibility(
440
+ networkClientId
441
+ );
442
+ _chunkVH47Q6TSjs.validateTxParams.call(void 0, txParams, isEIP1559Compatible);
443
+ if (origin) {
444
+ await _chunkVH47Q6TSjs.validateTransactionOrigin.call(void 0,
445
+ await this.getPermittedAccounts(origin),
446
+ this.getSelectedAddress(),
447
+ txParams.from,
448
+ origin
449
+ );
450
+ }
451
+ const dappSuggestedGasFees = this.generateDappSuggestedGasFees(
452
+ txParams,
453
+ origin
454
+ );
455
+ const chainId = this.getChainId(networkClientId);
456
+ const ethQuery = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
457
+ networkClientId,
458
+ chainId
459
+ });
460
+ const transactionType = type ?? (await _chunkHS277C77js.determineTransactionType.call(void 0, txParams, ethQuery)).type;
461
+ const existingTransactionMeta = this.getTransactionWithActionId(actionId);
462
+ let addedTransactionMeta = existingTransactionMeta ? _lodash.cloneDeep.call(void 0, existingTransactionMeta) : {
463
+ // Add actionId to txMeta to check if same actionId is seen again
464
+ actionId,
465
+ chainId,
466
+ dappSuggestedGasFees,
467
+ deviceConfirmedOn,
468
+ id: _uuid.v1.call(void 0, ),
469
+ origin,
470
+ securityAlertResponse,
471
+ status: "unapproved" /* unapproved */,
472
+ time: Date.now(),
473
+ txParams,
474
+ userEditedGasLimit: false,
475
+ verifiedOnBlockchain: false,
476
+ type: transactionType,
477
+ networkClientId
478
+ };
479
+ await Promise.all([
480
+ this.updateGasProperties(addedTransactionMeta),
481
+ _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _simulateTransaction, simulateTransaction_fn).call(this, addedTransactionMeta)
482
+ ]);
483
+ if (!existingTransactionMeta) {
484
+ if (method && this.securityProviderRequest) {
485
+ const securityProviderResponse = await this.securityProviderRequest(
486
+ addedTransactionMeta,
487
+ method
488
+ );
489
+ addedTransactionMeta.securityProviderResponse = securityProviderResponse;
490
+ }
491
+ if (!this.isSendFlowHistoryDisabled) {
492
+ addedTransactionMeta.sendFlowHistory = sendFlowHistory ?? [];
493
+ }
494
+ if (!this.isHistoryDisabled) {
495
+ addedTransactionMeta = _chunkQP75SWIQjs.addInitialHistorySnapshot.call(void 0, addedTransactionMeta);
496
+ }
497
+ addedTransactionMeta = _chunk5OQ373JSjs.updateSwapsTransaction.call(void 0,
498
+ addedTransactionMeta,
499
+ transactionType,
500
+ swaps,
501
+ {
502
+ isSwapsDisabled: this.isSwapsDisabled,
503
+ cancelTransaction: this.cancelTransaction.bind(this),
504
+ messenger: this.messagingSystem
505
+ }
506
+ );
507
+ this.addMetadata(addedTransactionMeta);
508
+ this.messagingSystem.publish(
509
+ `${controllerName}:unapprovedTransactionAdded`,
510
+ addedTransactionMeta
511
+ );
512
+ }
513
+ return {
514
+ result: this.processApproval(addedTransactionMeta, {
515
+ isExisting: Boolean(existingTransactionMeta),
516
+ requireApproval,
517
+ actionId
518
+ }),
519
+ transactionMeta: addedTransactionMeta
520
+ };
521
+ }
522
+ startIncomingTransactionPolling(networkClientIds = []) {
523
+ if (networkClientIds.length === 0) {
524
+ this.incomingTransactionHelper.start();
525
+ return;
526
+ }
527
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).startIncomingTransactionPolling(
528
+ networkClientIds
529
+ );
530
+ }
531
+ stopIncomingTransactionPolling(networkClientIds = []) {
532
+ if (networkClientIds.length === 0) {
533
+ this.incomingTransactionHelper.stop();
534
+ return;
535
+ }
536
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).stopIncomingTransactionPolling(
537
+ networkClientIds
538
+ );
539
+ }
540
+ stopAllIncomingTransactionPolling() {
541
+ this.incomingTransactionHelper.stop();
542
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).stopAllIncomingTransactionPolling();
543
+ }
544
+ async updateIncomingTransactions(networkClientIds = []) {
545
+ if (networkClientIds.length === 0) {
546
+ await this.incomingTransactionHelper.update();
547
+ return;
548
+ }
549
+ await _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).updateIncomingTransactions(
550
+ networkClientIds
551
+ );
552
+ }
553
+ /**
554
+ * Attempts to cancel a transaction based on its ID by setting its status to "rejected"
555
+ * and emitting a `<tx.id>:finished` hub event.
556
+ *
557
+ * @param transactionId - The ID of the transaction to cancel.
558
+ * @param gasValues - The gas values to use for the cancellation transaction.
559
+ * @param options - The options for the cancellation transaction.
560
+ * @param options.actionId - Unique ID to prevent duplicate requests.
561
+ * @param options.estimatedBaseFee - The estimated base fee of the transaction.
562
+ */
563
+ async stopTransaction(transactionId, gasValues, {
564
+ estimatedBaseFee,
565
+ actionId
566
+ } = {}) {
567
+ if (this.getTransactionWithActionId(actionId)) {
568
+ return;
569
+ }
570
+ if (gasValues) {
571
+ gasValues = _chunkUGFBA4GVjs.normalizeGasFeeValues.call(void 0, gasValues);
572
+ _chunkUGFBA4GVjs.validateGasValues.call(void 0, gasValues);
573
+ }
574
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Creating cancel transaction", transactionId, gasValues);
575
+ const transactionMeta = this.getTransaction(transactionId);
576
+ if (!transactionMeta) {
577
+ return;
578
+ }
579
+ if (!this.sign) {
580
+ throw new Error("No sign method defined.");
581
+ }
582
+ const minGasPrice = _chunkUGFBA4GVjs.getIncreasedPriceFromExisting.call(void 0,
583
+ transactionMeta.txParams.gasPrice,
584
+ CANCEL_RATE
585
+ );
586
+ const gasPriceFromValues = _chunkUGFBA4GVjs.isGasPriceValue.call(void 0, gasValues) && gasValues.gasPrice;
587
+ const newGasPrice = gasPriceFromValues && _chunkUGFBA4GVjs.validateMinimumIncrease.call(void 0, gasPriceFromValues, minGasPrice) || minGasPrice;
588
+ const existingMaxFeePerGas = transactionMeta.txParams?.maxFeePerGas;
589
+ const minMaxFeePerGas = _chunkUGFBA4GVjs.getIncreasedPriceFromExisting.call(void 0,
590
+ existingMaxFeePerGas,
591
+ CANCEL_RATE
592
+ );
593
+ const maxFeePerGasValues = _chunkUGFBA4GVjs.isFeeMarketEIP1559Values.call(void 0, gasValues) && gasValues.maxFeePerGas;
594
+ const newMaxFeePerGas = maxFeePerGasValues && _chunkUGFBA4GVjs.validateMinimumIncrease.call(void 0, maxFeePerGasValues, minMaxFeePerGas) || existingMaxFeePerGas && minMaxFeePerGas;
595
+ const existingMaxPriorityFeePerGas = transactionMeta.txParams?.maxPriorityFeePerGas;
596
+ const minMaxPriorityFeePerGas = _chunkUGFBA4GVjs.getIncreasedPriceFromExisting.call(void 0,
597
+ existingMaxPriorityFeePerGas,
598
+ CANCEL_RATE
599
+ );
600
+ const maxPriorityFeePerGasValues = _chunkUGFBA4GVjs.isFeeMarketEIP1559Values.call(void 0, gasValues) && gasValues.maxPriorityFeePerGas;
601
+ const newMaxPriorityFeePerGas = maxPriorityFeePerGasValues && _chunkUGFBA4GVjs.validateMinimumIncrease.call(void 0,
602
+ maxPriorityFeePerGasValues,
603
+ minMaxPriorityFeePerGas
604
+ ) || existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas;
605
+ const newTxParams = newMaxFeePerGas && newMaxPriorityFeePerGas ? {
606
+ from: transactionMeta.txParams.from,
607
+ gasLimit: transactionMeta.txParams.gas,
608
+ maxFeePerGas: newMaxFeePerGas,
609
+ maxPriorityFeePerGas: newMaxPriorityFeePerGas,
610
+ type: "0x2" /* feeMarket */,
611
+ nonce: transactionMeta.txParams.nonce,
612
+ to: transactionMeta.txParams.from,
613
+ value: "0x0"
614
+ } : {
615
+ from: transactionMeta.txParams.from,
616
+ gasLimit: transactionMeta.txParams.gas,
617
+ gasPrice: newGasPrice,
618
+ nonce: transactionMeta.txParams.nonce,
619
+ to: transactionMeta.txParams.from,
620
+ value: "0x0"
621
+ };
622
+ const unsignedEthTx = this.prepareUnsignedEthTx(
623
+ transactionMeta.chainId,
624
+ newTxParams
625
+ );
626
+ const signedTx = await this.sign(
627
+ unsignedEthTx,
628
+ transactionMeta.txParams.from
629
+ );
630
+ const rawTx = _util.bufferToHex.call(void 0, signedTx.serialize());
631
+ const newFee = newTxParams.maxFeePerGas ?? newTxParams.gasPrice;
632
+ const oldFee = newTxParams.maxFeePerGas ? transactionMeta.txParams.maxFeePerGas : transactionMeta.txParams.gasPrice;
633
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Submitting cancel transaction", {
634
+ oldFee,
635
+ newFee,
636
+ txParams: newTxParams
637
+ });
638
+ const ethQuery = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
639
+ networkClientId: transactionMeta.networkClientId,
640
+ chainId: transactionMeta.chainId
641
+ });
642
+ const hash = await this.publishTransactionForRetry(
643
+ ethQuery,
644
+ rawTx,
645
+ transactionMeta
646
+ );
647
+ const cancelTransactionMeta = {
648
+ actionId,
649
+ chainId: transactionMeta.chainId,
650
+ networkClientId: transactionMeta.networkClientId,
651
+ estimatedBaseFee,
652
+ hash,
653
+ id: _uuid.v1.call(void 0, ),
654
+ originalGasEstimate: transactionMeta.txParams.gas,
655
+ status: "submitted" /* submitted */,
656
+ time: Date.now(),
657
+ type: "cancel" /* cancel */,
658
+ txParams: newTxParams
659
+ };
660
+ this.addMetadata(cancelTransactionMeta);
661
+ this.messagingSystem.publish(`${controllerName}:transactionApproved`, {
662
+ transactionMeta: cancelTransactionMeta,
663
+ actionId
664
+ });
665
+ this.messagingSystem.publish(`${controllerName}:transactionSubmitted`, {
666
+ transactionMeta: cancelTransactionMeta,
667
+ actionId
668
+ });
669
+ this.messagingSystem.publish(
670
+ `${controllerName}:transactionFinished`,
671
+ cancelTransactionMeta
672
+ );
673
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _internalEvents).emit(
674
+ `${transactionMeta.id}:finished`,
675
+ cancelTransactionMeta
676
+ );
677
+ }
678
+ /**
679
+ * Attempts to speed up a transaction increasing transaction gasPrice by ten percent.
680
+ *
681
+ * @param transactionId - The ID of the transaction to speed up.
682
+ * @param gasValues - The gas values to use for the speed up transaction.
683
+ * @param options - The options for the speed up transaction.
684
+ * @param options.actionId - Unique ID to prevent duplicate requests
685
+ * @param options.estimatedBaseFee - The estimated base fee of the transaction.
686
+ */
687
+ async speedUpTransaction(transactionId, gasValues, {
688
+ actionId,
689
+ estimatedBaseFee
690
+ } = {}) {
691
+ if (this.getTransactionWithActionId(actionId)) {
692
+ return;
693
+ }
694
+ if (gasValues) {
695
+ gasValues = _chunkUGFBA4GVjs.normalizeGasFeeValues.call(void 0, gasValues);
696
+ _chunkUGFBA4GVjs.validateGasValues.call(void 0, gasValues);
697
+ }
698
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Creating speed up transaction", transactionId, gasValues);
699
+ const transactionMeta = this.state.transactions.find(
700
+ ({ id }) => id === transactionId
701
+ );
702
+ if (!transactionMeta) {
703
+ return;
704
+ }
705
+ if (!this.sign) {
706
+ throw new Error("No sign method defined.");
707
+ }
708
+ const minGasPrice = _chunkUGFBA4GVjs.getIncreasedPriceFromExisting.call(void 0,
709
+ transactionMeta.txParams.gasPrice,
710
+ SPEED_UP_RATE
711
+ );
712
+ const gasPriceFromValues = _chunkUGFBA4GVjs.isGasPriceValue.call(void 0, gasValues) && gasValues.gasPrice;
713
+ const newGasPrice = gasPriceFromValues && _chunkUGFBA4GVjs.validateMinimumIncrease.call(void 0, gasPriceFromValues, minGasPrice) || minGasPrice;
714
+ const existingMaxFeePerGas = transactionMeta.txParams?.maxFeePerGas;
715
+ const minMaxFeePerGas = _chunkUGFBA4GVjs.getIncreasedPriceFromExisting.call(void 0,
716
+ existingMaxFeePerGas,
717
+ SPEED_UP_RATE
718
+ );
719
+ const maxFeePerGasValues = _chunkUGFBA4GVjs.isFeeMarketEIP1559Values.call(void 0, gasValues) && gasValues.maxFeePerGas;
720
+ const newMaxFeePerGas = maxFeePerGasValues && _chunkUGFBA4GVjs.validateMinimumIncrease.call(void 0, maxFeePerGasValues, minMaxFeePerGas) || existingMaxFeePerGas && minMaxFeePerGas;
721
+ const existingMaxPriorityFeePerGas = transactionMeta.txParams?.maxPriorityFeePerGas;
722
+ const minMaxPriorityFeePerGas = _chunkUGFBA4GVjs.getIncreasedPriceFromExisting.call(void 0,
723
+ existingMaxPriorityFeePerGas,
724
+ SPEED_UP_RATE
725
+ );
726
+ const maxPriorityFeePerGasValues = _chunkUGFBA4GVjs.isFeeMarketEIP1559Values.call(void 0, gasValues) && gasValues.maxPriorityFeePerGas;
727
+ const newMaxPriorityFeePerGas = maxPriorityFeePerGasValues && _chunkUGFBA4GVjs.validateMinimumIncrease.call(void 0,
728
+ maxPriorityFeePerGasValues,
729
+ minMaxPriorityFeePerGas
730
+ ) || existingMaxPriorityFeePerGas && minMaxPriorityFeePerGas;
731
+ const txParams = newMaxFeePerGas && newMaxPriorityFeePerGas ? {
732
+ ...transactionMeta.txParams,
733
+ gasLimit: transactionMeta.txParams.gas,
734
+ maxFeePerGas: newMaxFeePerGas,
735
+ maxPriorityFeePerGas: newMaxPriorityFeePerGas,
736
+ type: "0x2" /* feeMarket */
737
+ } : {
738
+ ...transactionMeta.txParams,
739
+ gasLimit: transactionMeta.txParams.gas,
740
+ gasPrice: newGasPrice
741
+ };
742
+ const unsignedEthTx = this.prepareUnsignedEthTx(
743
+ transactionMeta.chainId,
744
+ txParams
745
+ );
746
+ const signedTx = await this.sign(
747
+ unsignedEthTx,
748
+ transactionMeta.txParams.from
749
+ );
750
+ const transactionMetaWithRsv = await this.updateTransactionMetaRSV(
751
+ transactionMeta,
752
+ signedTx
753
+ );
754
+ const rawTx = _util.bufferToHex.call(void 0, signedTx.serialize());
755
+ const newFee = txParams.maxFeePerGas ?? txParams.gasPrice;
756
+ const oldFee = txParams.maxFeePerGas ? transactionMetaWithRsv.txParams.maxFeePerGas : transactionMetaWithRsv.txParams.gasPrice;
757
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Submitting speed up transaction", { oldFee, newFee, txParams });
758
+ const ethQuery = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
759
+ networkClientId: transactionMeta.networkClientId,
760
+ chainId: transactionMeta.chainId
761
+ });
762
+ const hash = await this.publishTransactionForRetry(
763
+ ethQuery,
764
+ rawTx,
765
+ transactionMeta
766
+ );
767
+ const baseTransactionMeta = {
768
+ ...transactionMetaWithRsv,
769
+ estimatedBaseFee,
770
+ id: _uuid.v1.call(void 0, ),
771
+ time: Date.now(),
772
+ hash,
773
+ actionId,
774
+ originalGasEstimate: transactionMeta.txParams.gas,
775
+ type: "retry" /* retry */,
776
+ originalType: transactionMeta.type
777
+ };
778
+ const newTransactionMeta = newMaxFeePerGas && newMaxPriorityFeePerGas ? {
779
+ ...baseTransactionMeta,
780
+ txParams: {
781
+ ...transactionMeta.txParams,
782
+ maxFeePerGas: newMaxFeePerGas,
783
+ maxPriorityFeePerGas: newMaxPriorityFeePerGas
784
+ }
785
+ } : {
786
+ ...baseTransactionMeta,
787
+ txParams: {
788
+ ...transactionMeta.txParams,
789
+ gasPrice: newGasPrice
790
+ }
791
+ };
792
+ this.addMetadata(newTransactionMeta);
793
+ this.messagingSystem.publish(`${controllerName}:transactionApproved`, {
794
+ transactionMeta: newTransactionMeta,
795
+ actionId
796
+ });
797
+ this.messagingSystem.publish(`${controllerName}:transactionSubmitted`, {
798
+ transactionMeta: newTransactionMeta,
799
+ actionId
800
+ });
801
+ this.messagingSystem.publish(
802
+ `${controllerName}:speedupTransactionAdded`,
803
+ newTransactionMeta
804
+ );
805
+ }
806
+ /**
807
+ * Estimates required gas for a given transaction.
808
+ *
809
+ * @param transaction - The transaction to estimate gas for.
810
+ * @param networkClientId - The network client id to use for the estimate.
811
+ * @returns The gas and gas price.
812
+ */
813
+ async estimateGas(transaction, networkClientId) {
814
+ const ethQuery = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
815
+ networkClientId
816
+ });
817
+ const { estimatedGas, simulationFails } = await _chunkRQKICZYPjs.estimateGas.call(void 0,
818
+ transaction,
819
+ ethQuery
820
+ );
821
+ return { gas: estimatedGas, simulationFails };
822
+ }
823
+ /**
824
+ * Estimates required gas for a given transaction and add additional gas buffer with the given multiplier.
825
+ *
826
+ * @param transaction - The transaction params to estimate gas for.
827
+ * @param multiplier - The multiplier to use for the gas buffer.
828
+ * @param networkClientId - The network client id to use for the estimate.
829
+ */
830
+ async estimateGasBuffered(transaction, multiplier, networkClientId) {
831
+ const ethQuery = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
832
+ networkClientId
833
+ });
834
+ const { blockGasLimit, estimatedGas, simulationFails } = await _chunkRQKICZYPjs.estimateGas.call(void 0,
835
+ transaction,
836
+ ethQuery
837
+ );
838
+ const gas = _chunkRQKICZYPjs.addGasBuffer.call(void 0, estimatedGas, blockGasLimit, multiplier);
839
+ return {
840
+ gas,
841
+ simulationFails
842
+ };
843
+ }
844
+ /**
845
+ * Updates an existing transaction in state.
846
+ *
847
+ * @param transactionMeta - The new transaction to store in state.
848
+ * @param note - A note or update reason to include in the transaction history.
849
+ */
850
+ updateTransaction(transactionMeta, note) {
851
+ _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _updateTransactionInternal, updateTransactionInternal_fn).call(this, transactionMeta, {
852
+ note,
853
+ skipHistory: this.isHistoryDisabled
854
+ });
855
+ }
856
+ /**
857
+ * Update the security alert response for a transaction.
858
+ *
859
+ * @param transactionId - ID of the transaction.
860
+ * @param securityAlertResponse - The new security alert response for the transaction.
861
+ */
862
+ updateSecurityAlertResponse(transactionId, securityAlertResponse) {
863
+ if (!securityAlertResponse) {
864
+ throw new Error(
865
+ "updateSecurityAlertResponse: securityAlertResponse should not be null"
866
+ );
867
+ }
868
+ const transactionMeta = this.getTransaction(transactionId);
869
+ if (!transactionMeta) {
870
+ throw new Error(
871
+ `Cannot update security alert response as no transaction metadata found`
872
+ );
873
+ }
874
+ const updatedTransactionMeta = {
875
+ ...transactionMeta,
876
+ securityAlertResponse
877
+ };
878
+ this.updateTransaction(
879
+ updatedTransactionMeta,
880
+ `${controllerName}:updatesecurityAlertResponse - securityAlertResponse updated`
881
+ );
882
+ }
883
+ /**
884
+ * Removes all transactions from state, optionally based on the current network.
885
+ *
886
+ * @param ignoreNetwork - Determines whether to wipe all transactions, or just those on the
887
+ * current network. If `true`, all transactions are wiped.
888
+ * @param address - If specified, only transactions originating from this address will be
889
+ * wiped on current network.
890
+ */
891
+ wipeTransactions(ignoreNetwork, address) {
892
+ if (ignoreNetwork && !address) {
893
+ this.update((state) => {
894
+ state.transactions = [];
895
+ });
896
+ return;
897
+ }
898
+ const currentChainId = this.getChainId();
899
+ const newTransactions = this.state.transactions.filter(
900
+ ({ chainId, txParams }) => {
901
+ const isMatchingNetwork = ignoreNetwork || chainId === currentChainId;
902
+ if (!isMatchingNetwork) {
903
+ return true;
904
+ }
905
+ const isMatchingAddress = !address || txParams.from?.toLowerCase() === address.toLowerCase();
906
+ return !isMatchingAddress;
907
+ }
908
+ );
909
+ this.update((state) => {
910
+ state.transactions = this.trimTransactionsForState(newTransactions);
911
+ });
912
+ }
913
+ /**
914
+ * Adds external provided transaction to state as confirmed transaction.
915
+ *
916
+ * @param transactionMeta - TransactionMeta to add transactions.
917
+ * @param transactionReceipt - TransactionReceipt of the external transaction.
918
+ * @param baseFeePerGas - Base fee per gas of the external transaction.
919
+ */
920
+ async confirmExternalTransaction(transactionMeta, transactionReceipt, baseFeePerGas) {
921
+ const newTransactionMeta = this.addExternalTransaction(transactionMeta);
922
+ try {
923
+ const transactionId = newTransactionMeta.id;
924
+ const updatedTransactionMeta = {
925
+ ...newTransactionMeta,
926
+ status: "confirmed" /* confirmed */,
927
+ txReceipt: transactionReceipt
928
+ };
929
+ if (baseFeePerGas) {
930
+ updatedTransactionMeta.baseFeePerGas = baseFeePerGas;
931
+ }
932
+ this.markNonceDuplicatesDropped(transactionId);
933
+ this.updateTransaction(
934
+ updatedTransactionMeta,
935
+ `${controllerName}:confirmExternalTransaction - Add external transaction`
936
+ );
937
+ this.onTransactionStatusChange(updatedTransactionMeta);
938
+ this.updatePostBalance(updatedTransactionMeta);
939
+ this.messagingSystem.publish(
940
+ `${controllerName}:transactionConfirmed`,
941
+ updatedTransactionMeta
942
+ );
943
+ } catch (error) {
944
+ console.error("Failed to confirm external transaction", error);
945
+ }
946
+ }
947
+ /**
948
+ * Append new send flow history to a transaction.
949
+ *
950
+ * @param transactionID - The ID of the transaction to update.
951
+ * @param currentSendFlowHistoryLength - The length of the current sendFlowHistory array.
952
+ * @param sendFlowHistoryToAdd - The sendFlowHistory entries to add.
953
+ * @returns The updated transactionMeta.
954
+ */
955
+ updateTransactionSendFlowHistory(transactionID, currentSendFlowHistoryLength, sendFlowHistoryToAdd) {
956
+ if (this.isSendFlowHistoryDisabled) {
957
+ throw new Error(
958
+ "Send flow history is disabled for the current transaction controller"
959
+ );
960
+ }
961
+ const transactionMeta = this.getTransaction(transactionID);
962
+ if (!transactionMeta) {
963
+ throw new Error(
964
+ `Cannot update send flow history as no transaction metadata found`
965
+ );
966
+ }
967
+ _chunkUGFBA4GVjs.validateIfTransactionUnapproved.call(void 0,
968
+ transactionMeta,
969
+ "updateTransactionSendFlowHistory"
970
+ );
971
+ const sendFlowHistory = transactionMeta.sendFlowHistory ?? [];
972
+ if (currentSendFlowHistoryLength === sendFlowHistory.length) {
973
+ const updatedTransactionMeta = {
974
+ ...transactionMeta,
975
+ sendFlowHistory: [...sendFlowHistory, ...sendFlowHistoryToAdd]
976
+ };
977
+ this.updateTransaction(
978
+ updatedTransactionMeta,
979
+ `${controllerName}:updateTransactionSendFlowHistory - sendFlowHistory updated`
980
+ );
981
+ }
982
+ return this.getTransaction(transactionID);
983
+ }
984
+ /**
985
+ * Update the gas values of a transaction.
986
+ *
987
+ * @param transactionId - The ID of the transaction to update.
988
+ * @param gasValues - Gas values to update.
989
+ * @param gasValues.gas - Same as transaction.gasLimit.
990
+ * @param gasValues.gasLimit - Maxmimum number of units of gas to use for this transaction.
991
+ * @param gasValues.gasPrice - Price per gas for legacy transactions.
992
+ * @param gasValues.maxPriorityFeePerGas - Maximum amount per gas to give to validator as incentive.
993
+ * @param gasValues.maxFeePerGas - Maximum amount per gas to pay for the transaction, including the priority fee.
994
+ * @param gasValues.estimateUsed - Which estimate level was used.
995
+ * @param gasValues.estimateSuggested - Which estimate level that the API suggested.
996
+ * @param gasValues.defaultGasEstimates - The default estimate for gas.
997
+ * @param gasValues.originalGasEstimate - Original estimate for gas.
998
+ * @param gasValues.userEditedGasLimit - The gas limit supplied by user.
999
+ * @param gasValues.userFeeLevel - Estimate level user selected.
1000
+ * @returns The updated transactionMeta.
1001
+ */
1002
+ updateTransactionGasFees(transactionId, {
1003
+ defaultGasEstimates,
1004
+ estimateUsed,
1005
+ estimateSuggested,
1006
+ gas,
1007
+ gasLimit,
1008
+ gasPrice,
1009
+ maxPriorityFeePerGas,
1010
+ maxFeePerGas,
1011
+ originalGasEstimate,
1012
+ userEditedGasLimit,
1013
+ userFeeLevel
1014
+ }) {
1015
+ const transactionMeta = this.getTransaction(transactionId);
1016
+ if (!transactionMeta) {
1017
+ throw new Error(
1018
+ `Cannot update transaction as no transaction metadata found`
1019
+ );
1020
+ }
1021
+ _chunkUGFBA4GVjs.validateIfTransactionUnapproved.call(void 0,
1022
+ transactionMeta,
1023
+ "updateTransactionGasFees"
1024
+ );
1025
+ let transactionGasFees = {
1026
+ txParams: {
1027
+ gas,
1028
+ gasLimit,
1029
+ gasPrice,
1030
+ maxPriorityFeePerGas,
1031
+ maxFeePerGas
1032
+ },
1033
+ defaultGasEstimates,
1034
+ estimateUsed,
1035
+ estimateSuggested,
1036
+ originalGasEstimate,
1037
+ userEditedGasLimit,
1038
+ userFeeLevel
1039
+ // TODO: Replace `any` with type
1040
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1041
+ };
1042
+ transactionGasFees.txParams = _lodash.pickBy.call(void 0, transactionGasFees.txParams);
1043
+ transactionGasFees = _lodash.pickBy.call(void 0, transactionGasFees);
1044
+ const updatedMeta = _lodash.merge.call(void 0, {}, transactionMeta, transactionGasFees);
1045
+ this.updateTransaction(
1046
+ updatedMeta,
1047
+ `${controllerName}:updateTransactionGasFees - gas values updated`
1048
+ );
1049
+ return this.getTransaction(transactionId);
1050
+ }
1051
+ /**
1052
+ * Update the previous gas values of a transaction.
1053
+ *
1054
+ * @param transactionId - The ID of the transaction to update.
1055
+ * @param previousGas - Previous gas values to update.
1056
+ * @param previousGas.gasLimit - Maxmimum number of units of gas to use for this transaction.
1057
+ * @param previousGas.maxFeePerGas - Maximum amount per gas to pay for the transaction, including the priority fee.
1058
+ * @param previousGas.maxPriorityFeePerGas - Maximum amount per gas to give to validator as incentive.
1059
+ * @returns The updated transactionMeta.
1060
+ */
1061
+ updatePreviousGasParams(transactionId, {
1062
+ gasLimit,
1063
+ maxFeePerGas,
1064
+ maxPriorityFeePerGas
1065
+ }) {
1066
+ const transactionMeta = this.getTransaction(transactionId);
1067
+ if (!transactionMeta) {
1068
+ throw new Error(
1069
+ `Cannot update transaction as no transaction metadata found`
1070
+ );
1071
+ }
1072
+ _chunkUGFBA4GVjs.validateIfTransactionUnapproved.call(void 0, transactionMeta, "updatePreviousGasParams");
1073
+ const transactionPreviousGas = {
1074
+ previousGas: {
1075
+ gasLimit,
1076
+ maxFeePerGas,
1077
+ maxPriorityFeePerGas
1078
+ }
1079
+ // TODO: Replace `any` with type
1080
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1081
+ };
1082
+ transactionPreviousGas.previousGas = _lodash.pickBy.call(void 0,
1083
+ transactionPreviousGas.previousGas
1084
+ );
1085
+ const updatedMeta = _lodash.merge.call(void 0, {}, transactionMeta, transactionPreviousGas);
1086
+ this.updateTransaction(
1087
+ updatedMeta,
1088
+ `${controllerName}:updatePreviousGasParams - Previous gas values updated`
1089
+ );
1090
+ return this.getTransaction(transactionId);
1091
+ }
1092
+ async getNonceLock(address, networkClientId) {
1093
+ return _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getNonceLock(
1094
+ address,
1095
+ networkClientId
1096
+ );
1097
+ }
1098
+ /**
1099
+ * Updates the editable parameters of a transaction.
1100
+ *
1101
+ * @param txId - The ID of the transaction to update.
1102
+ * @param params - The editable parameters to update.
1103
+ * @param params.data - Data to pass with the transaction.
1104
+ * @param params.gas - Maximum number of units of gas to use for the transaction.
1105
+ * @param params.gasPrice - Price per gas for legacy transactions.
1106
+ * @param params.from - Address to send the transaction from.
1107
+ * @param params.to - Address to send the transaction to.
1108
+ * @param params.value - Value associated with the transaction.
1109
+ * @returns The updated transaction metadata.
1110
+ */
1111
+ async updateEditableParams(txId, {
1112
+ data,
1113
+ gas,
1114
+ gasPrice,
1115
+ from,
1116
+ to,
1117
+ value
1118
+ }) {
1119
+ const transactionMeta = this.getTransaction(txId);
1120
+ if (!transactionMeta) {
1121
+ throw new Error(
1122
+ `Cannot update editable params as no transaction metadata found`
1123
+ );
1124
+ }
1125
+ _chunkUGFBA4GVjs.validateIfTransactionUnapproved.call(void 0, transactionMeta, "updateEditableParams");
1126
+ const editableParams = {
1127
+ txParams: {
1128
+ data,
1129
+ from,
1130
+ to,
1131
+ value,
1132
+ gas,
1133
+ gasPrice
1134
+ }
1135
+ };
1136
+ editableParams.txParams = _lodash.pickBy.call(void 0,
1137
+ editableParams.txParams
1138
+ );
1139
+ const updatedTransaction = _lodash.merge.call(void 0, {}, transactionMeta, editableParams);
1140
+ const ethQuery = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
1141
+ networkClientId: transactionMeta.networkClientId,
1142
+ chainId: transactionMeta.chainId
1143
+ });
1144
+ const { type } = await _chunkHS277C77js.determineTransactionType.call(void 0,
1145
+ updatedTransaction.txParams,
1146
+ ethQuery
1147
+ );
1148
+ updatedTransaction.type = type;
1149
+ await _chunkR7NJVDWNjs.updateTransactionLayer1GasFee.call(void 0, {
1150
+ ethQuery,
1151
+ layer1GasFeeFlows: this.layer1GasFeeFlows,
1152
+ transactionMeta: updatedTransaction
1153
+ });
1154
+ this.updateTransaction(
1155
+ updatedTransaction,
1156
+ `Update Editable Params for ${txId}`
1157
+ );
1158
+ return this.getTransaction(txId);
1159
+ }
1160
+ /**
1161
+ * Signs and returns the raw transaction data for provided transaction params list.
1162
+ *
1163
+ * @param listOfTxParams - The list of transaction params to approve.
1164
+ * @param opts - Options bag.
1165
+ * @param opts.hasNonce - Whether the transactions already have a nonce.
1166
+ * @returns The raw transactions.
1167
+ */
1168
+ async approveTransactionsWithSameNonce(listOfTxParams = [], { hasNonce } = {}) {
1169
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Approving transactions with same nonce", {
1170
+ transactions: listOfTxParams
1171
+ });
1172
+ if (listOfTxParams.length === 0) {
1173
+ return "";
1174
+ }
1175
+ const initialTx = listOfTxParams[0];
1176
+ const common = this.getCommonConfiguration(initialTx.chainId);
1177
+ let networkClientId;
1178
+ try {
1179
+ networkClientId = this.messagingSystem.call(
1180
+ `NetworkController:findNetworkClientIdByChainId`,
1181
+ initialTx.chainId
1182
+ );
1183
+ } catch (err) {
1184
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "failed to find networkClientId from chainId", err);
1185
+ }
1186
+ const initialTxAsEthTx = _tx.TransactionFactory.fromTxData(initialTx, {
1187
+ common
1188
+ });
1189
+ const initialTxAsSerializedHex = _util.bufferToHex.call(void 0, initialTxAsEthTx.serialize());
1190
+ if (this.inProcessOfSigning.has(initialTxAsSerializedHex)) {
1191
+ return "";
1192
+ }
1193
+ this.inProcessOfSigning.add(initialTxAsSerializedHex);
1194
+ let rawTransactions, nonceLock;
1195
+ try {
1196
+ const fromAddress = initialTx.from;
1197
+ const requiresNonce = hasNonce !== true;
1198
+ nonceLock = requiresNonce ? await this.getNonceLock(fromAddress, networkClientId) : void 0;
1199
+ const nonce = nonceLock ? _utils.add0x.call(void 0, nonceLock.nextNonce.toString(16)) : initialTx.nonce;
1200
+ if (nonceLock) {
1201
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Using nonce from nonce tracker", nonce, nonceLock.nonceDetails);
1202
+ }
1203
+ rawTransactions = await Promise.all(
1204
+ listOfTxParams.map((txParams) => {
1205
+ txParams.nonce = nonce;
1206
+ return this.signExternalTransaction(txParams.chainId, txParams);
1207
+ })
1208
+ );
1209
+ } catch (err) {
1210
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Error while signing transactions with same nonce", err);
1211
+ throw err;
1212
+ } finally {
1213
+ nonceLock?.releaseLock();
1214
+ this.inProcessOfSigning.delete(initialTxAsSerializedHex);
1215
+ }
1216
+ return rawTransactions;
1217
+ }
1218
+ /**
1219
+ * Update a custodial transaction.
1220
+ *
1221
+ * @param transactionId - The ID of the transaction to update.
1222
+ * @param options - The custodial transaction options to update.
1223
+ * @param options.errorMessage - The error message to be assigned in case transaction status update to failed.
1224
+ * @param options.hash - The new hash value to be assigned.
1225
+ * @param options.status - The new status value to be assigned.
1226
+ */
1227
+ updateCustodialTransaction(transactionId, {
1228
+ errorMessage,
1229
+ hash,
1230
+ status
1231
+ }) {
1232
+ const transactionMeta = this.getTransaction(transactionId);
1233
+ if (!transactionMeta) {
1234
+ throw new Error(
1235
+ `Cannot update custodial transaction as no transaction metadata found`
1236
+ );
1237
+ }
1238
+ if (!transactionMeta.custodyId) {
1239
+ throw new Error("Transaction must be a custodian transaction");
1240
+ }
1241
+ if (status && ![
1242
+ "submitted" /* submitted */,
1243
+ "signed" /* signed */,
1244
+ "failed" /* failed */
1245
+ ].includes(status)) {
1246
+ throw new Error(
1247
+ `Cannot update custodial transaction with status: ${status}`
1248
+ );
1249
+ }
1250
+ const updatedTransactionMeta = _lodash.merge.call(void 0,
1251
+ {},
1252
+ transactionMeta,
1253
+ _lodash.pickBy.call(void 0, { hash, status })
1254
+ );
1255
+ if (status === "submitted" /* submitted */) {
1256
+ updatedTransactionMeta.submittedTime = (/* @__PURE__ */ new Date()).getTime();
1257
+ }
1258
+ if (status === "failed" /* failed */) {
1259
+ updatedTransactionMeta.error = _chunkUGFBA4GVjs.normalizeTxError.call(void 0, new Error(errorMessage));
1260
+ }
1261
+ this.updateTransaction(
1262
+ updatedTransactionMeta,
1263
+ `${controllerName}:updateCustodialTransaction - Custodial transaction updated`
1264
+ );
1265
+ if (["submitted" /* submitted */, "failed" /* failed */].includes(
1266
+ status
1267
+ )) {
1268
+ this.messagingSystem.publish(
1269
+ `${controllerName}:transactionFinished`,
1270
+ updatedTransactionMeta
1271
+ );
1272
+ }
1273
+ }
1274
+ /**
1275
+ * Creates approvals for all unapproved transactions persisted.
1276
+ */
1277
+ initApprovals() {
1278
+ const chainId = this.getChainId();
1279
+ const unapprovedTxs = this.state.transactions.filter(
1280
+ (transaction) => transaction.status === "unapproved" /* unapproved */ && transaction.chainId === chainId && !transaction.isUserOperation
1281
+ );
1282
+ for (const txMeta of unapprovedTxs) {
1283
+ this.processApproval(txMeta, {
1284
+ shouldShowRequest: false
1285
+ }).catch((error) => {
1286
+ if (error?.code === _rpcerrors.errorCodes.provider.userRejectedRequest) {
1287
+ return;
1288
+ }
1289
+ console.error("Error during persisted transaction approval", error);
1290
+ });
1291
+ }
1292
+ }
1293
+ /**
1294
+ * Search transaction metadata for matching entries.
1295
+ *
1296
+ * @param opts - Options bag.
1297
+ * @param opts.searchCriteria - An object containing values or functions for transaction properties to filter transactions with.
1298
+ * @param opts.initialList - The transactions to search. Defaults to the current state.
1299
+ * @param opts.filterToCurrentNetwork - Whether to filter the results to the current network. Defaults to true.
1300
+ * @param opts.limit - The maximum number of transactions to return. No limit by default.
1301
+ * @returns An array of transactions matching the provided options.
1302
+ */
1303
+ getTransactions({
1304
+ searchCriteria = {},
1305
+ initialList,
1306
+ filterToCurrentNetwork = true,
1307
+ limit
1308
+ } = {}) {
1309
+ const chainId = this.getChainId();
1310
+ const predicateMethods = _lodash.mapValues.call(void 0, searchCriteria, (predicate) => {
1311
+ return typeof predicate === "function" ? predicate : (
1312
+ // TODO: Replace `any` with type
1313
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1314
+ (v) => v === predicate
1315
+ );
1316
+ });
1317
+ const transactionsToFilter = initialList ?? this.state.transactions;
1318
+ const filteredTransactions = _lodash.sortBy.call(void 0,
1319
+ _lodash.pickBy.call(void 0, transactionsToFilter, (transaction) => {
1320
+ if (filterToCurrentNetwork && transaction.chainId !== chainId) {
1321
+ return false;
1322
+ }
1323
+ for (const [key, predicate] of Object.entries(predicateMethods)) {
1324
+ if (key in transaction.txParams) {
1325
+ if (predicate(transaction.txParams[key]) === false) {
1326
+ return false;
1327
+ }
1328
+ } else if (predicate(transaction[key]) === false) {
1329
+ return false;
1330
+ }
1331
+ }
1332
+ return true;
1333
+ }),
1334
+ "time"
1335
+ );
1336
+ if (limit !== void 0) {
1337
+ const nonces = /* @__PURE__ */ new Set();
1338
+ const txs = [];
1339
+ for (let i = filteredTransactions.length - 1; i > -1; i--) {
1340
+ const txMeta = filteredTransactions[i];
1341
+ const { nonce } = txMeta.txParams;
1342
+ if (!nonces.has(nonce)) {
1343
+ if (nonces.size < limit) {
1344
+ nonces.add(nonce);
1345
+ } else {
1346
+ continue;
1347
+ }
1348
+ }
1349
+ txs.unshift(txMeta);
1350
+ }
1351
+ return txs;
1352
+ }
1353
+ return filteredTransactions;
1354
+ }
1355
+ async signExternalTransaction(chainId, transactionParams) {
1356
+ if (!this.sign) {
1357
+ throw new Error("No sign method defined.");
1358
+ }
1359
+ const normalizedTransactionParams = _chunkUGFBA4GVjs.normalizeTransactionParams.call(void 0, transactionParams);
1360
+ const type = _chunkUGFBA4GVjs.isEIP1559Transaction.call(void 0, normalizedTransactionParams) ? "0x2" /* feeMarket */ : "0x0" /* legacy */;
1361
+ const updatedTransactionParams = {
1362
+ ...normalizedTransactionParams,
1363
+ type,
1364
+ gasLimit: normalizedTransactionParams.gas,
1365
+ chainId
1366
+ };
1367
+ const { from } = updatedTransactionParams;
1368
+ const common = this.getCommonConfiguration(chainId);
1369
+ const unsignedTransaction = _tx.TransactionFactory.fromTxData(
1370
+ updatedTransactionParams,
1371
+ { common }
1372
+ );
1373
+ const signedTransaction = await this.sign(unsignedTransaction, from);
1374
+ const rawTransaction = _util.bufferToHex.call(void 0, signedTransaction.serialize());
1375
+ return rawTransaction;
1376
+ }
1377
+ /**
1378
+ * Removes unapproved transactions from state.
1379
+ */
1380
+ clearUnapprovedTransactions() {
1381
+ const transactions = this.state.transactions.filter(
1382
+ ({ status }) => status !== "unapproved" /* unapproved */
1383
+ );
1384
+ this.update((state) => {
1385
+ state.transactions = this.trimTransactionsForState(transactions);
1386
+ });
1387
+ }
1388
+ /**
1389
+ * Stop the signing process for a specific transaction.
1390
+ * Throws an error causing the transaction status to be set to failed.
1391
+ * @param transactionId - The ID of the transaction to stop signing.
1392
+ */
1393
+ abortTransactionSigning(transactionId) {
1394
+ const transactionMeta = this.getTransaction(transactionId);
1395
+ if (!transactionMeta) {
1396
+ throw new Error(`Cannot abort signing as no transaction metadata found`);
1397
+ }
1398
+ const abortCallback = this.signAbortCallbacks.get(transactionId);
1399
+ if (!abortCallback) {
1400
+ throw new Error(
1401
+ `Cannot abort signing as transaction is not waiting for signing`
1402
+ );
1403
+ }
1404
+ abortCallback();
1405
+ this.signAbortCallbacks.delete(transactionId);
1406
+ }
1407
+ addMetadata(transactionMeta) {
1408
+ this.update((state) => {
1409
+ state.transactions = this.trimTransactionsForState([
1410
+ ...state.transactions,
1411
+ transactionMeta
1412
+ ]);
1413
+ });
1414
+ }
1415
+ async updateGasProperties(transactionMeta) {
1416
+ const isEIP1559Compatible = await this.getEIP1559Compatibility(transactionMeta.networkClientId) && transactionMeta.txParams.type !== "0x0" /* legacy */;
1417
+ const { networkClientId, chainId } = transactionMeta;
1418
+ const isCustomNetwork = networkClientId ? this.messagingSystem.call(
1419
+ `NetworkController:getNetworkClientById`,
1420
+ networkClientId
1421
+ ).configuration.type === _networkcontroller.NetworkClientType.Custom : this.getNetworkState().providerConfig.type === _controllerutils.NetworkType.rpc;
1422
+ const ethQuery = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
1423
+ networkClientId,
1424
+ chainId
1425
+ });
1426
+ await _chunkRQKICZYPjs.updateGas.call(void 0, {
1427
+ ethQuery,
1428
+ chainId,
1429
+ isCustomNetwork,
1430
+ txMeta: transactionMeta
1431
+ });
1432
+ await _chunkQPNEFZB3js.updateGasFees.call(void 0, {
1433
+ eip1559: isEIP1559Compatible,
1434
+ ethQuery,
1435
+ gasFeeFlows: this.gasFeeFlows,
1436
+ getGasFeeEstimates: this.getGasFeeEstimates,
1437
+ getSavedGasFees: this.getSavedGasFees.bind(this),
1438
+ txMeta: transactionMeta
1439
+ });
1440
+ await _chunkR7NJVDWNjs.updateTransactionLayer1GasFee.call(void 0, {
1441
+ ethQuery,
1442
+ layer1GasFeeFlows: this.layer1GasFeeFlows,
1443
+ transactionMeta
1444
+ });
1445
+ }
1446
+ onBootCleanup() {
1447
+ this.submitApprovedTransactions();
1448
+ }
1449
+ /**
1450
+ * Force submit approved transactions for all chains.
1451
+ */
1452
+ submitApprovedTransactions() {
1453
+ const approvedTransactions = this.state.transactions.filter(
1454
+ (transaction) => transaction.status === "approved" /* approved */
1455
+ );
1456
+ for (const transactionMeta of approvedTransactions) {
1457
+ if (this.beforeApproveOnInit(transactionMeta)) {
1458
+ this.approveTransaction(transactionMeta.id).catch((error) => {
1459
+ console.error("Error while submitting persisted transaction", error);
1460
+ });
1461
+ }
1462
+ }
1463
+ }
1464
+ async processApproval(transactionMeta, {
1465
+ isExisting = false,
1466
+ requireApproval,
1467
+ shouldShowRequest = true,
1468
+ actionId
1469
+ }) {
1470
+ const transactionId = transactionMeta.id;
1471
+ let resultCallbacks;
1472
+ const { meta, isCompleted } = this.isTransactionCompleted(transactionId);
1473
+ const finishedPromise = isCompleted ? Promise.resolve(meta) : this.waitForTransactionFinished(transactionId);
1474
+ if (meta && !isExisting && !isCompleted) {
1475
+ try {
1476
+ if (requireApproval !== false) {
1477
+ const acceptResult = await this.requestApproval(transactionMeta, {
1478
+ shouldShowRequest
1479
+ });
1480
+ resultCallbacks = acceptResult.resultCallbacks;
1481
+ const approvalValue = acceptResult.value;
1482
+ const updatedTransaction = approvalValue?.txMeta;
1483
+ if (updatedTransaction) {
1484
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Updating transaction with approval data", {
1485
+ customNonce: updatedTransaction.customNonceValue,
1486
+ params: updatedTransaction.txParams
1487
+ });
1488
+ this.updateTransaction(
1489
+ updatedTransaction,
1490
+ "TransactionController#processApproval - Updated with approval data"
1491
+ );
1492
+ }
1493
+ }
1494
+ const { isCompleted: isTxCompleted } = this.isTransactionCompleted(transactionId);
1495
+ if (!isTxCompleted) {
1496
+ const approvalResult = await this.approveTransaction(transactionId);
1497
+ if (approvalResult === "skipped-via-before-publish-hook" /* SkippedViaBeforePublishHook */ && resultCallbacks) {
1498
+ resultCallbacks.success();
1499
+ }
1500
+ const updatedTransactionMeta = this.getTransaction(
1501
+ transactionId
1502
+ );
1503
+ this.messagingSystem.publish(
1504
+ `${controllerName}:transactionApproved`,
1505
+ {
1506
+ transactionMeta: updatedTransactionMeta,
1507
+ actionId
1508
+ }
1509
+ );
1510
+ }
1511
+ } catch (error) {
1512
+ const { isCompleted: isTxCompleted } = this.isTransactionCompleted(transactionId);
1513
+ if (!isTxCompleted) {
1514
+ if (error?.code === _rpcerrors.errorCodes.provider.userRejectedRequest) {
1515
+ this.cancelTransaction(transactionId, actionId);
1516
+ throw _rpcerrors.providerErrors.userRejectedRequest(
1517
+ "MetaMask Tx Signature: User denied transaction signature."
1518
+ );
1519
+ } else {
1520
+ this.failTransaction(meta, error, actionId);
1521
+ }
1522
+ }
1523
+ }
1524
+ }
1525
+ const finalMeta = await finishedPromise;
1526
+ switch (finalMeta?.status) {
1527
+ case "failed" /* failed */:
1528
+ resultCallbacks?.error(finalMeta.error);
1529
+ throw _rpcerrors.rpcErrors.internal(finalMeta.error.message);
1530
+ case "submitted" /* submitted */:
1531
+ resultCallbacks?.success();
1532
+ return finalMeta.hash;
1533
+ default:
1534
+ const internalError = _rpcerrors.rpcErrors.internal(
1535
+ `MetaMask Tx Signature: Unknown problem: ${JSON.stringify(
1536
+ finalMeta || transactionId
1537
+ )}`
1538
+ );
1539
+ resultCallbacks?.error(internalError);
1540
+ throw internalError;
1541
+ }
1542
+ }
1543
+ /**
1544
+ * Approves a transaction and updates it's status in state. If this is not a
1545
+ * retry transaction, a nonce will be generated. The transaction is signed
1546
+ * using the sign configuration property, then published to the blockchain.
1547
+ * A `<tx.id>:finished` hub event is fired after success or failure.
1548
+ *
1549
+ * @param transactionId - The ID of the transaction to approve.
1550
+ */
1551
+ async approveTransaction(transactionId) {
1552
+ const { transactions } = this.state;
1553
+ const releaseLock = await this.mutex.acquire();
1554
+ const index = transactions.findIndex(({ id }) => transactionId === id);
1555
+ const transactionMeta = transactions[index];
1556
+ const updatedTransactionMeta = _lodash.cloneDeep.call(void 0, transactionMeta);
1557
+ const {
1558
+ txParams: { from },
1559
+ networkClientId
1560
+ } = transactionMeta;
1561
+ let releaseNonceLock;
1562
+ try {
1563
+ if (!this.sign) {
1564
+ releaseLock();
1565
+ this.failTransaction(
1566
+ transactionMeta,
1567
+ new Error("No sign method defined.")
1568
+ );
1569
+ return "not-approved" /* NotApproved */;
1570
+ } else if (!transactionMeta.chainId) {
1571
+ releaseLock();
1572
+ this.failTransaction(transactionMeta, new Error("No chainId defined."));
1573
+ return "not-approved" /* NotApproved */;
1574
+ }
1575
+ if (this.inProcessOfSigning.has(transactionId)) {
1576
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Skipping approval as signing in progress", transactionId);
1577
+ return "not-approved" /* NotApproved */;
1578
+ }
1579
+ const [nonce, releaseNonce] = await _chunkZNZEJDOEjs.getNextNonce.call(void 0,
1580
+ transactionMeta,
1581
+ (address) => _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getNonceLock(address, networkClientId)
1582
+ );
1583
+ releaseNonceLock = releaseNonce;
1584
+ updatedTransactionMeta.status = "approved" /* approved */;
1585
+ updatedTransactionMeta.txParams = {
1586
+ ...updatedTransactionMeta.txParams,
1587
+ nonce,
1588
+ chainId: transactionMeta.chainId
1589
+ };
1590
+ const baseTxParams = {
1591
+ ...updatedTransactionMeta.txParams,
1592
+ gasLimit: updatedTransactionMeta.txParams.gas
1593
+ };
1594
+ this.updateTransaction(
1595
+ updatedTransactionMeta,
1596
+ "TransactionController#approveTransaction - Transaction approved"
1597
+ );
1598
+ this.onTransactionStatusChange(updatedTransactionMeta);
1599
+ const isEIP1559 = _chunkUGFBA4GVjs.isEIP1559Transaction.call(void 0, updatedTransactionMeta.txParams);
1600
+ const txParams = isEIP1559 ? {
1601
+ ...baseTxParams,
1602
+ estimatedBaseFee: updatedTransactionMeta.txParams.estimatedBaseFee,
1603
+ type: "0x2" /* feeMarket */
1604
+ } : baseTxParams;
1605
+ const rawTx = await this.signTransaction(
1606
+ updatedTransactionMeta,
1607
+ txParams
1608
+ );
1609
+ if (!this.beforePublish(updatedTransactionMeta)) {
1610
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Skipping publishing transaction based on hook");
1611
+ this.messagingSystem.publish(
1612
+ `${controllerName}:transactionPublishingSkipped`,
1613
+ updatedTransactionMeta
1614
+ );
1615
+ return "skipped-via-before-publish-hook" /* SkippedViaBeforePublishHook */;
1616
+ }
1617
+ if (!rawTx) {
1618
+ return "not-approved" /* NotApproved */;
1619
+ }
1620
+ const ethQuery = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
1621
+ networkClientId: transactionMeta.networkClientId,
1622
+ chainId: transactionMeta.chainId
1623
+ });
1624
+ if (transactionMeta.type === "swap" /* swap */) {
1625
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Determining pre-transaction balance");
1626
+ const preTxBalance = await _controllerutils.query.call(void 0, ethQuery, "getBalance", [from]);
1627
+ updatedTransactionMeta.preTxBalance = preTxBalance;
1628
+ _chunkS6VGOPUYjs.projectLogger.call(void 0,
1629
+ "Updated pre-transaction balance",
1630
+ updatedTransactionMeta.preTxBalance
1631
+ );
1632
+ }
1633
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Publishing transaction", txParams);
1634
+ let { transactionHash: hash } = await this.publish(
1635
+ transactionMeta,
1636
+ rawTx
1637
+ );
1638
+ if (hash === void 0) {
1639
+ hash = await this.publishTransaction(ethQuery, rawTx);
1640
+ }
1641
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Publish successful", hash);
1642
+ updatedTransactionMeta.hash = hash;
1643
+ updatedTransactionMeta.status = "submitted" /* submitted */;
1644
+ updatedTransactionMeta.submittedTime = (/* @__PURE__ */ new Date()).getTime();
1645
+ this.updateTransaction(
1646
+ updatedTransactionMeta,
1647
+ "TransactionController#approveTransaction - Transaction submitted"
1648
+ );
1649
+ this.messagingSystem.publish(`${controllerName}:transactionSubmitted`, {
1650
+ transactionMeta: updatedTransactionMeta
1651
+ });
1652
+ this.messagingSystem.publish(
1653
+ `${controllerName}:transactionFinished`,
1654
+ updatedTransactionMeta
1655
+ );
1656
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _internalEvents).emit(
1657
+ `${updatedTransactionMeta.id}:finished`,
1658
+ updatedTransactionMeta
1659
+ );
1660
+ this.onTransactionStatusChange(updatedTransactionMeta);
1661
+ return "approved" /* Approved */;
1662
+ } catch (error) {
1663
+ this.failTransaction(transactionMeta, error);
1664
+ return "not-approved" /* NotApproved */;
1665
+ } finally {
1666
+ this.inProcessOfSigning.delete(transactionId);
1667
+ releaseNonceLock?.();
1668
+ releaseLock();
1669
+ }
1670
+ }
1671
+ async publishTransaction(ethQuery, rawTransaction) {
1672
+ return await _controllerutils.query.call(void 0, ethQuery, "sendRawTransaction", [rawTransaction]);
1673
+ }
1674
+ /**
1675
+ * Cancels a transaction based on its ID by setting its status to "rejected"
1676
+ * and emitting a `<tx.id>:finished` hub event.
1677
+ *
1678
+ * @param transactionId - The ID of the transaction to cancel.
1679
+ * @param actionId - The actionId passed from UI
1680
+ */
1681
+ cancelTransaction(transactionId, actionId) {
1682
+ const transactionMeta = this.state.transactions.find(
1683
+ ({ id }) => id === transactionId
1684
+ );
1685
+ if (!transactionMeta) {
1686
+ return;
1687
+ }
1688
+ this.update((state) => {
1689
+ const transactions = state.transactions.filter(
1690
+ ({ id }) => id !== transactionId
1691
+ );
1692
+ state.transactions = this.trimTransactionsForState(transactions);
1693
+ });
1694
+ const updatedTransactionMeta = {
1695
+ ...transactionMeta,
1696
+ status: "rejected" /* rejected */
1697
+ };
1698
+ this.messagingSystem.publish(
1699
+ `${controllerName}:transactionFinished`,
1700
+ updatedTransactionMeta
1701
+ );
1702
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _internalEvents).emit(
1703
+ `${transactionMeta.id}:finished`,
1704
+ updatedTransactionMeta
1705
+ );
1706
+ this.messagingSystem.publish(`${controllerName}:transactionRejected`, {
1707
+ transactionMeta: updatedTransactionMeta,
1708
+ actionId
1709
+ });
1710
+ this.onTransactionStatusChange(updatedTransactionMeta);
1711
+ }
1712
+ /**
1713
+ * Trim the amount of transactions that are set on the state. Checks
1714
+ * if the length of the tx history is longer then desired persistence
1715
+ * limit and then if it is removes the oldest confirmed or rejected tx.
1716
+ * Pending or unapproved transactions will not be removed by this
1717
+ * operation. For safety of presenting a fully functional transaction UI
1718
+ * representation, this function will not break apart transactions with the
1719
+ * same nonce, created on the same day, per network. Not accounting for
1720
+ * transactions of the same nonce, same day and network combo can result in
1721
+ * confusing or broken experiences in the UI.
1722
+ *
1723
+ * @param transactions - The transactions to be applied to the state.
1724
+ * @returns The trimmed list of transactions.
1725
+ */
1726
+ trimTransactionsForState(transactions) {
1727
+ const nonceNetworkSet = /* @__PURE__ */ new Set();
1728
+ const txsToKeep = [...transactions].sort((a, b) => a.time > b.time ? -1 : 1).filter((tx) => {
1729
+ const { chainId, status, txParams, time } = tx;
1730
+ if (txParams) {
1731
+ const key = `${String(txParams.nonce)}-${_controllerutils.convertHexToDecimal.call(void 0,
1732
+ chainId
1733
+ )}-${new Date(time).toDateString()}`;
1734
+ if (nonceNetworkSet.has(key)) {
1735
+ return true;
1736
+ } else if (nonceNetworkSet.size < _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _transactionHistoryLimit) || !this.isFinalState(status)) {
1737
+ nonceNetworkSet.add(key);
1738
+ return true;
1739
+ }
1740
+ }
1741
+ return false;
1742
+ });
1743
+ txsToKeep.reverse();
1744
+ return txsToKeep;
1745
+ }
1746
+ /**
1747
+ * Determines if the transaction is in a final state.
1748
+ *
1749
+ * @param status - The transaction status.
1750
+ * @returns Whether the transaction is in a final state.
1751
+ */
1752
+ isFinalState(status) {
1753
+ return status === "rejected" /* rejected */ || status === "confirmed" /* confirmed */ || status === "failed" /* failed */;
1754
+ }
1755
+ /**
1756
+ * Whether the transaction has at least completed all local processing.
1757
+ *
1758
+ * @param status - The transaction status.
1759
+ * @returns Whether the transaction is in a final state.
1760
+ */
1761
+ isLocalFinalState(status) {
1762
+ return [
1763
+ "confirmed" /* confirmed */,
1764
+ "failed" /* failed */,
1765
+ "rejected" /* rejected */,
1766
+ "submitted" /* submitted */
1767
+ ].includes(status);
1768
+ }
1769
+ async requestApproval(txMeta, { shouldShowRequest }) {
1770
+ const id = this.getApprovalId(txMeta);
1771
+ const { origin } = txMeta;
1772
+ const type = _controllerutils.ApprovalType.Transaction;
1773
+ const requestData = { txId: txMeta.id };
1774
+ return await this.messagingSystem.call(
1775
+ "ApprovalController:addRequest",
1776
+ {
1777
+ id,
1778
+ origin: origin || _controllerutils.ORIGIN_METAMASK,
1779
+ type,
1780
+ requestData,
1781
+ expectsResult: true
1782
+ },
1783
+ shouldShowRequest
1784
+ );
1785
+ }
1786
+ getTransaction(transactionId) {
1787
+ const { transactions } = this.state;
1788
+ return transactions.find(({ id }) => id === transactionId);
1789
+ }
1790
+ getApprovalId(txMeta) {
1791
+ return String(txMeta.id);
1792
+ }
1793
+ isTransactionCompleted(transactionId) {
1794
+ const transaction = this.getTransaction(transactionId);
1795
+ if (!transaction) {
1796
+ return { meta: void 0, isCompleted: false };
1797
+ }
1798
+ const isCompleted = this.isLocalFinalState(transaction.status);
1799
+ return { meta: transaction, isCompleted };
1800
+ }
1801
+ getChainId(networkClientId) {
1802
+ if (networkClientId) {
1803
+ return this.messagingSystem.call(
1804
+ `NetworkController:getNetworkClientById`,
1805
+ networkClientId
1806
+ ).configuration.chainId;
1807
+ }
1808
+ const { providerConfig } = this.getNetworkState();
1809
+ return providerConfig.chainId;
1810
+ }
1811
+ prepareUnsignedEthTx(chainId, txParams) {
1812
+ return _tx.TransactionFactory.fromTxData(txParams, {
1813
+ freeze: false,
1814
+ common: this.getCommonConfiguration(chainId)
1815
+ });
1816
+ }
1817
+ /**
1818
+ * `@ethereumjs/tx` uses `@ethereumjs/common` as a configuration tool for
1819
+ * specifying which chain, network, hardfork and EIPs to support for
1820
+ * a transaction. By referencing this configuration, and analyzing the fields
1821
+ * specified in txParams, @ethereumjs/tx is able to determine which EIP-2718
1822
+ * transaction type to use.
1823
+ *
1824
+ * @param chainId - The chainId to use for the configuration.
1825
+ * @returns common configuration object
1826
+ */
1827
+ getCommonConfiguration(chainId) {
1828
+ const customChainParams = {
1829
+ chainId: parseInt(chainId, 16),
1830
+ defaultHardfork: HARDFORK
1831
+ };
1832
+ return _common.Common.custom(customChainParams);
1833
+ }
1834
+ onIncomingTransactions({
1835
+ added,
1836
+ updated
1837
+ }) {
1838
+ this.update((state) => {
1839
+ const { transactions: currentTransactions } = state;
1840
+ const updatedTransactions = [
1841
+ ...added,
1842
+ ...currentTransactions.map((originalTransaction) => {
1843
+ const updatedTransaction = updated.find(
1844
+ ({ hash }) => hash === originalTransaction.hash
1845
+ );
1846
+ return updatedTransaction ?? originalTransaction;
1847
+ })
1848
+ ];
1849
+ state.transactions = this.trimTransactionsForState(updatedTransactions);
1850
+ });
1851
+ }
1852
+ onUpdatedLastFetchedBlockNumbers({
1853
+ lastFetchedBlockNumbers,
1854
+ blockNumber
1855
+ }) {
1856
+ this.update((state) => {
1857
+ state.lastFetchedBlockNumbers = lastFetchedBlockNumbers;
1858
+ });
1859
+ this.messagingSystem.publish(
1860
+ `${controllerName}:incomingTransactionBlockReceived`,
1861
+ blockNumber
1862
+ );
1863
+ }
1864
+ generateDappSuggestedGasFees(txParams, origin) {
1865
+ if (!origin || origin === _controllerutils.ORIGIN_METAMASK) {
1866
+ return void 0;
1867
+ }
1868
+ const { gasPrice, maxFeePerGas, maxPriorityFeePerGas, gas } = txParams;
1869
+ if (gasPrice === void 0 && maxFeePerGas === void 0 && maxPriorityFeePerGas === void 0 && gas === void 0) {
1870
+ return void 0;
1871
+ }
1872
+ const dappSuggestedGasFees = {};
1873
+ if (gasPrice !== void 0) {
1874
+ dappSuggestedGasFees.gasPrice = gasPrice;
1875
+ } else if (maxFeePerGas !== void 0 || maxPriorityFeePerGas !== void 0) {
1876
+ dappSuggestedGasFees.maxFeePerGas = maxFeePerGas;
1877
+ dappSuggestedGasFees.maxPriorityFeePerGas = maxPriorityFeePerGas;
1878
+ }
1879
+ if (gas !== void 0) {
1880
+ dappSuggestedGasFees.gas = gas;
1881
+ }
1882
+ return dappSuggestedGasFees;
1883
+ }
1884
+ /**
1885
+ * Validates and adds external provided transaction to state.
1886
+ *
1887
+ * @param transactionMeta - Nominated external transaction to be added to state.
1888
+ * @returns The new transaction.
1889
+ */
1890
+ addExternalTransaction(transactionMeta) {
1891
+ const { chainId } = transactionMeta;
1892
+ const { transactions } = this.state;
1893
+ const fromAddress = transactionMeta?.txParams?.from;
1894
+ const sameFromAndNetworkTransactions = transactions.filter(
1895
+ (transaction) => transaction.txParams.from === fromAddress && transaction.chainId === chainId
1896
+ );
1897
+ const confirmedTxs = sameFromAndNetworkTransactions.filter(
1898
+ (transaction) => transaction.status === "confirmed" /* confirmed */
1899
+ );
1900
+ const pendingTxs = sameFromAndNetworkTransactions.filter(
1901
+ (transaction) => transaction.status === "submitted" /* submitted */
1902
+ );
1903
+ _chunk7LXE4KHVjs.validateConfirmedExternalTransaction.call(void 0,
1904
+ transactionMeta,
1905
+ confirmedTxs,
1906
+ pendingTxs
1907
+ );
1908
+ const newTransactionMeta = (transactionMeta.history ?? []).length === 0 && !this.isHistoryDisabled ? _chunkQP75SWIQjs.addInitialHistorySnapshot.call(void 0, transactionMeta) : transactionMeta;
1909
+ this.update((state) => {
1910
+ state.transactions = this.trimTransactionsForState([
1911
+ ...state.transactions,
1912
+ newTransactionMeta
1913
+ ]);
1914
+ });
1915
+ return newTransactionMeta;
1916
+ }
1917
+ /**
1918
+ * Sets other txMeta statuses to dropped if the txMeta that has been confirmed has other transactions
1919
+ * in the transactions have the same nonce.
1920
+ *
1921
+ * @param transactionId - Used to identify original transaction.
1922
+ */
1923
+ markNonceDuplicatesDropped(transactionId) {
1924
+ const transactionMeta = this.getTransaction(transactionId);
1925
+ if (!transactionMeta) {
1926
+ return;
1927
+ }
1928
+ const nonce = transactionMeta.txParams?.nonce;
1929
+ const from = transactionMeta.txParams?.from;
1930
+ const { chainId } = transactionMeta;
1931
+ const sameNonceTransactions = this.state.transactions.filter(
1932
+ (transaction) => transaction.id !== transactionId && transaction.txParams.from === from && transaction.txParams.nonce === nonce && transaction.chainId === chainId && transaction.type !== "incoming" /* incoming */
1933
+ );
1934
+ const sameNonceTransactionIds = sameNonceTransactions.map(
1935
+ (transaction) => transaction.id
1936
+ );
1937
+ if (sameNonceTransactions.length === 0) {
1938
+ return;
1939
+ }
1940
+ this.update((state) => {
1941
+ for (const transaction of state.transactions) {
1942
+ if (sameNonceTransactionIds.includes(transaction.id)) {
1943
+ transaction.replacedBy = transactionMeta?.hash;
1944
+ transaction.replacedById = transactionMeta?.id;
1945
+ }
1946
+ }
1947
+ });
1948
+ for (const transaction of this.state.transactions) {
1949
+ if (sameNonceTransactionIds.includes(transaction.id) && transaction.status !== "failed" /* failed */) {
1950
+ this.setTransactionStatusDropped(transaction);
1951
+ }
1952
+ }
1953
+ }
1954
+ /**
1955
+ * Method to set transaction status to dropped.
1956
+ *
1957
+ * @param transactionMeta - TransactionMeta of transaction to be marked as dropped.
1958
+ */
1959
+ setTransactionStatusDropped(transactionMeta) {
1960
+ const updatedTransactionMeta = {
1961
+ ...transactionMeta,
1962
+ status: "dropped" /* dropped */
1963
+ };
1964
+ this.messagingSystem.publish(`${controllerName}:transactionDropped`, {
1965
+ transactionMeta: updatedTransactionMeta
1966
+ });
1967
+ this.updateTransaction(
1968
+ updatedTransactionMeta,
1969
+ "TransactionController#setTransactionStatusDropped - Transaction dropped"
1970
+ );
1971
+ this.onTransactionStatusChange(updatedTransactionMeta);
1972
+ }
1973
+ /**
1974
+ * Get transaction with provided actionId.
1975
+ *
1976
+ * @param actionId - Unique ID to prevent duplicate requests
1977
+ * @returns the filtered transaction
1978
+ */
1979
+ getTransactionWithActionId(actionId) {
1980
+ return this.state.transactions.find(
1981
+ (transaction) => actionId && transaction.actionId === actionId
1982
+ );
1983
+ }
1984
+ async waitForTransactionFinished(transactionId) {
1985
+ return new Promise((resolve) => {
1986
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _internalEvents).once(`${transactionId}:finished`, (txMeta) => {
1987
+ resolve(txMeta);
1988
+ });
1989
+ });
1990
+ }
1991
+ /**
1992
+ * Updates the r, s, and v properties of a TransactionMeta object
1993
+ * with values from a signed transaction.
1994
+ *
1995
+ * @param transactionMeta - The TransactionMeta object to update.
1996
+ * @param signedTx - The encompassing type for all transaction types containing r, s, and v values.
1997
+ */
1998
+ async updateTransactionMetaRSV(transactionMeta, signedTx) {
1999
+ const transactionMetaWithRsv = _lodash.cloneDeep.call(void 0, transactionMeta);
2000
+ for (const key of ["r", "s", "v"]) {
2001
+ const value = signedTx[key];
2002
+ if (value === void 0 || value === null) {
2003
+ continue;
2004
+ }
2005
+ transactionMetaWithRsv[key] = _utils.add0x.call(void 0, value.toString(16));
2006
+ }
2007
+ return transactionMetaWithRsv;
2008
+ }
2009
+ async getEIP1559Compatibility(networkClientId) {
2010
+ const currentNetworkIsEIP1559Compatible = await this.getCurrentNetworkEIP1559Compatibility(networkClientId);
2011
+ const currentAccountIsEIP1559Compatible = await this.getCurrentAccountEIP1559Compatibility();
2012
+ return currentNetworkIsEIP1559Compatible && currentAccountIsEIP1559Compatible;
2013
+ }
2014
+ async signTransaction(transactionMeta, txParams) {
2015
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Signing transaction", txParams);
2016
+ const unsignedEthTx = this.prepareUnsignedEthTx(
2017
+ transactionMeta.chainId,
2018
+ txParams
2019
+ );
2020
+ this.inProcessOfSigning.add(transactionMeta.id);
2021
+ const signedTx = await new Promise((resolve, reject) => {
2022
+ this.sign?.(
2023
+ unsignedEthTx,
2024
+ txParams.from,
2025
+ ...this.getAdditionalSignArguments(transactionMeta)
2026
+ ).then(resolve, reject);
2027
+ this.signAbortCallbacks.set(
2028
+ transactionMeta.id,
2029
+ () => reject(new Error("Signing aborted by user"))
2030
+ );
2031
+ });
2032
+ this.signAbortCallbacks.delete(transactionMeta.id);
2033
+ if (!signedTx) {
2034
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Skipping signed status as no signed transaction");
2035
+ return void 0;
2036
+ }
2037
+ if (!this.afterSign(transactionMeta, signedTx)) {
2038
+ this.updateTransaction(
2039
+ transactionMeta,
2040
+ "TransactionController#signTransaction - Update after sign"
2041
+ );
2042
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Skipping signed status based on hook");
2043
+ return void 0;
2044
+ }
2045
+ const transactionMetaWithRsv = {
2046
+ ...await this.updateTransactionMetaRSV(transactionMeta, signedTx),
2047
+ status: "signed" /* signed */
2048
+ };
2049
+ this.updateTransaction(
2050
+ transactionMetaWithRsv,
2051
+ "TransactionController#approveTransaction - Transaction signed"
2052
+ );
2053
+ this.onTransactionStatusChange(transactionMetaWithRsv);
2054
+ const rawTx = _util.bufferToHex.call(void 0, signedTx.serialize());
2055
+ const transactionMetaWithRawTx = _lodash.merge.call(void 0, {}, transactionMetaWithRsv, {
2056
+ rawTx
2057
+ });
2058
+ this.updateTransaction(
2059
+ transactionMetaWithRawTx,
2060
+ "TransactionController#approveTransaction - RawTransaction added"
2061
+ );
2062
+ return rawTx;
2063
+ }
2064
+ onTransactionStatusChange(transactionMeta) {
2065
+ this.messagingSystem.publish(`${controllerName}:transactionStatusUpdated`, {
2066
+ transactionMeta
2067
+ });
2068
+ }
2069
+ getNonceTrackerTransactions(status, address, chainId = this.getChainId()) {
2070
+ return _chunkZNZEJDOEjs.getAndFormatTransactionsForNonceTracker.call(void 0,
2071
+ chainId,
2072
+ address,
2073
+ status,
2074
+ this.state.transactions
2075
+ );
2076
+ }
2077
+ onConfirmedTransaction(transactionMeta) {
2078
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Processing confirmed transaction", transactionMeta.id);
2079
+ this.markNonceDuplicatesDropped(transactionMeta.id);
2080
+ this.messagingSystem.publish(
2081
+ `${controllerName}:transactionConfirmed`,
2082
+ transactionMeta
2083
+ );
2084
+ this.onTransactionStatusChange(transactionMeta);
2085
+ this.updatePostBalance(transactionMeta);
2086
+ }
2087
+ async updatePostBalance(transactionMeta) {
2088
+ try {
2089
+ if (transactionMeta.type !== "swap" /* swap */) {
2090
+ return;
2091
+ }
2092
+ const ethQuery = _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).getEthQuery({
2093
+ networkClientId: transactionMeta.networkClientId,
2094
+ chainId: transactionMeta.chainId
2095
+ });
2096
+ const { updatedTransactionMeta, approvalTransactionMeta } = await _chunk5OQ373JSjs.updatePostTransactionBalance.call(void 0, transactionMeta, {
2097
+ ethQuery,
2098
+ getTransaction: this.getTransaction.bind(this),
2099
+ updateTransaction: this.updateTransaction.bind(this)
2100
+ });
2101
+ this.messagingSystem.publish(
2102
+ `${controllerName}:postTransactionBalanceUpdated`,
2103
+ {
2104
+ transactionMeta: updatedTransactionMeta,
2105
+ approvalTransactionMeta
2106
+ }
2107
+ );
2108
+ } catch (error) {
2109
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Error while updating post transaction balance", error);
2110
+ }
2111
+ }
2112
+ async publishTransactionForRetry(ethQuery, rawTx, transactionMeta) {
2113
+ try {
2114
+ const hash = await this.publishTransaction(ethQuery, rawTx);
2115
+ return hash;
2116
+ } catch (error) {
2117
+ if (this.isTransactionAlreadyConfirmedError(error)) {
2118
+ await this.pendingTransactionTracker.forceCheckTransaction(
2119
+ transactionMeta
2120
+ );
2121
+ throw new Error("Previous transaction is already confirmed");
2122
+ }
2123
+ throw error;
2124
+ }
2125
+ }
2126
+ /**
2127
+ * Ensures that error is a nonce issue
2128
+ *
2129
+ * @param error - The error to check
2130
+ * @returns Whether or not the error is a nonce issue
2131
+ */
2132
+ // TODO: Replace `any` with type
2133
+ // Some networks are returning original error in the data field
2134
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2135
+ isTransactionAlreadyConfirmedError(error) {
2136
+ return error?.message?.includes("nonce too low") || error?.data?.message?.includes("nonce too low");
2137
+ }
2138
+ };
2139
+ _internalEvents = new WeakMap();
2140
+ _incomingTransactionOptions = new WeakMap();
2141
+ _pendingTransactionOptions = new WeakMap();
2142
+ _transactionHistoryLimit = new WeakMap();
2143
+ _isSimulationEnabled = new WeakMap();
2144
+ _multichainTrackingHelper = new WeakMap();
2145
+ _createNonceTracker = new WeakSet();
2146
+ createNonceTracker_fn = function({
2147
+ provider,
2148
+ blockTracker,
2149
+ chainId
2150
+ }) {
2151
+ return new (0, _noncetracker.NonceTracker)({
2152
+ // TODO: Replace `any` with type
2153
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
2154
+ provider,
2155
+ blockTracker,
2156
+ getPendingTransactions: _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _getNonceTrackerPendingTransactions, getNonceTrackerPendingTransactions_fn).bind(
2157
+ this,
2158
+ chainId
2159
+ ),
2160
+ getConfirmedTransactions: this.getNonceTrackerTransactions.bind(
2161
+ this,
2162
+ "confirmed" /* confirmed */
2163
+ )
2164
+ });
2165
+ };
2166
+ _createIncomingTransactionHelper = new WeakSet();
2167
+ createIncomingTransactionHelper_fn = function({
2168
+ blockTracker,
2169
+ etherscanRemoteTransactionSource,
2170
+ chainId
2171
+ }) {
2172
+ const incomingTransactionHelper = new (0, _chunkDTDTOMTBjs.IncomingTransactionHelper)({
2173
+ blockTracker,
2174
+ getCurrentAccount: this.getSelectedAddress,
2175
+ getLastFetchedBlockNumbers: () => this.state.lastFetchedBlockNumbers,
2176
+ getChainId: chainId ? () => chainId : this.getChainId.bind(this),
2177
+ isEnabled: _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _incomingTransactionOptions).isEnabled,
2178
+ queryEntireHistory: _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _incomingTransactionOptions).queryEntireHistory,
2179
+ remoteTransactionSource: etherscanRemoteTransactionSource,
2180
+ transactionLimit: _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _transactionHistoryLimit),
2181
+ updateTransactions: _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _incomingTransactionOptions).updateTransactions
2182
+ });
2183
+ _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _addIncomingTransactionHelperListeners, addIncomingTransactionHelperListeners_fn).call(this, incomingTransactionHelper);
2184
+ return incomingTransactionHelper;
2185
+ };
2186
+ _createPendingTransactionTracker = new WeakSet();
2187
+ createPendingTransactionTracker_fn = function({
2188
+ provider,
2189
+ blockTracker,
2190
+ chainId
2191
+ }) {
2192
+ const ethQuery = new (0, _ethquery2.default)(provider);
2193
+ const getChainId = chainId ? () => chainId : this.getChainId.bind(this);
2194
+ const pendingTransactionTracker = new (0, _chunk5XBULBP2js.PendingTransactionTracker)({
2195
+ approveTransaction: async (transactionId) => {
2196
+ await this.approveTransaction(transactionId);
2197
+ },
2198
+ blockTracker,
2199
+ getChainId,
2200
+ getEthQuery: () => ethQuery,
2201
+ getTransactions: () => this.state.transactions,
2202
+ isResubmitEnabled: _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _pendingTransactionOptions).isResubmitEnabled,
2203
+ getGlobalLock: () => _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).acquireNonceLockForChainIdKey({
2204
+ chainId: getChainId()
2205
+ }),
2206
+ publishTransaction: this.publishTransaction.bind(this),
2207
+ hooks: {
2208
+ beforeCheckPendingTransaction: this.beforeCheckPendingTransaction.bind(this),
2209
+ beforePublish: this.beforePublish.bind(this)
2210
+ }
2211
+ });
2212
+ _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _addPendingTransactionTrackerListeners, addPendingTransactionTrackerListeners_fn).call(this, pendingTransactionTracker);
2213
+ return pendingTransactionTracker;
2214
+ };
2215
+ _checkForPendingTransactionAndStartPolling = new WeakMap();
2216
+ _stopAllTracking = new WeakSet();
2217
+ stopAllTracking_fn = function() {
2218
+ this.pendingTransactionTracker.stop();
2219
+ _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _removePendingTransactionTrackerListeners, removePendingTransactionTrackerListeners_fn).call(this, this.pendingTransactionTracker);
2220
+ this.incomingTransactionHelper.stop();
2221
+ _chunkZ4BLTVTBjs.__privateMethod.call(void 0, this, _removeIncomingTransactionHelperListeners, removeIncomingTransactionHelperListeners_fn).call(this, this.incomingTransactionHelper);
2222
+ _chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _multichainTrackingHelper).stopAllTracking();
2223
+ };
2224
+ _removeIncomingTransactionHelperListeners = new WeakSet();
2225
+ removeIncomingTransactionHelperListeners_fn = function(incomingTransactionHelper) {
2226
+ incomingTransactionHelper.hub.removeAllListeners("transactions");
2227
+ incomingTransactionHelper.hub.removeAllListeners(
2228
+ "updatedLastFetchedBlockNumbers"
2229
+ );
2230
+ };
2231
+ _addIncomingTransactionHelperListeners = new WeakSet();
2232
+ addIncomingTransactionHelperListeners_fn = function(incomingTransactionHelper) {
2233
+ incomingTransactionHelper.hub.on(
2234
+ "transactions",
2235
+ this.onIncomingTransactions.bind(this)
2236
+ );
2237
+ incomingTransactionHelper.hub.on(
2238
+ "updatedLastFetchedBlockNumbers",
2239
+ this.onUpdatedLastFetchedBlockNumbers.bind(this)
2240
+ );
2241
+ };
2242
+ _removePendingTransactionTrackerListeners = new WeakSet();
2243
+ removePendingTransactionTrackerListeners_fn = function(pendingTransactionTracker) {
2244
+ pendingTransactionTracker.hub.removeAllListeners("transaction-confirmed");
2245
+ pendingTransactionTracker.hub.removeAllListeners("transaction-dropped");
2246
+ pendingTransactionTracker.hub.removeAllListeners("transaction-failed");
2247
+ pendingTransactionTracker.hub.removeAllListeners("transaction-updated");
2248
+ };
2249
+ _addPendingTransactionTrackerListeners = new WeakSet();
2250
+ addPendingTransactionTrackerListeners_fn = function(pendingTransactionTracker) {
2251
+ pendingTransactionTracker.hub.on(
2252
+ "transaction-confirmed",
2253
+ this.onConfirmedTransaction.bind(this)
2254
+ );
2255
+ pendingTransactionTracker.hub.on(
2256
+ "transaction-dropped",
2257
+ this.setTransactionStatusDropped.bind(this)
2258
+ );
2259
+ pendingTransactionTracker.hub.on(
2260
+ "transaction-failed",
2261
+ this.failTransaction.bind(this)
2262
+ );
2263
+ pendingTransactionTracker.hub.on(
2264
+ "transaction-updated",
2265
+ this.updateTransaction.bind(this)
2266
+ );
2267
+ };
2268
+ _getNonceTrackerPendingTransactions = new WeakSet();
2269
+ getNonceTrackerPendingTransactions_fn = function(chainId, address) {
2270
+ const standardPendingTransactions = this.getNonceTrackerTransactions(
2271
+ "submitted" /* submitted */,
2272
+ address,
2273
+ chainId
2274
+ );
2275
+ const externalPendingTransactions = this.getExternalPendingTransactions(
2276
+ address,
2277
+ chainId
2278
+ );
2279
+ return [...standardPendingTransactions, ...externalPendingTransactions];
2280
+ };
2281
+ _getGasFeeFlows = new WeakSet();
2282
+ getGasFeeFlows_fn = function() {
2283
+ return [new (0, _chunkCQBXHAYRjs.LineaGasFeeFlow)(), new (0, _chunkTXVH44HMjs.DefaultGasFeeFlow)()];
2284
+ };
2285
+ _getLayer1GasFeeFlows = new WeakSet();
2286
+ getLayer1GasFeeFlows_fn = function() {
2287
+ return [];
2288
+ };
2289
+ _updateTransactionInternal = new WeakSet();
2290
+ updateTransactionInternal_fn = function(transactionMeta, { note, skipHistory }) {
2291
+ const normalizedTransaction = {
2292
+ ...transactionMeta,
2293
+ txParams: _chunkUGFBA4GVjs.normalizeTransactionParams.call(void 0, transactionMeta.txParams)
2294
+ };
2295
+ _chunkVH47Q6TSjs.validateTxParams.call(void 0, normalizedTransaction.txParams);
2296
+ const transactionWithUpdatedHistory = skipHistory === true ? normalizedTransaction : _chunkQP75SWIQjs.updateTransactionHistory.call(void 0,
2297
+ normalizedTransaction,
2298
+ note ?? "Transaction updated"
2299
+ );
2300
+ this.update((state) => {
2301
+ const index = state.transactions.findIndex(
2302
+ ({ id }) => transactionMeta.id === id
2303
+ );
2304
+ state.transactions[index] = transactionWithUpdatedHistory;
2305
+ });
2306
+ };
2307
+ _simulateTransaction = new WeakSet();
2308
+ simulateTransaction_fn = async function(transactionMeta) {
2309
+ if (!_chunkZ4BLTVTBjs.__privateGet.call(void 0, this, _isSimulationEnabled).call(this)) {
2310
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Skipping simulation as disabled");
2311
+ return;
2312
+ }
2313
+ const { chainId, txParams } = transactionMeta;
2314
+ const { from, to, value, data } = txParams;
2315
+ transactionMeta.simulationData = await _chunkWXQZIUNWjs.getSimulationData.call(void 0, {
2316
+ chainId,
2317
+ from,
2318
+ to,
2319
+ value,
2320
+ data
2321
+ });
2322
+ _chunkS6VGOPUYjs.projectLogger.call(void 0, "Retrieved simulation data", transactionMeta.simulationData);
2323
+ };
2324
+
2325
+
2326
+
2327
+
2328
+
2329
+
2330
+
2331
+ exports.HARDFORK = HARDFORK; exports.CANCEL_RATE = CANCEL_RATE; exports.SPEED_UP_RATE = SPEED_UP_RATE; exports.ApprovalState = ApprovalState; exports.TransactionController = TransactionController;
2332
+ //# sourceMappingURL=chunk-QDIYZX5V.js.map