@metamask/transaction-controller 62.5.0 → 62.6.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 (176) hide show
  1. package/CHANGELOG.md +21 -1
  2. package/dist/TransactionController.cjs +105 -48
  3. package/dist/TransactionController.cjs.map +1 -1
  4. package/dist/TransactionController.d.cts +33 -21
  5. package/dist/TransactionController.d.cts.map +1 -1
  6. package/dist/TransactionController.d.mts +33 -21
  7. package/dist/TransactionController.d.mts.map +1 -1
  8. package/dist/TransactionController.mjs +106 -49
  9. package/dist/TransactionController.mjs.map +1 -1
  10. package/dist/api/accounts-api.cjs +1 -1
  11. package/dist/api/accounts-api.cjs.map +1 -1
  12. package/dist/api/accounts-api.mjs +1 -1
  13. package/dist/api/accounts-api.mjs.map +1 -1
  14. package/dist/api/simulation-api.cjs +1 -1
  15. package/dist/api/simulation-api.cjs.map +1 -1
  16. package/dist/api/simulation-api.mjs +1 -1
  17. package/dist/api/simulation-api.mjs.map +1 -1
  18. package/dist/gas-flows/LineaGasFeeFlow.cjs.map +1 -1
  19. package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -1
  20. package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs +28 -17
  21. package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs.map +1 -1
  22. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts +1 -6
  23. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts.map +1 -1
  24. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts +1 -6
  25. package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts.map +1 -1
  26. package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs +28 -17
  27. package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs.map +1 -1
  28. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs +1 -0
  29. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs.map +1 -1
  30. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.cts.map +1 -1
  31. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.mts.map +1 -1
  32. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs +1 -0
  33. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs.map +1 -1
  34. package/dist/helpers/AccountsApiRemoteTransactionSource.cjs.map +1 -1
  35. package/dist/helpers/AccountsApiRemoteTransactionSource.mjs.map +1 -1
  36. package/dist/helpers/GasFeePoller.cjs.map +1 -1
  37. package/dist/helpers/GasFeePoller.mjs.map +1 -1
  38. package/dist/helpers/IncomingTransactionHelper.cjs.map +1 -1
  39. package/dist/helpers/IncomingTransactionHelper.d.cts.map +1 -1
  40. package/dist/helpers/IncomingTransactionHelper.d.mts.map +1 -1
  41. package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -1
  42. package/dist/helpers/MultichainTrackingHelper.cjs +2 -2
  43. package/dist/helpers/MultichainTrackingHelper.cjs.map +1 -1
  44. package/dist/helpers/MultichainTrackingHelper.d.cts.map +1 -1
  45. package/dist/helpers/MultichainTrackingHelper.d.mts.map +1 -1
  46. package/dist/helpers/MultichainTrackingHelper.mjs +2 -2
  47. package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -1
  48. package/dist/helpers/PendingTransactionTracker.cjs +88 -22
  49. package/dist/helpers/PendingTransactionTracker.cjs.map +1 -1
  50. package/dist/helpers/PendingTransactionTracker.d.cts +7 -6
  51. package/dist/helpers/PendingTransactionTracker.d.cts.map +1 -1
  52. package/dist/helpers/PendingTransactionTracker.d.mts +7 -6
  53. package/dist/helpers/PendingTransactionTracker.d.mts.map +1 -1
  54. package/dist/helpers/PendingTransactionTracker.mjs +88 -22
  55. package/dist/helpers/PendingTransactionTracker.mjs.map +1 -1
  56. package/dist/helpers/ResimulateHelper.cjs.map +1 -1
  57. package/dist/helpers/ResimulateHelper.d.cts +1 -4
  58. package/dist/helpers/ResimulateHelper.d.cts.map +1 -1
  59. package/dist/helpers/ResimulateHelper.d.mts +1 -4
  60. package/dist/helpers/ResimulateHelper.d.mts.map +1 -1
  61. package/dist/helpers/ResimulateHelper.mjs.map +1 -1
  62. package/dist/helpers/TransactionPoller.cjs.map +1 -1
  63. package/dist/helpers/TransactionPoller.d.cts.map +1 -1
  64. package/dist/helpers/TransactionPoller.d.mts.map +1 -1
  65. package/dist/helpers/TransactionPoller.mjs.map +1 -1
  66. package/dist/hooks/CollectPublishHook.cjs +1 -1
  67. package/dist/hooks/CollectPublishHook.cjs.map +1 -1
  68. package/dist/hooks/CollectPublishHook.d.cts.map +1 -1
  69. package/dist/hooks/CollectPublishHook.d.mts.map +1 -1
  70. package/dist/hooks/CollectPublishHook.mjs +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/index.cjs.map +1 -1
  75. package/dist/index.d.cts +1 -1
  76. package/dist/index.d.cts.map +1 -1
  77. package/dist/index.d.mts +1 -1
  78. package/dist/index.d.mts.map +1 -1
  79. package/dist/index.mjs.map +1 -1
  80. package/dist/types.cjs +5 -0
  81. package/dist/types.cjs.map +1 -1
  82. package/dist/types.d.cts +6 -0
  83. package/dist/types.d.cts.map +1 -1
  84. package/dist/types.d.mts +6 -0
  85. package/dist/types.d.mts.map +1 -1
  86. package/dist/types.mjs +5 -0
  87. package/dist/types.mjs.map +1 -1
  88. package/dist/utils/balance-changes.cjs +5 -5
  89. package/dist/utils/balance-changes.cjs.map +1 -1
  90. package/dist/utils/balance-changes.d.cts.map +1 -1
  91. package/dist/utils/balance-changes.d.mts.map +1 -1
  92. package/dist/utils/balance-changes.mjs +5 -5
  93. package/dist/utils/balance-changes.mjs.map +1 -1
  94. package/dist/utils/balance.cjs.map +1 -1
  95. package/dist/utils/balance.d.cts.map +1 -1
  96. package/dist/utils/balance.d.mts.map +1 -1
  97. package/dist/utils/balance.mjs.map +1 -1
  98. package/dist/utils/batch.cjs +9 -4
  99. package/dist/utils/batch.cjs.map +1 -1
  100. package/dist/utils/batch.d.cts.map +1 -1
  101. package/dist/utils/batch.d.mts.map +1 -1
  102. package/dist/utils/batch.mjs +9 -4
  103. package/dist/utils/batch.mjs.map +1 -1
  104. package/dist/utils/eip7702.cjs +4 -3
  105. package/dist/utils/eip7702.cjs.map +1 -1
  106. package/dist/utils/eip7702.d.cts +1 -1
  107. package/dist/utils/eip7702.d.cts.map +1 -1
  108. package/dist/utils/eip7702.d.mts +1 -1
  109. package/dist/utils/eip7702.d.mts.map +1 -1
  110. package/dist/utils/eip7702.mjs +4 -3
  111. package/dist/utils/eip7702.mjs.map +1 -1
  112. package/dist/utils/external-transactions.cjs.map +1 -1
  113. package/dist/utils/external-transactions.d.cts.map +1 -1
  114. package/dist/utils/external-transactions.d.mts.map +1 -1
  115. package/dist/utils/external-transactions.mjs.map +1 -1
  116. package/dist/utils/feature-flags.cjs +22 -7
  117. package/dist/utils/feature-flags.cjs.map +1 -1
  118. package/dist/utils/feature-flags.d.cts +24 -0
  119. package/dist/utils/feature-flags.d.cts.map +1 -1
  120. package/dist/utils/feature-flags.d.mts +24 -0
  121. package/dist/utils/feature-flags.d.mts.map +1 -1
  122. package/dist/utils/feature-flags.mjs +20 -6
  123. package/dist/utils/feature-flags.mjs.map +1 -1
  124. package/dist/utils/first-time-interaction.cjs +3 -5
  125. package/dist/utils/first-time-interaction.cjs.map +1 -1
  126. package/dist/utils/first-time-interaction.d.cts.map +1 -1
  127. package/dist/utils/first-time-interaction.d.mts.map +1 -1
  128. package/dist/utils/first-time-interaction.mjs +3 -5
  129. package/dist/utils/first-time-interaction.mjs.map +1 -1
  130. package/dist/utils/gas-fee-tokens.cjs +1 -1
  131. package/dist/utils/gas-fee-tokens.cjs.map +1 -1
  132. package/dist/utils/gas-fee-tokens.d.cts.map +1 -1
  133. package/dist/utils/gas-fee-tokens.d.mts.map +1 -1
  134. package/dist/utils/gas-fee-tokens.mjs +1 -1
  135. package/dist/utils/gas-fee-tokens.mjs.map +1 -1
  136. package/dist/utils/gas-fees.cjs +1 -3
  137. package/dist/utils/gas-fees.cjs.map +1 -1
  138. package/dist/utils/gas-fees.d.cts +1 -1
  139. package/dist/utils/gas-fees.d.cts.map +1 -1
  140. package/dist/utils/gas-fees.d.mts +1 -1
  141. package/dist/utils/gas-fees.d.mts.map +1 -1
  142. package/dist/utils/gas-fees.mjs +1 -3
  143. package/dist/utils/gas-fees.mjs.map +1 -1
  144. package/dist/utils/gas.cjs +71 -15
  145. package/dist/utils/gas.cjs.map +1 -1
  146. package/dist/utils/gas.d.cts +18 -12
  147. package/dist/utils/gas.d.cts.map +1 -1
  148. package/dist/utils/gas.d.mts +18 -12
  149. package/dist/utils/gas.d.mts.map +1 -1
  150. package/dist/utils/gas.mjs +70 -15
  151. package/dist/utils/gas.mjs.map +1 -1
  152. package/dist/utils/layer1-gas-fee-flow.cjs.map +1 -1
  153. package/dist/utils/layer1-gas-fee-flow.d.cts.map +1 -1
  154. package/dist/utils/layer1-gas-fee-flow.d.mts.map +1 -1
  155. package/dist/utils/layer1-gas-fee-flow.mjs.map +1 -1
  156. package/dist/utils/prepare.cjs.map +1 -1
  157. package/dist/utils/prepare.d.cts +1 -1
  158. package/dist/utils/prepare.d.cts.map +1 -1
  159. package/dist/utils/prepare.d.mts +1 -1
  160. package/dist/utils/prepare.d.mts.map +1 -1
  161. package/dist/utils/prepare.mjs.map +1 -1
  162. package/dist/utils/swaps.cjs.map +1 -1
  163. package/dist/utils/swaps.mjs.map +1 -1
  164. package/dist/utils/utils.cjs +10 -10
  165. package/dist/utils/utils.cjs.map +1 -1
  166. package/dist/utils/utils.d.cts +4 -4
  167. package/dist/utils/utils.d.cts.map +1 -1
  168. package/dist/utils/utils.d.mts +4 -4
  169. package/dist/utils/utils.d.mts.map +1 -1
  170. package/dist/utils/utils.mjs +10 -10
  171. package/dist/utils/utils.mjs.map +1 -1
  172. package/dist/utils/validation.cjs.map +1 -1
  173. package/dist/utils/validation.d.cts.map +1 -1
  174. package/dist/utils/validation.d.mts.map +1 -1
  175. package/dist/utils/validation.mjs.map +1 -1
  176. package/package.json +1 -1
@@ -1 +1 @@
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,EAAE,CAAC,IAAA,aAAK,EAAC,QAAQ,CAAC;IAC/C,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,KAAK,CAAC;IACtC,EAAE,EAAE,CAAC,EAAU,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,EAAE,CAAC,CAAC,WAAW,EAAE;IAC3C,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,KAAK,CAAC;IACtC,YAAY,EAAE,CAAC,YAAoB,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,YA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AC,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;\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
+ {"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,EAAE,CAAC,IAAA,aAAK,EAAC,QAAQ,CAAC;IAC/C,KAAK,EAAE,CAAC,KAAa,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,KAAK,CAAC;IACtC,EAAE,EAAE,CAAC,EAAU,EAAE,EAAE,CAAC,IAA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Q,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(\n txParams: TransactionParams,\n): 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 normalizedTxParams.value ??= '0x0';\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): boolean =>\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): void => {\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): void {\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): string =>\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 hexValue - The hex string to ensure is even.\n * @returns The hex string with an even length.\n */\nexport function padHexToEvenLength(hexValue: string): string {\n const prefix = hexValue.toLowerCase().startsWith('0x')\n ? hexValue.slice(0, 2)\n : '';\n const data = prefix ? hexValue.slice(2) : hexValue;\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 hexValue - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hexValue: string | Hex): BN {\n const str = typeof hexValue === 'string' ? hexValue : (hexValue 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;\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): void {\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"]}
@@ -47,17 +47,17 @@ export declare function normalizeGasFeeValues(gasFeeValues: GasPriceValue | FeeM
47
47
  * Ensure a hex string is of even length by adding a leading 0 if necessary.
48
48
  * Any existing `0x` prefix is preserved but is not added if missing.
49
49
  *
50
- * @param hex - The hex string to ensure is even.
50
+ * @param hexValue - The hex string to ensure is even.
51
51
  * @returns The hex string with an even length.
52
52
  */
53
- export declare function padHexToEvenLength(hex: string): string;
53
+ export declare function padHexToEvenLength(hexValue: string): string;
54
54
  /**
55
55
  * Create a BN from a hex string, accepting an optional 0x prefix.
56
56
  *
57
- * @param hex - Hex string with or without 0x prefix.
57
+ * @param hexValue - Hex string with or without 0x prefix.
58
58
  * @returns BN parsed as base-16.
59
59
  */
60
- export declare function bnFromHex(hex: string | Hex): BN;
60
+ export declare function bnFromHex(hexValue: string | Hex): BN;
61
61
  /**
62
62
  * Convert various numeric-like values to a BN instance.
63
63
  * Accepts BN, ethers BigNumber, hex string, bigint, or number.
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAA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;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,GAC3B,IAAI,CAUN"}
@@ -47,17 +47,17 @@ export declare function normalizeGasFeeValues(gasFeeValues: GasPriceValue | FeeM
47
47
  * Ensure a hex string is of even length by adding a leading 0 if necessary.
48
48
  * Any existing `0x` prefix is preserved but is not added if missing.
49
49
  *
50
- * @param hex - The hex string to ensure is even.
50
+ * @param hexValue - The hex string to ensure is even.
51
51
  * @returns The hex string with an even length.
52
52
  */
53
- export declare function padHexToEvenLength(hex: string): string;
53
+ export declare function padHexToEvenLength(hexValue: string): string;
54
54
  /**
55
55
  * Create a BN from a hex string, accepting an optional 0x prefix.
56
56
  *
57
- * @param hex - Hex string with or without 0x prefix.
57
+ * @param hexValue - Hex string with or without 0x prefix.
58
58
  * @returns BN parsed as base-16.
59
59
  */
60
- export declare function bnFromHex(hex: string | Hex): BN;
60
+ export declare function bnFromHex(hexValue: string | Hex): BN;
61
61
  /**
62
62
  * Convert various numeric-like values to a BN instance.
63
63
  * Accepts BN, ethers BigNumber, hex string, bigint, or number.
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,GAAG,EAAQ,wBAAwB;AAMjD,OAAO,EAAE,cAAc;AAEvB,OAAO,KAAK,EACV,sBAAsB,EACtB,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,iBAAiB,EAClB,qBAAiB;AAGlB,eAAO,MAAM,kBAAkB,qCAAqC,CAAC;AAwBrE;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,iBAAiB,qBAkBrE;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,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AKG;AACH,wBAAgB,0BAA0B,CACxC,QAAQ,EAAE,iBAAiB,GAC1B,iBAAiB,CAgBnB;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAOzE;AAED,eAAO,MAAM,iBAAiB,cACjB,aAAa,GAAG,sBAAsB,KAChD,IAWF,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAC7C,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,GACb,IAAI,CAMN;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,QAAQ,EAAE,MAAM,GAAG,MAAM,CAQ3D;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,GAAG,GAAG,EAAE,CAQpD;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,GAC3B,IAAI,CAUN"}
@@ -40,9 +40,7 @@ export function normalizeTransactionParams(txParams) {
40
40
  normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);
41
41
  }
42
42
  }
43
- if (!normalizedTxParams.value) {
44
- normalizedTxParams.value = '0x0';
45
- }
43
+ normalizedTxParams.value ?? (normalizedTxParams.value = '0x0');
46
44
  if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {
47
45
  normalizedTxParams.gas = normalizedTxParams.gasLimit;
48
46
  }
@@ -136,23 +134,25 @@ function isJsonCompatible(value) {
136
134
  * Ensure a hex string is of even length by adding a leading 0 if necessary.
137
135
  * Any existing `0x` prefix is preserved but is not added if missing.
138
136
  *
139
- * @param hex - The hex string to ensure is even.
137
+ * @param hexValue - The hex string to ensure is even.
140
138
  * @returns The hex string with an even length.
141
139
  */
142
- export function padHexToEvenLength(hex) {
143
- const prefix = hex.toLowerCase().startsWith('0x') ? hex.slice(0, 2) : '';
144
- const data = prefix ? hex.slice(2) : hex;
140
+ export function padHexToEvenLength(hexValue) {
141
+ const prefix = hexValue.toLowerCase().startsWith('0x')
142
+ ? hexValue.slice(0, 2)
143
+ : '';
144
+ const data = prefix ? hexValue.slice(2) : hexValue;
145
145
  const evenData = data.length % 2 === 0 ? data : `0${data}`;
146
146
  return prefix + evenData;
147
147
  }
148
148
  /**
149
149
  * Create a BN from a hex string, accepting an optional 0x prefix.
150
150
  *
151
- * @param hex - Hex string with or without 0x prefix.
151
+ * @param hexValue - Hex string with or without 0x prefix.
152
152
  * @returns BN parsed as base-16.
153
153
  */
154
- export function bnFromHex(hex) {
155
- const str = typeof hex === 'string' ? hex : hex;
154
+ export function bnFromHex(hexValue) {
155
+ const str = typeof hexValue === 'string' ? hexValue : hexValue;
156
156
  const withoutPrefix = str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;
157
157
  if (withoutPrefix.length === 0) {
158
158
  return new BN(0);
@@ -1 +1 @@
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,OA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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;\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
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"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M,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(\n txParams: TransactionParams,\n): 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 normalizedTxParams.value ??= '0x0';\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): boolean =>\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): void => {\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): void {\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): string =>\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 hexValue - The hex string to ensure is even.\n * @returns The hex string with an even length.\n */\nexport function padHexToEvenLength(hexValue: string): string {\n const prefix = hexValue.toLowerCase().startsWith('0x')\n ? hexValue.slice(0, 2)\n : '';\n const data = prefix ? hexValue.slice(2) : hexValue;\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 hexValue - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hexValue: string | Hex): BN {\n const str = typeof hexValue === 'string' ? hexValue : (hexValue 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;\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): void {\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 +1 @@
1
- {"version":3,"file":"validation.cjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":";;;AAAA,4CAA+C;AAC/C,iEAAgF;AAChF,mEAAuD;AACvD,qDAA+E;AAE/E,2CAA8D;AAE9D,uCAA+C;AAC/C,wCAAoE;AAOpE,IAAY,SAIX;AAJD,WAAY,SAAS;IACnB,sEAAwB,CAAA;IACxB,gEAAqB,CAAA;IACrB,kEAAsB,CAAA;AACxB,CAAC,EAJW,SAAS,yBAAT,SAAS,QAIpB;AAED,MAAM,qCAAqC,GAAG;IAC5C,+BAAuB,CAAC,SAAS;IACjC,+BAAuB,CAAC,OAAO;CAChC,CAAC;AASF;;;;;;;;;;;;;GAaG;AACI,KAAK,UAAU,yBAAyB,CAAC,EAC9C,IAAI,EACJ,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,QAAQ,EACR,IAAI,GAUL;IACC,MAAM,UAAU,GAAG,CAAC,MAAM,IAAI,MAAM,KAAK,kCAAe,CAAC;IAEzD,IAAI,UAAU,EAAE,CAAC;QACf,OAAO;IACT,CAAC;IAED,MAAM,EAAE,iBAAiB,EAAE,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,QAAQ,CAAC;IAE/D,IAAI,kBAAkB,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7D,MAAM,2BAAc,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;IAC1D,CAAC;IAED,IAAI,IAAI,KAAK,uBAAe,CAAC,KAAK,EAAE,CAAC;QACnC,OAAO;IACT,CAAC;IAED,IAAI,iBAAiB,IAAI,YAAY,KAAK,+BAAuB,CAAC,OAAO,EAAE,CAAC;QAC1E,MAAM,sBAAS,CAAC,aAAa,CAC3B,kDAAkD,CACnD,C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,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;QACjD,MAAM,sBAAS,CAAC,aAAa,CAC3B,oEAAoE,OAAO,EAAE,CAC9E,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAS,iBAAiB,CACxB,KAAa,EACb,WAAmB,EACnB,SAAiB;IAEjB,MAAM,iBAAiB,GAAG,IAAA,gBAAQ,EAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAErD,IAAI,iBAAiB,KAAK,WAAW,EAAE,CAAC;QACtC,MAAM,sBAAS,CAAC,aAAa,CAC3B,+BAA+B,SAAS,YAAY,WAAW,gBAAgB,iBAAiB,QAAQ,CACzG,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { ORIGIN_METAMASK, isValidHexAddress } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { JsonRpcError, providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { isStrictHexString, remove0x } from '@metamask/utils';\n\nimport { isEIP1559Transaction } from './utils';\nimport { TransactionEnvelopeType, TransactionType } from '../types';\nimport type {\n Authorization,\n TransactionBatchRequest,\n TransactionParams,\n} from '../types';\n\nexport enum ErrorCode {\n DuplicateBundleId = 5720,\n BundleTooLarge = 5740,\n RejectedUpgrade = 5750,\n}\n\nconst TRANSACTION_ENVELOPE_TYPES_FEE_MARKET = [\n TransactionEnvelopeType.feeMarket,\n TransactionEnvelopeType.setCode,\n];\n\ntype GasFieldsToValidate =\n | 'gasPrice'\n | 'maxFeePerGas'\n | 'maxPriorityFeePerGas'\n | 'gas'\n | 'gasLimit';\n\n/**\n * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.\n *\n * @param options - Options bag.\n * @param options.data - The data included in the transaction.\n * @param options.from - The address from which the transaction is initiated.\n * @param options.internalAccounts - The internal accounts added to the wallet.\n * @param options.origin - The origin or source of the transaction.\n * @param options.permittedAddresses - The permitted accounts for the given origin.\n * @param options.selectedAddress - The currently selected Ethereum address in the wallet.\n * @param options.txParams - The transaction parameters.\n * @param options.type - The transaction type.\n * @throws Throws an error if the transaction is not permitted.\n */\nexport async function validateTransactionOrigin({\n data,\n from,\n internalAccounts,\n origin,\n permittedAddresses,\n txParams,\n type,\n}: {\n data?: string;\n from: string;\n internalAccounts?: string[];\n origin?: string;\n permittedAddresses?: string[];\n selectedAddress?: string;\n txParams: TransactionParams;\n type?: TransactionType;\n}) {\n const isInternal = !origin || origin === ORIGIN_METAMASK;\n\n if (isInternal) {\n return;\n }\n\n const { authorizationList, to, type: envelopeType } = txParams;\n\n if (permittedAddresses && !permittedAddresses.includes(from)) {\n throw providerErrors.unauthorized({ data: { origin } });\n }\n\n if (type === TransactionType.batch) {\n return;\n }\n\n if (authorizationList || envelopeType === TransactionEnvelopeType.setCode) {\n throw rpcErrors.invalidParams(\n 'External EIP-7702 transactions are not supported',\n );\n }\n\n const hasData = Boolean(data && data !== '0x');\n\n if (\n hasData &&\n internalAccounts?.some(\n (account) => account.toLowerCase() === to?.toLowerCase(),\n )\n ) {\n throw rpcErrors.invalidParams(\n 'External transactions to internal accounts cannot include data',\n );\n }\n}\n\n/**\n * Validates the transaction params for required properties and throws in\n * the event of any validation error.\n *\n * @param txParams - Transaction params object to validate.\n * @param isEIP1559Compatible - whether or not the current network supports EIP-1559 transactions.\n * @param chainId - The chain ID of the transaction.\n */\nexport function validateTxParams(\n txParams: TransactionParams,\n isEIP1559Compatible = true,\n chainId?: Hex,\n) {\n validateEnvelopeType(txParams.type);\n validateEIP1559Compatibility(txParams, isEIP1559Compatible);\n validateParamFrom(txParams.from);\n validateParamRecipient(txParams);\n validateParamValue(txParams.value);\n validateParamData(txParams.data);\n validateParamChainId(txParams.chainId, chainId);\n validateGasFeeParams(txParams);\n validateAuthorizationList(txParams);\n}\n\n/**\n * Validates the `type` property, ensuring that if it is specified, it is a valid transaction envelope type.\n *\n * @param type - The transaction envelope type to validate.\n * @throws Throws invalid params if the type is not a valid transaction envelope type.\n */\nfunction validateEnvelopeType(type: string | undefined) {\n if (\n type &&\n !Object.values(TransactionEnvelopeType).includes(\n type as TransactionEnvelopeType,\n )\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: \"${type}\". Must be one of: ${Object.values(\n TransactionEnvelopeType,\n ).join(', ')}`,\n );\n }\n}\n\n/**\n * Validates EIP-1559 compatibility for transaction creation.\n *\n * @param txParams - The transaction parameters to validate.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n * @throws Throws invalid params if the transaction specifies EIP-1559 but the network does not support it.\n */\nfunction validateEIP1559Compatibility(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (isEIP1559Transaction(txParams) && !isEIP1559Compatible) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559',\n );\n }\n}\n\n/**\n * Validates value property, ensuring it is a valid positive integer number\n * denominated in wei.\n *\n * @param value - The value to validate, expressed as a string.\n * @throws Throws an error if the value is not a valid positive integer\n * number denominated in wei.\n * - If the value contains a hyphen (-), it is considered invalid.\n * - If the value contains a decimal point (.), it is considered invalid.\n * - If the value is not a finite number, is NaN, or is not a safe integer, it is considered invalid.\n */\nfunction validateParamValue(value?: string) {\n if (value !== undefined) {\n if (value.includes('-')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": not a positive number.`,\n );\n }\n\n if (value.includes('.')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": number must be in wei.`,\n );\n }\n const intValue = parseInt(value, 10);\n const isValid =\n Number.isFinite(intValue) &&\n !Number.isNaN(intValue) &&\n !isNaN(Number(value)) &&\n Number.isSafeInteger(intValue);\n if (!isValid) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value ${value}: number must be a valid number.`,\n );\n }\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param txParams - The transaction parameters object to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamRecipient(txParams: TransactionParams) {\n if (txParams.to === '0x' || txParams.to === undefined) {\n if (txParams.data) {\n delete txParams.to;\n } else {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n } else if (txParams.to !== undefined && !isValidHexAddress(txParams.to)) {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param from - The from property to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamFrom(from: string) {\n if (!from || typeof from !== 'string') {\n throw rpcErrors.invalidParams(\n `Invalid \"from\" address ${from}: not a string.`,\n );\n }\n if (!isValidHexAddress(from)) {\n throw rpcErrors.invalidParams('Invalid \"from\" address.');\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param to - The to property to validate.\n * @throws Throws an error if the recipient address is invalid.\n */\nexport function validateParamTo(to?: string) {\n if (!to || typeof to !== 'string') {\n throw rpcErrors.invalidParams(`Invalid \"to\" address`);\n }\n}\n\n/**\n * Validates a transaction batch request.\n *\n * @param options - Options bag.\n * @param options.internalAccounts - The internal accounts added to the wallet.\n * @param options.request - The batch request object.\n * @param options.sizeLimit - The maximum number of calls allowed in a batch request.\n */\nexport function validateBatchRequest({\n internalAccounts,\n request,\n sizeLimit,\n}: {\n internalAccounts: string[];\n request: TransactionBatchRequest;\n sizeLimit: number;\n}) {\n const { origin } = request;\n const isExternal = origin && origin !== ORIGIN_METAMASK;\n\n const internalAccountsNormalized = internalAccounts.map((account) =>\n account.toLowerCase(),\n );\n\n if (\n isExternal &&\n request.transactions.some((nestedTransaction) => {\n const normalizedCallTo =\n nestedTransaction.params.to?.toLowerCase() as string;\n\n const callData = nestedTransaction.params.data;\n\n const isInternalAccount =\n internalAccountsNormalized.includes(normalizedCallTo);\n\n const hasData = Boolean(callData && callData !== '0x');\n\n return isInternalAccount && hasData;\n })\n ) {\n throw rpcErrors.invalidParams(\n 'External calls to internal accounts cannot include data',\n );\n }\n\n if (isExternal && request.transactions.length > sizeLimit) {\n throw new JsonRpcError(\n ErrorCode.BundleTooLarge,\n `Batch size cannot exceed ${sizeLimit}. got: ${request.transactions.length}`,\n );\n }\n}\n\n/**\n * Validates input data for transactions.\n *\n * @param value - The input data to validate.\n * @throws Throws invalid params if the input data is invalid.\n */\nfunction validateParamData(value?: string) {\n if (value) {\n const ERC20Interface = new Interface(abiERC20);\n try {\n ERC20Interface.parseTransaction({ data: value });\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.message.match(/BUFFER_OVERRUN/u)) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: data out-of-bounds, BUFFER_OVERRUN.',\n );\n }\n }\n }\n}\n\n/**\n * Validates chainId type.\n *\n * @param chainIdParams - The chain ID to validate.\n * @param chainIdNetworkClient - The chain ID of the network client.\n */\nfunction validateParamChainId(chainIdParams?: Hex, chainIdNetworkClient?: Hex) {\n if (\n chainIdParams &&\n chainIdNetworkClient &&\n chainIdParams.toLowerCase?.() !== chainIdNetworkClient.toLowerCase()\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: chainId must match the network client, got: ${chainIdParams}, expected: ${chainIdNetworkClient}`,\n );\n }\n}\n\n/**\n * Validates gas values.\n *\n * @param txParams - The transaction parameters to validate.\n */\nfunction validateGasFeeParams(txParams: TransactionParams) {\n if (txParams.gasPrice) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'gasPrice');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxPriorityFeePerGas',\n );\n ensureFieldIsValidHex(txParams, 'gasPrice');\n }\n\n if (txParams.maxFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'maxFeePerGas');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsValidHex(txParams, 'maxFeePerGas');\n }\n\n if (txParams.maxPriorityFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(\n txParams,\n 'maxPriorityFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxPriorityFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsValidHex(txParams, 'maxPriorityFeePerGas');\n }\n\n if (txParams.gasLimit) {\n ensureFieldIsValidHex(txParams, 'gasLimit');\n }\n\n if (txParams.gas) {\n ensureFieldIsValidHex(txParams, 'gas');\n }\n}\n\n/**\n * Ensures that the provided txParams has the proper 'type' specified for the\n * given field, if it is provided. If types do not match throws an\n * invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param field - The current field being validated\n * @throws {ethErrors.rpc.invalidParams} Throws if type does not match the\n * expectations for provided field.\n */\nfunction ensureProperTransactionEnvelopeTypeProvided(\n txParams: TransactionParams,\n field: keyof TransactionParams,\n) {\n const type = txParams.type as TransactionEnvelopeType | undefined;\n\n switch (field) {\n case 'authorizationList':\n if (type && type !== TransactionEnvelopeType.setCode) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but including authorizationList requires type: \"${TransactionEnvelopeType.setCode}\"`,\n );\n }\n break;\n case 'maxFeePerGas':\n case 'maxPriorityFeePerGas':\n if (type && !TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but including maxFeePerGas and maxPriorityFeePerGas requires type: \"${TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.join(', ')}\"`,\n );\n }\n break;\n case 'gasPrice':\n default:\n if (type && TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`,\n );\n }\n }\n}\n\n/**\n * Given two fields, ensure that the second field is not included in txParams,\n * and if it is throw an invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param fieldBeingValidated - The current field being validated\n * @param mutuallyExclusiveField - The field to ensure is not provided\n * @throws {ethErrors.rpc.invalidParams} Throws if mutuallyExclusiveField is\n * present in txParams.\n */\nfunction ensureMutuallyExclusiveFieldsNotProvided(\n txParams: TransactionParams,\n fieldBeingValidated: GasFieldsToValidate,\n mutuallyExclusiveField: GasFieldsToValidate,\n) {\n if (typeof txParams[mutuallyExclusiveField] !== 'undefined') {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`,\n );\n }\n}\n\n/**\n * Ensures that the provided value for field is a valid hexadecimal.\n * Throws an invalidParams error if field is not a valid hexadecimal.\n *\n * @param data - The object containing the field\n * @param field - The current field being validated\n * @throws {rpcErrors.invalidParams} Throws if field is not a valid hexadecimal\n */\nfunction ensureFieldIsValidHex<T>(data: T, field: keyof T) {\n const value = data[field];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${String(field)} is not a valid hexadecimal string. got: (${String(\n value,\n )})`,\n );\n }\n}\n\n/**\n * Validate the authorization list property in the transaction parameters.\n *\n * @param txParams - The transaction parameters containing the authorization list to validate.\n */\nfunction validateAuthorizationList(txParams: TransactionParams) {\n const { authorizationList } = txParams;\n\n if (!authorizationList) {\n return;\n }\n\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'authorizationList');\n\n if (!Array.isArray(authorizationList)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: authorizationList must be an array`,\n );\n }\n\n for (const authorization of authorizationList) {\n validateAuthorization(authorization);\n }\n}\n\n/**\n * Validate an authorization object.\n *\n * @param authorization - The authorization object to validate.\n */\nfunction validateAuthorization(authorization: Authorization) {\n ensureFieldIsValidHex(authorization, 'address');\n validateHexLength(authorization.address, 20, 'address');\n\n for (const field of ['chainId', 'nonce', 'r', 's'] as const) {\n if (authorization[field]) {\n ensureFieldIsValidHex(authorization, field);\n }\n }\n\n const { yParity } = authorization;\n\n if (yParity && !['0x0', '0x1'].includes(yParity)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: yParity must be '0x0' or '0x1'. got: ${yParity}`,\n );\n }\n}\n\n/**\n * Validate the number of bytes in a hex string.\n *\n * @param value - The hex string to validate.\n * @param lengthBytes - The expected length in bytes.\n * @param fieldName - The name of the field being validated.\n */\nfunction validateHexLength(\n value: string,\n lengthBytes: number,\n fieldName: string,\n) {\n const actualLengthBytes = remove0x(value).length / 2;\n\n if (actualLengthBytes !== lengthBytes) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${fieldName} must be ${lengthBytes} bytes. got: ${actualLengthBytes} bytes`,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"validation.cjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":";;;AAAA,4CAA+C;AAC/C,iEAAgF;AAChF,mEAAuD;AACvD,qDAA+E;AAE/E,2CAA8D;AAE9D,uCAA+C;AAC/C,wCAAoE;AAOpE,IAAY,SAIX;AAJD,WAAY,SAAS;IACnB,sEAAwB,CAAA;IACxB,gEAAqB,CAAA;IACrB,kEAAsB,CAAA;AACxB,CAAC,EAJW,SAAS,yBAAT,SAAS,QAIpB;AAED,MAAM,qCAAqC,GAAG;IAC5C,+BAAuB,CAAC,SAAS;IACjC,+BAAuB,CAAC,OAAO;CAChC,CAAC;AASF;;;;;;;;;;;;;GAaG;A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ethersproject/abi';\nimport { ORIGIN_METAMASK, isValidHexAddress } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { JsonRpcError, providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { isStrictHexString, remove0x } from '@metamask/utils';\n\nimport { isEIP1559Transaction } from './utils';\nimport { TransactionEnvelopeType, TransactionType } from '../types';\nimport type {\n Authorization,\n TransactionBatchRequest,\n TransactionParams,\n} from '../types';\n\nexport enum ErrorCode {\n DuplicateBundleId = 5720,\n BundleTooLarge = 5740,\n RejectedUpgrade = 5750,\n}\n\nconst TRANSACTION_ENVELOPE_TYPES_FEE_MARKET = [\n TransactionEnvelopeType.feeMarket,\n TransactionEnvelopeType.setCode,\n];\n\ntype GasFieldsToValidate =\n | 'gasPrice'\n | 'maxFeePerGas'\n | 'maxPriorityFeePerGas'\n | 'gas'\n | 'gasLimit';\n\n/**\n * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.\n *\n * @param options - Options bag.\n * @param options.data - The data included in the transaction.\n * @param options.from - The address from which the transaction is initiated.\n * @param options.internalAccounts - The internal accounts added to the wallet.\n * @param options.origin - The origin or source of the transaction.\n * @param options.permittedAddresses - The permitted accounts for the given origin.\n * @param options.selectedAddress - The currently selected Ethereum address in the wallet.\n * @param options.txParams - The transaction parameters.\n * @param options.type - The transaction type.\n * @throws Throws an error if the transaction is not permitted.\n */\nexport async function validateTransactionOrigin({\n data,\n from,\n internalAccounts,\n origin,\n permittedAddresses,\n txParams,\n type,\n}: {\n data?: string;\n from: string;\n internalAccounts?: string[];\n origin?: string;\n permittedAddresses?: string[];\n selectedAddress?: string;\n txParams: TransactionParams;\n type?: TransactionType;\n}): Promise<void> {\n const isInternal = !origin || origin === ORIGIN_METAMASK;\n\n if (isInternal) {\n return;\n }\n\n const { authorizationList, to, type: envelopeType } = txParams;\n\n if (permittedAddresses && !permittedAddresses.includes(from)) {\n throw providerErrors.unauthorized({ data: { origin } });\n }\n\n if (type === TransactionType.batch) {\n return;\n }\n\n if (authorizationList || envelopeType === TransactionEnvelopeType.setCode) {\n throw rpcErrors.invalidParams(\n 'External EIP-7702 transactions are not supported',\n );\n }\n\n const hasData = Boolean(data && data !== '0x');\n\n if (\n hasData &&\n internalAccounts?.some(\n (account) => account.toLowerCase() === to?.toLowerCase(),\n )\n ) {\n throw rpcErrors.invalidParams(\n 'External transactions to internal accounts cannot include data',\n );\n }\n}\n\n/**\n * Validates the transaction params for required properties and throws in\n * the event of any validation error.\n *\n * @param txParams - Transaction params object to validate.\n * @param isEIP1559Compatible - whether or not the current network supports EIP-1559 transactions.\n * @param chainId - The chain ID of the transaction.\n */\nexport function validateTxParams(\n txParams: TransactionParams,\n isEIP1559Compatible = true,\n chainId?: Hex,\n): void {\n validateEnvelopeType(txParams.type);\n validateEIP1559Compatibility(txParams, isEIP1559Compatible);\n validateParamFrom(txParams.from);\n validateParamRecipient(txParams);\n validateParamValue(txParams.value);\n validateParamData(txParams.data);\n validateParamChainId(txParams.chainId, chainId);\n validateGasFeeParams(txParams);\n validateAuthorizationList(txParams);\n}\n\n/**\n * Validates the `type` property, ensuring that if it is specified, it is a valid transaction envelope type.\n *\n * @param type - The transaction envelope type to validate.\n * @throws Throws invalid params if the type is not a valid transaction envelope type.\n */\nfunction validateEnvelopeType(type: string | undefined): void {\n if (\n type &&\n !Object.values(TransactionEnvelopeType).includes(\n type as TransactionEnvelopeType,\n )\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: \"${type}\". Must be one of: ${Object.values(\n TransactionEnvelopeType,\n ).join(', ')}`,\n );\n }\n}\n\n/**\n * Validates EIP-1559 compatibility for transaction creation.\n *\n * @param txParams - The transaction parameters to validate.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n * @throws Throws invalid params if the transaction specifies EIP-1559 but the network does not support it.\n */\nfunction validateEIP1559Compatibility(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n): void {\n if (isEIP1559Transaction(txParams) && !isEIP1559Compatible) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559',\n );\n }\n}\n\n/**\n * Validates value property, ensuring it is a valid positive integer number\n * denominated in wei.\n *\n * @param value - The value to validate, expressed as a string.\n * @throws Throws an error if the value is not a valid positive integer\n * number denominated in wei.\n * - If the value contains a hyphen (-), it is considered invalid.\n * - If the value contains a decimal point (.), it is considered invalid.\n * - If the value is not a finite number, is NaN, or is not a safe integer, it is considered invalid.\n */\nfunction validateParamValue(value?: string): void {\n if (value !== undefined) {\n if (value.includes('-')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": not a positive number.`,\n );\n }\n\n if (value.includes('.')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": number must be in wei.`,\n );\n }\n const intValue = parseInt(value, 10);\n const isValid =\n Number.isFinite(intValue) &&\n !Number.isNaN(intValue) &&\n !isNaN(Number(value)) &&\n Number.isSafeInteger(intValue);\n if (!isValid) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value ${value}: number must be a valid number.`,\n );\n }\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param txParams - The transaction parameters object to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamRecipient(txParams: TransactionParams): void {\n if (txParams.to === '0x' || txParams.to === undefined) {\n if (txParams.data) {\n delete txParams.to;\n } else {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n } else if (txParams.to !== undefined && !isValidHexAddress(txParams.to)) {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param from - The from property to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamFrom(from: string): void {\n if (!from || typeof from !== 'string') {\n throw rpcErrors.invalidParams(\n `Invalid \"from\" address ${from}: not a string.`,\n );\n }\n if (!isValidHexAddress(from)) {\n throw rpcErrors.invalidParams('Invalid \"from\" address.');\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param to - The to property to validate.\n * @throws Throws an error if the recipient address is invalid.\n */\nexport function validateParamTo(to?: string): void {\n if (!to || typeof to !== 'string') {\n throw rpcErrors.invalidParams(`Invalid \"to\" address`);\n }\n}\n\n/**\n * Validates a transaction batch request.\n *\n * @param options - Options bag.\n * @param options.internalAccounts - The internal accounts added to the wallet.\n * @param options.request - The batch request object.\n * @param options.sizeLimit - The maximum number of calls allowed in a batch request.\n */\nexport function validateBatchRequest({\n internalAccounts,\n request,\n sizeLimit,\n}: {\n internalAccounts: string[];\n request: TransactionBatchRequest;\n sizeLimit: number;\n}): void {\n const { origin } = request;\n const isExternal = origin && origin !== ORIGIN_METAMASK;\n\n const internalAccountsNormalized = internalAccounts.map((account) =>\n account.toLowerCase(),\n );\n\n if (\n isExternal &&\n request.transactions.some((nestedTransaction) => {\n const normalizedCallTo =\n nestedTransaction.params.to?.toLowerCase() as string;\n\n const callData = nestedTransaction.params.data;\n\n const isInternalAccount =\n internalAccountsNormalized.includes(normalizedCallTo);\n\n const hasData = Boolean(callData && callData !== '0x');\n\n return isInternalAccount && hasData;\n })\n ) {\n throw rpcErrors.invalidParams(\n 'External calls to internal accounts cannot include data',\n );\n }\n\n if (isExternal && request.transactions.length > sizeLimit) {\n throw new JsonRpcError(\n ErrorCode.BundleTooLarge,\n `Batch size cannot exceed ${sizeLimit}. got: ${request.transactions.length}`,\n );\n }\n}\n\n/**\n * Validates input data for transactions.\n *\n * @param value - The input data to validate.\n * @throws Throws invalid params if the input data is invalid.\n */\nfunction validateParamData(value?: string): void {\n if (value) {\n const ERC20Interface = new Interface(abiERC20);\n try {\n ERC20Interface.parseTransaction({ data: value });\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.message.match(/BUFFER_OVERRUN/u)) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: data out-of-bounds, BUFFER_OVERRUN.',\n );\n }\n }\n }\n}\n\n/**\n * Validates chainId type.\n *\n * @param chainIdParams - The chain ID to validate.\n * @param chainIdNetworkClient - The chain ID of the network client.\n */\nfunction validateParamChainId(\n chainIdParams?: Hex,\n chainIdNetworkClient?: Hex,\n): void {\n if (\n chainIdParams &&\n chainIdNetworkClient &&\n chainIdParams.toLowerCase?.() !== chainIdNetworkClient.toLowerCase()\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: chainId must match the network client, got: ${chainIdParams}, expected: ${chainIdNetworkClient}`,\n );\n }\n}\n\n/**\n * Validates gas values.\n *\n * @param txParams - The transaction parameters to validate.\n */\nfunction validateGasFeeParams(txParams: TransactionParams): void {\n if (txParams.gasPrice) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'gasPrice');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxPriorityFeePerGas',\n );\n ensureFieldIsValidHex(txParams, 'gasPrice');\n }\n\n if (txParams.maxFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'maxFeePerGas');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsValidHex(txParams, 'maxFeePerGas');\n }\n\n if (txParams.maxPriorityFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(\n txParams,\n 'maxPriorityFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxPriorityFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsValidHex(txParams, 'maxPriorityFeePerGas');\n }\n\n if (txParams.gasLimit) {\n ensureFieldIsValidHex(txParams, 'gasLimit');\n }\n\n if (txParams.gas) {\n ensureFieldIsValidHex(txParams, 'gas');\n }\n}\n\n/**\n * Ensures that the provided txParams has the proper 'type' specified for the\n * given field, if it is provided. If types do not match throws an\n * invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param field - The current field being validated\n * @throws {ethErrors.rpc.invalidParams} Throws if type does not match the\n * expectations for provided field.\n */\nfunction ensureProperTransactionEnvelopeTypeProvided(\n txParams: TransactionParams,\n field: keyof TransactionParams,\n): void {\n const type = txParams.type as TransactionEnvelopeType | undefined;\n\n switch (field) {\n case 'authorizationList':\n if (type && type !== TransactionEnvelopeType.setCode) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but including authorizationList requires type: \"${TransactionEnvelopeType.setCode}\"`,\n );\n }\n break;\n case 'maxFeePerGas':\n case 'maxPriorityFeePerGas':\n if (type && !TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but including maxFeePerGas and maxPriorityFeePerGas requires type: \"${TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.join(', ')}\"`,\n );\n }\n break;\n case 'gasPrice':\n default:\n if (type && TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`,\n );\n }\n }\n}\n\n/**\n * Given two fields, ensure that the second field is not included in txParams,\n * and if it is throw an invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param fieldBeingValidated - The current field being validated\n * @param mutuallyExclusiveField - The field to ensure is not provided\n * @throws {ethErrors.rpc.invalidParams} Throws if mutuallyExclusiveField is\n * present in txParams.\n */\nfunction ensureMutuallyExclusiveFieldsNotProvided(\n txParams: TransactionParams,\n fieldBeingValidated: GasFieldsToValidate,\n mutuallyExclusiveField: GasFieldsToValidate,\n): void {\n if (typeof txParams[mutuallyExclusiveField] !== 'undefined') {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`,\n );\n }\n}\n\n/**\n * Ensures that the provided value for field is a valid hexadecimal.\n * Throws an invalidParams error if field is not a valid hexadecimal.\n *\n * @param data - The object containing the field\n * @param field - The current field being validated\n * @throws {rpcErrors.invalidParams} Throws if field is not a valid hexadecimal\n */\nfunction ensureFieldIsValidHex<DataType>(\n data: DataType,\n field: keyof DataType,\n): void {\n const value = data[field];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${String(field)} is not a valid hexadecimal string. got: (${String(\n value,\n )})`,\n );\n }\n}\n\n/**\n * Validate the authorization list property in the transaction parameters.\n *\n * @param txParams - The transaction parameters containing the authorization list to validate.\n */\nfunction validateAuthorizationList(txParams: TransactionParams): void {\n const { authorizationList } = txParams;\n\n if (!authorizationList) {\n return;\n }\n\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'authorizationList');\n\n if (!Array.isArray(authorizationList)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: authorizationList must be an array`,\n );\n }\n\n for (const authorization of authorizationList) {\n validateAuthorization(authorization);\n }\n}\n\n/**\n * Validate an authorization object.\n *\n * @param authorization - The authorization object to validate.\n */\nfunction validateAuthorization(authorization: Authorization): void {\n ensureFieldIsValidHex(authorization, 'address');\n validateHexLength(authorization.address, 20, 'address');\n\n for (const field of ['chainId', 'nonce', 'r', 's'] as const) {\n if (authorization[field]) {\n ensureFieldIsValidHex(authorization, field);\n }\n }\n\n const { yParity } = authorization;\n\n if (yParity && !['0x0', '0x1'].includes(yParity)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: yParity must be '0x0' or '0x1'. got: ${yParity}`,\n );\n }\n}\n\n/**\n * Validate the number of bytes in a hex string.\n *\n * @param value - The hex string to validate.\n * @param lengthBytes - The expected length in bytes.\n * @param fieldName - The name of the field being validated.\n */\nfunction validateHexLength(\n value: string,\n lengthBytes: number,\n fieldName: string,\n): void {\n const actualLengthBytes = remove0x(value).length / 2;\n\n if (actualLengthBytes !== lengthBytes) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${fieldName} must be ${lengthBytes} bytes. got: ${actualLengthBytes} bytes`,\n );\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"validation.d.cts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,EAA2B,eAAe,EAAE,qBAAiB;AACpE,OAAO,KAAK,EAEV,uBAAuB,EACvB,iBAAiB,EAClB,qBAAiB;AAElB,oBAAY,SAAS;IACnB,iBAAiB,OAAO;IACxB,cAAc,OAAO;IACrB,eAAe,OAAO;CACvB;AAcD;;;;;;;;;;;;;GAaG;AACH,wBAAsB,yBAAyB,CAAC,EAC9C,IAAI,EACJ,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,QAAQ,EACR,IAAI,GACL,EAAE;IACD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kBAAkB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,EAAE,iBAAiB,CAAC;IAC5B,IAAI,CAAC,EAAE,eAAe,CAAC;CACxB,iBAmCA;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,UAAO,EAC1B,OAAO,CAAC,EAAE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C;IAChD,iBAAiB,CAAC,aAAa,CAAC,OAAO,EAAE,EAAE,EAAE,SAAS,CAAC,CAAC;IAExD,KAAK,MAAM,KAAK,IAAI,CAAC,SAAS,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,CAAU,EAAE,CAAC;QAC5D,IAAI,aAAa,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,qBAAqB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;QAC9C,CAAC;IACH,CAAC;IAED,MAAM,EAAE,OAAO,EAAE,GAAG,aAAa,CAAC;IAElC,IAAI,OAAO,IAAI,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;QACjD,MAAM,SAAS,CAAC,aAAa,CAC3B,oEAAoE,OAAO,EAAE,CAC9E,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAS,iBAAiB,CACxB,KAAa,EACb,WAAmB,EACnB,SAAiB;IAEjB,MAAM,iBAAiB,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAErD,IAAI,iBAAiB,KAAK,WAAW,EAAE,CAAC;QACtC,MAAM,SAAS,CAAC,aAAa,CAC3B,+BAA+B,SAAS,YAAY,WAAW,gBAAgB,iBAAiB,QAAQ,CACzG,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { ORIGIN_METAMASK, isValidHexAddress } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { JsonRpcError, providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { isStrictHexString, remove0x } from '@metamask/utils';\n\nimport { isEIP1559Transaction } from './utils';\nimport { TransactionEnvelopeType, TransactionType } from '../types';\nimport type {\n Authorization,\n TransactionBatchRequest,\n TransactionParams,\n} from '../types';\n\nexport enum ErrorCode {\n DuplicateBundleId = 5720,\n BundleTooLarge = 5740,\n RejectedUpgrade = 5750,\n}\n\nconst TRANSACTION_ENVELOPE_TYPES_FEE_MARKET = [\n TransactionEnvelopeType.feeMarket,\n TransactionEnvelopeType.setCode,\n];\n\ntype GasFieldsToValidate =\n | 'gasPrice'\n | 'maxFeePerGas'\n | 'maxPriorityFeePerGas'\n | 'gas'\n | 'gasLimit';\n\n/**\n * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.\n *\n * @param options - Options bag.\n * @param options.data - The data included in the transaction.\n * @param options.from - The address from which the transaction is initiated.\n * @param options.internalAccounts - The internal accounts added to the wallet.\n * @param options.origin - The origin or source of the transaction.\n * @param options.permittedAddresses - The permitted accounts for the given origin.\n * @param options.selectedAddress - The currently selected Ethereum address in the wallet.\n * @param options.txParams - The transaction parameters.\n * @param options.type - The transaction type.\n * @throws Throws an error if the transaction is not permitted.\n */\nexport async function validateTransactionOrigin({\n data,\n from,\n internalAccounts,\n origin,\n permittedAddresses,\n txParams,\n type,\n}: {\n data?: string;\n from: string;\n internalAccounts?: string[];\n origin?: string;\n permittedAddresses?: string[];\n selectedAddress?: string;\n txParams: TransactionParams;\n type?: TransactionType;\n}) {\n const isInternal = !origin || origin === ORIGIN_METAMASK;\n\n if (isInternal) {\n return;\n }\n\n const { authorizationList, to, type: envelopeType } = txParams;\n\n if (permittedAddresses && !permittedAddresses.includes(from)) {\n throw providerErrors.unauthorized({ data: { origin } });\n }\n\n if (type === TransactionType.batch) {\n return;\n }\n\n if (authorizationList || envelopeType === TransactionEnvelopeType.setCode) {\n throw rpcErrors.invalidParams(\n 'External EIP-7702 transactions are not supported',\n );\n }\n\n const hasData = Boolean(data && data !== '0x');\n\n if (\n hasData &&\n internalAccounts?.some(\n (account) => account.toLowerCase() === to?.toLowerCase(),\n )\n ) {\n throw rpcErrors.invalidParams(\n 'External transactions to internal accounts cannot include data',\n );\n }\n}\n\n/**\n * Validates the transaction params for required properties and throws in\n * the event of any validation error.\n *\n * @param txParams - Transaction params object to validate.\n * @param isEIP1559Compatible - whether or not the current network supports EIP-1559 transactions.\n * @param chainId - The chain ID of the transaction.\n */\nexport function validateTxParams(\n txParams: TransactionParams,\n isEIP1559Compatible = true,\n chainId?: Hex,\n) {\n validateEnvelopeType(txParams.type);\n validateEIP1559Compatibility(txParams, isEIP1559Compatible);\n validateParamFrom(txParams.from);\n validateParamRecipient(txParams);\n validateParamValue(txParams.value);\n validateParamData(txParams.data);\n validateParamChainId(txParams.chainId, chainId);\n validateGasFeeParams(txParams);\n validateAuthorizationList(txParams);\n}\n\n/**\n * Validates the `type` property, ensuring that if it is specified, it is a valid transaction envelope type.\n *\n * @param type - The transaction envelope type to validate.\n * @throws Throws invalid params if the type is not a valid transaction envelope type.\n */\nfunction validateEnvelopeType(type: string | undefined) {\n if (\n type &&\n !Object.values(TransactionEnvelopeType).includes(\n type as TransactionEnvelopeType,\n )\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: \"${type}\". Must be one of: ${Object.values(\n TransactionEnvelopeType,\n ).join(', ')}`,\n );\n }\n}\n\n/**\n * Validates EIP-1559 compatibility for transaction creation.\n *\n * @param txParams - The transaction parameters to validate.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n * @throws Throws invalid params if the transaction specifies EIP-1559 but the network does not support it.\n */\nfunction validateEIP1559Compatibility(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (isEIP1559Transaction(txParams) && !isEIP1559Compatible) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559',\n );\n }\n}\n\n/**\n * Validates value property, ensuring it is a valid positive integer number\n * denominated in wei.\n *\n * @param value - The value to validate, expressed as a string.\n * @throws Throws an error if the value is not a valid positive integer\n * number denominated in wei.\n * - If the value contains a hyphen (-), it is considered invalid.\n * - If the value contains a decimal point (.), it is considered invalid.\n * - If the value is not a finite number, is NaN, or is not a safe integer, it is considered invalid.\n */\nfunction validateParamValue(value?: string) {\n if (value !== undefined) {\n if (value.includes('-')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": not a positive number.`,\n );\n }\n\n if (value.includes('.')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": number must be in wei.`,\n );\n }\n const intValue = parseInt(value, 10);\n const isValid =\n Number.isFinite(intValue) &&\n !Number.isNaN(intValue) &&\n !isNaN(Number(value)) &&\n Number.isSafeInteger(intValue);\n if (!isValid) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value ${value}: number must be a valid number.`,\n );\n }\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param txParams - The transaction parameters object to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamRecipient(txParams: TransactionParams) {\n if (txParams.to === '0x' || txParams.to === undefined) {\n if (txParams.data) {\n delete txParams.to;\n } else {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n } else if (txParams.to !== undefined && !isValidHexAddress(txParams.to)) {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param from - The from property to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamFrom(from: string) {\n if (!from || typeof from !== 'string') {\n throw rpcErrors.invalidParams(\n `Invalid \"from\" address ${from}: not a string.`,\n );\n }\n if (!isValidHexAddress(from)) {\n throw rpcErrors.invalidParams('Invalid \"from\" address.');\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param to - The to property to validate.\n * @throws Throws an error if the recipient address is invalid.\n */\nexport function validateParamTo(to?: string) {\n if (!to || typeof to !== 'string') {\n throw rpcErrors.invalidParams(`Invalid \"to\" address`);\n }\n}\n\n/**\n * Validates a transaction batch request.\n *\n * @param options - Options bag.\n * @param options.internalAccounts - The internal accounts added to the wallet.\n * @param options.request - The batch request object.\n * @param options.sizeLimit - The maximum number of calls allowed in a batch request.\n */\nexport function validateBatchRequest({\n internalAccounts,\n request,\n sizeLimit,\n}: {\n internalAccounts: string[];\n request: TransactionBatchRequest;\n sizeLimit: number;\n}) {\n const { origin } = request;\n const isExternal = origin && origin !== ORIGIN_METAMASK;\n\n const internalAccountsNormalized = internalAccounts.map((account) =>\n account.toLowerCase(),\n );\n\n if (\n isExternal &&\n request.transactions.some((nestedTransaction) => {\n const normalizedCallTo =\n nestedTransaction.params.to?.toLowerCase() as string;\n\n const callData = nestedTransaction.params.data;\n\n const isInternalAccount =\n internalAccountsNormalized.includes(normalizedCallTo);\n\n const hasData = Boolean(callData && callData !== '0x');\n\n return isInternalAccount && hasData;\n })\n ) {\n throw rpcErrors.invalidParams(\n 'External calls to internal accounts cannot include data',\n );\n }\n\n if (isExternal && request.transactions.length > sizeLimit) {\n throw new JsonRpcError(\n ErrorCode.BundleTooLarge,\n `Batch size cannot exceed ${sizeLimit}. got: ${request.transactions.length}`,\n );\n }\n}\n\n/**\n * Validates input data for transactions.\n *\n * @param value - The input data to validate.\n * @throws Throws invalid params if the input data is invalid.\n */\nfunction validateParamData(value?: string) {\n if (value) {\n const ERC20Interface = new Interface(abiERC20);\n try {\n ERC20Interface.parseTransaction({ data: value });\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.message.match(/BUFFER_OVERRUN/u)) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: data out-of-bounds, BUFFER_OVERRUN.',\n );\n }\n }\n }\n}\n\n/**\n * Validates chainId type.\n *\n * @param chainIdParams - The chain ID to validate.\n * @param chainIdNetworkClient - The chain ID of the network client.\n */\nfunction validateParamChainId(chainIdParams?: Hex, chainIdNetworkClient?: Hex) {\n if (\n chainIdParams &&\n chainIdNetworkClient &&\n chainIdParams.toLowerCase?.() !== chainIdNetworkClient.toLowerCase()\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: chainId must match the network client, got: ${chainIdParams}, expected: ${chainIdNetworkClient}`,\n );\n }\n}\n\n/**\n * Validates gas values.\n *\n * @param txParams - The transaction parameters to validate.\n */\nfunction validateGasFeeParams(txParams: TransactionParams) {\n if (txParams.gasPrice) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'gasPrice');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxPriorityFeePerGas',\n );\n ensureFieldIsValidHex(txParams, 'gasPrice');\n }\n\n if (txParams.maxFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'maxFeePerGas');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsValidHex(txParams, 'maxFeePerGas');\n }\n\n if (txParams.maxPriorityFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(\n txParams,\n 'maxPriorityFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxPriorityFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsValidHex(txParams, 'maxPriorityFeePerGas');\n }\n\n if (txParams.gasLimit) {\n ensureFieldIsValidHex(txParams, 'gasLimit');\n }\n\n if (txParams.gas) {\n ensureFieldIsValidHex(txParams, 'gas');\n }\n}\n\n/**\n * Ensures that the provided txParams has the proper 'type' specified for the\n * given field, if it is provided. If types do not match throws an\n * invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param field - The current field being validated\n * @throws {ethErrors.rpc.invalidParams} Throws if type does not match the\n * expectations for provided field.\n */\nfunction ensureProperTransactionEnvelopeTypeProvided(\n txParams: TransactionParams,\n field: keyof TransactionParams,\n) {\n const type = txParams.type as TransactionEnvelopeType | undefined;\n\n switch (field) {\n case 'authorizationList':\n if (type && type !== TransactionEnvelopeType.setCode) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but including authorizationList requires type: \"${TransactionEnvelopeType.setCode}\"`,\n );\n }\n break;\n case 'maxFeePerGas':\n case 'maxPriorityFeePerGas':\n if (type && !TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but including maxFeePerGas and maxPriorityFeePerGas requires type: \"${TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.join(', ')}\"`,\n );\n }\n break;\n case 'gasPrice':\n default:\n if (type && TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`,\n );\n }\n }\n}\n\n/**\n * Given two fields, ensure that the second field is not included in txParams,\n * and if it is throw an invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param fieldBeingValidated - The current field being validated\n * @param mutuallyExclusiveField - The field to ensure is not provided\n * @throws {ethErrors.rpc.invalidParams} Throws if mutuallyExclusiveField is\n * present in txParams.\n */\nfunction ensureMutuallyExclusiveFieldsNotProvided(\n txParams: TransactionParams,\n fieldBeingValidated: GasFieldsToValidate,\n mutuallyExclusiveField: GasFieldsToValidate,\n) {\n if (typeof txParams[mutuallyExclusiveField] !== 'undefined') {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`,\n );\n }\n}\n\n/**\n * Ensures that the provided value for field is a valid hexadecimal.\n * Throws an invalidParams error if field is not a valid hexadecimal.\n *\n * @param data - The object containing the field\n * @param field - The current field being validated\n * @throws {rpcErrors.invalidParams} Throws if field is not a valid hexadecimal\n */\nfunction ensureFieldIsValidHex<T>(data: T, field: keyof T) {\n const value = data[field];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${String(field)} is not a valid hexadecimal string. got: (${String(\n value,\n )})`,\n );\n }\n}\n\n/**\n * Validate the authorization list property in the transaction parameters.\n *\n * @param txParams - The transaction parameters containing the authorization list to validate.\n */\nfunction validateAuthorizationList(txParams: TransactionParams) {\n const { authorizationList } = txParams;\n\n if (!authorizationList) {\n return;\n }\n\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'authorizationList');\n\n if (!Array.isArray(authorizationList)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: authorizationList must be an array`,\n );\n }\n\n for (const authorization of authorizationList) {\n validateAuthorization(authorization);\n }\n}\n\n/**\n * Validate an authorization object.\n *\n * @param authorization - The authorization object to validate.\n */\nfunction validateAuthorization(authorization: Authorization) {\n ensureFieldIsValidHex(authorization, 'address');\n validateHexLength(authorization.address, 20, 'address');\n\n for (const field of ['chainId', 'nonce', 'r', 's'] as const) {\n if (authorization[field]) {\n ensureFieldIsValidHex(authorization, field);\n }\n }\n\n const { yParity } = authorization;\n\n if (yParity && !['0x0', '0x1'].includes(yParity)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: yParity must be '0x0' or '0x1'. got: ${yParity}`,\n );\n }\n}\n\n/**\n * Validate the number of bytes in a hex string.\n *\n * @param value - The hex string to validate.\n * @param lengthBytes - The expected length in bytes.\n * @param fieldName - The name of the field being validated.\n */\nfunction validateHexLength(\n value: string,\n lengthBytes: number,\n fieldName: string,\n) {\n const actualLengthBytes = remove0x(value).length / 2;\n\n if (actualLengthBytes !== lengthBytes) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${fieldName} must be ${lengthBytes} bytes. got: ${actualLengthBytes} bytes`,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"validation.mjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"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AI,OAAO,IAAI,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC;QACjD,MAAM,SAAS,CAAC,aAAa,CAC3B,oEAAoE,OAAO,EAAE,CAC9E,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,SAAS,iBAAiB,CACxB,KAAa,EACb,WAAmB,EACnB,SAAiB;IAEjB,MAAM,iBAAiB,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAErD,IAAI,iBAAiB,KAAK,WAAW,EAAE,CAAC;QACtC,MAAM,SAAS,CAAC,aAAa,CAC3B,+BAA+B,SAAS,YAAY,WAAW,gBAAgB,iBAAiB,QAAQ,CACzG,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { ORIGIN_METAMASK, isValidHexAddress } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { JsonRpcError, providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { isStrictHexString, remove0x } from '@metamask/utils';\n\nimport { isEIP1559Transaction } from './utils';\nimport { TransactionEnvelopeType, TransactionType } from '../types';\nimport type {\n Authorization,\n TransactionBatchRequest,\n TransactionParams,\n} from '../types';\n\nexport enum ErrorCode {\n DuplicateBundleId = 5720,\n BundleTooLarge = 5740,\n RejectedUpgrade = 5750,\n}\n\nconst TRANSACTION_ENVELOPE_TYPES_FEE_MARKET = [\n TransactionEnvelopeType.feeMarket,\n TransactionEnvelopeType.setCode,\n];\n\ntype GasFieldsToValidate =\n | 'gasPrice'\n | 'maxFeePerGas'\n | 'maxPriorityFeePerGas'\n | 'gas'\n | 'gasLimit';\n\n/**\n * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.\n *\n * @param options - Options bag.\n * @param options.data - The data included in the transaction.\n * @param options.from - The address from which the transaction is initiated.\n * @param options.internalAccounts - The internal accounts added to the wallet.\n * @param options.origin - The origin or source of the transaction.\n * @param options.permittedAddresses - The permitted accounts for the given origin.\n * @param options.selectedAddress - The currently selected Ethereum address in the wallet.\n * @param options.txParams - The transaction parameters.\n * @param options.type - The transaction type.\n * @throws Throws an error if the transaction is not permitted.\n */\nexport async function validateTransactionOrigin({\n data,\n from,\n internalAccounts,\n origin,\n permittedAddresses,\n txParams,\n type,\n}: {\n data?: string;\n from: string;\n internalAccounts?: string[];\n origin?: string;\n permittedAddresses?: string[];\n selectedAddress?: string;\n txParams: TransactionParams;\n type?: TransactionType;\n}): Promise<void> {\n const isInternal = !origin || origin === ORIGIN_METAMASK;\n\n if (isInternal) {\n return;\n }\n\n const { authorizationList, to, type: envelopeType } = txParams;\n\n if (permittedAddresses && !permittedAddresses.includes(from)) {\n throw providerErrors.unauthorized({ data: { origin } });\n }\n\n if (type === TransactionType.batch) {\n return;\n }\n\n if (authorizationList || envelopeType === TransactionEnvelopeType.setCode) {\n throw rpcErrors.invalidParams(\n 'External EIP-7702 transactions are not supported',\n );\n }\n\n const hasData = Boolean(data && data !== '0x');\n\n if (\n hasData &&\n internalAccounts?.some(\n (account) => account.toLowerCase() === to?.toLowerCase(),\n )\n ) {\n throw rpcErrors.invalidParams(\n 'External transactions to internal accounts cannot include data',\n );\n }\n}\n\n/**\n * Validates the transaction params for required properties and throws in\n * the event of any validation error.\n *\n * @param txParams - Transaction params object to validate.\n * @param isEIP1559Compatible - whether or not the current network supports EIP-1559 transactions.\n * @param chainId - The chain ID of the transaction.\n */\nexport function validateTxParams(\n txParams: TransactionParams,\n isEIP1559Compatible = true,\n chainId?: Hex,\n): void {\n validateEnvelopeType(txParams.type);\n validateEIP1559Compatibility(txParams, isEIP1559Compatible);\n validateParamFrom(txParams.from);\n validateParamRecipient(txParams);\n validateParamValue(txParams.value);\n validateParamData(txParams.data);\n validateParamChainId(txParams.chainId, chainId);\n validateGasFeeParams(txParams);\n validateAuthorizationList(txParams);\n}\n\n/**\n * Validates the `type` property, ensuring that if it is specified, it is a valid transaction envelope type.\n *\n * @param type - The transaction envelope type to validate.\n * @throws Throws invalid params if the type is not a valid transaction envelope type.\n */\nfunction validateEnvelopeType(type: string | undefined): void {\n if (\n type &&\n !Object.values(TransactionEnvelopeType).includes(\n type as TransactionEnvelopeType,\n )\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: \"${type}\". Must be one of: ${Object.values(\n TransactionEnvelopeType,\n ).join(', ')}`,\n );\n }\n}\n\n/**\n * Validates EIP-1559 compatibility for transaction creation.\n *\n * @param txParams - The transaction parameters to validate.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n * @throws Throws invalid params if the transaction specifies EIP-1559 but the network does not support it.\n */\nfunction validateEIP1559Compatibility(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n): void {\n if (isEIP1559Transaction(txParams) && !isEIP1559Compatible) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559',\n );\n }\n}\n\n/**\n * Validates value property, ensuring it is a valid positive integer number\n * denominated in wei.\n *\n * @param value - The value to validate, expressed as a string.\n * @throws Throws an error if the value is not a valid positive integer\n * number denominated in wei.\n * - If the value contains a hyphen (-), it is considered invalid.\n * - If the value contains a decimal point (.), it is considered invalid.\n * - If the value is not a finite number, is NaN, or is not a safe integer, it is considered invalid.\n */\nfunction validateParamValue(value?: string): void {\n if (value !== undefined) {\n if (value.includes('-')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": not a positive number.`,\n );\n }\n\n if (value.includes('.')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": number must be in wei.`,\n );\n }\n const intValue = parseInt(value, 10);\n const isValid =\n Number.isFinite(intValue) &&\n !Number.isNaN(intValue) &&\n !isNaN(Number(value)) &&\n Number.isSafeInteger(intValue);\n if (!isValid) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value ${value}: number must be a valid number.`,\n );\n }\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param txParams - The transaction parameters object to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamRecipient(txParams: TransactionParams): void {\n if (txParams.to === '0x' || txParams.to === undefined) {\n if (txParams.data) {\n delete txParams.to;\n } else {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n } else if (txParams.to !== undefined && !isValidHexAddress(txParams.to)) {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param from - The from property to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamFrom(from: string): void {\n if (!from || typeof from !== 'string') {\n throw rpcErrors.invalidParams(\n `Invalid \"from\" address ${from}: not a string.`,\n );\n }\n if (!isValidHexAddress(from)) {\n throw rpcErrors.invalidParams('Invalid \"from\" address.');\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param to - The to property to validate.\n * @throws Throws an error if the recipient address is invalid.\n */\nexport function validateParamTo(to?: string): void {\n if (!to || typeof to !== 'string') {\n throw rpcErrors.invalidParams(`Invalid \"to\" address`);\n }\n}\n\n/**\n * Validates a transaction batch request.\n *\n * @param options - Options bag.\n * @param options.internalAccounts - The internal accounts added to the wallet.\n * @param options.request - The batch request object.\n * @param options.sizeLimit - The maximum number of calls allowed in a batch request.\n */\nexport function validateBatchRequest({\n internalAccounts,\n request,\n sizeLimit,\n}: {\n internalAccounts: string[];\n request: TransactionBatchRequest;\n sizeLimit: number;\n}): void {\n const { origin } = request;\n const isExternal = origin && origin !== ORIGIN_METAMASK;\n\n const internalAccountsNormalized = internalAccounts.map((account) =>\n account.toLowerCase(),\n );\n\n if (\n isExternal &&\n request.transactions.some((nestedTransaction) => {\n const normalizedCallTo =\n nestedTransaction.params.to?.toLowerCase() as string;\n\n const callData = nestedTransaction.params.data;\n\n const isInternalAccount =\n internalAccountsNormalized.includes(normalizedCallTo);\n\n const hasData = Boolean(callData && callData !== '0x');\n\n return isInternalAccount && hasData;\n })\n ) {\n throw rpcErrors.invalidParams(\n 'External calls to internal accounts cannot include data',\n );\n }\n\n if (isExternal && request.transactions.length > sizeLimit) {\n throw new JsonRpcError(\n ErrorCode.BundleTooLarge,\n `Batch size cannot exceed ${sizeLimit}. got: ${request.transactions.length}`,\n );\n }\n}\n\n/**\n * Validates input data for transactions.\n *\n * @param value - The input data to validate.\n * @throws Throws invalid params if the input data is invalid.\n */\nfunction validateParamData(value?: string): void {\n if (value) {\n const ERC20Interface = new Interface(abiERC20);\n try {\n ERC20Interface.parseTransaction({ data: value });\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.message.match(/BUFFER_OVERRUN/u)) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: data out-of-bounds, BUFFER_OVERRUN.',\n );\n }\n }\n }\n}\n\n/**\n * Validates chainId type.\n *\n * @param chainIdParams - The chain ID to validate.\n * @param chainIdNetworkClient - The chain ID of the network client.\n */\nfunction validateParamChainId(\n chainIdParams?: Hex,\n chainIdNetworkClient?: Hex,\n): void {\n if (\n chainIdParams &&\n chainIdNetworkClient &&\n chainIdParams.toLowerCase?.() !== chainIdNetworkClient.toLowerCase()\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: chainId must match the network client, got: ${chainIdParams}, expected: ${chainIdNetworkClient}`,\n );\n }\n}\n\n/**\n * Validates gas values.\n *\n * @param txParams - The transaction parameters to validate.\n */\nfunction validateGasFeeParams(txParams: TransactionParams): void {\n if (txParams.gasPrice) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'gasPrice');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxPriorityFeePerGas',\n );\n ensureFieldIsValidHex(txParams, 'gasPrice');\n }\n\n if (txParams.maxFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'maxFeePerGas');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsValidHex(txParams, 'maxFeePerGas');\n }\n\n if (txParams.maxPriorityFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(\n txParams,\n 'maxPriorityFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxPriorityFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsValidHex(txParams, 'maxPriorityFeePerGas');\n }\n\n if (txParams.gasLimit) {\n ensureFieldIsValidHex(txParams, 'gasLimit');\n }\n\n if (txParams.gas) {\n ensureFieldIsValidHex(txParams, 'gas');\n }\n}\n\n/**\n * Ensures that the provided txParams has the proper 'type' specified for the\n * given field, if it is provided. If types do not match throws an\n * invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param field - The current field being validated\n * @throws {ethErrors.rpc.invalidParams} Throws if type does not match the\n * expectations for provided field.\n */\nfunction ensureProperTransactionEnvelopeTypeProvided(\n txParams: TransactionParams,\n field: keyof TransactionParams,\n): void {\n const type = txParams.type as TransactionEnvelopeType | undefined;\n\n switch (field) {\n case 'authorizationList':\n if (type && type !== TransactionEnvelopeType.setCode) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but including authorizationList requires type: \"${TransactionEnvelopeType.setCode}\"`,\n );\n }\n break;\n case 'maxFeePerGas':\n case 'maxPriorityFeePerGas':\n if (type && !TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but including maxFeePerGas and maxPriorityFeePerGas requires type: \"${TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.join(', ')}\"`,\n );\n }\n break;\n case 'gasPrice':\n default:\n if (type && TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${type}\" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`,\n );\n }\n }\n}\n\n/**\n * Given two fields, ensure that the second field is not included in txParams,\n * and if it is throw an invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param fieldBeingValidated - The current field being validated\n * @param mutuallyExclusiveField - The field to ensure is not provided\n * @throws {ethErrors.rpc.invalidParams} Throws if mutuallyExclusiveField is\n * present in txParams.\n */\nfunction ensureMutuallyExclusiveFieldsNotProvided(\n txParams: TransactionParams,\n fieldBeingValidated: GasFieldsToValidate,\n mutuallyExclusiveField: GasFieldsToValidate,\n): void {\n if (typeof txParams[mutuallyExclusiveField] !== 'undefined') {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`,\n );\n }\n}\n\n/**\n * Ensures that the provided value for field is a valid hexadecimal.\n * Throws an invalidParams error if field is not a valid hexadecimal.\n *\n * @param data - The object containing the field\n * @param field - The current field being validated\n * @throws {rpcErrors.invalidParams} Throws if field is not a valid hexadecimal\n */\nfunction ensureFieldIsValidHex<DataType>(\n data: DataType,\n field: keyof DataType,\n): void {\n const value = data[field];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${String(field)} is not a valid hexadecimal string. got: (${String(\n value,\n )})`,\n );\n }\n}\n\n/**\n * Validate the authorization list property in the transaction parameters.\n *\n * @param txParams - The transaction parameters containing the authorization list to validate.\n */\nfunction validateAuthorizationList(txParams: TransactionParams): void {\n const { authorizationList } = txParams;\n\n if (!authorizationList) {\n return;\n }\n\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'authorizationList');\n\n if (!Array.isArray(authorizationList)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: authorizationList must be an array`,\n );\n }\n\n for (const authorization of authorizationList) {\n validateAuthorization(authorization);\n }\n}\n\n/**\n * Validate an authorization object.\n *\n * @param authorization - The authorization object to validate.\n */\nfunction validateAuthorization(authorization: Authorization): void {\n ensureFieldIsValidHex(authorization, 'address');\n validateHexLength(authorization.address, 20, 'address');\n\n for (const field of ['chainId', 'nonce', 'r', 's'] as const) {\n if (authorization[field]) {\n ensureFieldIsValidHex(authorization, field);\n }\n }\n\n const { yParity } = authorization;\n\n if (yParity && !['0x0', '0x1'].includes(yParity)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: yParity must be '0x0' or '0x1'. got: ${yParity}`,\n );\n }\n}\n\n/**\n * Validate the number of bytes in a hex string.\n *\n * @param value - The hex string to validate.\n * @param lengthBytes - The expected length in bytes.\n * @param fieldName - The name of the field being validated.\n */\nfunction validateHexLength(\n value: string,\n lengthBytes: number,\n fieldName: string,\n): void {\n const actualLengthBytes = remove0x(value).length / 2;\n\n if (actualLengthBytes !== lengthBytes) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${fieldName} must be ${lengthBytes} bytes. got: ${actualLengthBytes} bytes`,\n );\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask/transaction-controller",
3
- "version": "62.5.0",
3
+ "version": "62.6.0",
4
4
  "description": "Stores transactions alongside their periodically updated statuses and manages interactions such as approval and cancellation",
5
5
  "keywords": [
6
6
  "MetaMask",