@metamask/transaction-controller 16.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 (44) hide show
  1. package/CHANGELOG.md +42 -1
  2. package/dist/TransactionController.d.ts +139 -15
  3. package/dist/TransactionController.d.ts.map +1 -1
  4. package/dist/TransactionController.js +461 -83
  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 +22 -4
  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 +219 -6
  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 +240 -0
  35. package/dist/utils/swaps.js.map +1 -0
  36. package/dist/utils/utils.d.ts +11 -1
  37. package/dist/utils/utils.d.ts.map +1 -1
  38. package/dist/utils/utils.js +18 -2
  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 +10 -9
@@ -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,CAAC,OAA6B;;QAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QAC3B,MAAM,aAAa,qBAAQ,MAAM,CAAC,QAAQ,CAAE,CAAC;QAE7C,MAAM,gBAAgB,GAAG,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;QAE5D,GAAG,CAAC,oBAAoB,EAAE,gBAAgB,CAAC,CAAC;QAE5C,MAAM,gBAAgB,mCAAQ,OAAO,KAAE,aAAa,EAAE,gBAAgB,GAAE,CAAC;QAEzE,MAAM,CAAC,QAAQ,CAAC,YAAY,GAAG,eAAe,CAAC,gBAAgB,CAAC,CAAC;QAEjE,MAAM,CAAC,QAAQ,CAAC,oBAAoB;YAClC,uBAAuB,CAAC,gBAAgB,CAAC,CAAC;QAE5C,MAAM,CAAC,QAAQ,CAAC,QAAQ,GAAG,WAAW,CAAC,gBAAgB,CAAC,CAAC;QACzD,MAAM,CAAC,YAAY,GAAG,eAAe,CAAC,gBAAgB,CAAC,CAAC;QAExD,GAAG,CAAC,4BAA4B,EAAE;YAChC,YAAY,EAAE,MAAM,CAAC,QAAQ,CAAC,YAAY;YAC1C,oBAAoB,EAAE,MAAM,CAAC,QAAQ,CAAC,oBAAoB;YAC1D,QAAQ,EAAE,MAAM,C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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 { 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;;;;;;;;;;;;AAExC,iEAKoC;AAGpC,qEAAkE;AAClE,2CAAqD;AACrD,qDAA+C;AAE/C,sCAA0C;AAO1C,oCAAwC;AACxC,mCAAiD;AAgBjD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,UAAU,CAAC,CAAC;AAE1D,SAAsB,aAAa,CAAC,OAA6B;;QAC/D,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;QAC3B,MAAM,aAAa,qBAAQ,MAAM,CAAC,QAAQ,CAAE,CAAC;QAE7C,MAAM,MAAM,GAAG,8BAAsB,CAAC,QAAQ,CAC5C,MAAM,CAAC,IAAuB,CAC/B,CAAC;QACF,MAAM,YAAY,GAAG,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,eAAe,EAAE,CAAC;QAEpE,MAAM,gBAAgB,GAAG,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;QAE5D,GAAG,CAAC,oBAAoB,EAAE,gBAAgB,CAAC,CAAC;QAE5C,MAAM,gBAAgB,mCACjB,OAAO,KACV,YAAY;YACZ,aAAa;YACb,gBAAgB,GACjB,CAAC;QAEF,MAAM,CAAC,QAAQ,CAAC,YAAY,GAAG,eAAe,CAAC,g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C,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,i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IAAI,KAAK,8BAAW,CAAC,GAAG,CAAC;QAEhE,MAAM,EACJ,QAAQ,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,GACvB,GAAG,MAAM,CAAC;QAEX,IAAI,eAAe,EAAE;YACnB,OAAO,KAAK,CAAC;SACd;QAED,IAAI,CAAC,EAAE,EAAE;YACP,OAAO,IAAI,CAAC;SACb;QAED,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;QAEzC,OAAO,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC;IAC3C,CAAC;CAAA;AAED,SAAe,OAAO,CACpB,QAAkB,EAClB,OAAe;;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,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KAAK,CAAC;SACd;QAED,IAAI,CAAC,EAAE,EAAE;YACP,OAAO,IAAI,CAAC;SACb;QAED,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;QAEzC,OAAO,CAAC,IAAI,IAAI,CAAC,CAAC,IAAI,IAAI,IAAI,KAAK,IAAI,CAAC,CAAC;IAC3C,CAAC;CAAA;AAED,SAAe,OAAO,CACpB,QAAkB,EAClB,OAAe;;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';\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.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,OAAO,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAG3C;;GAEG;AACH,eAAO,MAAM,8BAA8B,OAAO,CAAC;AAEnD;;GAEG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAIjD;;GAEG;AACH,eAAO,MAAM,qBAAqB,+CACY,CAAC;AAI/C,UAAU,gBAAgB;IACxB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;CAClB;AAkDD,eAAO,MAAM,+BAA+B;;;;;;;;;;CAUlC,CAAC;AAEX,eAAO,MAAM,sBAAsB,mBAGlC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAsB,sBAAsB,CAC1C,eAAe,EAAE,eAAe,EAChC,eAAe,EAAE,eAAe,EAChC,KAAK,EAAE;IACL,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,IAAI,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;CACjC,EACD,EACE,eAAe,EACf,iBAAiB,EACjB,oBAAoB,GACrB,EAAE;IACD,eAAe,EAAE,OAAO,CAAC;IACzB,iBAAiB,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,IAAI,CAAC;IACnD,oBAAoB,EAAE,CAAC,CAAC,SAAS,MAAM,MAAM,EAC3C,SAAS,EAAE,CAAC,EACZ,GAAG,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,KACf,OAAO,CAAC;CACd,iBAyCF;AAED;;;;;;;;GAQG;AACH,wBAAsB,4BAA4B,CAChD,eAAe,EAAE,eAAe,EAChC,EACE,QAAQ,EACR,cAAc,EACd,iBAAiB,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,CAqCD"}
@@ -0,0 +1,240 @@
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 types_1 = require("../types");
17
+ const utils_1 = require("./utils");
18
+ /**
19
+ * Interval in milliseconds between checks of post transaction balance
20
+ */
21
+ exports.UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;
22
+ /**
23
+ * Retry attempts for checking post transaction balance
24
+ */
25
+ exports.UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;
26
+ const SWAPS_TESTNET_CHAIN_ID = '0x539';
27
+ /**
28
+ * 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
29
+ */
30
+ exports.DEFAULT_TOKEN_ADDRESS = '0x0000000000000000000000000000000000000000';
31
+ const ETH_SWAPS_TOKEN_OBJECT = {
32
+ name: 'Ether',
33
+ address: exports.DEFAULT_TOKEN_ADDRESS,
34
+ decimals: 18,
35
+ };
36
+ const BNB_SWAPS_TOKEN_OBJECT = {
37
+ name: 'Binance Coin',
38
+ address: exports.DEFAULT_TOKEN_ADDRESS,
39
+ decimals: 18,
40
+ };
41
+ const MATIC_SWAPS_TOKEN_OBJECT = {
42
+ name: 'Matic',
43
+ address: exports.DEFAULT_TOKEN_ADDRESS,
44
+ decimals: 18,
45
+ };
46
+ const AVAX_SWAPS_TOKEN_OBJECT = {
47
+ name: 'Avalanche',
48
+ address: exports.DEFAULT_TOKEN_ADDRESS,
49
+ decimals: 18,
50
+ };
51
+ const TEST_ETH_SWAPS_TOKEN_OBJECT = {
52
+ name: 'Test Ether',
53
+ address: exports.DEFAULT_TOKEN_ADDRESS,
54
+ decimals: 18,
55
+ };
56
+ const GOERLI_SWAPS_TOKEN_OBJECT = {
57
+ name: 'Ether',
58
+ address: exports.DEFAULT_TOKEN_ADDRESS,
59
+ decimals: 18,
60
+ };
61
+ const ARBITRUM_SWAPS_TOKEN_OBJECT = Object.assign({}, ETH_SWAPS_TOKEN_OBJECT);
62
+ const OPTIMISM_SWAPS_TOKEN_OBJECT = Object.assign({}, ETH_SWAPS_TOKEN_OBJECT);
63
+ const ZKSYNC_ERA_SWAPS_TOKEN_OBJECT = Object.assign({}, ETH_SWAPS_TOKEN_OBJECT);
64
+ exports.SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {
65
+ [constants_1.CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,
66
+ [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,
67
+ [constants_1.CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,
68
+ [constants_1.CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,
69
+ [constants_1.CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,
70
+ [constants_1.CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,
71
+ [constants_1.CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,
72
+ [constants_1.CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,
73
+ [constants_1.CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,
74
+ };
75
+ exports.SWAP_TRANSACTION_TYPES = [
76
+ types_1.TransactionType.swap,
77
+ types_1.TransactionType.swapApproval,
78
+ ];
79
+ /**
80
+ * Updates the transaction meta object with the swap information
81
+ *
82
+ * @param transactionMeta - The transaction meta object to update
83
+ * @param transactionType - The type of the transaction
84
+ * @param swaps - The swaps object
85
+ * @param swaps.hasApproveTx - Whether the swap has an approval transaction
86
+ * @param swaps.meta - The swap meta object
87
+ * @param updateSwapsTransactionRequest - Dependency bag
88
+ * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled
89
+ * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction
90
+ * @param updateSwapsTransactionRequest.controllerHubEmitter - Function to emit an event to the controller hub
91
+ */
92
+ function updateSwapsTransaction(transactionMeta, transactionType, swaps, { isSwapsDisabled, cancelTransaction, controllerHubEmitter, }) {
93
+ return __awaiter(this, void 0, void 0, function* () {
94
+ if (isSwapsDisabled || !exports.SWAP_TRANSACTION_TYPES.includes(transactionType)) {
95
+ return;
96
+ }
97
+ // The simulationFails property is added if the estimateGas call fails. In cases
98
+ // when no swaps approval tx is required, this indicates that the swap will likely
99
+ // fail. There was an earlier estimateGas call made by the swaps controller,
100
+ // but it is possible that external conditions have change since then, and
101
+ // a previously succeeding estimate gas call could now fail. By checking for
102
+ // the `simulationFails` property here, we can reduce the number of swap
103
+ // transactions that get published to the blockchain only to fail and thereby
104
+ // waste the user's funds on gas.
105
+ if (transactionType === types_1.TransactionType.swap &&
106
+ (swaps === null || swaps === void 0 ? void 0 : swaps.hasApproveTx) === false &&
107
+ transactionMeta.simulationFails) {
108
+ yield cancelTransaction(transactionMeta.id);
109
+ throw new Error('Simulation failed');
110
+ }
111
+ const swapsMeta = swaps === null || swaps === void 0 ? void 0 : swaps.meta;
112
+ if (!swapsMeta) {
113
+ return;
114
+ }
115
+ if (transactionType === types_1.TransactionType.swapApproval) {
116
+ updateSwapApprovalTransaction(transactionMeta, swapsMeta);
117
+ controllerHubEmitter('transaction-new-swap-approval', {
118
+ transactionMeta,
119
+ });
120
+ }
121
+ if (transactionType === types_1.TransactionType.swap) {
122
+ updateSwapTransaction(transactionMeta, swapsMeta);
123
+ controllerHubEmitter('transaction-new-swap', {
124
+ transactionMeta,
125
+ });
126
+ }
127
+ });
128
+ }
129
+ exports.updateSwapsTransaction = updateSwapsTransaction;
130
+ /**
131
+ * Attempts to update the post transaction balance of the provided transaction
132
+ *
133
+ * @param transactionMeta - Transaction meta object to update
134
+ * @param updatePostTransactionBalanceRequest - Dependency bag
135
+ * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object
136
+ * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state
137
+ * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function
138
+ */
139
+ function updatePostTransactionBalance(transactionMeta, { ethQuery, getTransaction, updateTransaction, }) {
140
+ return __awaiter(this, void 0, void 0, function* () {
141
+ const transactionId = transactionMeta.id;
142
+ let latestTransactionMeta, approvalTransactionMeta;
143
+ for (let i = 0; i < exports.UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {
144
+ const postTransactionBalance = yield (0, controller_utils_1.query)(ethQuery, 'getBalance', [
145
+ transactionMeta.txParams.from,
146
+ ]);
147
+ latestTransactionMeta = getTransaction(transactionId);
148
+ approvalTransactionMeta = latestTransactionMeta.approvalTxId
149
+ ? getTransaction(latestTransactionMeta.approvalTxId)
150
+ : undefined;
151
+ latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);
152
+ const isDefaultTokenAddress = isSwapsDefaultTokenAddress(transactionMeta.destinationTokenAddress, transactionMeta.chainId);
153
+ if (!isDefaultTokenAddress ||
154
+ transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance) {
155
+ break;
156
+ }
157
+ yield sleep(exports.UPDATE_POST_TX_BALANCE_TIMEOUT);
158
+ }
159
+ updateTransaction(latestTransactionMeta, 'TransactionController#updatePostTransactionBalance - Add post transaction balance');
160
+ return {
161
+ updatedTransactionMeta: latestTransactionMeta,
162
+ approvalTransactionMeta,
163
+ };
164
+ });
165
+ }
166
+ exports.updatePostTransactionBalance = updatePostTransactionBalance;
167
+ /**
168
+ * Updates the transaction meta object with the swap information
169
+ *
170
+ * @param transactionMeta - Transaction meta object to update
171
+ * @param propsToUpdate - Properties to update
172
+ * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped
173
+ * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received
174
+ * @param propsToUpdate.type - Type of the transaction
175
+ * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received
176
+ * @param propsToUpdate.destinationTokenAddress - Address of the token to be received
177
+ * @param propsToUpdate.swapMetaData - Metadata of the swap
178
+ * @param propsToUpdate.swapTokenValue - Value of the token to be swapped
179
+ * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction
180
+ * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction
181
+ */
182
+ function updateSwapTransaction(transactionMeta, { sourceTokenSymbol, destinationTokenSymbol, type, destinationTokenDecimals, destinationTokenAddress, swapMetaData, swapTokenValue, estimatedBaseFee, approvalTxId, }) {
183
+ (0, utils_1.validateIfTransactionUnapproved)(transactionMeta, 'updateSwapTransaction');
184
+ let swapTransaction = {
185
+ sourceTokenSymbol,
186
+ destinationTokenSymbol,
187
+ type,
188
+ destinationTokenDecimals,
189
+ destinationTokenAddress,
190
+ swapMetaData,
191
+ swapTokenValue,
192
+ estimatedBaseFee,
193
+ approvalTxId,
194
+ };
195
+ swapTransaction = (0, lodash_1.pickBy)(swapTransaction);
196
+ (0, lodash_1.merge)(transactionMeta, swapTransaction);
197
+ }
198
+ /**
199
+ * Updates the transaction meta object with the swap approval information
200
+ *
201
+ * @param transactionMeta - Transaction meta object to update
202
+ * @param propsToUpdate - Properties to update
203
+ * @param propsToUpdate.type - Type of the transaction
204
+ * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped
205
+ */
206
+ function updateSwapApprovalTransaction(transactionMeta, { type, sourceTokenSymbol }) {
207
+ (0, utils_1.validateIfTransactionUnapproved)(transactionMeta, 'updateSwapApprovalTransaction');
208
+ let swapApprovalTransaction = { type, sourceTokenSymbol };
209
+ swapApprovalTransaction = (0, lodash_1.pickBy)({
210
+ type,
211
+ sourceTokenSymbol,
212
+ });
213
+ (0, lodash_1.merge)(transactionMeta, swapApprovalTransaction);
214
+ }
215
+ /**
216
+ * Checks whether the provided address is strictly equal to the address for
217
+ * the default swaps token of the provided chain.
218
+ *
219
+ * @param address - The string to compare to the default token address
220
+ * @param chainId - The hex encoded chain ID of the default swaps token to check
221
+ * @returns Whether the address is the provided chain's default token address
222
+ */
223
+ function isSwapsDefaultTokenAddress(address, chainId) {
224
+ var _a;
225
+ if (!address || !chainId) {
226
+ return false;
227
+ }
228
+ return (address ===
229
+ ((_a = exports.SWAPS_CHAINID_DEFAULT_TOKEN_MAP[chainId]) === null || _a === void 0 ? void 0 : _a.address));
230
+ }
231
+ /**
232
+ * Sleeps for the provided number of milliseconds
233
+ *
234
+ * @param ms - Number of milliseconds to sleep
235
+ * @returns Promise that resolves after the provided number of milliseconds
236
+ */
237
+ function sleep(ms) {
238
+ return new Promise((resolve) => setTimeout(resolve, ms));
239
+ }
240
+ //# sourceMappingURL=swaps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"swaps.js","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,iEAAmD;AAEnD,mCAAuC;AAEvC,4CAAyC;AAEzC,oCAA2C;AAC3C,mCAA0D;AAE1D;;GAEG;AACU,QAAA,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACU,QAAA,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACU,QAAA,qBAAqB,GAChC,4CAA4C,CAAC;AAmB/C,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACb,CAAC;AAEF,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,cAAc;IACpB,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,wBAAwB,GAAqB;IACjD,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,uBAAuB,GAAqB;IAChD,IAAI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,CAAC;IACjD,IAAA,cAAK,EAAC,eAAe,EAAE,eAAe,CAAC,CAAC;AAC1C,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,6BAA6B,CACpC,eAAgC,EAChC,EAAE,IAAI,EAAE,iBAAiB,EAA4B;IAErD,IAAA,uCAA+B,EAC7B,eAAe,EACf,+BAA+B,CAChC,CAAC;IAEF,IAAI,uBAAuB,GAAG,EAAE,IAAI,EAAE,iBAAiB,EAAS,CAAC;IACjE,uBAAuB,GAAG,IAAA,eAAM,EAAC;QAC/B,IAAI;QACJ,iBAAiB;KAClB,CAA6B,CAAC;IAC/B,IAAA,cAAK,EAAC,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAClD,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE;QACxB,OAAO,KAAK,CAAC;KACd;IAED,OAAO,CACL,OAAO;SACP,MAAA,uCAA+B,CAC7B,OAAuD,CACxD,0CAAE,OAAO,CAAA,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { CHAIN_IDS } from '../constants';\nimport type { Events, TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\nimport { validateIfTransactionUnapproved } from './utils';\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * 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\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.controllerHubEmitter - Function to emit an event to the controller hub\n */\nexport async function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n controllerHubEmitter,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n controllerHubEmitter: <T extends keyof Events>(\n eventName: T,\n ...args: Events[T]\n ) => boolean;\n },\n) {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return;\n }\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n await cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return;\n }\n\n if (transactionType === TransactionType.swapApproval) {\n updateSwapApprovalTransaction(transactionMeta, swapsMeta);\n controllerHubEmitter('transaction-new-swap-approval', {\n transactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updateSwapTransaction(transactionMeta, swapsMeta);\n controllerHubEmitter('transaction-new-swap', {\n transactionMeta,\n });\n }\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n const transactionId = transactionMeta.id;\n\n let latestTransactionMeta, approvalTransactionMeta;\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n latestTransactionMeta = getTransaction(transactionId) as TransactionMeta;\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n break;\n }\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n) {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n swapTransaction = pickBy(swapTransaction) as any;\n merge(transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n) {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n merge(transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string) {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { Transaction as NonceTrackerTransaction } from 'nonce-tracker/dist/NonceTracker';
2
2
  import type { GasPriceValue, FeeMarketEIP1559Values } from '../TransactionController';
3
3
  import { TransactionStatus } from '../types';
4
- import type { TransactionParams, TransactionMeta } from '../types';
4
+ import type { TransactionParams, TransactionMeta, TransactionError } from '../types';
5
5
  export declare const ESTIMATE_GAS_ERROR = "eth_estimateGas rpc method error";
6
6
  /**
7
7
  * Normalizes properties on transaction params.
@@ -49,4 +49,14 @@ export declare function getAndFormatTransactionsForNonceTracker(fromAddress: str
49
49
  * @param fnName - The name of the function calling this helper.
50
50
  */
51
51
  export declare function validateIfTransactionUnapproved(transactionMeta: TransactionMeta | undefined, fnName: string): void;
52
+ /**
53
+ * Normalizes properties on transaction params.
54
+ *
55
+ * @param error - The error to be normalize.
56
+ * @returns Normalized transaction error.
57
+ */
58
+ export declare function normalizeTxError(error: Error & {
59
+ code?: string;
60
+ value?: unknown;
61
+ }): TransactionError;
52
62
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,IAAI,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAE9F,OAAO,KAAK,EACV,aAAa,EACb,sBAAsB,EACvB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AAC7C,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEnE,eAAO,MAAM,kBAAkB,qCAAqC,CAAC;AAmBrE;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,iBAAiB,qBAQ5D;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAOzE;AAED,eAAO,MAAM,iBAAiB,cACjB,aAAa,GAAG,sBAAsB,SAUlD,CAAC;AAEF,eAAO,MAAM,wBAAwB,eACvB,aAAa,GAAG,sBAAsB,wCAGuB,CAAC;AAE5E,eAAO,MAAM,eAAe,eACd,aAAa,GAAG,sBAAsB,+BAEE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