@metamask/transaction-controller 15.0.0 → 17.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +48 -1
  2. package/dist/TransactionController.d.ts +159 -20
  3. package/dist/TransactionController.d.ts.map +1 -1
  4. package/dist/TransactionController.js +489 -151
  5. package/dist/TransactionController.js.map +1 -1
  6. package/dist/constants.d.ts +2 -3
  7. package/dist/constants.d.ts.map +1 -1
  8. package/dist/constants.js +3 -15
  9. package/dist/constants.js.map +1 -1
  10. package/dist/{EtherscanRemoteTransactionSource.d.ts → helpers/EtherscanRemoteTransactionSource.d.ts} +1 -1
  11. package/dist/helpers/EtherscanRemoteTransactionSource.d.ts.map +1 -0
  12. package/dist/{EtherscanRemoteTransactionSource.js → helpers/EtherscanRemoteTransactionSource.js} +4 -4
  13. package/dist/helpers/EtherscanRemoteTransactionSource.js.map +1 -0
  14. package/dist/{IncomingTransactionHelper.d.ts → helpers/IncomingTransactionHelper.d.ts} +1 -1
  15. package/dist/helpers/IncomingTransactionHelper.d.ts.map +1 -0
  16. package/dist/{IncomingTransactionHelper.js → helpers/IncomingTransactionHelper.js} +1 -1
  17. package/dist/helpers/IncomingTransactionHelper.js.map +1 -0
  18. package/dist/helpers/PendingTransactionTracker.d.ts +38 -0
  19. package/dist/helpers/PendingTransactionTracker.d.ts.map +1 -0
  20. package/dist/helpers/PendingTransactionTracker.js +329 -0
  21. package/dist/helpers/PendingTransactionTracker.js.map +1 -0
  22. package/dist/index.d.ts +2 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +1 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/logger.d.ts +0 -1
  27. package/dist/logger.d.ts.map +1 -1
  28. package/dist/logger.js +1 -2
  29. package/dist/logger.js.map +1 -1
  30. package/dist/types.d.ts +290 -8
  31. package/dist/types.d.ts.map +1 -1
  32. package/dist/types.js +37 -1
  33. package/dist/types.js.map +1 -1
  34. package/dist/utils/etherscan.d.ts.map +1 -0
  35. package/dist/{etherscan.js → utils/etherscan.js} +3 -4
  36. package/dist/utils/etherscan.js.map +1 -0
  37. package/dist/{external-transactions.d.ts → utils/external-transactions.d.ts} +1 -1
  38. package/dist/utils/external-transactions.d.ts.map +1 -0
  39. package/dist/{external-transactions.js → utils/external-transactions.js} +1 -1
  40. package/dist/utils/external-transactions.js.map +1 -0
  41. package/dist/utils/gas-fees.d.ts +31 -0
  42. package/dist/utils/gas-fees.d.ts.map +1 -0
  43. package/dist/utils/gas-fees.js +212 -0
  44. package/dist/utils/gas-fees.js.map +1 -0
  45. package/dist/utils/gas.d.ts +27 -0
  46. package/dist/utils/gas.d.ts.map +1 -0
  47. package/dist/utils/gas.js +134 -0
  48. package/dist/utils/gas.js.map +1 -0
  49. package/dist/{history.d.ts → utils/history.d.ts} +1 -1
  50. package/dist/utils/history.d.ts.map +1 -0
  51. package/dist/utils/history.js.map +1 -0
  52. package/dist/utils/swaps.d.ts +81 -0
  53. package/dist/utils/swaps.d.ts.map +1 -0
  54. package/dist/utils/swaps.js +240 -0
  55. package/dist/utils/swaps.js.map +1 -0
  56. package/dist/{transaction-type.d.ts → utils/transaction-type.d.ts} +1 -1
  57. package/dist/utils/transaction-type.d.ts.map +1 -0
  58. package/dist/{transaction-type.js → utils/transaction-type.js} +1 -1
  59. package/dist/utils/transaction-type.js.map +1 -0
  60. package/dist/{utils.d.ts → utils/utils.d.ts} +13 -3
  61. package/dist/utils/utils.d.ts.map +1 -0
  62. package/dist/{utils.js → utils/utils.js} +21 -5
  63. package/dist/utils/utils.js.map +1 -0
  64. package/dist/{validation.d.ts → utils/validation.d.ts} +1 -1
  65. package/dist/utils/validation.d.ts.map +1 -0
  66. package/dist/{validation.js → utils/validation.js} +90 -7
  67. package/dist/utils/validation.js.map +1 -0
  68. package/package.json +12 -9
  69. package/dist/EtherscanRemoteTransactionSource.d.ts.map +0 -1
  70. package/dist/EtherscanRemoteTransactionSource.js.map +0 -1
  71. package/dist/IncomingTransactionHelper.d.ts.map +0 -1
  72. package/dist/IncomingTransactionHelper.js.map +0 -1
  73. package/dist/PendingTransactionTracker.d.ts +0 -18
  74. package/dist/PendingTransactionTracker.d.ts.map +0 -1
  75. package/dist/PendingTransactionTracker.js +0 -144
  76. package/dist/PendingTransactionTracker.js.map +0 -1
  77. package/dist/etherscan.d.ts.map +0 -1
  78. package/dist/etherscan.js.map +0 -1
  79. package/dist/external-transactions.d.ts.map +0 -1
  80. package/dist/external-transactions.js.map +0 -1
  81. package/dist/history.d.ts.map +0 -1
  82. package/dist/history.js.map +0 -1
  83. package/dist/transaction-type.d.ts.map +0 -1
  84. package/dist/transaction-type.js.map +0 -1
  85. package/dist/utils.d.ts.map +0 -1
  86. package/dist/utils.js.map +0 -1
  87. package/dist/validation.d.ts.map +0 -1
  88. package/dist/validation.js.map +0 -1
  89. /package/dist/{etherscan.d.ts → utils/etherscan.d.ts} +0 -0
  90. /package/dist/{history.js → utils/history.js} +0 -0
@@ -1,4 +1,4 @@
1
- import type { TransactionMeta } from './types';
1
+ import type { TransactionMeta } from '../types';
2
2
  /**
3
3
  * Validates the external provided transaction meta.
4
4
  *
@@ -0,0 +1 @@
1
+ {"version":3,"file":"external-transactions.d.ts","sourceRoot":"","sources":["../../src/utils/external-transactions.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEhD;;;;;;GAMG;AACH,wBAAgB,oCAAoC,CAClD,eAAe,CAAC,EAAE,eAAe,EACjC,YAAY,CAAC,EAAE,eAAe,EAAE,EAChC,UAAU,CAAC,EAAE,eAAe,EAAE,QAoC/B"}
@@ -3,7 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateConfirmedExternalTransaction = void 0;
4
4
  // These utility functions are exclusively used by `confirmExternalTransaction` method in controller
5
5
  const rpc_errors_1 = require("@metamask/rpc-errors");
6
- const types_1 = require("./types");
6
+ const types_1 = require("../types");
7
7
  /**
8
8
  * Validates the external provided transaction meta.
9
9
  *
@@ -0,0 +1 @@
1
+ {"version":3,"file":"external-transactions.js","sourceRoot":"","sources":["../../src/utils/external-transactions.ts"],"names":[],"mappings":";;;AAAA,oGAAoG;AACpG,qDAAiD;AAEjD,oCAA6C;AAG7C;;;;;;GAMG;AACH,SAAgB,oCAAoC,CAClD,eAAiC,EACjC,YAAgC,EAChC,UAA8B;IAE9B,IAAI,CAAC,eAAe,IAAI,CAAC,eAAe,CAAC,QAAQ,EAAE;QACjD,MAAM,sBAAS,CAAC,aAAa,CAC3B,4DAA4D,CAC7D,CAAC;KACH;IAED,IAAI,eAAe,CAAC,MAAM,KAAK,yBAAiB,CAAC,SAAS,EAAE;QAC1D,MAAM,sBAAS,CAAC,aAAa,CAC3B,mDAAmD,CACpD,CAAC;KACH;IAED,MAAM,eAAe,GAAG,eAAe,CAAC,QAAQ,CAAC,KAAK,CAAC;IACvD,IAAI,UAAU,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE;QACvC,MAAM,qBAAqB,GAAG,UAAU,CAAC,IAAI,CAC3C,CAAC,EAAE,EAAE,EAAE,WAAC,OAAA,CAAA,MAAA,EAAE,CAAC,QAAQ,0CAAE,KAAK,MAAK,eAAe,CAAA,EAAA,CAC/C,CAAC;QACF,IAAI,qBAAqB,EAAE;YACzB,MAAM,sBAAS,CAAC,aAAa,CAC3B,yDAAyD,CAC1D,CAAC;SACH;KACF;IAED,IAAI,YAAY,IAAI,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE;QAC3C,MAAM,uBAAuB,GAAG,YAAY,CAAC,IAAI,CAC/C,CAAC,EAAE,EAAE,EAAE,WAAC,OAAA,CAAA,MAAA,EAAE,CAAC,QAAQ,0CAAE,KAAK,MAAK,eAAe,CAAA,EAAA,CAC/C,CAAC;QACF,IAAI,uBAAuB,EAAE;YAC3B,MAAM,sBAAS,CAAC,aAAa,CAC3B,2DAA2D,CAC5D,CAAC;SACH;KACF;AACH,CAAC;AAvCD,oFAuCC","sourcesContent":["// These utility functions are exclusively used by `confirmExternalTransaction` method in controller\nimport { rpcErrors } from '@metamask/rpc-errors';\n\nimport { TransactionStatus } from '../types';\nimport type { TransactionMeta } from '../types';\n\n/**\n * Validates the external provided transaction meta.\n *\n * @param transactionMeta - The transaction meta to validate.\n * @param confirmedTxs - The confirmed transactions in controller state.\n * @param pendingTxs - The submitted transactions in controller state.\n */\nexport function validateConfirmedExternalTransaction(\n transactionMeta?: TransactionMeta,\n confirmedTxs?: TransactionMeta[],\n pendingTxs?: TransactionMeta[],\n) {\n if (!transactionMeta || !transactionMeta.txParams) {\n throw rpcErrors.invalidParams(\n '\"transactionMeta\" or \"transactionMeta.txParams\" is missing',\n );\n }\n\n if (transactionMeta.status !== TransactionStatus.confirmed) {\n throw rpcErrors.invalidParams(\n 'External transaction status should be \"confirmed\"',\n );\n }\n\n const externalTxNonce = transactionMeta.txParams.nonce;\n if (pendingTxs && pendingTxs.length > 0) {\n const foundPendingTxByNonce = pendingTxs.find(\n (tx) => tx.txParams?.nonce === externalTxNonce,\n );\n if (foundPendingTxByNonce) {\n throw rpcErrors.invalidParams(\n 'External transaction nonce should not be in pending txs',\n );\n }\n }\n\n if (confirmedTxs && confirmedTxs.length > 0) {\n const foundConfirmedTxByNonce = confirmedTxs.find(\n (tx) => tx.txParams?.nonce === externalTxNonce,\n );\n if (foundConfirmedTxByNonce) {\n throw rpcErrors.invalidParams(\n 'External transaction nonce should not be in confirmed txs',\n );\n }\n }\n}\n"]}
@@ -0,0 +1,31 @@
1
+ import type EthQuery from '@metamask/eth-query';
2
+ import type { GasFeeState } from '@metamask/gas-fee-controller';
3
+ import type { SavedGasFees, TransactionParams, TransactionMeta } from '../types';
4
+ export declare type UpdateGasFeesRequest = {
5
+ eip1559: boolean;
6
+ ethQuery: EthQuery;
7
+ getSavedGasFees: () => SavedGasFees | undefined;
8
+ getGasFeeEstimates: () => Promise<GasFeeState>;
9
+ txMeta: TransactionMeta;
10
+ };
11
+ export declare type GetGasFeeRequest = UpdateGasFeesRequest & {
12
+ savedGasFees?: SavedGasFees;
13
+ initialParams: TransactionParams;
14
+ suggestedGasFees: Awaited<ReturnType<typeof getSuggestedGasFees>>;
15
+ };
16
+ export declare function updateGasFees(request: UpdateGasFeesRequest): Promise<void>;
17
+ declare function getSuggestedGasFees(request: UpdateGasFeesRequest): Promise<{
18
+ maxFeePerGas?: undefined;
19
+ maxPriorityFeePerGas?: undefined;
20
+ gasPrice?: undefined;
21
+ } | {
22
+ maxFeePerGas: `0x${string}`;
23
+ maxPriorityFeePerGas: `0x${string}`;
24
+ gasPrice?: undefined;
25
+ } | {
26
+ gasPrice: string | undefined;
27
+ maxFeePerGas?: undefined;
28
+ maxPriorityFeePerGas?: undefined;
29
+ }>;
30
+ export {};
31
+ //# sourceMappingURL=gas-fees.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gas-fees.d.ts","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAChD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAMhE,OAAO,KAAK,EACV,YAAY,EACZ,iBAAiB,EACjB,eAAe,EAEhB,MAAM,UAAU,CAAC;AAIlB,oBAAY,oBAAoB,GAAG;IACjC,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,QAAQ,CAAC;IACnB,eAAe,EAAE,MAAM,YAAY,GAAG,SAAS,CAAC;IAChD,kBAAkB,EAAE,MAAM,OAAO,CAAC,WAAW,CAAC,CAAC;IAC/C,MAAM,EAAE,eAAe,CAAC;CACzB,CAAC;AAEF,oBAAY,gBAAgB,GAAG,oBAAoB,GAAG;IACpD,YAAY,CAAC,EAAE,YAAY,CAAC;IAC5B,aAAa,EAAE,iBAAiB,CAAC;IACjC,gBAAgB,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,mBAAmB,CAAC,CAAC,CAAC;CACnE,CAAC;AAIF,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,iBA4ChE;AA6KD,iBAAe,mBAAmB,CAAC,OAAO,EAAE,oBAAoB;;;;;;;;;;;;GAwD/D"}
@@ -0,0 +1,212 @@
1
+ "use strict";
2
+ /* eslint-disable jsdoc/require-jsdoc */
3
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
+ return new (P || (P = Promise))(function (resolve, reject) {
6
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10
+ });
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.updateGasFees = void 0;
14
+ const controller_utils_1 = require("@metamask/controller-utils");
15
+ const gas_fee_controller_1 = require("@metamask/gas-fee-controller");
16
+ const utils_1 = require("@metamask/utils");
17
+ const ethereumjs_util_1 = require("ethereumjs-util");
18
+ const logger_1 = require("../logger");
19
+ const types_1 = require("../types");
20
+ const swaps_1 = require("./swaps");
21
+ const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'gas-fees');
22
+ function updateGasFees(request) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ const { txMeta } = request;
25
+ const initialParams = Object.assign({}, txMeta.txParams);
26
+ const isSwap = swaps_1.SWAP_TRANSACTION_TYPES.includes(txMeta.type);
27
+ const savedGasFees = isSwap ? undefined : request.getSavedGasFees();
28
+ const suggestedGasFees = yield getSuggestedGasFees(request);
29
+ log('Suggested gas fees', suggestedGasFees);
30
+ const getGasFeeRequest = Object.assign(Object.assign({}, request), { savedGasFees,
31
+ initialParams,
32
+ suggestedGasFees });
33
+ txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);
34
+ txMeta.txParams.maxPriorityFeePerGas =
35
+ getMaxPriorityFeePerGas(getGasFeeRequest);
36
+ txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);
37
+ txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);
38
+ log('Updated gas fee properties', {
39
+ maxFeePerGas: txMeta.txParams.maxFeePerGas,
40
+ maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,
41
+ gasPrice: txMeta.txParams.gasPrice,
42
+ });
43
+ if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {
44
+ delete txMeta.txParams.gasPrice;
45
+ }
46
+ if (txMeta.txParams.gasPrice) {
47
+ delete txMeta.txParams.maxFeePerGas;
48
+ delete txMeta.txParams.maxPriorityFeePerGas;
49
+ }
50
+ updateDefaultGasEstimates(txMeta);
51
+ });
52
+ }
53
+ exports.updateGasFees = updateGasFees;
54
+ function getMaxFeePerGas(request) {
55
+ const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;
56
+ if (!eip1559) {
57
+ return undefined;
58
+ }
59
+ if (savedGasFees) {
60
+ const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee);
61
+ log('Using maxFeePerGas from savedGasFees', maxFeePerGas);
62
+ return maxFeePerGas;
63
+ }
64
+ if (initialParams.maxFeePerGas) {
65
+ log('Using maxFeePerGas from request', initialParams.maxFeePerGas);
66
+ return initialParams.maxFeePerGas;
67
+ }
68
+ if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {
69
+ log('Setting maxFeePerGas to gasPrice from request', initialParams.gasPrice);
70
+ return initialParams.gasPrice;
71
+ }
72
+ if (suggestedGasFees.maxFeePerGas) {
73
+ log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);
74
+ return suggestedGasFees.maxFeePerGas;
75
+ }
76
+ if (suggestedGasFees.gasPrice) {
77
+ log('Setting maxFeePerGas to suggested gasPrice', suggestedGasFees.gasPrice);
78
+ return suggestedGasFees.gasPrice;
79
+ }
80
+ log('maxFeePerGas not set');
81
+ return undefined;
82
+ }
83
+ function getMaxPriorityFeePerGas(request) {
84
+ const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } = request;
85
+ if (!eip1559) {
86
+ return undefined;
87
+ }
88
+ if (savedGasFees) {
89
+ const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);
90
+ log('Using maxPriorityFeePerGas from savedGasFees.priorityFee', maxPriorityFeePerGas);
91
+ return maxPriorityFeePerGas;
92
+ }
93
+ if (initialParams.maxPriorityFeePerGas) {
94
+ log('Using maxPriorityFeePerGas from request', initialParams.maxPriorityFeePerGas);
95
+ return initialParams.maxPriorityFeePerGas;
96
+ }
97
+ if (initialParams.gasPrice && !initialParams.maxFeePerGas) {
98
+ log('Setting maxPriorityFeePerGas to gasPrice from request', initialParams.gasPrice);
99
+ return initialParams.gasPrice;
100
+ }
101
+ if (suggestedGasFees.maxPriorityFeePerGas) {
102
+ log('Using suggested maxPriorityFeePerGas', suggestedGasFees.maxPriorityFeePerGas);
103
+ return suggestedGasFees.maxPriorityFeePerGas;
104
+ }
105
+ if (txMeta.txParams.maxFeePerGas) {
106
+ log('Setting maxPriorityFeePerGas to maxFeePerGas', txMeta.txParams.maxFeePerGas);
107
+ return txMeta.txParams.maxFeePerGas;
108
+ }
109
+ log('maxPriorityFeePerGas not set');
110
+ return undefined;
111
+ }
112
+ function getGasPrice(request) {
113
+ const { eip1559, initialParams, suggestedGasFees } = request;
114
+ if (eip1559) {
115
+ return undefined;
116
+ }
117
+ if (initialParams.gasPrice) {
118
+ log('Using gasPrice from request', initialParams.gasPrice);
119
+ return initialParams.gasPrice;
120
+ }
121
+ if (suggestedGasFees.gasPrice) {
122
+ log('Using suggested gasPrice', suggestedGasFees.gasPrice);
123
+ return suggestedGasFees.gasPrice;
124
+ }
125
+ log('gasPrice not set');
126
+ return undefined;
127
+ }
128
+ function getUserFeeLevel(request) {
129
+ const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } = request;
130
+ if (!eip1559) {
131
+ return undefined;
132
+ }
133
+ if (savedGasFees) {
134
+ return types_1.UserFeeLevel.CUSTOM;
135
+ }
136
+ if (!initialParams.maxFeePerGas &&
137
+ !initialParams.maxPriorityFeePerGas &&
138
+ initialParams.gasPrice) {
139
+ return txMeta.origin === controller_utils_1.ORIGIN_METAMASK
140
+ ? types_1.UserFeeLevel.CUSTOM
141
+ : types_1.UserFeeLevel.DAPP_SUGGESTED;
142
+ }
143
+ if (!initialParams.maxFeePerGas &&
144
+ !initialParams.maxPriorityFeePerGas &&
145
+ suggestedGasFees.maxFeePerGas &&
146
+ suggestedGasFees.maxPriorityFeePerGas) {
147
+ return types_1.UserFeeLevel.MEDIUM;
148
+ }
149
+ if (txMeta.origin === controller_utils_1.ORIGIN_METAMASK) {
150
+ return types_1.UserFeeLevel.MEDIUM;
151
+ }
152
+ return types_1.UserFeeLevel.DAPP_SUGGESTED;
153
+ }
154
+ function updateDefaultGasEstimates(txMeta) {
155
+ if (!txMeta.defaultGasEstimates) {
156
+ txMeta.defaultGasEstimates = {};
157
+ }
158
+ txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;
159
+ txMeta.defaultGasEstimates.maxPriorityFeePerGas =
160
+ txMeta.txParams.maxPriorityFeePerGas;
161
+ txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;
162
+ txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;
163
+ }
164
+ function getSuggestedGasFees(request) {
165
+ return __awaiter(this, void 0, void 0, function* () {
166
+ const { eip1559, ethQuery, getGasFeeEstimates, txMeta } = request;
167
+ if ((!eip1559 && txMeta.txParams.gasPrice) ||
168
+ (eip1559 &&
169
+ txMeta.txParams.maxFeePerGas &&
170
+ txMeta.txParams.maxPriorityFeePerGas)) {
171
+ return {};
172
+ }
173
+ try {
174
+ const { gasFeeEstimates, gasEstimateType } = yield getGasFeeEstimates();
175
+ if (eip1559 && gasEstimateType === gas_fee_controller_1.GAS_ESTIMATE_TYPES.FEE_MARKET) {
176
+ const { medium: { suggestedMaxPriorityFeePerGas, suggestedMaxFeePerGas } = {}, } = gasFeeEstimates;
177
+ if (suggestedMaxPriorityFeePerGas && suggestedMaxFeePerGas) {
178
+ return {
179
+ maxFeePerGas: gweiDecimalToWeiHex(suggestedMaxFeePerGas),
180
+ maxPriorityFeePerGas: gweiDecimalToWeiHex(suggestedMaxPriorityFeePerGas),
181
+ };
182
+ }
183
+ }
184
+ if (gasEstimateType === gas_fee_controller_1.GAS_ESTIMATE_TYPES.LEGACY) {
185
+ // The LEGACY type includes low, medium and high estimates of
186
+ // gas price values.
187
+ return {
188
+ gasPrice: gweiDecimalToWeiHex(gasFeeEstimates.medium),
189
+ };
190
+ }
191
+ if (gasEstimateType === gas_fee_controller_1.GAS_ESTIMATE_TYPES.ETH_GASPRICE) {
192
+ // The ETH_GASPRICE type just includes a single gas price property,
193
+ // which we can assume was retrieved from eth_gasPrice
194
+ return {
195
+ gasPrice: gweiDecimalToWeiHex(gasFeeEstimates.gasPrice),
196
+ };
197
+ }
198
+ }
199
+ catch (error) {
200
+ log('Failed to get suggested gas fees', error);
201
+ }
202
+ const gasPriceDecimal = (yield (0, controller_utils_1.query)(ethQuery, 'gasPrice'));
203
+ const gasPrice = gasPriceDecimal
204
+ ? (0, ethereumjs_util_1.addHexPrefix)(gasPriceDecimal.toString(16))
205
+ : undefined;
206
+ return { gasPrice };
207
+ });
208
+ }
209
+ function gweiDecimalToWeiHex(value) {
210
+ return (0, controller_utils_1.toHex)((0, controller_utils_1.gweiDecToWEIBN)(value));
211
+ }
212
+ //# sourceMappingURL=gas-fees.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gas-fees.js","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":";AAAA,wCAAwC;;;;;;;;;;;;AAExC,iEAKoC;AAGpC,qEAAkE;AA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,mBAAmB,CAAC,qBAAqB,CAAC;wBACxD,oBAAoB,EAAE,mBAAmB,CACvC,6BAA6B,CAC9B;qBACF,CAAC;iBACH;aACF;YAED,IAAI,eAAe,KAAK,uCAAkB,CAAC,MAAM,EAAE;gBACjD,6DAA6D;gBAC7D,oBAAoB;gBACpB,OAAO;oBACL,QAAQ,EAAE,mBAAmB,CAAC,eAAe,CAAC,MAAM,CAAC;iBACtD,CAAC;aACH;YAED,IAAI,eAAe,KAAK,uCAAkB,CAAC,YAAY,EAAE;gBACvD,mEAAmE;gBACnE,sDAAsD;gBACtD,OAAO;oBACL,QAAQ,EAAE,mBAAmB,CAAC,eAAe,CAAC,QAAQ,CAAC;iBACxD,CAAC;aACH;SACF;QAAC,OAAO,KAAK,EAAE;YACd,GAAG,CAAC,kCAAkC,EAAE,KAAK,CAAC,CAAC;SAChD;QAED,MAAM,eAAe,GAAG,CAAC,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,UAAU,CAAC,CAAW,CAAC;QAEtE,MAAM,QAAQ,GAAG,eAAe;YAC9B,CAAC,CAAC,IAAA,8BAAY,EAAC,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;YAC5C,CAAC,CAAC,SAAS,CAAC;QAEd,OAAO,EAAE,QAAQ,EAAE,CAAC;IACtB,CAAC;CAAA;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,IAAA,wBAAK,EAAC,IAAA,iCAAc,EAAC,KAAK,CAAC,CAAC,CAAC;AACtC,CAAC","sourcesContent":["/* eslint-disable jsdoc/require-jsdoc */\n\nimport {\n ORIGIN_METAMASK,\n gweiDecToWEIBN,\n query,\n toHex,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type { GasFeeState } from '@metamask/gas-fee-controller';\nimport { GAS_ESTIMATE_TYPES } from '@metamask/gas-fee-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport { addHexPrefix } from 'ethereumjs-util';\n\nimport { projectLogger } from '../logger';\nimport type {\n SavedGasFees,\n TransactionParams,\n TransactionMeta,\n TransactionType,\n} from '../types';\nimport { UserFeeLevel } from '../types';\nimport { SWAP_TRANSACTION_TYPES } from './swaps';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n getSavedGasFees: () => SavedGasFees | undefined;\n getGasFeeEstimates: () => Promise<GasFeeState>;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\n savedGasFees?: SavedGasFees;\n initialParams: TransactionParams;\n suggestedGasFees: Awaited<ReturnType<typeof getSuggestedGasFees>>;\n};\n\nconst log = createModuleLogger(projectLogger, 'gas-fees');\n\nexport async function updateGasFees(request: UpdateGasFeesRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const isSwap = SWAP_TRANSACTION_TYPES.includes(\n txMeta.type as TransactionType,\n );\n const savedGasFees = isSwap ? undefined : request.getSavedGasFees();\n\n const suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest = {\n ...request,\n savedGasFees,\n initialParams,\n suggestedGasFees,\n };\n\n txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.maxPriorityFeePerGas =\n getMaxPriorityFeePerGas(getGasFeeRequest);\n\n txMeta.txParams.gasPrice = getGasPrice(getGasFeeRequest);\n txMeta.userFeeLevel = getUserFeeLevel(getGasFeeRequest);\n\n log('Updated gas fee properties', {\n maxFeePerGas: txMeta.txParams.maxFeePerGas,\n maxPriorityFeePerGas: txMeta.txParams.maxPriorityFeePerGas,\n gasPrice: txMeta.txParams.gasPrice,\n });\n\n if (txMeta.txParams.maxFeePerGas || txMeta.txParams.maxPriorityFeePerGas) {\n delete txMeta.txParams.gasPrice;\n }\n\n if (txMeta.txParams.gasPrice) {\n delete txMeta.txParams.maxFeePerGas;\n delete txMeta.txParams.maxPriorityFeePerGas;\n }\n\n updateDefaultGasEstimates(txMeta);\n}\n\nfunction getMaxFeePerGas(request: GetGasFeeRequest): string | undefined {\n const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee as string);\n log('Using maxFeePerGas from savedGasFees', maxFeePerGas);\n return maxFeePerGas;\n }\n\n if (initialParams.maxFeePerGas) {\n log('Using maxFeePerGas from request', initialParams.maxFeePerGas);\n return initialParams.maxFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxPriorityFeePerGas) {\n log(\n 'Setting maxFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxFeePerGas) {\n log('Using suggested maxFeePerGas', suggestedGasFees.maxFeePerGas);\n return suggestedGasFees.maxFeePerGas;\n }\n\n if (suggestedGasFees.gasPrice) {\n log(\n 'Setting maxFeePerGas to suggested gasPrice',\n suggestedGasFees.gasPrice,\n );\n return suggestedGasFees.gasPrice;\n }\n\n log('maxFeePerGas not set');\n return undefined;\n}\n\nfunction getMaxPriorityFeePerGas(\n request: GetGasFeeRequest,\n): string | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);\n log(\n 'Using maxPriorityFeePerGas from savedGasFees.priorityFee',\n maxPriorityFeePerGas,\n );\n return maxPriorityFeePerGas;\n }\n\n if (initialParams.maxPriorityFeePerGas) {\n log(\n 'Using maxPriorityFeePerGas from request',\n initialParams.maxPriorityFeePerGas,\n );\n return initialParams.maxPriorityFeePerGas;\n }\n\n if (initialParams.gasPrice && !initialParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to gasPrice from request',\n initialParams.gasPrice,\n );\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.maxPriorityFeePerGas) {\n log(\n 'Using suggested maxPriorityFeePerGas',\n suggestedGasFees.maxPriorityFeePerGas,\n );\n return suggestedGasFees.maxPriorityFeePerGas;\n }\n\n if (txMeta.txParams.maxFeePerGas) {\n log(\n 'Setting maxPriorityFeePerGas to maxFeePerGas',\n txMeta.txParams.maxFeePerGas,\n );\n return txMeta.txParams.maxFeePerGas;\n }\n\n log('maxPriorityFeePerGas not set');\n return undefined;\n}\n\nfunction getGasPrice(request: GetGasFeeRequest): string | undefined {\n const { eip1559, initialParams, suggestedGasFees } = request;\n\n if (eip1559) {\n return undefined;\n }\n\n if (initialParams.gasPrice) {\n log('Using gasPrice from request', initialParams.gasPrice);\n return initialParams.gasPrice;\n }\n\n if (suggestedGasFees.gasPrice) {\n log('Using suggested gasPrice', suggestedGasFees.gasPrice);\n return suggestedGasFees.gasPrice;\n }\n\n log('gasPrice not set');\n return undefined;\n}\n\nfunction getUserFeeLevel(request: GetGasFeeRequest): UserFeeLevel | undefined {\n const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } =\n request;\n\n if (!eip1559) {\n return undefined;\n }\n\n if (savedGasFees) {\n return UserFeeLevel.CUSTOM;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n initialParams.gasPrice\n ) {\n return txMeta.origin === ORIGIN_METAMASK\n ? UserFeeLevel.CUSTOM\n : UserFeeLevel.DAPP_SUGGESTED;\n }\n\n if (\n !initialParams.maxFeePerGas &&\n !initialParams.maxPriorityFeePerGas &&\n suggestedGasFees.maxFeePerGas &&\n suggestedGasFees.maxPriorityFeePerGas\n ) {\n return UserFeeLevel.MEDIUM;\n }\n\n if (txMeta.origin === ORIGIN_METAMASK) {\n return UserFeeLevel.MEDIUM;\n }\n\n return UserFeeLevel.DAPP_SUGGESTED;\n}\n\nfunction updateDefaultGasEstimates(txMeta: TransactionMeta) {\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.maxFeePerGas = txMeta.txParams.maxFeePerGas;\n\n txMeta.defaultGasEstimates.maxPriorityFeePerGas =\n txMeta.txParams.maxPriorityFeePerGas;\n\n txMeta.defaultGasEstimates.gasPrice = txMeta.txParams.gasPrice;\n txMeta.defaultGasEstimates.estimateType = txMeta.userFeeLevel;\n}\n\nasync function getSuggestedGasFees(request: UpdateGasFeesRequest) {\n const { eip1559, ethQuery, getGasFeeEstimates, txMeta } = request;\n\n if (\n (!eip1559 && txMeta.txParams.gasPrice) ||\n (eip1559 &&\n txMeta.txParams.maxFeePerGas &&\n txMeta.txParams.maxPriorityFeePerGas)\n ) {\n return {};\n }\n\n try {\n const { gasFeeEstimates, gasEstimateType } = await getGasFeeEstimates();\n\n if (eip1559 && gasEstimateType === GAS_ESTIMATE_TYPES.FEE_MARKET) {\n const {\n medium: { suggestedMaxPriorityFeePerGas, suggestedMaxFeePerGas } = {},\n } = gasFeeEstimates;\n\n if (suggestedMaxPriorityFeePerGas && suggestedMaxFeePerGas) {\n return {\n maxFeePerGas: gweiDecimalToWeiHex(suggestedMaxFeePerGas),\n maxPriorityFeePerGas: gweiDecimalToWeiHex(\n suggestedMaxPriorityFeePerGas,\n ),\n };\n }\n }\n\n if (gasEstimateType === GAS_ESTIMATE_TYPES.LEGACY) {\n // The LEGACY type includes low, medium and high estimates of\n // gas price values.\n return {\n gasPrice: gweiDecimalToWeiHex(gasFeeEstimates.medium),\n };\n }\n\n if (gasEstimateType === GAS_ESTIMATE_TYPES.ETH_GASPRICE) {\n // The ETH_GASPRICE type just includes a single gas price property,\n // which we can assume was retrieved from eth_gasPrice\n return {\n gasPrice: gweiDecimalToWeiHex(gasFeeEstimates.gasPrice),\n };\n }\n } catch (error) {\n log('Failed to get suggested gas fees', error);\n }\n\n const gasPriceDecimal = (await query(ethQuery, 'gasPrice')) as number;\n\n const gasPrice = gasPriceDecimal\n ? addHexPrefix(gasPriceDecimal.toString(16))\n : undefined;\n\n return { gasPrice };\n}\n\nfunction gweiDecimalToWeiHex(value: string) {\n return toHex(gweiDecToWEIBN(value));\n}\n"]}
@@ -0,0 +1,27 @@
1
+ /// <reference types="debug" />
2
+ import type EthQuery from '@metamask/eth-query';
3
+ import type { ProviderConfig } from '@metamask/network-controller';
4
+ import type { TransactionMeta, TransactionParams } from '../types';
5
+ export declare type UpdateGasRequest = {
6
+ ethQuery: EthQuery;
7
+ providerConfig: ProviderConfig;
8
+ txMeta: TransactionMeta;
9
+ };
10
+ export declare const log: import("debug").Debugger;
11
+ export declare const FIXED_GAS = "0x5208";
12
+ export declare const DEFAULT_GAS_MULTIPLIER = 1.5;
13
+ export declare function updateGas(request: UpdateGasRequest): Promise<void>;
14
+ export declare function estimateGas(txParams: TransactionParams, ethQuery: EthQuery): Promise<{
15
+ blockGasLimit: string;
16
+ estimatedGas: string;
17
+ simulationFails: {
18
+ reason: any;
19
+ errorKey: any;
20
+ debug: {
21
+ blockNumber: string;
22
+ blockGasLimit: string;
23
+ };
24
+ } | undefined;
25
+ }>;
26
+ export declare function addGasBuffer(estimatedGas: string, blockGasLimit: string, multiplier: number): string;
27
+ //# sourceMappingURL=gas.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gas.d.ts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";AASA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAChD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAKnE,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAEnE,oBAAY,gBAAgB,GAAG;IAC7B,QAAQ,EAAE,QAAQ,CAAC;IACnB,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,EAAE,eAAe,CAAC;CACzB,CAAC;AAEF,eAAO,MAAM,GAAG,0BAA2C,CAAC;AAE5D,eAAO,MAAM,SAAS,WAAW,CAAC;AAClC,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAE1C,wBAAsB,SAAS,CAAC,OAAO,EAAE,gBAAgB,iBAkBxD;AAED,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,iBAAiB,EAC3B,QAAQ,EAAE,QAAQ;;;;;;;;;;;GAsCnB;AAED,wBAAgB,YAAY,CAC1B,YAAY,EAAE,MAAM,EACpB,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,MAAM,UAqBnB"}
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ /* eslint-disable jsdoc/require-jsdoc */
3
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
+ return new (P || (P = Promise))(function (resolve, reject) {
6
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
10
+ });
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.addGasBuffer = exports.estimateGas = exports.updateGas = exports.DEFAULT_GAS_MULTIPLIER = exports.FIXED_GAS = exports.log = void 0;
14
+ const controller_utils_1 = require("@metamask/controller-utils");
15
+ const utils_1 = require("@metamask/utils");
16
+ const ethereumjs_util_1 = require("ethereumjs-util");
17
+ const logger_1 = require("../logger");
18
+ exports.log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'gas');
19
+ exports.FIXED_GAS = '0x5208';
20
+ exports.DEFAULT_GAS_MULTIPLIER = 1.5;
21
+ function updateGas(request) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ const { txMeta } = request;
24
+ const initialParams = Object.assign({}, txMeta.txParams);
25
+ const [gas, simulationFails] = yield getGas(request);
26
+ txMeta.txParams.gas = gas;
27
+ txMeta.simulationFails = simulationFails;
28
+ if (!initialParams.gas) {
29
+ txMeta.originalGasEstimate = txMeta.txParams.gas;
30
+ }
31
+ if (!txMeta.defaultGasEstimates) {
32
+ txMeta.defaultGasEstimates = {};
33
+ }
34
+ txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;
35
+ });
36
+ }
37
+ exports.updateGas = updateGas;
38
+ function estimateGas(txParams, ethQuery) {
39
+ return __awaiter(this, void 0, void 0, function* () {
40
+ const request = Object.assign({}, txParams);
41
+ const { data, value } = request;
42
+ const { gasLimit: gasLimitHex, number: blockNumber } = yield getLatestBlock(ethQuery);
43
+ const gasLimitBN = (0, controller_utils_1.hexToBN)(gasLimitHex);
44
+ request.data = data ? (0, ethereumjs_util_1.addHexPrefix)(data) : data;
45
+ request.gas = (0, controller_utils_1.BNToHex)((0, controller_utils_1.fractionBN)(gasLimitBN, 19, 20));
46
+ request.value = value || '0x0';
47
+ let estimatedGas = request.gas;
48
+ let simulationFails;
49
+ try {
50
+ estimatedGas = yield (0, controller_utils_1.query)(ethQuery, 'estimateGas', [request]);
51
+ }
52
+ catch (error) {
53
+ simulationFails = {
54
+ reason: error.message,
55
+ errorKey: error.errorKey,
56
+ debug: {
57
+ blockNumber,
58
+ blockGasLimit: gasLimitHex,
59
+ },
60
+ };
61
+ (0, exports.log)('Estimation failed', Object.assign(Object.assign({}, simulationFails), { fallback: estimateGas }));
62
+ }
63
+ return {
64
+ blockGasLimit: gasLimitHex,
65
+ estimatedGas,
66
+ simulationFails,
67
+ };
68
+ });
69
+ }
70
+ exports.estimateGas = estimateGas;
71
+ function addGasBuffer(estimatedGas, blockGasLimit, multiplier) {
72
+ const estimatedGasBN = (0, controller_utils_1.hexToBN)(estimatedGas);
73
+ const maxGasBN = (0, controller_utils_1.hexToBN)(blockGasLimit).muln(0.9);
74
+ const paddedGasBN = estimatedGasBN.muln(multiplier);
75
+ if (estimatedGasBN.gt(maxGasBN)) {
76
+ const estimatedGasHex = (0, ethereumjs_util_1.addHexPrefix)(estimatedGas);
77
+ (0, exports.log)('Using estimated value', estimatedGasHex);
78
+ return estimatedGasHex;
79
+ }
80
+ if (paddedGasBN.lt(maxGasBN)) {
81
+ const paddedHex = (0, ethereumjs_util_1.addHexPrefix)((0, controller_utils_1.BNToHex)(paddedGasBN));
82
+ (0, exports.log)('Using padded estimate', paddedHex, multiplier);
83
+ return paddedHex;
84
+ }
85
+ const maxHex = (0, ethereumjs_util_1.addHexPrefix)((0, controller_utils_1.BNToHex)(maxGasBN));
86
+ (0, exports.log)('Using 90% of block gas limit', maxHex);
87
+ return maxHex;
88
+ }
89
+ exports.addGasBuffer = addGasBuffer;
90
+ function getGas(request) {
91
+ return __awaiter(this, void 0, void 0, function* () {
92
+ const { providerConfig, txMeta } = request;
93
+ if (txMeta.txParams.gas) {
94
+ (0, exports.log)('Using value from request', txMeta.txParams.gas);
95
+ return [txMeta.txParams.gas];
96
+ }
97
+ if (yield requiresFixedGas(request)) {
98
+ (0, exports.log)('Using fixed value', exports.FIXED_GAS);
99
+ return [exports.FIXED_GAS];
100
+ }
101
+ const { blockGasLimit, estimatedGas, simulationFails } = yield estimateGas(txMeta.txParams, request.ethQuery);
102
+ if (providerConfig.type === controller_utils_1.NetworkType.rpc) {
103
+ (0, exports.log)('Using original estimate as custom network');
104
+ return [estimatedGas, simulationFails];
105
+ }
106
+ const bufferedGas = addGasBuffer(estimatedGas, blockGasLimit, exports.DEFAULT_GAS_MULTIPLIER);
107
+ return [bufferedGas, simulationFails];
108
+ });
109
+ }
110
+ function requiresFixedGas({ ethQuery, txMeta, providerConfig, }) {
111
+ return __awaiter(this, void 0, void 0, function* () {
112
+ const isCustomNetwork = providerConfig.type === controller_utils_1.NetworkType.rpc;
113
+ const { txParams: { to, data }, } = txMeta;
114
+ if (isCustomNetwork) {
115
+ return false;
116
+ }
117
+ if (!to) {
118
+ return true;
119
+ }
120
+ const code = yield getCode(ethQuery, to);
121
+ return !data && (!code || code === '0x');
122
+ });
123
+ }
124
+ function getCode(ethQuery, address) {
125
+ return __awaiter(this, void 0, void 0, function* () {
126
+ return yield (0, controller_utils_1.query)(ethQuery, 'getCode', [address]);
127
+ });
128
+ }
129
+ function getLatestBlock(ethQuery) {
130
+ return __awaiter(this, void 0, void 0, function* () {
131
+ return yield (0, controller_utils_1.query)(ethQuery, 'getBlockByNumber', ['latest', false]);
132
+ });
133
+ }
134
+ //# sourceMappingURL=gas.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"gas.js","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";AAAA,wCAAwC;;;;;;;;;;;;AAExC,iEAMoC;AAGpC,2CAAqD;AACrD,qDAA+C;AAE/C,sCAA0C;AAS7B,QAAA,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,KAAK,CAAC,CAAC;AAE/C,QAAA,SAAS,GAAG,QAAQ,CAAC;AACrB,QAAA,sBAAsB,GAAG,GAAG,CAAC;AAE1C,SAAsB,SAAS,CAAC,OAAyB;;QACvD,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QAC3B,MAAM,aAAa,qBAAQ,MAAM,CAAC,QAAQ,CAAE,CAAC;QAE7C,MAAM,CAAC,GAAG,EAAE,eAAe,CAAC,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,CAAC;QAErD,MAAM,CAAC,QAAQ,CAAC,GAAG,GAAG,GAAG,CAAC;QAC1B,MAAM,CAAC,eAAe,GAAG,eAAe,CAAC;QAEzC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE;YACtB,MAAM,CAAC,mBAAmB,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;SAClD;QAED,IAAI,CAAC,MAAM,CAAC,mBAAmB,EAAE;YAC/B,MAAM,CAAC,mBAAmB,GAAG,EAAE,CAAC;SACjC;QAED,MAAM,CAAC,mBAAmB,CAAC,GAAG,GAAG,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC;IACvD,CAAC;CAAA;AAlBD,8BAkBC;AAED,SAAsB,WAAW,CAC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IAAA,wBAAK,EAAC,QAAQ,EAAE,kBAAkB,EAAE,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAC;IACtE,CAAC;CAAA","sourcesContent":["/* eslint-disable jsdoc/require-jsdoc */\n\nimport {\n BNToHex,\n NetworkType,\n fractionBN,\n hexToBN,\n query,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type { ProviderConfig } from '@metamask/network-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport { addHexPrefix } from 'ethereumjs-util';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionMeta, TransactionParams } from '../types';\n\nexport type UpdateGasRequest = {\n ethQuery: EthQuery;\n providerConfig: ProviderConfig;\n txMeta: TransactionMeta;\n};\n\nexport const log = createModuleLogger(projectLogger, 'gas');\n\nexport const FIXED_GAS = '0x5208';\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\n\nexport async function updateGas(request: UpdateGasRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const [gas, simulationFails] = await getGas(request);\n\n txMeta.txParams.gas = gas;\n txMeta.simulationFails = simulationFails;\n\n if (!initialParams.gas) {\n txMeta.originalGasEstimate = txMeta.txParams.gas;\n }\n\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;\n}\n\nexport async function estimateGas(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n) {\n const request = { ...txParams };\n const { data, value } = request;\n\n const { gasLimit: gasLimitHex, number: blockNumber } = await getLatestBlock(\n ethQuery,\n );\n\n const gasLimitBN = hexToBN(gasLimitHex);\n\n request.data = data ? addHexPrefix(data) : data;\n request.gas = BNToHex(fractionBN(gasLimitBN, 19, 20));\n request.value = value || '0x0';\n\n let estimatedGas = request.gas;\n let simulationFails;\n\n try {\n estimatedGas = await query(ethQuery, 'estimateGas', [request]);\n } catch (error: any) {\n simulationFails = {\n reason: error.message,\n errorKey: error.errorKey,\n debug: {\n blockNumber,\n blockGasLimit: gasLimitHex,\n },\n };\n\n log('Estimation failed', { ...simulationFails, fallback: estimateGas });\n }\n\n return {\n blockGasLimit: gasLimitHex,\n estimatedGas,\n simulationFails,\n };\n}\n\nexport function addGasBuffer(\n estimatedGas: string,\n blockGasLimit: string,\n multiplier: number,\n) {\n const estimatedGasBN = hexToBN(estimatedGas);\n const maxGasBN = hexToBN(blockGasLimit).muln(0.9);\n const paddedGasBN = estimatedGasBN.muln(multiplier);\n\n if (estimatedGasBN.gt(maxGasBN)) {\n const estimatedGasHex = addHexPrefix(estimatedGas);\n log('Using estimated value', estimatedGasHex);\n return estimatedGasHex;\n }\n\n if (paddedGasBN.lt(maxGasBN)) {\n const paddedHex = addHexPrefix(BNToHex(paddedGasBN));\n log('Using padded estimate', paddedHex, multiplier);\n return paddedHex;\n }\n\n const maxHex = addHexPrefix(BNToHex(maxGasBN));\n log('Using 90% of block gas limit', maxHex);\n return maxHex;\n}\n\nasync function getGas(\n request: UpdateGasRequest,\n): Promise<[string, TransactionMeta['simulationFails']?]> {\n const { providerConfig, txMeta } = request;\n\n if (txMeta.txParams.gas) {\n log('Using value from request', txMeta.txParams.gas);\n return [txMeta.txParams.gas];\n }\n\n if (await requiresFixedGas(request)) {\n log('Using fixed value', FIXED_GAS);\n return [FIXED_GAS];\n }\n\n const { blockGasLimit, estimatedGas, simulationFails } = await estimateGas(\n txMeta.txParams,\n request.ethQuery,\n );\n\n if (providerConfig.type === NetworkType.rpc) {\n log('Using original estimate as custom network');\n return [estimatedGas, simulationFails];\n }\n\n const bufferedGas = addGasBuffer(\n estimatedGas,\n blockGasLimit,\n DEFAULT_GAS_MULTIPLIER,\n );\n\n return [bufferedGas, simulationFails];\n}\n\nasync function requiresFixedGas({\n ethQuery,\n txMeta,\n providerConfig,\n}: UpdateGasRequest): Promise<boolean> {\n const isCustomNetwork = providerConfig.type === NetworkType.rpc;\n\n const {\n txParams: { to, data },\n } = txMeta;\n\n if (isCustomNetwork) {\n return false;\n }\n\n if (!to) {\n return true;\n }\n\n const code = await getCode(ethQuery, to);\n\n return !data && (!code || code === '0x');\n}\n\nasync function getCode(\n ethQuery: EthQuery,\n address: string,\n): Promise<string | undefined> {\n return await query(ethQuery, 'getCode', [address]);\n}\n\nasync function getLatestBlock(\n ethQuery: EthQuery,\n): Promise<{ gasLimit: string; number: string }> {\n return await query(ethQuery, 'getBlockByNumber', ['latest', false]);\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { TransactionMeta } from './types';
1
+ import type { TransactionMeta } from '../types';
2
2
  /**
3
3
  * Add initial history snapshot to the provided transactionMeta history.
4
4
  *
@@ -0,0 +1 @@
1
+ {"version":3,"file":"history.d.ts","sourceRoot":"","sources":["../../src/utils/history.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAGV,eAAe,EAChB,MAAM,UAAU,CAAC;AAElB;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,eAAe,EAAE,eAAe,QAGzE;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,eAAe,EAAE,eAAe,EAChC,IAAI,EAAE,MAAM,GACX,IAAI,CAWN"}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"history.js","sourceRoot":"","sources":["../../src/utils/history.ts"],"names":[],"mappings":";;;;;;AAAA,sEAAyC;AACzC,mCAAmC;AAQnC;;;;GAIG;AACH,SAAgB,yBAAyB,CAAC,eAAgC;IACxE,MAAM,QAAQ,GAAG,2BAA2B,CAAC,eAAe,CAAC,CAAC;IAC9D,eAAe,CAAC,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC;AACvC,CAAC;AAHD,8DAGC;AAED;;;;;GAKG;AACH,SAAgB,wBAAwB,CACtC,eAAgC,EAChC,IAAY;;IAEZ,MAAM,YAAY,GAAG,2BAA2B,CAAC,eAAe,CAAC,CAAC;IAClE,MAAM,aAAa,GAAG,aAAa,CACjC,eAAe,CAAC,OAA6B,CAC9C,CAAC;IAEF,MAAM,YAAY,GAAG,oBAAoB,CAAC,aAAa,EAAE,YAAY,EAAE,IAAI,CAAC,CAAC;IAE7E,IAAI,YAAY,CAAC,MAAM,EAAE;QACvB,MAAA,eAAe,aAAf,eAAe,uBAAf,eAAe,CAAE,OAAO,0CAAE,IAAI,CAAC,YAAY,CAAC,CAAC;KAC9C;AACH,CAAC;AAdD,4DAcC;AAED;;;;;;;GAOG;AACH,SAAS,oBAAoB,CAC3B,aAAkB,EAClB,YAA6B,EAC7B,IAAY;IAEZ,MAAM,sBAAsB,GAAG,yBAAU,CAAC,OAAO,CAC/C,aAAa,EACb,YAAY,CACc,CAAC;IAC7B,kFAAkF;IAClF,IAAI,sBAAsB,CAAC,CAAC,CAAC,EAAE;QAC7B,IAAI,IAAI,EAAE;YACR,sBAAsB,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC;SACvC;QACD,sBAAsB,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;KAClD;IACD,OAAO,sBAAsB,CAAC;AAChC,CAAC;AAED;;;;;GAKG;AACH,SAAS,aAAa,CACpB,kBAAsC;IAEtC,MAAM,YAAY,GAAG,IAAA,kBAAS,EAAC,kBAAkB,CAAC,CAAC;IACnD,OAAO,YAAY,CAAC,MAAM,CACxB,CAAC,GAAG,EAAE,KAAU,EAAE,EAAE,CAAC,yBAAU,CAAC,UAAU,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,WAAW,CAChD,CAAC;AACvB,CAAC;AAED;;;;;GAKG;AACH,SAAS,2BAA2B,CAClC,eAAgC;IAEhC,MAAM,QAAQ,qBAAQ,eAAe,CAAE,CAAC;IACxC,OAAO,QAAQ,CAAC,OAAO,CAAC;IACxB,OAAO,IAAA,kBAAS,EAAC,QAAQ,CAAC,CAAC;AAC7B,CAAC","sourcesContent":["import jsonDiffer from 'fast-json-patch';\nimport { cloneDeep } from 'lodash';\n\nimport type {\n TransactionHistory,\n TransactionHistoryEntry,\n TransactionMeta,\n} from '../types';\n\n/**\n * Add initial history snapshot to the provided transactionMeta history.\n *\n * @param transactionMeta - TransactionMeta to add initial history snapshot to.\n */\nexport function addInitialHistorySnapshot(transactionMeta: TransactionMeta) {\n const snapshot = snapshotFromTransactionMeta(transactionMeta);\n transactionMeta.history = [snapshot];\n}\n\n/**\n * Compares and adds history entry to the provided transactionMeta history.\n *\n * @param transactionMeta - TransactionMeta to add history entry to.\n * @param note - Note to add to history entry.\n */\nexport function updateTransactionHistory(\n transactionMeta: TransactionMeta,\n note: string,\n): void {\n const currentState = snapshotFromTransactionMeta(transactionMeta);\n const previousState = replayHistory(\n transactionMeta.history as TransactionHistory,\n );\n\n const historyEntry = generateHistoryEntry(previousState, currentState, note);\n\n if (historyEntry.length) {\n transactionMeta?.history?.push(historyEntry);\n }\n}\n\n/**\n * Generates a history entry from the previous and new transaction metadata.\n *\n * @param previousState - The previous transaction metadata.\n * @param currentState - The new transaction metadata.\n * @param note - A note for the transaction metada update.\n * @returns An array of history operation.\n */\nfunction generateHistoryEntry(\n previousState: any,\n currentState: TransactionMeta,\n note: string,\n): TransactionHistoryEntry {\n const historyOperationsEntry = jsonDiffer.compare(\n previousState,\n currentState,\n ) as TransactionHistoryEntry;\n // Add a note to the first operation, since it breaks if we append it to the entry\n if (historyOperationsEntry[0]) {\n if (note) {\n historyOperationsEntry[0].note = note;\n }\n historyOperationsEntry[0].timestamp = Date.now();\n }\n return historyOperationsEntry;\n}\n\n/**\n * Recovers previous transactionMeta from passed history array.\n *\n * @param transactionHistory - The transaction metadata to replay.\n * @returns The transaction metadata.\n */\nfunction replayHistory(\n transactionHistory: TransactionHistory,\n): TransactionMeta {\n const shortHistory = cloneDeep(transactionHistory);\n return shortHistory.reduce(\n (val, entry: any) => jsonDiffer.applyPatch(val, entry).newDocument,\n ) as TransactionMeta;\n}\n\n/**\n * Clone the transaction meta data without the history property.\n *\n * @param transactionMeta - The transaction metadata to snapshot.\n * @returns A deep clone of transaction metadata without history property.\n */\nfunction snapshotFromTransactionMeta(\n transactionMeta: TransactionMeta,\n): TransactionMeta {\n const snapshot = { ...transactionMeta };\n delete snapshot.history;\n return cloneDeep(snapshot);\n}\n"]}
@@ -0,0 +1,81 @@
1
+ import type EthQuery from '@metamask/eth-query';
2
+ import type { Events, TransactionMeta } from '../types';
3
+ import { TransactionType } from '../types';
4
+ /**
5
+ * Interval in milliseconds between checks of post transaction balance
6
+ */
7
+ export declare const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;
8
+ /**
9
+ * Retry attempts for checking post transaction balance
10
+ */
11
+ export declare const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;
12
+ /**
13
+ * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have
14
+ */
15
+ export declare const DEFAULT_TOKEN_ADDRESS = "0x0000000000000000000000000000000000000000";
16
+ interface SwapsTokenObject {
17
+ /**
18
+ * The name for the network
19
+ */
20
+ name: string;
21
+ /**
22
+ * An address that the metaswap-api recognizes as the default token
23
+ */
24
+ address: string;
25
+ /**
26
+ * Number of digits after decimal point
27
+ */
28
+ decimals: number;
29
+ }
30
+ export declare const SWAPS_CHAINID_DEFAULT_TOKEN_MAP: {
31
+ readonly "0x1": SwapsTokenObject;
32
+ readonly "0x539": SwapsTokenObject;
33
+ readonly "0x38": SwapsTokenObject;
34
+ readonly "0x89": SwapsTokenObject;
35
+ readonly "0x5": SwapsTokenObject;
36
+ readonly "0xa86a": SwapsTokenObject;
37
+ readonly "0xa": SwapsTokenObject;
38
+ readonly "0xa4b1": SwapsTokenObject;
39
+ readonly "0x144": SwapsTokenObject;
40
+ };
41
+ export declare const SWAP_TRANSACTION_TYPES: TransactionType[];
42
+ /**
43
+ * Updates the transaction meta object with the swap information
44
+ *
45
+ * @param transactionMeta - The transaction meta object to update
46
+ * @param transactionType - The type of the transaction
47
+ * @param swaps - The swaps object
48
+ * @param swaps.hasApproveTx - Whether the swap has an approval transaction
49
+ * @param swaps.meta - The swap meta object
50
+ * @param updateSwapsTransactionRequest - Dependency bag
51
+ * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled
52
+ * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction
53
+ * @param updateSwapsTransactionRequest.controllerHubEmitter - Function to emit an event to the controller hub
54
+ */
55
+ export declare function updateSwapsTransaction(transactionMeta: TransactionMeta, transactionType: TransactionType, swaps: {
56
+ hasApproveTx?: boolean;
57
+ meta?: Partial<TransactionMeta>;
58
+ }, { isSwapsDisabled, cancelTransaction, controllerHubEmitter, }: {
59
+ isSwapsDisabled: boolean;
60
+ cancelTransaction: (transactionId: string) => void;
61
+ controllerHubEmitter: <T extends keyof Events>(eventName: T, ...args: Events[T]) => boolean;
62
+ }): Promise<void>;
63
+ /**
64
+ * Attempts to update the post transaction balance of the provided transaction
65
+ *
66
+ * @param transactionMeta - Transaction meta object to update
67
+ * @param updatePostTransactionBalanceRequest - Dependency bag
68
+ * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object
69
+ * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state
70
+ * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function
71
+ */
72
+ export declare function updatePostTransactionBalance(transactionMeta: TransactionMeta, { ethQuery, getTransaction, updateTransaction, }: {
73
+ ethQuery: EthQuery;
74
+ getTransaction: (transactionId: string) => TransactionMeta | undefined;
75
+ updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;
76
+ }): Promise<{
77
+ updatedTransactionMeta: TransactionMeta;
78
+ approvalTransactionMeta?: TransactionMeta;
79
+ }>;
80
+ export {};
81
+ //# sourceMappingURL=swaps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"swaps.d.ts","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,MAAM,qBAAqB,CAAC;AAIhD,OAAO,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AACxD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