@metamask/transaction-controller 61.0.0 → 61.2.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 (132) hide show
  1. package/CHANGELOG.md +25 -1
  2. package/dist/TransactionController.cjs +2 -1
  3. package/dist/TransactionController.cjs.map +1 -1
  4. package/dist/TransactionController.d.cts.map +1 -1
  5. package/dist/TransactionController.d.mts.map +1 -1
  6. package/dist/TransactionController.mjs +2 -1
  7. package/dist/TransactionController.mjs.map +1 -1
  8. package/dist/api/accounts-api.cjs +9 -9
  9. package/dist/api/accounts-api.cjs.map +1 -1
  10. package/dist/api/accounts-api.mjs +9 -9
  11. package/dist/api/accounts-api.mjs.map +1 -1
  12. package/dist/api/simulation-api.cjs.map +1 -1
  13. package/dist/api/simulation-api.mjs.map +1 -1
  14. package/dist/gas-flows/DefaultGasFeeFlow.cjs.map +1 -1
  15. package/dist/gas-flows/DefaultGasFeeFlow.mjs.map +1 -1
  16. package/dist/gas-flows/LineaGasFeeFlow.cjs.map +1 -1
  17. package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -1
  18. package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs +26 -7
  19. package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs.map +1 -1
  20. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts +7 -2
  21. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts.map +1 -1
  22. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts +7 -2
  23. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts.map +1 -1
  24. package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs +26 -7
  25. package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs.map +1 -1
  26. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs +99 -25
  27. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs.map +1 -1
  28. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.cts +20 -2
  29. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.cts.map +1 -1
  30. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.mts +20 -2
  31. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.mts.map +1 -1
  32. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs +104 -26
  33. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs.map +1 -1
  34. package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.cjs.map +1 -1
  35. package/dist/gas-flows/RandomisedEstimationsGasFeeFlow.mjs.map +1 -1
  36. package/dist/gas-flows/ScrollLayer1GasFeeFlow.cjs +6 -3
  37. package/dist/gas-flows/ScrollLayer1GasFeeFlow.cjs.map +1 -1
  38. package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.cts +4 -2
  39. package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.cts.map +1 -1
  40. package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.mts +4 -2
  41. package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.mts.map +1 -1
  42. package/dist/gas-flows/ScrollLayer1GasFeeFlow.mjs +6 -3
  43. package/dist/gas-flows/ScrollLayer1GasFeeFlow.mjs.map +1 -1
  44. package/dist/gas-flows/TestGasFeeFlow.cjs.map +1 -1
  45. package/dist/gas-flows/TestGasFeeFlow.mjs.map +1 -1
  46. package/dist/helpers/AccountsApiRemoteTransactionSource.cjs.map +1 -1
  47. package/dist/helpers/AccountsApiRemoteTransactionSource.mjs.map +1 -1
  48. package/dist/helpers/GasFeePoller.cjs.map +1 -1
  49. package/dist/helpers/GasFeePoller.mjs.map +1 -1
  50. package/dist/helpers/IncomingTransactionHelper.cjs.map +1 -1
  51. package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -1
  52. package/dist/helpers/MethodDataHelper.cjs.map +1 -1
  53. package/dist/helpers/MethodDataHelper.mjs.map +1 -1
  54. package/dist/helpers/MultichainTrackingHelper.cjs.map +1 -1
  55. package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -1
  56. package/dist/helpers/PendingTransactionTracker.cjs +19 -12
  57. package/dist/helpers/PendingTransactionTracker.cjs.map +1 -1
  58. package/dist/helpers/PendingTransactionTracker.d.cts.map +1 -1
  59. package/dist/helpers/PendingTransactionTracker.d.mts.map +1 -1
  60. package/dist/helpers/PendingTransactionTracker.mjs +19 -12
  61. package/dist/helpers/PendingTransactionTracker.mjs.map +1 -1
  62. package/dist/helpers/ResimulateHelper.cjs +0 -1
  63. package/dist/helpers/ResimulateHelper.cjs.map +1 -1
  64. package/dist/helpers/ResimulateHelper.d.cts.map +1 -1
  65. package/dist/helpers/ResimulateHelper.d.mts.map +1 -1
  66. package/dist/helpers/ResimulateHelper.mjs +0 -1
  67. package/dist/helpers/ResimulateHelper.mjs.map +1 -1
  68. package/dist/helpers/TransactionPoller.cjs.map +1 -1
  69. package/dist/helpers/TransactionPoller.mjs.map +1 -1
  70. package/dist/hooks/CollectPublishHook.cjs.map +1 -1
  71. package/dist/hooks/CollectPublishHook.mjs.map +1 -1
  72. package/dist/hooks/ExtraTransactionsPublishHook.cjs.map +1 -1
  73. package/dist/hooks/ExtraTransactionsPublishHook.mjs.map +1 -1
  74. package/dist/hooks/SequentialPublishBatchHook.cjs.map +1 -1
  75. package/dist/hooks/SequentialPublishBatchHook.mjs.map +1 -1
  76. package/dist/types.cjs.map +1 -1
  77. package/dist/types.d.cts +8 -2
  78. package/dist/types.d.cts.map +1 -1
  79. package/dist/types.d.mts +8 -2
  80. package/dist/types.d.mts.map +1 -1
  81. package/dist/types.mjs.map +1 -1
  82. package/dist/utils/balance-changes.cjs.map +1 -1
  83. package/dist/utils/balance-changes.mjs.map +1 -1
  84. package/dist/utils/batch.cjs +1 -0
  85. package/dist/utils/batch.cjs.map +1 -1
  86. package/dist/utils/batch.mjs +1 -0
  87. package/dist/utils/batch.mjs.map +1 -1
  88. package/dist/utils/eip7702.cjs.map +1 -1
  89. package/dist/utils/eip7702.mjs.map +1 -1
  90. package/dist/utils/external-transactions.cjs.map +1 -1
  91. package/dist/utils/external-transactions.mjs.map +1 -1
  92. package/dist/utils/first-time-interaction.cjs.map +1 -1
  93. package/dist/utils/first-time-interaction.mjs.map +1 -1
  94. package/dist/utils/gas-fee-tokens.cjs.map +1 -1
  95. package/dist/utils/gas-fee-tokens.mjs.map +1 -1
  96. package/dist/utils/gas-fees.cjs.map +1 -1
  97. package/dist/utils/gas-fees.mjs.map +1 -1
  98. package/dist/utils/gas-flow.cjs.map +1 -1
  99. package/dist/utils/gas-flow.mjs.map +1 -1
  100. package/dist/utils/gas.cjs.map +1 -1
  101. package/dist/utils/gas.mjs.map +1 -1
  102. package/dist/utils/history.cjs.map +1 -1
  103. package/dist/utils/history.mjs.map +1 -1
  104. package/dist/utils/layer1-gas-fee-flow.cjs +12 -6
  105. package/dist/utils/layer1-gas-fee-flow.cjs.map +1 -1
  106. package/dist/utils/layer1-gas-fee-flow.d.cts.map +1 -1
  107. package/dist/utils/layer1-gas-fee-flow.d.mts.map +1 -1
  108. package/dist/utils/layer1-gas-fee-flow.mjs +12 -6
  109. package/dist/utils/layer1-gas-fee-flow.mjs.map +1 -1
  110. package/dist/utils/nonce.cjs.map +1 -1
  111. package/dist/utils/nonce.mjs.map +1 -1
  112. package/dist/utils/prepare.cjs.map +1 -1
  113. package/dist/utils/prepare.mjs.map +1 -1
  114. package/dist/utils/retry.cjs.map +1 -1
  115. package/dist/utils/retry.mjs.map +1 -1
  116. package/dist/utils/signature.cjs.map +1 -1
  117. package/dist/utils/signature.mjs.map +1 -1
  118. package/dist/utils/swaps.cjs.map +1 -1
  119. package/dist/utils/swaps.mjs.map +1 -1
  120. package/dist/utils/transaction-type.cjs.map +1 -1
  121. package/dist/utils/transaction-type.mjs.map +1 -1
  122. package/dist/utils/utils.cjs +54 -1
  123. package/dist/utils/utils.cjs.map +1 -1
  124. package/dist/utils/utils.d.cts +17 -1
  125. package/dist/utils/utils.d.cts.map +1 -1
  126. package/dist/utils/utils.d.mts +17 -1
  127. package/dist/utils/utils.d.mts.map +1 -1
  128. package/dist/utils/utils.mjs +51 -0
  129. package/dist/utils/utils.mjs.map +1 -1
  130. package/dist/utils/validation.cjs.map +1 -1
  131. package/dist/utils/validation.mjs.map +1 -1
  132. package/package.json +5 -4
@@ -1 +1 @@
1
- {"version":3,"file":"swaps.mjs","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;;;AAInD,OAAO,EAAE,+BAA+B,EAAE,oBAAgB;AAC1D,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAG9D,OAAO,EAAE,eAAe,EAAE,qBAAiB;AAE3C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAChC,4CAA4C,CAAC;AAmB/C,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACb,CAAC;AAEF,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,cAAc;IACpB,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,wBAAwB,GAAqB;IACjD,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,uBAAuB,GAAqB;IAChD,IAAI,EAAE,WAAW;IACjB,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,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,OAAuD,CACxD,EAAE,OAAO,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 { validateIfTransactionUnapproved } from './utils';\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\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\nconst SEI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Sei',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MONAD_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Mon',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\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 [CHAIN_IDS.SEI]: SEI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.MONAD]: MONAD_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\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.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\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 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 transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\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 * @returns Updated transaction metadata and approval transaction metadata if applicable.\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 log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\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 log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\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\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\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 * @returns The updated transaction meta object.\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): TransactionMeta {\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\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.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return 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 * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return 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
+ {"version":3,"file":"swaps.mjs","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;;;AAInD,OAAO,EAAE,+BAA+B,EAAE,oBAAgB;AAC1D,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAG9D,OAAO,EAAE,eAAe,EAAE,qBAAiB;AAE3C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAChC,4CAA4C,CAAC;AAmB/C,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACb,CAAC;AAEF,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,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AE,IAAI,EAAE,iBAAiB,EAAS,CAAC;IACjE,uBAAuB,GAAG,MAAM,CAAC;QAC/B,IAAI;QACJ,iBAAiB;KAClB,CAA6B,CAAC;IAE/B,OAAO,KAAK,CAAC,EAAE,EAAE,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE,CAAC;QACzB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,CACL,OAAO;QACP,+BAA+B,CAC7B,OAAuD,CACxD,EAAE,OAAO,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 { validateIfTransactionUnapproved } from './utils';\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\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\nconst SEI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Sei',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MONAD_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Mon',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\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 [CHAIN_IDS.SEI]: SEI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.MONAD]: MONAD_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\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.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\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 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 transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\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 * @returns Updated transaction metadata and approval transaction metadata if applicable.\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 log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\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 log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\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\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\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 * @returns The updated transaction meta object.\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): TransactionMeta {\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 // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\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.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return 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 * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return 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 +1 @@
1
- {"version":3,"file":"transaction-type.cjs","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":";;;AAAA,4CAA4E;AAC5E,iEAAmD;AAEnD,mEAKqC;AAErC,2CAA8C;AAE9C,wCAA2C;AAE9B,QAAA,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,MAAM,cAAc,GAAG,IAAI,eAAS,CAAC,4BAAQ,CAAC,CAAC;AAC/C,MAAM,eAAe,GAAG,IAAI,eAAS,CAAC,6BAAS,CAAC,CAAC;AACjD,MAAM,gBAAgB,GAAG,IA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AC;IACjB,IAAI;QACF,YAAY,GAAG,MAAM,IAAA,wBAAK,EAAC,QAAQ,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;QAC3D,WAAW;QACX,6DAA6D;KAC9D;IAAC,OAAO,KAAK,EAAE;QACd,YAAY,GAAG,IAAI,CAAC;KACrB;IAED,MAAM,iBAAiB,GAAG,YAAY;QACpC,CAAC,CAAC,YAAY,KAAK,IAAI;YACrB,YAAY,KAAK,KAAK;YACtB,CAAC,YAAY,CAAC,UAAU,CAAC,2BAAiB,CAAC;QAC7C,CAAC,CAAC,KAAK,CAAC;IACV,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import { Interface, type TransactionDescription } from '@ethersproject/abi';\nimport { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport {\n abiERC721,\n abiERC20,\n abiERC1155,\n abiFiatTokenV2,\n} from '@metamask/metamask-eth-abis';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport type { InferTransactionTypeResult, TransactionParams } from '../types';\nimport { TransactionType } from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\nconst ERC20Interface = new Interface(abiERC20);\nconst ERC721Interface = new Interface(abiERC721);\nconst ERC1155Interface = new Interface(abiERC1155);\nconst USDCInterface = new Interface(abiFiatTokenV2);\n\n/**\n * Determines the type of the transaction by analyzing the txParams.\n * It will never return TRANSACTION_TYPE_CANCEL or TRANSACTION_TYPE_RETRY as these\n * represent specific events that we specify manually at transaction creation.\n *\n * @param txParams - Parameters for the transaction.\n * @param ethQuery - EthQuery instance.\n * @returns A object with the transaction type and the contract code response in Hex.\n */\nexport async function determineTransactionType(\n txParams: TransactionParams,\n ethQuery?: EthQuery,\n): Promise<InferTransactionTypeResult> {\n const { data, to } = txParams;\n\n if (data && !to) {\n return { type: TransactionType.deployContract, getCodeResponse: undefined };\n }\n\n let getCodeResponse;\n let isContractAddress = Boolean(data?.length);\n\n if (ethQuery) {\n const response = await readAddressAsContract(ethQuery, to);\n\n getCodeResponse = response.contractCode;\n isContractAddress = response.isContractAddress;\n }\n\n if (!isContractAddress) {\n return { type: TransactionType.simpleSend, getCodeResponse };\n }\n\n const hasValue = Number(txParams.value ?? '0') !== 0;\n\n const contractInteractionResult = {\n type: TransactionType.contractInteraction,\n getCodeResponse,\n };\n\n if (!data || hasValue) {\n return contractInteractionResult;\n }\n\n const name = getMethodName(data);\n\n if (!name) {\n return contractInteractionResult;\n }\n\n const tokenMethodName = [\n TransactionType.tokenMethodApprove,\n TransactionType.tokenMethodSetApprovalForAll,\n TransactionType.tokenMethodTransfer,\n TransactionType.tokenMethodTransferFrom,\n TransactionType.tokenMethodSafeTransferFrom,\n TransactionType.tokenMethodIncreaseAllowance,\n ].find(\n (methodName) => methodName.toLowerCase() === (name as string).toLowerCase(),\n );\n\n if (tokenMethodName) {\n return { type: tokenMethodName, getCodeResponse };\n }\n\n return contractInteractionResult;\n}\n\n/**\n * Parses transaction data using ABIs for three different token standards: ERC20, ERC721, ERC1155 and USDC.\n * The data will decode correctly if the transaction is an interaction with a contract that matches one of these\n * contract standards\n *\n * @param data - Encoded transaction data.\n * @param options - Options bag.\n * @param options.getMethodName - Whether to get the method name.\n * @returns A representation of an ethereum contract call.\n */\nexport function decodeTransactionData(\n data: string,\n options?: {\n getMethodName?: boolean;\n },\n): undefined | TransactionDescription | string {\n if (!data || data.length < 10) {\n return undefined;\n }\n\n const fourByte = data.substring(0, 10).toLowerCase();\n\n for (const iface of [\n ERC20Interface,\n ERC721Interface,\n ERC1155Interface,\n USDCInterface,\n ]) {\n try {\n if (options?.getMethodName) {\n return iface.getFunction(fourByte)?.name;\n }\n return iface.parseTransaction({ data });\n } catch {\n // Intentionally empty\n }\n }\n\n return undefined;\n}\n\n/**\n * Attempts to get the method name from the given transaction data.\n *\n * @param data - Encoded transaction data.\n * @returns The method name.\n */\nfunction getMethodName(data?: string): string | undefined {\n return decodeTransactionData(data as string, {\n getMethodName: true,\n }) as string | undefined;\n}\n\n/**\n * Reads an Ethereum address and determines if it is a contract address.\n *\n * @param ethQuery - The Ethereum query object used to interact with the Ethereum blockchain.\n * @param address - The Ethereum address.\n * @returns An object containing the contract code and a boolean indicating if it is a contract address.\n */\nasync function readAddressAsContract(\n ethQuery: EthQuery,\n address?: string,\n): Promise<{\n contractCode: string | null;\n isContractAddress: boolean;\n}> {\n let contractCode;\n try {\n contractCode = await query(ethQuery, 'getCode', [address]);\n // Not used\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (error) {\n contractCode = null;\n }\n\n const isContractAddress = contractCode\n ? contractCode !== '0x' &&\n contractCode !== '0x0' &&\n !contractCode.startsWith(DELEGATION_PREFIX)\n : false;\n return { contractCode, isContractAddress };\n}\n"]}
1
+ {"version":3,"file":"transaction-type.cjs","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":";;;AAAA,4CAA4E;AAC5E,iEAAmD;AAEnD,mEAKqC;AAErC,2CAA8C;AAE9C,wCAA2C;AAE9B,QAAA,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,MAAM,cAAc,GAAG,IAAI,eAAS,CAAC,4BAAQ,CAAC,CAAC;AAC/C,MAAM,eAAe,GAAG,IAAI,eAAS,CAAC,6BAAS,CAAC,CAAC;AACjD,MAAM,gBAAgB,GAAG,IAAI,eAAS,CAAC,8BAAU,CAAC,CAAC;AACnD,MAAM,aAAa,GAAG,IAAI,eAAS,CAAC,kCAAc,CAAC,CAAC;AAEpD;;;;;;;;GAQG;AACI,KAAK,UAAU,wBAAwB,CAC5C,QAA2B,EAC3B,QAAmB;IAEnB,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,QAAQ,CAAC;IAE9B,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC;QAChB,OAAO,EAAE,IAAI,EAAE,uBAAe,CAAC,cAAc,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;IA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M,iBAAiB,GAAG,YAAY;QACpC,CAAC,CAAC,YAAY,KAAK,IAAI;YACrB,YAAY,KAAK,KAAK;YACtB,CAAC,YAAY,CAAC,UAAU,CAAC,2BAAiB,CAAC;QAC7C,CAAC,CAAC,KAAK,CAAC;IACV,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import { Interface, type TransactionDescription } from '@ethersproject/abi';\nimport { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport {\n abiERC721,\n abiERC20,\n abiERC1155,\n abiFiatTokenV2,\n} from '@metamask/metamask-eth-abis';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport type { InferTransactionTypeResult, TransactionParams } from '../types';\nimport { TransactionType } from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\nconst ERC20Interface = new Interface(abiERC20);\nconst ERC721Interface = new Interface(abiERC721);\nconst ERC1155Interface = new Interface(abiERC1155);\nconst USDCInterface = new Interface(abiFiatTokenV2);\n\n/**\n * Determines the type of the transaction by analyzing the txParams.\n * It will never return TRANSACTION_TYPE_CANCEL or TRANSACTION_TYPE_RETRY as these\n * represent specific events that we specify manually at transaction creation.\n *\n * @param txParams - Parameters for the transaction.\n * @param ethQuery - EthQuery instance.\n * @returns A object with the transaction type and the contract code response in Hex.\n */\nexport async function determineTransactionType(\n txParams: TransactionParams,\n ethQuery?: EthQuery,\n): Promise<InferTransactionTypeResult> {\n const { data, to } = txParams;\n\n if (data && !to) {\n return { type: TransactionType.deployContract, getCodeResponse: undefined };\n }\n\n let getCodeResponse;\n let isContractAddress = Boolean(data?.length);\n\n if (ethQuery) {\n const response = await readAddressAsContract(ethQuery, to);\n\n getCodeResponse = response.contractCode;\n isContractAddress = response.isContractAddress;\n }\n\n if (!isContractAddress) {\n return { type: TransactionType.simpleSend, getCodeResponse };\n }\n\n const hasValue = Number(txParams.value ?? '0') !== 0;\n\n const contractInteractionResult = {\n type: TransactionType.contractInteraction,\n getCodeResponse,\n };\n\n if (!data || hasValue) {\n return contractInteractionResult;\n }\n\n const name = getMethodName(data);\n\n if (!name) {\n return contractInteractionResult;\n }\n\n const tokenMethodName = [\n TransactionType.tokenMethodApprove,\n TransactionType.tokenMethodSetApprovalForAll,\n TransactionType.tokenMethodTransfer,\n TransactionType.tokenMethodTransferFrom,\n TransactionType.tokenMethodSafeTransferFrom,\n TransactionType.tokenMethodIncreaseAllowance,\n ].find(\n (methodName) => methodName.toLowerCase() === (name as string).toLowerCase(),\n );\n\n if (tokenMethodName) {\n return { type: tokenMethodName, getCodeResponse };\n }\n\n return contractInteractionResult;\n}\n\n/**\n * Parses transaction data using ABIs for three different token standards: ERC20, ERC721, ERC1155 and USDC.\n * The data will decode correctly if the transaction is an interaction with a contract that matches one of these\n * contract standards\n *\n * @param data - Encoded transaction data.\n * @param options - Options bag.\n * @param options.getMethodName - Whether to get the method name.\n * @returns A representation of an ethereum contract call.\n */\nexport function decodeTransactionData(\n data: string,\n options?: {\n getMethodName?: boolean;\n },\n): undefined | TransactionDescription | string {\n if (!data || data.length < 10) {\n return undefined;\n }\n\n const fourByte = data.substring(0, 10).toLowerCase();\n\n for (const iface of [\n ERC20Interface,\n ERC721Interface,\n ERC1155Interface,\n USDCInterface,\n ]) {\n try {\n if (options?.getMethodName) {\n return iface.getFunction(fourByte)?.name;\n }\n return iface.parseTransaction({ data });\n } catch {\n // Intentionally empty\n }\n }\n\n return undefined;\n}\n\n/**\n * Attempts to get the method name from the given transaction data.\n *\n * @param data - Encoded transaction data.\n * @returns The method name.\n */\nfunction getMethodName(data?: string): string | undefined {\n return decodeTransactionData(data as string, {\n getMethodName: true,\n }) as string | undefined;\n}\n\n/**\n * Reads an Ethereum address and determines if it is a contract address.\n *\n * @param ethQuery - The Ethereum query object used to interact with the Ethereum blockchain.\n * @param address - The Ethereum address.\n * @returns An object containing the contract code and a boolean indicating if it is a contract address.\n */\nasync function readAddressAsContract(\n ethQuery: EthQuery,\n address?: string,\n): Promise<{\n contractCode: string | null;\n isContractAddress: boolean;\n}> {\n let contractCode;\n try {\n contractCode = await query(ethQuery, 'getCode', [address]);\n // Not used\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (error) {\n contractCode = null;\n }\n\n const isContractAddress = contractCode\n ? contractCode !== '0x' &&\n contractCode !== '0x0' &&\n !contractCode.startsWith(DELEGATION_PREFIX)\n : false;\n return { contractCode, isContractAddress };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-type.mjs","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAA+B,2BAA2B;AAC5E,OAAO,EAAE,KAAK,EAAE,mCAAmC;AAEnD,OAAO,EACL,SAAS,EACT,QAAQ,EACR,UAAU,EACV,cAAc,EACf,oCAAoC;AAErC,OAAO,EAAE,iBAAiB,EAAE,sBAAkB;AAE9C,OAAO,EAAE,eAAe,EAAE,qBAAiB;AAE3C,MAAM,CAAC,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,MAAM,cAAc,GAAG,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC;AAC/C,MAAM,eAAe,GAAG,IAAI,SAAS,CAAC,SAAS,CAAC,CAAC;AACjD,MAAM,gBAAgB,GAAG,IAAI,SAAS,CAAC,UAAU,CAAC,CAAC;AACnD,MAAM,aAAa,GAAG,IAAI,SAAS,CAAC,cAAc,CAAC,CAAC;AAEpD;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,QAA2B,EAC3B,QAAmB;IAEnB,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,QAAQ,CAAC;IAE9B,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE;QACf,OAAO,EAAE,IAAI,EAAE,eAAe,CAAC,cAAc,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;KAC7E;IAED,IAAI,eAAe,CAAC;IACpB,IAA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esContent":["import { Interface, type TransactionDescription } from '@ethersproject/abi';\nimport { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport {\n abiERC721,\n abiERC20,\n abiERC1155,\n abiFiatTokenV2,\n} from '@metamask/metamask-eth-abis';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport type { InferTransactionTypeResult, TransactionParams } from '../types';\nimport { TransactionType } from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\nconst ERC20Interface = new Interface(abiERC20);\nconst ERC721Interface = new Interface(abiERC721);\nconst ERC1155Interface = new Interface(abiERC1155);\nconst USDCInterface = new Interface(abiFiatTokenV2);\n\n/**\n * Determines the type of the transaction by analyzing the txParams.\n * It will never return TRANSACTION_TYPE_CANCEL or TRANSACTION_TYPE_RETRY as these\n * represent specific events that we specify manually at transaction creation.\n *\n * @param txParams - Parameters for the transaction.\n * @param ethQuery - EthQuery instance.\n * @returns A object with the transaction type and the contract code response in Hex.\n */\nexport async function determineTransactionType(\n txParams: TransactionParams,\n ethQuery?: EthQuery,\n): Promise<InferTransactionTypeResult> {\n const { data, to } = txParams;\n\n if (data && !to) {\n return { type: TransactionType.deployContract, getCodeResponse: undefined };\n }\n\n let getCodeResponse;\n let isContractAddress = Boolean(data?.length);\n\n if (ethQuery) {\n const response = await readAddressAsContract(ethQuery, to);\n\n getCodeResponse = response.contractCode;\n isContractAddress = response.isContractAddress;\n }\n\n if (!isContractAddress) {\n return { type: TransactionType.simpleSend, getCodeResponse };\n }\n\n const hasValue = Number(txParams.value ?? '0') !== 0;\n\n const contractInteractionResult = {\n type: TransactionType.contractInteraction,\n getCodeResponse,\n };\n\n if (!data || hasValue) {\n return contractInteractionResult;\n }\n\n const name = getMethodName(data);\n\n if (!name) {\n return contractInteractionResult;\n }\n\n const tokenMethodName = [\n TransactionType.tokenMethodApprove,\n TransactionType.tokenMethodSetApprovalForAll,\n TransactionType.tokenMethodTransfer,\n TransactionType.tokenMethodTransferFrom,\n TransactionType.tokenMethodSafeTransferFrom,\n TransactionType.tokenMethodIncreaseAllowance,\n ].find(\n (methodName) => methodName.toLowerCase() === (name as string).toLowerCase(),\n );\n\n if (tokenMethodName) {\n return { type: tokenMethodName, getCodeResponse };\n }\n\n return contractInteractionResult;\n}\n\n/**\n * Parses transaction data using ABIs for three different token standards: ERC20, ERC721, ERC1155 and USDC.\n * The data will decode correctly if the transaction is an interaction with a contract that matches one of these\n * contract standards\n *\n * @param data - Encoded transaction data.\n * @param options - Options bag.\n * @param options.getMethodName - Whether to get the method name.\n * @returns A representation of an ethereum contract call.\n */\nexport function decodeTransactionData(\n data: string,\n options?: {\n getMethodName?: boolean;\n },\n): undefined | TransactionDescription | string {\n if (!data || data.length < 10) {\n return undefined;\n }\n\n const fourByte = data.substring(0, 10).toLowerCase();\n\n for (const iface of [\n ERC20Interface,\n ERC721Interface,\n ERC1155Interface,\n USDCInterface,\n ]) {\n try {\n if (options?.getMethodName) {\n return iface.getFunction(fourByte)?.name;\n }\n return iface.parseTransaction({ data });\n } catch {\n // Intentionally empty\n }\n }\n\n return undefined;\n}\n\n/**\n * Attempts to get the method name from the given transaction data.\n *\n * @param data - Encoded transaction data.\n * @returns The method name.\n */\nfunction getMethodName(data?: string): string | undefined {\n return decodeTransactionData(data as string, {\n getMethodName: true,\n }) as string | undefined;\n}\n\n/**\n * Reads an Ethereum address and determines if it is a contract address.\n *\n * @param ethQuery - The Ethereum query object used to interact with the Ethereum blockchain.\n * @param address - The Ethereum address.\n * @returns An object containing the contract code and a boolean indicating if it is a contract address.\n */\nasync function readAddressAsContract(\n ethQuery: EthQuery,\n address?: string,\n): Promise<{\n contractCode: string | null;\n isContractAddress: boolean;\n}> {\n let contractCode;\n try {\n contractCode = await query(ethQuery, 'getCode', [address]);\n // Not used\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (error) {\n contractCode = null;\n }\n\n const isContractAddress = contractCode\n ? contractCode !== '0x' &&\n contractCode !== '0x0' &&\n !contractCode.startsWith(DELEGATION_PREFIX)\n : false;\n return { contractCode, isContractAddress };\n}\n"]}
1
+ {"version":3,"file":"transaction-type.mjs","sourceRoot":"","sources":["../../src/utils/transaction-type.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAA+B,2BAA2B;AAC5E,OAAO,EAAE,KAAK,EAAE,mCAAmC;AAEnD,OAAO,EACL,SAAS,EACT,QAAQ,EACR,UAAU,EACV,cAAc,EACf,oCAAoC;AAErC,OAAO,EAAE,iBAAiB,EAAE,sBAAkB;AAE9C,OAAO,EAAE,eAAe,EAAE,qBAAiB;AAE3C,MAAM,CAAC,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,MAAM,cAAc,GAAG,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC;AAC/C,MAAM,eAAe,GAAG,IAAI,SAAS,CAAC,SAAS,CAAC,CAAC;AACjD,MAAM,gBAAgB,GAAG,IAAI,SAAS,CAAC,UAAU,CAAC,CAAC;AACnD,MAAM,aAAa,GAAG,IAAI,SAAS,CAAC,cAAc,CAAC,CAAC;AAEpD;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAC5C,QAA2B,EAC3B,QAAmB;IAEnB,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,GAAG,QAAQ,CAAC;IAE9B,IAAI,IAAI,IAAI,CAAC,EAAE,EAAE,CAAC;QAChB,OAAO,EAAE,IAAI,EAAE,eAAe,CAAC,cAAc,EAAE,eAAe,EAAE,SAAS,EAAE,CAAC;IAC9E,CAAC;IAED,IAAI,eAAe,CAAC;IACpB,IAAI,iBAAiB,GAAG,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IAE9C,IAAI,QAAQ,EAAE,CAAC;QACb,MAAM,QAAQ,GAAG,MAAM,qBAAqB,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;QAE3D,eAAe,GAAG,QAAQ,CAAC,YAAY,CAAC;QACxC,iBAAiB,GAAG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AAC,EAAE,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;IAErD,KAAK,MAAM,KAAK,IAAI;QAClB,cAAc;QACd,eAAe;QACf,gBAAgB;QAChB,aAAa;KACd,EAAE,CAAC;QACF,IAAI,CAAC;YACH,IAAI,OAAO,EAAE,aAAa,EAAE,CAAC;gBAC3B,OAAO,KAAK,CAAC,WAAW,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC;YAC3C,CAAC;YACD,OAAO,KAAK,CAAC,gBAAgB,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC;QAC1C,CAAC;QAAC,MAAM,CAAC;YACP,sBAAsB;QACxB,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;;GAKG;AACH,SAAS,aAAa,CAAC,IAAa;IAClC,OAAO,qBAAqB,CAAC,IAAc,EAAE;QAC3C,aAAa,EAAE,IAAI;KACpB,CAAuB,CAAC;AAC3B,CAAC;AAED;;;;;;GAMG;AACH,KAAK,UAAU,qBAAqB,CAClC,QAAkB,EAClB,OAAgB;IAKhB,IAAI,YAAY,CAAC;IACjB,IAAI,CAAC;QACH,YAAY,GAAG,MAAM,KAAK,CAAC,QAAQ,EAAE,SAAS,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;QAC3D,WAAW;QACX,6DAA6D;IAC/D,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,YAAY,GAAG,IAAI,CAAC;IACtB,CAAC;IAED,MAAM,iBAAiB,GAAG,YAAY;QACpC,CAAC,CAAC,YAAY,KAAK,IAAI;YACrB,YAAY,KAAK,KAAK;YACtB,CAAC,YAAY,CAAC,UAAU,CAAC,iBAAiB,CAAC;QAC7C,CAAC,CAAC,KAAK,CAAC;IACV,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,CAAC;AAC7C,CAAC","sourcesContent":["import { Interface, type TransactionDescription } from '@ethersproject/abi';\nimport { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport {\n abiERC721,\n abiERC20,\n abiERC1155,\n abiFiatTokenV2,\n} from '@metamask/metamask-eth-abis';\n\nimport { DELEGATION_PREFIX } from './eip7702';\nimport type { InferTransactionTypeResult, TransactionParams } from '../types';\nimport { TransactionType } from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\nconst ERC20Interface = new Interface(abiERC20);\nconst ERC721Interface = new Interface(abiERC721);\nconst ERC1155Interface = new Interface(abiERC1155);\nconst USDCInterface = new Interface(abiFiatTokenV2);\n\n/**\n * Determines the type of the transaction by analyzing the txParams.\n * It will never return TRANSACTION_TYPE_CANCEL or TRANSACTION_TYPE_RETRY as these\n * represent specific events that we specify manually at transaction creation.\n *\n * @param txParams - Parameters for the transaction.\n * @param ethQuery - EthQuery instance.\n * @returns A object with the transaction type and the contract code response in Hex.\n */\nexport async function determineTransactionType(\n txParams: TransactionParams,\n ethQuery?: EthQuery,\n): Promise<InferTransactionTypeResult> {\n const { data, to } = txParams;\n\n if (data && !to) {\n return { type: TransactionType.deployContract, getCodeResponse: undefined };\n }\n\n let getCodeResponse;\n let isContractAddress = Boolean(data?.length);\n\n if (ethQuery) {\n const response = await readAddressAsContract(ethQuery, to);\n\n getCodeResponse = response.contractCode;\n isContractAddress = response.isContractAddress;\n }\n\n if (!isContractAddress) {\n return { type: TransactionType.simpleSend, getCodeResponse };\n }\n\n const hasValue = Number(txParams.value ?? '0') !== 0;\n\n const contractInteractionResult = {\n type: TransactionType.contractInteraction,\n getCodeResponse,\n };\n\n if (!data || hasValue) {\n return contractInteractionResult;\n }\n\n const name = getMethodName(data);\n\n if (!name) {\n return contractInteractionResult;\n }\n\n const tokenMethodName = [\n TransactionType.tokenMethodApprove,\n TransactionType.tokenMethodSetApprovalForAll,\n TransactionType.tokenMethodTransfer,\n TransactionType.tokenMethodTransferFrom,\n TransactionType.tokenMethodSafeTransferFrom,\n TransactionType.tokenMethodIncreaseAllowance,\n ].find(\n (methodName) => methodName.toLowerCase() === (name as string).toLowerCase(),\n );\n\n if (tokenMethodName) {\n return { type: tokenMethodName, getCodeResponse };\n }\n\n return contractInteractionResult;\n}\n\n/**\n * Parses transaction data using ABIs for three different token standards: ERC20, ERC721, ERC1155 and USDC.\n * The data will decode correctly if the transaction is an interaction with a contract that matches one of these\n * contract standards\n *\n * @param data - Encoded transaction data.\n * @param options - Options bag.\n * @param options.getMethodName - Whether to get the method name.\n * @returns A representation of an ethereum contract call.\n */\nexport function decodeTransactionData(\n data: string,\n options?: {\n getMethodName?: boolean;\n },\n): undefined | TransactionDescription | string {\n if (!data || data.length < 10) {\n return undefined;\n }\n\n const fourByte = data.substring(0, 10).toLowerCase();\n\n for (const iface of [\n ERC20Interface,\n ERC721Interface,\n ERC1155Interface,\n USDCInterface,\n ]) {\n try {\n if (options?.getMethodName) {\n return iface.getFunction(fourByte)?.name;\n }\n return iface.parseTransaction({ data });\n } catch {\n // Intentionally empty\n }\n }\n\n return undefined;\n}\n\n/**\n * Attempts to get the method name from the given transaction data.\n *\n * @param data - Encoded transaction data.\n * @returns The method name.\n */\nfunction getMethodName(data?: string): string | undefined {\n return decodeTransactionData(data as string, {\n getMethodName: true,\n }) as string | undefined;\n}\n\n/**\n * Reads an Ethereum address and determines if it is a contract address.\n *\n * @param ethQuery - The Ethereum query object used to interact with the Ethereum blockchain.\n * @param address - The Ethereum address.\n * @returns An object containing the contract code and a boolean indicating if it is a contract address.\n */\nasync function readAddressAsContract(\n ethQuery: EthQuery,\n address?: string,\n): Promise<{\n contractCode: string | null;\n isContractAddress: boolean;\n}> {\n let contractCode;\n try {\n contractCode = await query(ethQuery, 'getCode', [address]);\n // Not used\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (error) {\n contractCode = null;\n }\n\n const isContractAddress = contractCode\n ? contractCode !== '0x' &&\n contractCode !== '0x0' &&\n !contractCode.startsWith(DELEGATION_PREFIX)\n : false;\n return { contractCode, isContractAddress };\n}\n"]}
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.setEnvelopeType = exports.getPercentageChange = exports.padHexToEvenLength = exports.normalizeGasFeeValues = exports.normalizeTxError = exports.validateIfTransactionUnapproved = exports.validateGasValues = exports.isEIP1559Transaction = exports.normalizeTransactionParams = exports.ESTIMATE_GAS_ERROR = void 0;
6
+ exports.setEnvelopeType = exports.getPercentageChange = exports.toBN = exports.bnFromHex = exports.padHexToEvenLength = exports.normalizeGasFeeValues = exports.normalizeTxError = exports.validateIfTransactionUnapproved = exports.validateGasValues = exports.isEIP1559Transaction = exports.normalizeTransactionParams = exports.ESTIMATE_GAS_ERROR = void 0;
7
7
  const utils_1 = require("@metamask/utils");
8
8
  const bn_js_1 = __importDefault(require("bn.js"));
9
9
  const types_1 = require("../types.cjs");
@@ -151,6 +151,59 @@ function padHexToEvenLength(hex) {
151
151
  return prefix + evenData;
152
152
  }
153
153
  exports.padHexToEvenLength = padHexToEvenLength;
154
+ /**
155
+ * Create a BN from a hex string, accepting an optional 0x prefix.
156
+ *
157
+ * @param hex - Hex string with or without 0x prefix.
158
+ * @returns BN parsed as base-16.
159
+ */
160
+ function bnFromHex(hex) {
161
+ const str = typeof hex === 'string' ? hex : hex;
162
+ const withoutPrefix = str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;
163
+ if (withoutPrefix.length === 0) {
164
+ return new bn_js_1.default(0);
165
+ }
166
+ return new bn_js_1.default(withoutPrefix, 16);
167
+ }
168
+ exports.bnFromHex = bnFromHex;
169
+ /**
170
+ * Convert various numeric-like values to a BN instance.
171
+ * Accepts BN, ethers BigNumber, hex string, bigint, or number.
172
+ *
173
+ * @param value - The value to convert.
174
+ * @returns BN representation of the input value.
175
+ */
176
+ function toBN(value) {
177
+ if (value instanceof bn_js_1.default) {
178
+ return value;
179
+ }
180
+ if (typeof bn_js_1.default.isBN ===
181
+ 'function' &&
182
+ bn_js_1.default.isBN(value)) {
183
+ return value;
184
+ }
185
+ if (value !== null &&
186
+ typeof value === 'object' &&
187
+ typeof value.toHexString === 'function') {
188
+ return bnFromHex(value.toHexString());
189
+ }
190
+ if (value !== null &&
191
+ typeof value === 'object' &&
192
+ typeof value._hex === 'string') {
193
+ return bnFromHex(value._hex);
194
+ }
195
+ if (typeof value === 'string') {
196
+ return bnFromHex(value);
197
+ }
198
+ if (typeof value === 'bigint') {
199
+ return new bn_js_1.default(value.toString());
200
+ }
201
+ if (typeof value === 'number') {
202
+ return new bn_js_1.default(value);
203
+ }
204
+ throw new Error('Unexpected value returned from oracle contract');
205
+ }
206
+ exports.toBN = toBN;
154
207
  /**
155
208
  * Calculate the absolute percentage change between two values.
156
209
  *
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AACA,2CAIyB;AAEzB,kDAAuB;AAEvB,wCAAsE;AASzD,QAAA,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,MAAM,WAAW,GAAgD;IAC/D,UAAU,EAAE,CAAC,UAAuB,EAAE,EAAE,CAAC,UAAU;IACnD,iBAAiB,EAAE,CAAC,iBAAqC,EAAE,EAAE,CAC3D,iBAAiB;IACnB,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,IAAI,CAAC,CAAC,WAAW,EAAE;IACjD,GAAG,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,GAAG,CAAC;IAChC,QAAQ,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,GAAG,CAAC;IACrC,QAAQ,EAAE,CAAC,QAAgB,EAAE,EAAE,CAAC,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AC;KACjD;SAAM;QACL,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,+BAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,+BAAuB,CAAC,MAAM,CAAC;KACpC;AACH,CAAC;AAbD,0CAaC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport { TransactionEnvelopeType, TransactionStatus } from '../types';\nimport type {\n TransactionParams,\n TransactionMeta,\n TransactionError,\n GasPriceValue,\n FeeMarketEIP1559Values,\n} from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NORMALIZERS: { [param in keyof TransactionParams]: any } = {\n accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\n data: (data: string) => add0x(padHexToEvenLength(data)),\n from: (from: string) => add0x(from).toLowerCase(),\n gas: (gas: string) => add0x(gas),\n gasLimit: (gas: string) => add0x(gas),\n gasPrice: (gasPrice: string) => add0x(gasPrice),\n nonce: (nonce: string) => add0x(nonce),\n to: (to: string) => add0x(to).toLowerCase(),\n value: (value: string) => add0x(value),\n maxFeePerGas: (maxFeePerGas: string) => add0x(maxFeePerGas),\n maxPriorityFeePerGas: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n estimatedBaseFee: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n type: (type: string) => add0x(type),\n};\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param txParams - The transaction params to normalize.\n * @returns Normalized transaction params.\n */\nexport function normalizeTransactionParams(txParams: TransactionParams) {\n const normalizedTxParams: TransactionParams = { from: '' };\n\n for (const key of getKnownPropertyNames(NORMALIZERS)) {\n if (txParams[key]) {\n normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);\n }\n }\n\n if (!normalizedTxParams.value) {\n normalizedTxParams.value = '0x0';\n }\n\n if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\n }\n\n return normalizedTxParams;\n}\n\n/**\n * Checks if a transaction is EIP-1559 by checking for the existence of\n * maxFeePerGas and maxPriorityFeePerGas within its parameters.\n *\n * @param txParams - Transaction params object to add.\n * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.\n */\nexport function isEIP1559Transaction(txParams: TransactionParams): boolean {\n const hasOwnProp = (obj: TransactionParams, key: string) =>\n Object.prototype.hasOwnProperty.call(obj, key);\n return (\n hasOwnProp(txParams, 'maxFeePerGas') &&\n hasOwnProp(txParams, 'maxPriorityFeePerGas')\n );\n}\n\nexport const validateGasValues = (\n gasValues: GasPriceValue | FeeMarketEIP1559Values,\n) => {\n Object.keys(gasValues).forEach((key) => {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (gasValues as any)[key];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw new TypeError(\n `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\n};\n\n/**\n * Validates that a transaction is unapproved.\n * Throws if the transaction is not unapproved.\n *\n * @param transactionMeta - The transaction metadata to check.\n * @param fnName - The name of the function calling this helper.\n */\nexport function validateIfTransactionUnapproved(\n transactionMeta: TransactionMeta | undefined,\n fnName: string,\n) {\n if (transactionMeta?.status !== TransactionStatus.unapproved) {\n throw new Error(\n `TransactionsController: Can only call ${fnName} on an unapproved transaction.\\n Current tx status: ${transactionMeta?.status}`,\n );\n }\n}\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param error - The error to be normalize.\n * @returns Normalized transaction error.\n */\nexport function normalizeTxError(\n error: Error & { code?: string; value?: unknown },\n): TransactionError {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n code: error.code,\n rpc: isJsonCompatible(error.value) ? error.value : undefined,\n };\n}\n\n/**\n * Normalize an object containing gas fee values.\n *\n * @param gasFeeValues - An object containing gas fee values.\n * @returns An object containing normalized gas fee values.\n */\nexport function normalizeGasFeeValues(\n gasFeeValues: GasPriceValue | FeeMarketEIP1559Values,\n): GasPriceValue | FeeMarketEIP1559Values {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const normalize = (value: any) =>\n typeof value === 'string' ? add0x(value) : value;\n\n if ('gasPrice' in gasFeeValues) {\n return {\n gasPrice: normalize(gasFeeValues.gasPrice),\n };\n }\n\n return {\n maxFeePerGas: normalize(gasFeeValues.maxFeePerGas),\n maxPriorityFeePerGas: normalize(gasFeeValues.maxPriorityFeePerGas),\n };\n}\n\n/**\n * Determines whether the given value can be encoded as JSON.\n *\n * @param value - The value.\n * @returns True if the value is JSON-encodable, false if not.\n */\nfunction isJsonCompatible(value: unknown): value is Json {\n try {\n JSON.parse(JSON.stringify(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a hex string is of even length by adding a leading 0 if necessary.\n * Any existing `0x` prefix is preserved but is not added if missing.\n *\n * @param hex - The hex string to ensure is even.\n * @returns The hex string with an even length.\n */\nexport function padHexToEvenLength(hex: string) {\n const prefix = hex.toLowerCase().startsWith('0x') ? hex.slice(0, 2) : '';\n const data = prefix ? hex.slice(2) : hex;\n const evenData = data.length % 2 === 0 ? data : `0${data}`;\n\n return prefix + evenData;\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
1
+ {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AAEA,2CAIyB;AACzB,kDAAuB;AASvB,wCAAsE;AAEzD,QAAA,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,MAAM,WAAW,GAAgD;IAC/D,UAAU,EAAE,CAAC,UAAuB,EAAE,EAAE,CAAC,UAAU;IACnD,iBAAiB,EAAE,CAAC,iBAAqC,EAAE,EAAE,CAC3D,iBAAiB;IACnB,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,IAAI,CAAC,CAAC,WAAW,EAAE;IACjD,GAAG,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,GAAG,CAAC;IAChC,QAAQ,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,GAAG,CAAC;IACrC,QAAQ,EAAE,CAAC,QAAgB,EAAE,EA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AAE,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,EAAE,CAAC;QACnE,OAAO,GAAG,CAAC;IACb,CAAC;IAED,OAAO,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC;AAC3E,CAAC;AAhBD,kDAgBC;AAED;;;;;;GAMG;AACH,SAAgB,eAAe,CAC7B,QAA2B,EAC3B,mBAA4B;IAE5B,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;QACxB,QAAQ,CAAC,IAAI,GAAG,+BAAuB,CAAC,UAAU,CAAC;IACrD,CAAC;SAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE,CAAC;QACtC,QAAQ,CAAC,IAAI,GAAG,+BAAuB,CAAC,OAAO,CAAC;IAClD,CAAC;SAAM,CAAC;QACN,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,+BAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,+BAAuB,CAAC,MAAM,CAAC;IACrC,CAAC;AACH,CAAC;AAbD,0CAaC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionError,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { TransactionEnvelopeType, TransactionStatus } from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NORMALIZERS: { [param in keyof TransactionParams]: any } = {\n accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\n data: (data: string) => add0x(padHexToEvenLength(data)),\n from: (from: string) => add0x(from).toLowerCase(),\n gas: (gas: string) => add0x(gas),\n gasLimit: (gas: string) => add0x(gas),\n gasPrice: (gasPrice: string) => add0x(gasPrice),\n nonce: (nonce: string) => add0x(nonce),\n to: (to: string) => add0x(to).toLowerCase(),\n value: (value: string) => add0x(value),\n maxFeePerGas: (maxFeePerGas: string) => add0x(maxFeePerGas),\n maxPriorityFeePerGas: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n estimatedBaseFee: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n type: (type: string) => add0x(type),\n};\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param txParams - The transaction params to normalize.\n * @returns Normalized transaction params.\n */\nexport function normalizeTransactionParams(txParams: TransactionParams) {\n const normalizedTxParams: TransactionParams = { from: '' };\n\n for (const key of getKnownPropertyNames(NORMALIZERS)) {\n if (txParams[key]) {\n normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);\n }\n }\n\n if (!normalizedTxParams.value) {\n normalizedTxParams.value = '0x0';\n }\n\n if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\n }\n\n return normalizedTxParams;\n}\n\n/**\n * Checks if a transaction is EIP-1559 by checking for the existence of\n * maxFeePerGas and maxPriorityFeePerGas within its parameters.\n *\n * @param txParams - Transaction params object to add.\n * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.\n */\nexport function isEIP1559Transaction(txParams: TransactionParams): boolean {\n const hasOwnProp = (obj: TransactionParams, key: string) =>\n Object.prototype.hasOwnProperty.call(obj, key);\n return (\n hasOwnProp(txParams, 'maxFeePerGas') &&\n hasOwnProp(txParams, 'maxPriorityFeePerGas')\n );\n}\n\nexport const validateGasValues = (\n gasValues: GasPriceValue | FeeMarketEIP1559Values,\n) => {\n Object.keys(gasValues).forEach((key) => {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (gasValues as any)[key];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw new TypeError(\n `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\n};\n\n/**\n * Validates that a transaction is unapproved.\n * Throws if the transaction is not unapproved.\n *\n * @param transactionMeta - The transaction metadata to check.\n * @param fnName - The name of the function calling this helper.\n */\nexport function validateIfTransactionUnapproved(\n transactionMeta: TransactionMeta | undefined,\n fnName: string,\n) {\n if (transactionMeta?.status !== TransactionStatus.unapproved) {\n throw new Error(\n `TransactionsController: Can only call ${fnName} on an unapproved transaction.\\n Current tx status: ${transactionMeta?.status}`,\n );\n }\n}\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param error - The error to be normalize.\n * @returns Normalized transaction error.\n */\nexport function normalizeTxError(\n error: Error & { code?: string; value?: unknown },\n): TransactionError {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n code: error.code,\n rpc: isJsonCompatible(error.value) ? error.value : undefined,\n };\n}\n\n/**\n * Normalize an object containing gas fee values.\n *\n * @param gasFeeValues - An object containing gas fee values.\n * @returns An object containing normalized gas fee values.\n */\nexport function normalizeGasFeeValues(\n gasFeeValues: GasPriceValue | FeeMarketEIP1559Values,\n): GasPriceValue | FeeMarketEIP1559Values {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const normalize = (value: any) =>\n typeof value === 'string' ? add0x(value) : value;\n\n if ('gasPrice' in gasFeeValues) {\n return {\n gasPrice: normalize(gasFeeValues.gasPrice),\n };\n }\n\n return {\n maxFeePerGas: normalize(gasFeeValues.maxFeePerGas),\n maxPriorityFeePerGas: normalize(gasFeeValues.maxPriorityFeePerGas),\n };\n}\n\n/**\n * Determines whether the given value can be encoded as JSON.\n *\n * @param value - The value.\n * @returns True if the value is JSON-encodable, false if not.\n */\nfunction isJsonCompatible(value: unknown): value is Json {\n try {\n JSON.parse(JSON.stringify(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a hex string is of even length by adding a leading 0 if necessary.\n * Any existing `0x` prefix is preserved but is not added if missing.\n *\n * @param hex - The hex string to ensure is even.\n * @returns The hex string with an even length.\n */\nexport function padHexToEvenLength(hex: string) {\n const prefix = hex.toLowerCase().startsWith('0x') ? hex.slice(0, 2) : '';\n const data = prefix ? hex.slice(2) : hex;\n const evenData = data.length % 2 === 0 ? data : `0${data}`;\n\n return prefix + evenData;\n}\n\n/**\n * Create a BN from a hex string, accepting an optional 0x prefix.\n *\n * @param hex - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hex: string | Hex): BN {\n const str = typeof hex === 'string' ? hex : (hex as string);\n const withoutPrefix =\n str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;\n if (withoutPrefix.length === 0) {\n return new BN(0);\n }\n return new BN(withoutPrefix, 16);\n}\n\n/**\n * Convert various numeric-like values to a BN instance.\n * Accepts BN, ethers BigNumber, hex string, bigint, or number.\n *\n * @param value - The value to convert.\n * @returns BN representation of the input value.\n */\nexport function toBN(value: unknown): BN {\n if (value instanceof BN) {\n return value as BN;\n }\n if (\n typeof (BN as unknown as { isBN?: (v: unknown) => boolean }).isBN ===\n 'function' &&\n (BN as unknown as { isBN: (v: unknown) => boolean }).isBN(value)\n ) {\n return value as BN;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { toHexString?: () => string }).toHexString === 'function'\n ) {\n return bnFromHex((value as { toHexString: () => string }).toHexString());\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { _hex?: string })._hex === 'string'\n ) {\n return bnFromHex((value as { _hex: string })._hex);\n }\n if (typeof value === 'string') {\n return bnFromHex(value);\n }\n if (typeof value === 'bigint') {\n return new BN(value.toString());\n }\n if (typeof value === 'number') {\n return new BN(value);\n }\n throw new Error('Unexpected value returned from oracle contract');\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
+ import type { Hex } from "@metamask/utils";
1
2
  import BN from "bn.js";
2
- import type { TransactionParams, TransactionMeta, TransactionError, GasPriceValue, FeeMarketEIP1559Values } from "../types.cjs";
3
+ import type { FeeMarketEIP1559Values, GasPriceValue, TransactionError, TransactionMeta, TransactionParams } from "../types.cjs";
3
4
  export declare const ESTIMATE_GAS_ERROR = "eth_estimateGas rpc method error";
4
5
  /**
5
6
  * Normalizes properties on transaction params.
@@ -50,6 +51,21 @@ export declare function normalizeGasFeeValues(gasFeeValues: GasPriceValue | FeeM
50
51
  * @returns The hex string with an even length.
51
52
  */
52
53
  export declare function padHexToEvenLength(hex: string): string;
54
+ /**
55
+ * Create a BN from a hex string, accepting an optional 0x prefix.
56
+ *
57
+ * @param hex - Hex string with or without 0x prefix.
58
+ * @returns BN parsed as base-16.
59
+ */
60
+ export declare function bnFromHex(hex: string | Hex): BN;
61
+ /**
62
+ * Convert various numeric-like values to a BN instance.
63
+ * Accepts BN, ethers BigNumber, hex string, bigint, or number.
64
+ *
65
+ * @param value - The value to convert.
66
+ * @returns BN representation of the input value.
67
+ */
68
+ export declare function toBN(value: unknown): BN;
53
69
  /**
54
70
  * Calculate the absolute percentage change between two values.
55
71
  *
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,cAAc;AAGvB,OAAO,KAAK,EACV,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,sBAAsB,EACvB,qBAAiB;AAElB,eAAO,MAAM,kBAAkB,qCAAqC,CAAC;AAwBrE;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,iBAAiB,qBAkBrE;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAOzE;AAED,eAAO,MAAM,iBAAiB,cACjB,aAAa,GAAG,sBAAsB,SAYlD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAC7C,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,QAOf;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,KAAK,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,GAChD,gBAAgB,CAQlB;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,aAAa,GAAG,sBAAsB,GACnD,aAAa,GAAG,sBAAsB,CAgBxC;AAiBD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,UAM7C;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,E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ACH,wBAAgB,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG,EAAE,CAmCvC;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,GAAG,MAAM,CAgB3E;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,EAAE,OAAO,QAW7B"}
@@ -1,5 +1,6 @@
1
+ import type { Hex } from "@metamask/utils";
1
2
  import BN from "bn.js";
2
- import type { TransactionParams, TransactionMeta, TransactionError, GasPriceValue, FeeMarketEIP1559Values } from "../types.mjs";
3
+ import type { FeeMarketEIP1559Values, GasPriceValue, TransactionError, TransactionMeta, TransactionParams } from "../types.mjs";
3
4
  export declare const ESTIMATE_GAS_ERROR = "eth_estimateGas rpc method error";
4
5
  /**
5
6
  * Normalizes properties on transaction params.
@@ -50,6 +51,21 @@ export declare function normalizeGasFeeValues(gasFeeValues: GasPriceValue | FeeM
50
51
  * @returns The hex string with an even length.
51
52
  */
52
53
  export declare function padHexToEvenLength(hex: string): string;
54
+ /**
55
+ * Create a BN from a hex string, accepting an optional 0x prefix.
56
+ *
57
+ * @param hex - Hex string with or without 0x prefix.
58
+ * @returns BN parsed as base-16.
59
+ */
60
+ export declare function bnFromHex(hex: string | Hex): BN;
61
+ /**
62
+ * Convert various numeric-like values to a BN instance.
63
+ * Accepts BN, ethers BigNumber, hex string, bigint, or number.
64
+ *
65
+ * @param value - The value to convert.
66
+ * @returns BN representation of the input value.
67
+ */
68
+ export declare function toBN(value: unknown): BN;
53
69
  /**
54
70
  * Calculate the absolute percentage change between two values.
55
71
  *
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,cAAc;AAGvB,OAAO,KAAK,EACV,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,sBAA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C,CAAC;AAwBrE;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,iBAAiB,qBAkBrE;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAOzE;AAED,eAAO,MAAM,iBAAiB,cACjB,aAAa,GAAG,sBAAsB,SAYlD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAC7C,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,QAOf;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,KAAK,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,GAChD,gBAAgB,CAQlB;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,aAAa,GAAG,sBAAsB,GACnD,aAAa,GAAG,sBAAsB,CAgBxC;AAiBD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,UAM7C;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,EAAE,CAQ/C;AAED;;;;;;GAMG;AACH,wBAAgB,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG,EAAE,CAmCvC;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,GAAG,MAAM,CAgB3E;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,EAAE,OAAO,QAW7B"}
@@ -145,6 +145,57 @@ export function padHexToEvenLength(hex) {
145
145
  const evenData = data.length % 2 === 0 ? data : `0${data}`;
146
146
  return prefix + evenData;
147
147
  }
148
+ /**
149
+ * Create a BN from a hex string, accepting an optional 0x prefix.
150
+ *
151
+ * @param hex - Hex string with or without 0x prefix.
152
+ * @returns BN parsed as base-16.
153
+ */
154
+ export function bnFromHex(hex) {
155
+ const str = typeof hex === 'string' ? hex : hex;
156
+ const withoutPrefix = str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;
157
+ if (withoutPrefix.length === 0) {
158
+ return new BN(0);
159
+ }
160
+ return new BN(withoutPrefix, 16);
161
+ }
162
+ /**
163
+ * Convert various numeric-like values to a BN instance.
164
+ * Accepts BN, ethers BigNumber, hex string, bigint, or number.
165
+ *
166
+ * @param value - The value to convert.
167
+ * @returns BN representation of the input value.
168
+ */
169
+ export function toBN(value) {
170
+ if (value instanceof BN) {
171
+ return value;
172
+ }
173
+ if (typeof BN.isBN ===
174
+ 'function' &&
175
+ BN.isBN(value)) {
176
+ return value;
177
+ }
178
+ if (value !== null &&
179
+ typeof value === 'object' &&
180
+ typeof value.toHexString === 'function') {
181
+ return bnFromHex(value.toHexString());
182
+ }
183
+ if (value !== null &&
184
+ typeof value === 'object' &&
185
+ typeof value._hex === 'string') {
186
+ return bnFromHex(value._hex);
187
+ }
188
+ if (typeof value === 'string') {
189
+ return bnFromHex(value);
190
+ }
191
+ if (typeof value === 'bigint') {
192
+ return new BN(value.toString());
193
+ }
194
+ if (typeof value === 'number') {
195
+ return new BN(value);
196
+ }
197
+ throw new Error('Unexpected value returned from oracle contract');
198
+ }
148
199
  /**
149
200
  * Calculate the absolute percentage change between two values.
150
201
  *
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,iBAAiB,EAClB,wBAAwB;AAEzB,OAAO,GAAE,cAAc;;AAEvB,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,qBAAiB;AAStE,MAAM,CAAC,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,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I,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC;AAC3E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,QAA2B,EAC3B,mBAA4B;IAE5B,IAAI,QAAQ,CAAC,UAAU,EAAE;QACvB,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,UAAU,CAAC;KACpD;SAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE;QACrC,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,OAAO,CAAC;KACjD;SAAM;QACL,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,uBAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,uBAAuB,CAAC,MAAM,CAAC;KACpC;AACH,CAAC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport { TransactionEnvelopeType, TransactionStatus } from '../types';\nimport type {\n TransactionParams,\n TransactionMeta,\n TransactionError,\n GasPriceValue,\n FeeMarketEIP1559Values,\n} from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NORMALIZERS: { [param in keyof TransactionParams]: any } = {\n accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\n data: (data: string) => add0x(padHexToEvenLength(data)),\n from: (from: string) => add0x(from).toLowerCase(),\n gas: (gas: string) => add0x(gas),\n gasLimit: (gas: string) => add0x(gas),\n gasPrice: (gasPrice: string) => add0x(gasPrice),\n nonce: (nonce: string) => add0x(nonce),\n to: (to: string) => add0x(to).toLowerCase(),\n value: (value: string) => add0x(value),\n maxFeePerGas: (maxFeePerGas: string) => add0x(maxFeePerGas),\n maxPriorityFeePerGas: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n estimatedBaseFee: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n type: (type: string) => add0x(type),\n};\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param txParams - The transaction params to normalize.\n * @returns Normalized transaction params.\n */\nexport function normalizeTransactionParams(txParams: TransactionParams) {\n const normalizedTxParams: TransactionParams = { from: '' };\n\n for (const key of getKnownPropertyNames(NORMALIZERS)) {\n if (txParams[key]) {\n normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);\n }\n }\n\n if (!normalizedTxParams.value) {\n normalizedTxParams.value = '0x0';\n }\n\n if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\n }\n\n return normalizedTxParams;\n}\n\n/**\n * Checks if a transaction is EIP-1559 by checking for the existence of\n * maxFeePerGas and maxPriorityFeePerGas within its parameters.\n *\n * @param txParams - Transaction params object to add.\n * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.\n */\nexport function isEIP1559Transaction(txParams: TransactionParams): boolean {\n const hasOwnProp = (obj: TransactionParams, key: string) =>\n Object.prototype.hasOwnProperty.call(obj, key);\n return (\n hasOwnProp(txParams, 'maxFeePerGas') &&\n hasOwnProp(txParams, 'maxPriorityFeePerGas')\n );\n}\n\nexport const validateGasValues = (\n gasValues: GasPriceValue | FeeMarketEIP1559Values,\n) => {\n Object.keys(gasValues).forEach((key) => {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (gasValues as any)[key];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw new TypeError(\n `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\n};\n\n/**\n * Validates that a transaction is unapproved.\n * Throws if the transaction is not unapproved.\n *\n * @param transactionMeta - The transaction metadata to check.\n * @param fnName - The name of the function calling this helper.\n */\nexport function validateIfTransactionUnapproved(\n transactionMeta: TransactionMeta | undefined,\n fnName: string,\n) {\n if (transactionMeta?.status !== TransactionStatus.unapproved) {\n throw new Error(\n `TransactionsController: Can only call ${fnName} on an unapproved transaction.\\n Current tx status: ${transactionMeta?.status}`,\n );\n }\n}\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param error - The error to be normalize.\n * @returns Normalized transaction error.\n */\nexport function normalizeTxError(\n error: Error & { code?: string; value?: unknown },\n): TransactionError {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n code: error.code,\n rpc: isJsonCompatible(error.value) ? error.value : undefined,\n };\n}\n\n/**\n * Normalize an object containing gas fee values.\n *\n * @param gasFeeValues - An object containing gas fee values.\n * @returns An object containing normalized gas fee values.\n */\nexport function normalizeGasFeeValues(\n gasFeeValues: GasPriceValue | FeeMarketEIP1559Values,\n): GasPriceValue | FeeMarketEIP1559Values {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const normalize = (value: any) =>\n typeof value === 'string' ? add0x(value) : value;\n\n if ('gasPrice' in gasFeeValues) {\n return {\n gasPrice: normalize(gasFeeValues.gasPrice),\n };\n }\n\n return {\n maxFeePerGas: normalize(gasFeeValues.maxFeePerGas),\n maxPriorityFeePerGas: normalize(gasFeeValues.maxPriorityFeePerGas),\n };\n}\n\n/**\n * Determines whether the given value can be encoded as JSON.\n *\n * @param value - The value.\n * @returns True if the value is JSON-encodable, false if not.\n */\nfunction isJsonCompatible(value: unknown): value is Json {\n try {\n JSON.parse(JSON.stringify(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a hex string is of even length by adding a leading 0 if necessary.\n * Any existing `0x` prefix is preserved but is not added if missing.\n *\n * @param hex - The hex string to ensure is even.\n * @returns The hex string with an even length.\n */\nexport function padHexToEvenLength(hex: string) {\n const prefix = hex.toLowerCase().startsWith('0x') ? hex.slice(0, 2) : '';\n const data = prefix ? hex.slice(2) : hex;\n const evenData = data.length % 2 === 0 ? data : `0${data}`;\n\n return prefix + evenData;\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
1
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AAEA,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,iBAAiB,EAClB,wBAAwB;AACzB,OAAO,GAAE,cAAc;;AASvB,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,qBAAiB;AAEtE,MAAM,CAAC,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,MAAM,WAAW,GAAgD;IAC/D,UAAU,EAAE,CAAC,UAAuB,EAA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AG,aAAa,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;IAClE,MAAM,iBAAiB,GAAG,QAAQ,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;IAExD,MAAM,UAAU,GAAG,iBAAiB,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAEjE,IAAI,UAAU,CAAC,MAAM,EAAE,EAAE,CAAC;QACxB,OAAO,CAAC,CAAC;IACX,CAAC;IAED,IAAI,sBAAsB,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,CAAC,MAAM,EAAE,EAAE,CAAC;QACnE,OAAO,GAAG,CAAC;IACb,CAAC;IAED,OAAO,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC;AAC3E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,QAA2B,EAC3B,mBAA4B;IAE5B,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;QACxB,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,UAAU,CAAC;IACrD,CAAC;SAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE,CAAC;QACtC,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,OAAO,CAAC;IAClD,CAAC;SAAM,CAAC;QACN,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,uBAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,uBAAuB,CAAC,MAAM,CAAC;IACrC,CAAC;AACH,CAAC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionError,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { TransactionEnvelopeType, TransactionStatus } from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NORMALIZERS: { [param in keyof TransactionParams]: any } = {\n accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\n data: (data: string) => add0x(padHexToEvenLength(data)),\n from: (from: string) => add0x(from).toLowerCase(),\n gas: (gas: string) => add0x(gas),\n gasLimit: (gas: string) => add0x(gas),\n gasPrice: (gasPrice: string) => add0x(gasPrice),\n nonce: (nonce: string) => add0x(nonce),\n to: (to: string) => add0x(to).toLowerCase(),\n value: (value: string) => add0x(value),\n maxFeePerGas: (maxFeePerGas: string) => add0x(maxFeePerGas),\n maxPriorityFeePerGas: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n estimatedBaseFee: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n type: (type: string) => add0x(type),\n};\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param txParams - The transaction params to normalize.\n * @returns Normalized transaction params.\n */\nexport function normalizeTransactionParams(txParams: TransactionParams) {\n const normalizedTxParams: TransactionParams = { from: '' };\n\n for (const key of getKnownPropertyNames(NORMALIZERS)) {\n if (txParams[key]) {\n normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);\n }\n }\n\n if (!normalizedTxParams.value) {\n normalizedTxParams.value = '0x0';\n }\n\n if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\n }\n\n return normalizedTxParams;\n}\n\n/**\n * Checks if a transaction is EIP-1559 by checking for the existence of\n * maxFeePerGas and maxPriorityFeePerGas within its parameters.\n *\n * @param txParams - Transaction params object to add.\n * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.\n */\nexport function isEIP1559Transaction(txParams: TransactionParams): boolean {\n const hasOwnProp = (obj: TransactionParams, key: string) =>\n Object.prototype.hasOwnProperty.call(obj, key);\n return (\n hasOwnProp(txParams, 'maxFeePerGas') &&\n hasOwnProp(txParams, 'maxPriorityFeePerGas')\n );\n}\n\nexport const validateGasValues = (\n gasValues: GasPriceValue | FeeMarketEIP1559Values,\n) => {\n Object.keys(gasValues).forEach((key) => {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (gasValues as any)[key];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw new TypeError(\n `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\n};\n\n/**\n * Validates that a transaction is unapproved.\n * Throws if the transaction is not unapproved.\n *\n * @param transactionMeta - The transaction metadata to check.\n * @param fnName - The name of the function calling this helper.\n */\nexport function validateIfTransactionUnapproved(\n transactionMeta: TransactionMeta | undefined,\n fnName: string,\n) {\n if (transactionMeta?.status !== TransactionStatus.unapproved) {\n throw new Error(\n `TransactionsController: Can only call ${fnName} on an unapproved transaction.\\n Current tx status: ${transactionMeta?.status}`,\n );\n }\n}\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param error - The error to be normalize.\n * @returns Normalized transaction error.\n */\nexport function normalizeTxError(\n error: Error & { code?: string; value?: unknown },\n): TransactionError {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n code: error.code,\n rpc: isJsonCompatible(error.value) ? error.value : undefined,\n };\n}\n\n/**\n * Normalize an object containing gas fee values.\n *\n * @param gasFeeValues - An object containing gas fee values.\n * @returns An object containing normalized gas fee values.\n */\nexport function normalizeGasFeeValues(\n gasFeeValues: GasPriceValue | FeeMarketEIP1559Values,\n): GasPriceValue | FeeMarketEIP1559Values {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const normalize = (value: any) =>\n typeof value === 'string' ? add0x(value) : value;\n\n if ('gasPrice' in gasFeeValues) {\n return {\n gasPrice: normalize(gasFeeValues.gasPrice),\n };\n }\n\n return {\n maxFeePerGas: normalize(gasFeeValues.maxFeePerGas),\n maxPriorityFeePerGas: normalize(gasFeeValues.maxPriorityFeePerGas),\n };\n}\n\n/**\n * Determines whether the given value can be encoded as JSON.\n *\n * @param value - The value.\n * @returns True if the value is JSON-encodable, false if not.\n */\nfunction isJsonCompatible(value: unknown): value is Json {\n try {\n JSON.parse(JSON.stringify(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a hex string is of even length by adding a leading 0 if necessary.\n * Any existing `0x` prefix is preserved but is not added if missing.\n *\n * @param hex - The hex string to ensure is even.\n * @returns The hex string with an even length.\n */\nexport function padHexToEvenLength(hex: string) {\n const prefix = hex.toLowerCase().startsWith('0x') ? hex.slice(0, 2) : '';\n const data = prefix ? hex.slice(2) : hex;\n const evenData = data.length % 2 === 0 ? data : `0${data}`;\n\n return prefix + evenData;\n}\n\n/**\n * Create a BN from a hex string, accepting an optional 0x prefix.\n *\n * @param hex - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hex: string | Hex): BN {\n const str = typeof hex === 'string' ? hex : (hex as string);\n const withoutPrefix =\n str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;\n if (withoutPrefix.length === 0) {\n return new BN(0);\n }\n return new BN(withoutPrefix, 16);\n}\n\n/**\n * Convert various numeric-like values to a BN instance.\n * Accepts BN, ethers BigNumber, hex string, bigint, or number.\n *\n * @param value - The value to convert.\n * @returns BN representation of the input value.\n */\nexport function toBN(value: unknown): BN {\n if (value instanceof BN) {\n return value as BN;\n }\n if (\n typeof (BN as unknown as { isBN?: (v: unknown) => boolean }).isBN ===\n 'function' &&\n (BN as unknown as { isBN: (v: unknown) => boolean }).isBN(value)\n ) {\n return value as BN;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { toHexString?: () => string }).toHexString === 'function'\n ) {\n return bnFromHex((value as { toHexString: () => string }).toHexString());\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { _hex?: string })._hex === 'string'\n ) {\n return bnFromHex((value as { _hex: string })._hex);\n }\n if (typeof value === 'string') {\n return bnFromHex(value);\n }\n if (typeof value === 'bigint') {\n return new BN(value.toString());\n }\n if (typeof value === 'number') {\n return new BN(value);\n }\n throw new Error('Unexpected value returned from oracle contract');\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}