@metamask/transaction-controller 16.0.0 → 18.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 (44) hide show
  1. package/CHANGELOG.md +66 -1
  2. package/dist/TransactionController.d.ts +184 -21
  3. package/dist/TransactionController.d.ts.map +1 -1
  4. package/dist/TransactionController.js +635 -121
  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/helpers/PendingTransactionTracker.d.ts +23 -5
  11. package/dist/helpers/PendingTransactionTracker.d.ts.map +1 -1
  12. package/dist/helpers/PendingTransactionTracker.js +263 -108
  13. package/dist/helpers/PendingTransactionTracker.js.map +1 -1
  14. package/dist/logger.d.ts +0 -1
  15. package/dist/logger.d.ts.map +1 -1
  16. package/dist/logger.js +1 -2
  17. package/dist/logger.js.map +1 -1
  18. package/dist/types.d.ts +225 -8
  19. package/dist/types.d.ts.map +1 -1
  20. package/dist/types.js +1 -0
  21. package/dist/types.js.map +1 -1
  22. package/dist/utils/etherscan.d.ts.map +1 -1
  23. package/dist/utils/etherscan.js.map +1 -1
  24. package/dist/utils/gas-fees.d.ts +3 -2
  25. package/dist/utils/gas-fees.d.ts.map +1 -1
  26. package/dist/utils/gas-fees.js +22 -4
  27. package/dist/utils/gas-fees.js.map +1 -1
  28. package/dist/utils/gas.d.ts +2 -0
  29. package/dist/utils/gas.d.ts.map +1 -1
  30. package/dist/utils/gas.js +26 -17
  31. package/dist/utils/gas.js.map +1 -1
  32. package/dist/utils/swaps.d.ts +81 -0
  33. package/dist/utils/swaps.d.ts.map +1 -0
  34. package/dist/utils/swaps.js +253 -0
  35. package/dist/utils/swaps.js.map +1 -0
  36. package/dist/utils/utils.d.ts +21 -3
  37. package/dist/utils/utils.d.ts.map +1 -1
  38. package/dist/utils/utils.js +45 -4
  39. package/dist/utils/utils.js.map +1 -1
  40. package/dist/utils/validation.d.ts +1 -1
  41. package/dist/utils/validation.d.ts.map +1 -1
  42. package/dist/utils/validation.js +90 -7
  43. package/dist/utils/validation.js.map +1 -1
  44. package/package.json +16 -15
@@ -17,14 +17,19 @@ const utils_1 = require("@metamask/utils");
17
17
  const ethereumjs_util_1 = require("ethereumjs-util");
18
18
  const logger_1 = require("../logger");
19
19
  const types_1 = require("../types");
20
+ const swaps_1 = require("./swaps");
20
21
  const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'gas-fees');
21
22
  function updateGasFees(request) {
22
23
  return __awaiter(this, void 0, void 0, function* () {
23
24
  const { txMeta } = request;
24
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();
25
28
  const suggestedGasFees = yield getSuggestedGasFees(request);
26
29
  log('Suggested gas fees', suggestedGasFees);
27
- const getGasFeeRequest = Object.assign(Object.assign({}, request), { initialParams, suggestedGasFees });
30
+ const getGasFeeRequest = Object.assign(Object.assign({}, request), { savedGasFees,
31
+ initialParams,
32
+ suggestedGasFees });
28
33
  txMeta.txParams.maxFeePerGas = getMaxFeePerGas(getGasFeeRequest);
29
34
  txMeta.txParams.maxPriorityFeePerGas =
30
35
  getMaxPriorityFeePerGas(getGasFeeRequest);
@@ -47,10 +52,15 @@ function updateGasFees(request) {
47
52
  }
48
53
  exports.updateGasFees = updateGasFees;
49
54
  function getMaxFeePerGas(request) {
50
- const { eip1559, initialParams, suggestedGasFees } = request;
55
+ const { savedGasFees, eip1559, initialParams, suggestedGasFees } = request;
51
56
  if (!eip1559) {
52
57
  return undefined;
53
58
  }
59
+ if (savedGasFees) {
60
+ const maxFeePerGas = gweiDecimalToWeiHex(savedGasFees.maxBaseFee);
61
+ log('Using maxFeePerGas from savedGasFees', maxFeePerGas);
62
+ return maxFeePerGas;
63
+ }
54
64
  if (initialParams.maxFeePerGas) {
55
65
  log('Using maxFeePerGas from request', initialParams.maxFeePerGas);
56
66
  return initialParams.maxFeePerGas;
@@ -71,10 +81,15 @@ function getMaxFeePerGas(request) {
71
81
  return undefined;
72
82
  }
73
83
  function getMaxPriorityFeePerGas(request) {
74
- const { eip1559, initialParams, suggestedGasFees, txMeta } = request;
84
+ const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } = request;
75
85
  if (!eip1559) {
76
86
  return undefined;
77
87
  }
88
+ if (savedGasFees) {
89
+ const maxPriorityFeePerGas = gweiDecimalToWeiHex(savedGasFees.priorityFee);
90
+ log('Using maxPriorityFeePerGas from savedGasFees.priorityFee', maxPriorityFeePerGas);
91
+ return maxPriorityFeePerGas;
92
+ }
78
93
  if (initialParams.maxPriorityFeePerGas) {
79
94
  log('Using maxPriorityFeePerGas from request', initialParams.maxPriorityFeePerGas);
80
95
  return initialParams.maxPriorityFeePerGas;
@@ -111,10 +126,13 @@ function getGasPrice(request) {
111
126
  return undefined;
112
127
  }
113
128
  function getUserFeeLevel(request) {
114
- const { eip1559, initialParams, suggestedGasFees, txMeta } = request;
129
+ const { eip1559, initialParams, savedGasFees, suggestedGasFees, txMeta } = request;
115
130
  if (!eip1559) {
116
131
  return undefined;
117
132
  }
133
+ if (savedGasFees) {
134
+ return types_1.UserFeeLevel.CUSTOM;
135
+ }
118
136
  if (!initialParams.maxFeePerGas &&
119
137
  !initialParams.maxPriorityFeePerGas &&
120
138
  initialParams.gasPrice) {
@@ -1 +1 @@
1
- {"version":3,"file":"gas-fees.js","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":";AAAA,wCAAwC;;;;;;;;;;;;AAExC,iEAKoC;AAGpC,qEAAkE;AAClE,2CAAqD;AACrD,qDAA+C;AAE/C,sCAA0C;AAE1C,oCAA8D;AAc9D,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,UAAU,CAAC,CAAC;AAE1D,SAAsB,aAAa,CA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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 { TransactionParams } from '../types';\nimport { UserFeeLevel, type TransactionMeta } from '../types';\n\nexport type UpdateGasFeesRequest = {\n eip1559: boolean;\n ethQuery: EthQuery;\n getGasFeeEstimates: () => Promise<GasFeeState>;\n txMeta: TransactionMeta;\n};\n\nexport type GetGasFeeRequest = UpdateGasFeesRequest & {\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 suggestedGasFees = await getSuggestedGasFees(request);\n\n log('Suggested gas fees', suggestedGasFees);\n\n const getGasFeeRequest = { ...request, initialParams, suggestedGasFees };\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 { eip1559, initialParams, suggestedGasFees } = request;\n\n if (!eip1559) {\n return undefined;\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, suggestedGasFees, txMeta } = request;\n\n if (!eip1559) {\n return undefined;\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, suggestedGasFees, txMeta } = request;\n\n if (!eip1559) {\n return undefined;\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"]}
1
+ {"version":3,"file":"gas-fees.js","sourceRoot":"","sources":["../../src/utils/gas-fees.ts"],"names":[],"mappings":";AAAA,wCAAwC;;;;;;;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,EAAE;oBAC1D,OAAO;wBACL,YAAY,EAAE,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"]}
@@ -9,6 +9,7 @@ export declare type UpdateGasRequest = {
9
9
  };
10
10
  export declare const log: import("debug").Debugger;
11
11
  export declare const FIXED_GAS = "0x5208";
12
+ export declare const DEFAULT_GAS_MULTIPLIER = 1.5;
12
13
  export declare function updateGas(request: UpdateGasRequest): Promise<void>;
13
14
  export declare function estimateGas(txParams: TransactionParams, ethQuery: EthQuery): Promise<{
14
15
  blockGasLimit: string;
@@ -22,4 +23,5 @@ export declare function estimateGas(txParams: TransactionParams, ethQuery: EthQu
22
23
  };
23
24
  } | undefined;
24
25
  }>;
26
+ export declare function addGasBuffer(estimatedGas: string, blockGasLimit: string, multiplier: number): string;
25
27
  //# sourceMappingURL=gas.d.ts.map
@@ -1 +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;AAElC,wBAAsB,SAAS,CAAC,OAAO,EAAE,gBAAgB,iBAkBxD;AAED,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,iBAAiB,EAC3B,QAAQ,EAAE,QAAQ;;;;;;;;;;;GAsCnB"}
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"}
package/dist/utils/gas.js CHANGED
@@ -10,13 +10,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  });
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
- exports.estimateGas = exports.updateGas = exports.FIXED_GAS = exports.log = void 0;
13
+ exports.addGasBuffer = exports.estimateGas = exports.updateGas = exports.DEFAULT_GAS_MULTIPLIER = exports.FIXED_GAS = exports.log = void 0;
14
14
  const controller_utils_1 = require("@metamask/controller-utils");
15
15
  const utils_1 = require("@metamask/utils");
16
16
  const ethereumjs_util_1 = require("ethereumjs-util");
17
17
  const logger_1 = require("../logger");
18
18
  exports.log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'gas');
19
19
  exports.FIXED_GAS = '0x5208';
20
+ exports.DEFAULT_GAS_MULTIPLIER = 1.5;
20
21
  function updateGas(request) {
21
22
  return __awaiter(this, void 0, void 0, function* () {
22
23
  const { txMeta } = request;
@@ -67,6 +68,25 @@ function estimateGas(txParams, ethQuery) {
67
68
  });
68
69
  }
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;
70
90
  function getGas(request) {
71
91
  return __awaiter(this, void 0, void 0, function* () {
72
92
  const { providerConfig, txMeta } = request;
@@ -79,23 +99,12 @@ function getGas(request) {
79
99
  return [exports.FIXED_GAS];
80
100
  }
81
101
  const { blockGasLimit, estimatedGas, simulationFails } = yield estimateGas(txMeta.txParams, request.ethQuery);
82
- const estimatedGasBN = (0, controller_utils_1.hexToBN)(estimatedGas);
83
- const maxGasBN = (0, controller_utils_1.hexToBN)(blockGasLimit).muln(0.9);
84
- const paddedGasBN = estimatedGasBN.muln(1.5);
85
- const isCustomNetwork = providerConfig.type === controller_utils_1.NetworkType.rpc;
86
- if (estimatedGasBN.gt(maxGasBN) || isCustomNetwork) {
87
- const estimatedGasHex = (0, ethereumjs_util_1.addHexPrefix)(estimatedGas);
88
- (0, exports.log)('Using estimated value', estimatedGasHex);
89
- return [estimatedGasHex, simulationFails];
90
- }
91
- if (paddedGasBN.lt(maxGasBN)) {
92
- const paddedHex = (0, ethereumjs_util_1.addHexPrefix)((0, controller_utils_1.BNToHex)(paddedGasBN));
93
- (0, exports.log)('Using 150% of estimated value', paddedHex);
94
- return [paddedHex, simulationFails];
102
+ if (providerConfig.type === controller_utils_1.NetworkType.rpc) {
103
+ (0, exports.log)('Using original estimate as custom network');
104
+ return [estimatedGas, simulationFails];
95
105
  }
96
- const maxHex = (0, ethereumjs_util_1.addHexPrefix)((0, controller_utils_1.BNToHex)(maxGasBN));
97
- (0, exports.log)('Using 90% of block gas limit', maxHex);
98
- return [maxHex, simulationFails];
106
+ const bufferedGas = addGasBuffer(estimatedGas, blockGasLimit, exports.DEFAULT_GAS_MULTIPLIER);
107
+ return [bufferedGas, simulationFails];
99
108
  });
100
109
  }
101
110
  function requiresFixedGas({ ethQuery, txMeta, providerConfig, }) {
@@ -1 +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;AAElC,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;QA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;QAEf,OAAO,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IACrD,CAAC;CAAA;AAED,SAAe,cAAc,CAC3B,QAAkB;;QAElB,OAAO,MAAM,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';\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\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 const estimatedGasBN = hexToBN(estimatedGas);\n const maxGasBN = hexToBN(blockGasLimit).muln(0.9);\n const paddedGasBN = estimatedGasBN.muln(1.5);\n const isCustomNetwork = providerConfig.type === NetworkType.rpc;\n\n if (estimatedGasBN.gt(maxGasBN) || isCustomNetwork) {\n const estimatedGasHex = addHexPrefix(estimatedGas);\n log('Using estimated value', estimatedGasHex);\n return [estimatedGasHex, simulationFails];\n }\n\n if (paddedGasBN.lt(maxGasBN)) {\n const paddedHex = addHexPrefix(BNToHex(paddedGasBN));\n log('Using 150% of estimated value', paddedHex);\n return [paddedHex, simulationFails];\n }\n\n const maxHex = addHexPrefix(BNToHex(maxGasBN));\n log('Using 90% of block gas limit', maxHex);\n return [maxHex, 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
+ {"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,C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M,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"]}
@@ -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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,GAClB,EAAE;IACD,QAAQ,EAAE,QAAQ,CAAC;IACnB,cAAc,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,eAAe,GAAG,SAAS,CAAC;IACvE,iBAAiB,EAAE,CAAC,eAAe,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7E,GACA,OAAO,CAAC;IACT,sBAAsB,EAAE,eAAe,CAAC;IACxC,uBAAuB,CAAC,EAAE,eAAe,CAAC;CAC3C,CAAC,CAyDD"}
@@ -0,0 +1,253 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.updatePostTransactionBalance = exports.updateSwapsTransaction = exports.SWAP_TRANSACTION_TYPES = exports.SWAPS_CHAINID_DEFAULT_TOKEN_MAP = exports.DEFAULT_TOKEN_ADDRESS = exports.UPDATE_POST_TX_BALANCE_ATTEMPTS = exports.UPDATE_POST_TX_BALANCE_TIMEOUT = void 0;
13
+ const controller_utils_1 = require("@metamask/controller-utils");
14
+ const lodash_1 = require("lodash");
15
+ const constants_1 = require("../constants");
16
+ const logger_1 = require("../logger");
17
+ const types_1 = require("../types");
18
+ const utils_1 = require("./utils");
19
+ const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'swaps');
20
+ /**
21
+ * Interval in milliseconds between checks of post transaction balance
22
+ */
23
+ exports.UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;
24
+ /**
25
+ * Retry attempts for checking post transaction balance
26
+ */
27
+ exports.UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;
28
+ const SWAPS_TESTNET_CHAIN_ID = '0x539';
29
+ /**
30
+ * 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
31
+ */
32
+ exports.DEFAULT_TOKEN_ADDRESS = '0x0000000000000000000000000000000000000000';
33
+ const ETH_SWAPS_TOKEN_OBJECT = {
34
+ name: 'Ether',
35
+ address: exports.DEFAULT_TOKEN_ADDRESS,
36
+ decimals: 18,
37
+ };
38
+ const BNB_SWAPS_TOKEN_OBJECT = {
39
+ name: 'Binance Coin',
40
+ address: exports.DEFAULT_TOKEN_ADDRESS,
41
+ decimals: 18,
42
+ };
43
+ const MATIC_SWAPS_TOKEN_OBJECT = {
44
+ name: 'Matic',
45
+ address: exports.DEFAULT_TOKEN_ADDRESS,
46
+ decimals: 18,
47
+ };
48
+ const AVAX_SWAPS_TOKEN_OBJECT = {
49
+ name: 'Avalanche',
50
+ address: exports.DEFAULT_TOKEN_ADDRESS,
51
+ decimals: 18,
52
+ };
53
+ const TEST_ETH_SWAPS_TOKEN_OBJECT = {
54
+ name: 'Test Ether',
55
+ address: exports.DEFAULT_TOKEN_ADDRESS,
56
+ decimals: 18,
57
+ };
58
+ const GOERLI_SWAPS_TOKEN_OBJECT = {
59
+ name: 'Ether',
60
+ address: exports.DEFAULT_TOKEN_ADDRESS,
61
+ decimals: 18,
62
+ };
63
+ const ARBITRUM_SWAPS_TOKEN_OBJECT = Object.assign({}, ETH_SWAPS_TOKEN_OBJECT);
64
+ const OPTIMISM_SWAPS_TOKEN_OBJECT = Object.assign({}, ETH_SWAPS_TOKEN_OBJECT);
65
+ const ZKSYNC_ERA_SWAPS_TOKEN_OBJECT = Object.assign({}, ETH_SWAPS_TOKEN_OBJECT);
66
+ exports.SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {
67
+ [constants_1.CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,
68
+ [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,
69
+ [constants_1.CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,
70
+ [constants_1.CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,
71
+ [constants_1.CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,
72
+ [constants_1.CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,
73
+ [constants_1.CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,
74
+ [constants_1.CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,
75
+ [constants_1.CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,
76
+ };
77
+ exports.SWAP_TRANSACTION_TYPES = [
78
+ types_1.TransactionType.swap,
79
+ types_1.TransactionType.swapApproval,
80
+ ];
81
+ /**
82
+ * Updates the transaction meta object with the swap information
83
+ *
84
+ * @param transactionMeta - The transaction meta object to update
85
+ * @param transactionType - The type of the transaction
86
+ * @param swaps - The swaps object
87
+ * @param swaps.hasApproveTx - Whether the swap has an approval transaction
88
+ * @param swaps.meta - The swap meta object
89
+ * @param updateSwapsTransactionRequest - Dependency bag
90
+ * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled
91
+ * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction
92
+ * @param updateSwapsTransactionRequest.controllerHubEmitter - Function to emit an event to the controller hub
93
+ */
94
+ function updateSwapsTransaction(transactionMeta, transactionType, swaps, { isSwapsDisabled, cancelTransaction, controllerHubEmitter, }) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ if (isSwapsDisabled || !exports.SWAP_TRANSACTION_TYPES.includes(transactionType)) {
97
+ return;
98
+ }
99
+ // The simulationFails property is added if the estimateGas call fails. In cases
100
+ // when no swaps approval tx is required, this indicates that the swap will likely
101
+ // fail. There was an earlier estimateGas call made by the swaps controller,
102
+ // but it is possible that external conditions have change since then, and
103
+ // a previously succeeding estimate gas call could now fail. By checking for
104
+ // the `simulationFails` property here, we can reduce the number of swap
105
+ // transactions that get published to the blockchain only to fail and thereby
106
+ // waste the user's funds on gas.
107
+ if (transactionType === types_1.TransactionType.swap &&
108
+ (swaps === null || swaps === void 0 ? void 0 : swaps.hasApproveTx) === false &&
109
+ transactionMeta.simulationFails) {
110
+ yield cancelTransaction(transactionMeta.id);
111
+ throw new Error('Simulation failed');
112
+ }
113
+ const swapsMeta = swaps === null || swaps === void 0 ? void 0 : swaps.meta;
114
+ if (!swapsMeta) {
115
+ return;
116
+ }
117
+ if (transactionType === types_1.TransactionType.swapApproval) {
118
+ updateSwapApprovalTransaction(transactionMeta, swapsMeta);
119
+ controllerHubEmitter('transaction-new-swap-approval', {
120
+ transactionMeta,
121
+ });
122
+ }
123
+ if (transactionType === types_1.TransactionType.swap) {
124
+ updateSwapTransaction(transactionMeta, swapsMeta);
125
+ controllerHubEmitter('transaction-new-swap', {
126
+ transactionMeta,
127
+ });
128
+ }
129
+ });
130
+ }
131
+ exports.updateSwapsTransaction = updateSwapsTransaction;
132
+ /**
133
+ * Attempts to update the post transaction balance of the provided transaction
134
+ *
135
+ * @param transactionMeta - Transaction meta object to update
136
+ * @param updatePostTransactionBalanceRequest - Dependency bag
137
+ * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object
138
+ * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state
139
+ * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function
140
+ */
141
+ function updatePostTransactionBalance(transactionMeta, { ethQuery, getTransaction, updateTransaction, }) {
142
+ return __awaiter(this, void 0, void 0, function* () {
143
+ log('Updating post transaction balance', transactionMeta.id);
144
+ const transactionId = transactionMeta.id;
145
+ let latestTransactionMeta, approvalTransactionMeta;
146
+ for (let i = 0; i < exports.UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {
147
+ log('Querying balance', { attempt: i });
148
+ const postTransactionBalance = yield (0, controller_utils_1.query)(ethQuery, 'getBalance', [
149
+ transactionMeta.txParams.from,
150
+ ]);
151
+ latestTransactionMeta = getTransaction(transactionId);
152
+ approvalTransactionMeta = latestTransactionMeta.approvalTxId
153
+ ? getTransaction(latestTransactionMeta.approvalTxId)
154
+ : undefined;
155
+ latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);
156
+ const isDefaultTokenAddress = isSwapsDefaultTokenAddress(transactionMeta.destinationTokenAddress, transactionMeta.chainId);
157
+ if (!isDefaultTokenAddress ||
158
+ transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance) {
159
+ log('Finishing post balance update', {
160
+ isDefaultTokenAddress,
161
+ preTxBalance: transactionMeta.preTxBalance,
162
+ postTxBalance: latestTransactionMeta.postTxBalance,
163
+ });
164
+ break;
165
+ }
166
+ log('Waiting for balance to update', {
167
+ delay: exports.UPDATE_POST_TX_BALANCE_TIMEOUT,
168
+ });
169
+ yield sleep(exports.UPDATE_POST_TX_BALANCE_TIMEOUT);
170
+ }
171
+ updateTransaction(latestTransactionMeta, 'TransactionController#updatePostTransactionBalance - Add post transaction balance');
172
+ log('Completed post balance update', latestTransactionMeta === null || latestTransactionMeta === void 0 ? void 0 : latestTransactionMeta.postTxBalance);
173
+ return {
174
+ updatedTransactionMeta: latestTransactionMeta,
175
+ approvalTransactionMeta,
176
+ };
177
+ });
178
+ }
179
+ exports.updatePostTransactionBalance = updatePostTransactionBalance;
180
+ /**
181
+ * Updates the transaction meta object with the swap information
182
+ *
183
+ * @param transactionMeta - Transaction meta object to update
184
+ * @param propsToUpdate - Properties to update
185
+ * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped
186
+ * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received
187
+ * @param propsToUpdate.type - Type of the transaction
188
+ * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received
189
+ * @param propsToUpdate.destinationTokenAddress - Address of the token to be received
190
+ * @param propsToUpdate.swapMetaData - Metadata of the swap
191
+ * @param propsToUpdate.swapTokenValue - Value of the token to be swapped
192
+ * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction
193
+ * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction
194
+ */
195
+ function updateSwapTransaction(transactionMeta, { sourceTokenSymbol, destinationTokenSymbol, type, destinationTokenDecimals, destinationTokenAddress, swapMetaData, swapTokenValue, estimatedBaseFee, approvalTxId, }) {
196
+ (0, utils_1.validateIfTransactionUnapproved)(transactionMeta, 'updateSwapTransaction');
197
+ let swapTransaction = {
198
+ sourceTokenSymbol,
199
+ destinationTokenSymbol,
200
+ type,
201
+ destinationTokenDecimals,
202
+ destinationTokenAddress,
203
+ swapMetaData,
204
+ swapTokenValue,
205
+ estimatedBaseFee,
206
+ approvalTxId,
207
+ };
208
+ swapTransaction = (0, lodash_1.pickBy)(swapTransaction);
209
+ (0, lodash_1.merge)(transactionMeta, swapTransaction);
210
+ }
211
+ /**
212
+ * Updates the transaction meta object with the swap approval information
213
+ *
214
+ * @param transactionMeta - Transaction meta object to update
215
+ * @param propsToUpdate - Properties to update
216
+ * @param propsToUpdate.type - Type of the transaction
217
+ * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped
218
+ */
219
+ function updateSwapApprovalTransaction(transactionMeta, { type, sourceTokenSymbol }) {
220
+ (0, utils_1.validateIfTransactionUnapproved)(transactionMeta, 'updateSwapApprovalTransaction');
221
+ let swapApprovalTransaction = { type, sourceTokenSymbol };
222
+ swapApprovalTransaction = (0, lodash_1.pickBy)({
223
+ type,
224
+ sourceTokenSymbol,
225
+ });
226
+ (0, lodash_1.merge)(transactionMeta, swapApprovalTransaction);
227
+ }
228
+ /**
229
+ * Checks whether the provided address is strictly equal to the address for
230
+ * the default swaps token of the provided chain.
231
+ *
232
+ * @param address - The string to compare to the default token address
233
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
234
+ * @returns Whether the address is the provided chain's default token address
235
+ */
236
+ function isSwapsDefaultTokenAddress(address, chainId) {
237
+ var _a;
238
+ if (!address || !chainId) {
239
+ return false;
240
+ }
241
+ return (address ===
242
+ ((_a = exports.SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId]) === null || _a === void 0 ? void 0 : _a.address));
243
+ }
244
+ /**
245
+ * Sleeps for the provided number of milliseconds
246
+ *
247
+ * @param ms - Number of milliseconds to sleep
248
+ * @returns Promise that resolves after the provided number of milliseconds
249
+ */
250
+ function sleep(ms) {
251
+ return new Promise((resolve) => setTimeout(resolve, ms));
252
+ }
253
+ //# sourceMappingURL=swaps.js.map