@metamask-previews/transaction-controller 45.0.0-preview-1adbaffc → 45.1.0-preview-ee98fad1

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 (86) hide show
  1. package/CHANGELOG.md +39 -1
  2. package/dist/TransactionController.cjs +85 -67
  3. package/dist/TransactionController.cjs.map +1 -1
  4. package/dist/TransactionController.d.cts +22 -17
  5. package/dist/TransactionController.d.cts.map +1 -1
  6. package/dist/TransactionController.d.mts +22 -17
  7. package/dist/TransactionController.d.mts.map +1 -1
  8. package/dist/TransactionController.mjs +84 -66
  9. package/dist/TransactionController.mjs.map +1 -1
  10. package/dist/abi/IERC7821.cjs +23 -0
  11. package/dist/abi/IERC7821.cjs.map +1 -0
  12. package/dist/abi/IERC7821.d.cts +16 -0
  13. package/dist/abi/IERC7821.d.cts.map +1 -0
  14. package/dist/abi/IERC7821.d.mts +16 -0
  15. package/dist/abi/IERC7821.d.mts.map +1 -0
  16. package/dist/abi/IERC7821.mjs +20 -0
  17. package/dist/abi/IERC7821.mjs.map +1 -0
  18. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs +4 -13
  19. package/dist/gas-flows/OracleLayer1GasFeeFlow.cjs.map +1 -1
  20. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.cts.map +1 -1
  21. package/dist/gas-flows/OracleLayer1GasFeeFlow.d.mts.map +1 -1
  22. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs +4 -13
  23. package/dist/gas-flows/OracleLayer1GasFeeFlow.mjs.map +1 -1
  24. package/dist/index.cjs +3 -2
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +3 -2
  27. package/dist/index.d.cts.map +1 -1
  28. package/dist/index.d.mts +3 -2
  29. package/dist/index.d.mts.map +1 -1
  30. package/dist/index.mjs +2 -1
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/types.cjs +11 -37
  33. package/dist/types.cjs.map +1 -1
  34. package/dist/types.d.cts +98 -1
  35. package/dist/types.d.cts.map +1 -1
  36. package/dist/types.d.mts +98 -1
  37. package/dist/types.d.mts.map +1 -1
  38. package/dist/types.mjs +11 -37
  39. package/dist/types.mjs.map +1 -1
  40. package/dist/utils/batch.cjs +84 -0
  41. package/dist/utils/batch.cjs.map +1 -0
  42. package/dist/utils/batch.d.cts +32 -0
  43. package/dist/utils/batch.d.cts.map +1 -0
  44. package/dist/utils/batch.d.mts +32 -0
  45. package/dist/utils/batch.d.mts.map +1 -0
  46. package/dist/utils/batch.mjs +79 -0
  47. package/dist/utils/batch.mjs.map +1 -0
  48. package/dist/utils/eip7702.cjs +160 -0
  49. package/dist/utils/eip7702.cjs.map +1 -0
  50. package/dist/utils/eip7702.d.cts +63 -0
  51. package/dist/utils/eip7702.d.cts.map +1 -0
  52. package/dist/utils/eip7702.d.mts +63 -0
  53. package/dist/utils/eip7702.d.mts.map +1 -0
  54. package/dist/utils/eip7702.mjs +153 -0
  55. package/dist/utils/eip7702.mjs.map +1 -0
  56. package/dist/utils/feature-flags.cjs +53 -0
  57. package/dist/utils/feature-flags.cjs.map +1 -0
  58. package/dist/utils/feature-flags.d.cts +34 -0
  59. package/dist/utils/feature-flags.d.cts.map +1 -0
  60. package/dist/utils/feature-flags.d.mts +34 -0
  61. package/dist/utils/feature-flags.d.mts.map +1 -0
  62. package/dist/utils/feature-flags.mjs +47 -0
  63. package/dist/utils/feature-flags.mjs.map +1 -0
  64. package/dist/utils/prepare.cjs +49 -0
  65. package/dist/utils/prepare.cjs.map +1 -0
  66. package/dist/utils/prepare.d.cts +21 -0
  67. package/dist/utils/prepare.d.cts.map +1 -0
  68. package/dist/utils/prepare.d.mts +21 -0
  69. package/dist/utils/prepare.d.mts.map +1 -0
  70. package/dist/utils/prepare.mjs +44 -0
  71. package/dist/utils/prepare.mjs.map +1 -0
  72. package/dist/utils/utils.cjs +3 -8
  73. package/dist/utils/utils.cjs.map +1 -1
  74. package/dist/utils/utils.d.cts.map +1 -1
  75. package/dist/utils/utils.d.mts.map +1 -1
  76. package/dist/utils/utils.mjs +3 -8
  77. package/dist/utils/utils.mjs.map +1 -1
  78. package/dist/utils/validation.cjs +102 -31
  79. package/dist/utils/validation.cjs.map +1 -1
  80. package/dist/utils/validation.d.cts +18 -6
  81. package/dist/utils/validation.d.cts.map +1 -1
  82. package/dist/utils/validation.d.mts +18 -6
  83. package/dist/utils/validation.d.mts.map +1 -1
  84. package/dist/utils/validation.mjs +103 -32
  85. package/dist/utils/validation.mjs.map +1 -1
  86. package/package.json +11 -9
@@ -6,36 +6,51 @@ const controller_utils_1 = require("@metamask/controller-utils");
6
6
  const metamask_eth_abis_1 = require("@metamask/metamask-eth-abis");
7
7
  const rpc_errors_1 = require("@metamask/rpc-errors");
8
8
  const utils_1 = require("@metamask/utils");
9
- const types_1 = require("../types.cjs");
10
9
  const utils_2 = require("./utils.cjs");
10
+ const types_1 = require("../types.cjs");
11
+ const TRANSACTION_ENVELOPE_TYPES_FEE_MARKET = [
12
+ types_1.TransactionEnvelopeType.feeMarket,
13
+ types_1.TransactionEnvelopeType.setCode,
14
+ ];
11
15
  /**
12
16
  * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.
13
17
  *
14
- * @param permittedAddresses - The permitted accounts for the given origin.
15
- * @param selectedAddress - The currently selected Ethereum address in the wallet.
16
- * @param from - The address from which the transaction is initiated.
17
- * @param origin - The origin or source of the transaction.
18
+ * @param options - Options bag.
19
+ * @param options.from - The address from which the transaction is initiated.
20
+ * @param options.internalAccounts - The internal accounts added to the wallet.
21
+ * @param options.origin - The origin or source of the transaction.
22
+ * @param options.permittedAddresses - The permitted accounts for the given origin.
23
+ * @param options.selectedAddress - The currently selected Ethereum address in the wallet.
24
+ * @param options.txParams - The transaction parameters.
25
+ * @param options.type - The transaction type.
18
26
  * @throws Throws an error if the transaction is not permitted.
19
27
  */
20
- async function validateTransactionOrigin(permittedAddresses, selectedAddress, from, origin) {
21
- if (origin === controller_utils_1.ORIGIN_METAMASK) {
22
- // Ensure the 'from' address matches the currently selected address
23
- if (from !== selectedAddress) {
24
- throw rpc_errors_1.rpcErrors.internal({
25
- message: `Internally initiated transaction is using invalid account.`,
26
- data: {
27
- origin,
28
- fromAddress: from,
29
- selectedAddress,
30
- },
31
- });
32
- }
33
- return;
28
+ async function validateTransactionOrigin({ from, internalAccounts, origin, permittedAddresses, selectedAddress, txParams, type, }) {
29
+ const isInternal = origin === controller_utils_1.ORIGIN_METAMASK;
30
+ const isExternal = origin && origin !== controller_utils_1.ORIGIN_METAMASK;
31
+ const { authorizationList, to, type: envelopeType } = txParams;
32
+ if (isInternal && from !== selectedAddress) {
33
+ throw rpc_errors_1.rpcErrors.internal({
34
+ message: `Internally initiated transaction is using invalid account.`,
35
+ data: {
36
+ origin,
37
+ fromAddress: from,
38
+ selectedAddress,
39
+ },
40
+ });
34
41
  }
35
- // Check if the origin has permissions to initiate transactions from the specified address
36
- if (!permittedAddresses.includes(from)) {
42
+ if (isExternal && permittedAddresses && !permittedAddresses.includes(from)) {
37
43
  throw rpc_errors_1.providerErrors.unauthorized({ data: { origin } });
38
44
  }
45
+ if (isExternal &&
46
+ (authorizationList || envelopeType === types_1.TransactionEnvelopeType.setCode)) {
47
+ throw rpc_errors_1.rpcErrors.invalidParams('External EIP-7702 transactions are not supported');
48
+ }
49
+ if (isExternal &&
50
+ internalAccounts?.some((account) => account.toLowerCase() === to?.toLowerCase()) &&
51
+ type !== types_1.TransactionType.batch) {
52
+ throw rpc_errors_1.rpcErrors.invalidParams('External transactions to internal accounts are not supported');
53
+ }
39
54
  }
40
55
  exports.validateTransactionOrigin = validateTransactionOrigin;
41
56
  /**
@@ -54,6 +69,7 @@ function validateTxParams(txParams, isEIP1559Compatible = true) {
54
69
  validateParamData(txParams.data);
55
70
  validateParamChainId(txParams.chainId);
56
71
  validateGasFeeParams(txParams);
72
+ validateAuthorizationList(txParams);
57
73
  }
58
74
  exports.validateTxParams = validateTxParams;
59
75
  /**
@@ -236,19 +252,25 @@ function validateGasFeeParams(txParams) {
236
252
  * expectations for provided field.
237
253
  */
238
254
  function ensureProperTransactionEnvelopeTypeProvided(txParams, field) {
255
+ const type = txParams.type;
239
256
  switch (field) {
257
+ case 'authorizationList':
258
+ if (type && type !== types_1.TransactionEnvelopeType.setCode) {
259
+ throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${type}" but including authorizationList requires type: "${types_1.TransactionEnvelopeType.setCode}"`);
260
+ }
261
+ break;
240
262
  case 'maxFeePerGas':
241
263
  case 'maxPriorityFeePerGas':
242
- if (txParams.type &&
243
- txParams.type !== types_1.TransactionEnvelopeType.feeMarket) {
244
- throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${txParams.type}" but including maxFeePerGas and maxPriorityFeePerGas requires type: "${types_1.TransactionEnvelopeType.feeMarket}"`);
264
+ if (type &&
265
+ !TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {
266
+ throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${type}" but including maxFeePerGas and maxPriorityFeePerGas requires type: "${TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.join(', ')}"`);
245
267
  }
246
268
  break;
247
269
  case 'gasPrice':
248
270
  default:
249
- if (txParams.type &&
250
- txParams.type === types_1.TransactionEnvelopeType.feeMarket) {
251
- throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${txParams.type}" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`);
271
+ if (type &&
272
+ TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {
273
+ throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${type}" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`);
252
274
  }
253
275
  }
254
276
  }
@@ -271,14 +293,63 @@ function ensureMutuallyExclusiveFieldsNotProvided(txParams, fieldBeingValidated,
271
293
  * Ensures that the provided value for field is a valid hexadecimal.
272
294
  * Throws an invalidParams error if field is not a valid hexadecimal.
273
295
  *
274
- * @param txParams - The transaction parameters object
296
+ * @param data - The object containing the field
275
297
  * @param field - The current field being validated
276
298
  * @throws {rpcErrors.invalidParams} Throws if field is not a valid hexadecimal
277
299
  */
278
- function ensureFieldIsValidHex(txParams, field) {
279
- const value = txParams[field];
300
+ function ensureFieldIsValidHex(data, field) {
301
+ const value = data[field];
280
302
  if (typeof value !== 'string' || !(0, utils_1.isStrictHexString)(value)) {
281
- throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction params: ${field} is not a valid hexadecimal. got: (${String(value)})`);
303
+ throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction params: ${String(field)} is not a valid hexadecimal string. got: (${String(value)})`);
304
+ }
305
+ }
306
+ /**
307
+ * Validate the authorization list property in the transaction parameters.
308
+ *
309
+ * @param txParams - The transaction parameters containing the authorization list to validate.
310
+ */
311
+ function validateAuthorizationList(txParams) {
312
+ const { authorizationList } = txParams;
313
+ if (!authorizationList) {
314
+ return;
315
+ }
316
+ ensureProperTransactionEnvelopeTypeProvided(txParams, 'authorizationList');
317
+ if (!Array.isArray(authorizationList)) {
318
+ throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction params: authorizationList must be an array`);
319
+ }
320
+ for (const authorization of authorizationList) {
321
+ validateAuthorization(authorization);
322
+ }
323
+ }
324
+ /**
325
+ * Validate an authorization object.
326
+ *
327
+ * @param authorization - The authorization object to validate.
328
+ */
329
+ function validateAuthorization(authorization) {
330
+ ensureFieldIsValidHex(authorization, 'address');
331
+ validateHexLength(authorization.address, 20, 'address');
332
+ for (const field of ['chainId', 'nonce', 'r', 's']) {
333
+ if (authorization[field]) {
334
+ ensureFieldIsValidHex(authorization, field);
335
+ }
336
+ }
337
+ const { yParity } = authorization;
338
+ if (yParity && !['0x', '0x1'].includes(yParity)) {
339
+ throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction params: yParity must be '0x' or '0x1'. got: ${yParity}`);
340
+ }
341
+ }
342
+ /**
343
+ * Validate the number of bytes in a hex string.
344
+ *
345
+ * @param value - The hex string to validate.
346
+ * @param lengthBytes - The expected length in bytes.
347
+ * @param fieldName - The name of the field being validated.
348
+ */
349
+ function validateHexLength(value, lengthBytes, fieldName) {
350
+ const actualLengthBytes = (0, utils_1.remove0x)(value).length / 2;
351
+ if (actualLengthBytes !== lengthBytes) {
352
+ throw rpc_errors_1.rpcErrors.invalidParams(`Invalid transaction params: ${fieldName} must be ${lengthBytes} bytes. got: ${actualLengthBytes} bytes`);
282
353
  }
283
354
  }
284
355
  //# sourceMappingURL=validation.cjs.map
@@ -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,qDAAiE;AACjE,2CAAoD;AAEpD,wCAA2E;AAC3E,uCAA+C;AAS/C;;;;;;;;GAQG;AACI,KAAK,UAAU,yBAAyB,CAC7C,kBAA4B,EAC5B,eAAuB,EACvB,IAAY,EACZ,MAAc;IAEd,IAAI,MAAM,KAAK,kCAAe,EAAE;QAC9B,mEAAmE;QACnE,IAAI,IAAI,KAAK,eAAe,EAAE;YAC5B,MAAM,sBAAS,CAAC,QAAQ,CAAC;gBACvB,OAAO,EAAE,4DAA4D;gBACrE,IAAI,EAAE;oBACJ,MAAM;oBACN,WAAW,EAAE,IAAI;oBACjB,eAAe;iBAChB;aACF,CAAC,CAAC;SACJ;QACD,OAAO;KACR;IAED,0FAA0F;IAC1F,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;QACtC,MAAM,2BAAc,CAAC,YAAY,CAAC,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC;KACzD;AACH,CAAC;AAzBD,8DAyBC;AAED;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAC9B,QAA2B,EAC3B,mBAAmB,GAAG,IAAI;IAE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G;AACH,SAAS,wCAAwC,CAC/C,QAA2B,EAC3B,mBAAwC,EACxC,sBAA2C;IAE3C,IAAI,OAAO,QAAQ,CAAC,sBAAsB,CAAC,KAAK,WAAW,EAAE;QAC3D,MAAM,sBAAS,CAAC,aAAa,CAC3B,yCAAyC,mBAAmB,sBAAsB,sBAAsB,yBAAyB,CAClI,CAAC;KACH;AACH,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,qBAAqB,CAC5B,QAA2B,EAC3B,KAA0B;IAE1B,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC9B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,IAAA,yBAAiB,EAAC,KAAK,CAAC,EAAE;QAC1D,MAAM,sBAAS,CAAC,aAAa,CAC3B,+BAA+B,KAAK,sCAAsC,MAAM,CAC9E,KAAK,CACN,GAAG,CACL,CAAC;KACH;AACH,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { ORIGIN_METAMASK, isValidHexAddress } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport { isStrictHexString } from '@metamask/utils';\n\nimport { TransactionEnvelopeType, type TransactionParams } from '../types';\nimport { isEIP1559Transaction } from './utils';\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 permittedAddresses - The permitted accounts for the given origin.\n * @param selectedAddress - The currently selected Ethereum address in the wallet.\n * @param from - The address from which the transaction is initiated.\n * @param origin - The origin or source of the transaction.\n * @throws Throws an error if the transaction is not permitted.\n */\nexport async function validateTransactionOrigin(\n permittedAddresses: string[],\n selectedAddress: string,\n from: string,\n origin: string,\n) {\n if (origin === ORIGIN_METAMASK) {\n // Ensure the 'from' address matches the currently selected address\n if (from !== selectedAddress) {\n throw rpcErrors.internal({\n message: `Internally initiated transaction is using invalid account.`,\n data: {\n origin,\n fromAddress: from,\n selectedAddress,\n },\n });\n }\n return;\n }\n\n // Check if the origin has permissions to initiate transactions from the specified address\n if (!permittedAddresses.includes(from)) {\n throw providerErrors.unauthorized({ data: { origin } });\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 */\nexport function validateTxParams(\n txParams: TransactionParams,\n isEIP1559Compatible = true,\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);\n validateGasFeeParams(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 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 chainId - The chainId to validate.\n */\nfunction validateParamChainId(chainId: number | string | undefined) {\n if (\n chainId !== undefined &&\n typeof chainId !== 'number' &&\n typeof chainId !== 'string'\n ) {\n throw rpcErrors.invalidParams(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Invalid transaction params: chainId is not a Number or hex string. got: (${chainId})`,\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: GasFieldsToValidate,\n) {\n switch (field) {\n case 'maxFeePerGas':\n case 'maxPriorityFeePerGas':\n if (\n txParams.type &&\n txParams.type !== TransactionEnvelopeType.feeMarket\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${txParams.type}\" but including maxFeePerGas and maxPriorityFeePerGas requires type: \"${TransactionEnvelopeType.feeMarket}\"`,\n );\n }\n break;\n case 'gasPrice':\n default:\n if (\n txParams.type &&\n txParams.type === TransactionEnvelopeType.feeMarket\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${txParams.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 txParams - The transaction parameters object\n * @param field - The current field being validated\n * @throws {rpcErrors.invalidParams} Throws if field is not a valid hexadecimal\n */\nfunction ensureFieldIsValidHex(\n txParams: TransactionParams,\n field: GasFieldsToValidate,\n) {\n const value = txParams[field];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${field} is not a valid hexadecimal. got: (${String(\n value,\n )})`,\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,qDAAiE;AACjE,2CAA8D;AAE9D,uCAA+C;AAE/C,wCAIkB;AAElB,MAAM,qCAAqC,GAAG;IAC5C,+BAAuB,CAAC,SAAS;IACjC,+BAAuB,CAAC,OAAO;CAChC,CAAC;AASF;;;;;;;;;;;;GAYG;AACI,KAAK,UAAU,yBAAyB,CAAC,EAC9C,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,QAAQ,EACR,IAAI,GASL;IACC,MAAM,UAAU,GAAG,MAAM,KAAK,kCAAe,CAAC;IAC9C,MAAM,UAAU,GAAG,MAAM,IAAI,MAAM,KAAK,kCA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AAI,CAAC,SAAS,EAAE,OAAO,EAAE,GAAG,EAAE,GAAG,CAAU,EAAE;QAC3D,IAAI,aAAa,CAAC,KAAK,CAAC,EAAE;YACxB,qBAAqB,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;SAC7C;KACF;IAED,MAAM,EAAE,OAAO,EAAE,GAAG,aAAa,CAAC;IAElC,IAAI,OAAO,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QAC/C,MAAM,sBAAS,CAAC,aAAa,CAC3B,mEAAmE,OAAO,EAAE,CAC7E,CAAC;KACH;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;QACrC,MAAM,sBAAS,CAAC,aAAa,CAC3B,+BAA+B,SAAS,YAAY,WAAW,gBAAgB,iBAAiB,QAAQ,CACzG,CAAC;KACH;AACH,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { ORIGIN_METAMASK, isValidHexAddress } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\nimport { isStrictHexString, remove0x } from '@metamask/utils';\n\nimport { isEIP1559Transaction } from './utils';\nimport type { Authorization } from '../types';\nimport {\n TransactionEnvelopeType,\n TransactionType,\n type TransactionParams,\n} from '../types';\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.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 from,\n internalAccounts,\n origin,\n permittedAddresses,\n selectedAddress,\n txParams,\n type,\n}: {\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_METAMASK;\n const isExternal = origin && origin !== ORIGIN_METAMASK;\n const { authorizationList, to, type: envelopeType } = txParams;\n\n if (isInternal && from !== selectedAddress) {\n throw rpcErrors.internal({\n message: `Internally initiated transaction is using invalid account.`,\n data: {\n origin,\n fromAddress: from,\n selectedAddress,\n },\n });\n }\n\n if (isExternal && permittedAddresses && !permittedAddresses.includes(from)) {\n throw providerErrors.unauthorized({ data: { origin } });\n }\n\n if (\n isExternal &&\n (authorizationList || envelopeType === TransactionEnvelopeType.setCode)\n ) {\n throw rpcErrors.invalidParams(\n 'External EIP-7702 transactions are not supported',\n );\n }\n\n if (\n isExternal &&\n internalAccounts?.some(\n (account) => account.toLowerCase() === to?.toLowerCase(),\n ) &&\n type !== TransactionType.batch\n ) {\n throw rpcErrors.invalidParams(\n 'External transactions to internal accounts are not supported',\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 */\nexport function validateTxParams(\n txParams: TransactionParams,\n isEIP1559Compatible = true,\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);\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 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 chainId - The chainId to validate.\n */\nfunction validateParamChainId(chainId: number | string | undefined) {\n if (\n chainId !== undefined &&\n typeof chainId !== 'number' &&\n typeof chainId !== 'string'\n ) {\n throw rpcErrors.invalidParams(\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Invalid transaction params: chainId is not a Number or hex string. got: (${chainId})`,\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 (\n type &&\n !TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(\n type as TransactionEnvelopeType,\n )\n ) {\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 (\n type &&\n TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(\n type as TransactionEnvelopeType,\n )\n ) {\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 && !['0x', '0x1'].includes(yParity)) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: yParity must be '0x' 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,14 +1,26 @@
1
- import { type TransactionParams } from "../types.cjs";
1
+ import { TransactionType, type TransactionParams } from "../types.cjs";
2
2
  /**
3
3
  * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.
4
4
  *
5
- * @param permittedAddresses - The permitted accounts for the given origin.
6
- * @param selectedAddress - The currently selected Ethereum address in the wallet.
7
- * @param from - The address from which the transaction is initiated.
8
- * @param origin - The origin or source of the transaction.
5
+ * @param options - Options bag.
6
+ * @param options.from - The address from which the transaction is initiated.
7
+ * @param options.internalAccounts - The internal accounts added to the wallet.
8
+ * @param options.origin - The origin or source of the transaction.
9
+ * @param options.permittedAddresses - The permitted accounts for the given origin.
10
+ * @param options.selectedAddress - The currently selected Ethereum address in the wallet.
11
+ * @param options.txParams - The transaction parameters.
12
+ * @param options.type - The transaction type.
9
13
  * @throws Throws an error if the transaction is not permitted.
10
14
  */
11
- export declare function validateTransactionOrigin(permittedAddresses: string[], selectedAddress: string, from: string, origin: string): Promise<void>;
15
+ export declare function validateTransactionOrigin({ from, internalAccounts, origin, permittedAddresses, selectedAddress, txParams, type, }: {
16
+ from: string;
17
+ internalAccounts?: string[];
18
+ origin?: string;
19
+ permittedAddresses?: string[];
20
+ selectedAddress?: string;
21
+ txParams: TransactionParams;
22
+ type?: TransactionType;
23
+ }): Promise<void>;
12
24
  /**
13
25
  * Validates the transaction params for required properties and throws in
14
26
  * the event of any validation error.
@@ -1 +1 @@
1
- {"version":3,"file":"validation.d.cts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAMA,OAAO,EAA2B,KAAK,iBAAiB,EAAE,qBAAiB;AAU3E;;;;;;;;GAQG;AACH,wBAAsB,yBAAyB,CAC7C,kBAAkB,EAAE,MAAM,EAAE,EAC5B,eAAe,EAAE,MAAM,EACvB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,iBAqBf;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,UAAO,QAU3B;AAwHD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,EAAE,CAAC,EAAE,MAAM,QAI1C"}
1
+ {"version":3,"file":"validation.d.cts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAQA,OAAO,EAEL,eAAe,EACf,KAAK,iBAAiB,EACvB,qBAAiB;AAclB;;;;;;;;;;;;GAYG;AACH,wBAAsB,yBAAyB,CAAC,EAC9C,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,QAAQ,EACR,IAAI,GACL,EAAE;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,iBAwCA;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,UAAO,QAW3B;AAwHD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,EAAE,CAAC,EAAE,MAAM,QAI1C"}
@@ -1,14 +1,26 @@
1
- import { type TransactionParams } from "../types.mjs";
1
+ import { TransactionType, type TransactionParams } from "../types.mjs";
2
2
  /**
3
3
  * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.
4
4
  *
5
- * @param permittedAddresses - The permitted accounts for the given origin.
6
- * @param selectedAddress - The currently selected Ethereum address in the wallet.
7
- * @param from - The address from which the transaction is initiated.
8
- * @param origin - The origin or source of the transaction.
5
+ * @param options - Options bag.
6
+ * @param options.from - The address from which the transaction is initiated.
7
+ * @param options.internalAccounts - The internal accounts added to the wallet.
8
+ * @param options.origin - The origin or source of the transaction.
9
+ * @param options.permittedAddresses - The permitted accounts for the given origin.
10
+ * @param options.selectedAddress - The currently selected Ethereum address in the wallet.
11
+ * @param options.txParams - The transaction parameters.
12
+ * @param options.type - The transaction type.
9
13
  * @throws Throws an error if the transaction is not permitted.
10
14
  */
11
- export declare function validateTransactionOrigin(permittedAddresses: string[], selectedAddress: string, from: string, origin: string): Promise<void>;
15
+ export declare function validateTransactionOrigin({ from, internalAccounts, origin, permittedAddresses, selectedAddress, txParams, type, }: {
16
+ from: string;
17
+ internalAccounts?: string[];
18
+ origin?: string;
19
+ permittedAddresses?: string[];
20
+ selectedAddress?: string;
21
+ txParams: TransactionParams;
22
+ type?: TransactionType;
23
+ }): Promise<void>;
12
24
  /**
13
25
  * Validates the transaction params for required properties and throws in
14
26
  * the event of any validation error.
@@ -1 +1 @@
1
- {"version":3,"file":"validation.d.mts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAMA,OAAO,EAA2B,KAAK,iBAAiB,EAAE,qBAAiB;AAU3E;;;;;;;;GAQG;AACH,wBAAsB,yBAAyB,CAC7C,kBAAkB,EAAE,MAAM,EAAE,EAC5B,eAAe,EAAE,MAAM,EACvB,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,iBAqBf;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,UAAO,QAU3B;AAwHD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,EAAE,CAAC,EAAE,MAAM,QAI1C"}
1
+ {"version":3,"file":"validation.d.mts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAQA,OAAO,EAEL,eAAe,EACf,KAAK,iBAAiB,EACvB,qBAAiB;AAclB;;;;;;;;;;;;GAYG;AACH,wBAAsB,yBAAyB,CAAC,EAC9C,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,QAAQ,EACR,IAAI,GACL,EAAE;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,iBAwCA;AAED;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,UAAO,QAW3B;AAwHD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,EAAE,CAAC,EAAE,MAAM,QAI1C"}
@@ -2,37 +2,52 @@ import { Interface } from "@ethersproject/abi";
2
2
  import { ORIGIN_METAMASK, isValidHexAddress } from "@metamask/controller-utils";
3
3
  import { abiERC20 } from "@metamask/metamask-eth-abis";
4
4
  import { providerErrors, rpcErrors } from "@metamask/rpc-errors";
5
- import { isStrictHexString } from "@metamask/utils";
6
- import { TransactionEnvelopeType } from "../types.mjs";
5
+ import { isStrictHexString, remove0x } from "@metamask/utils";
7
6
  import { isEIP1559Transaction } from "./utils.mjs";
7
+ import { TransactionEnvelopeType, TransactionType } from "../types.mjs";
8
+ const TRANSACTION_ENVELOPE_TYPES_FEE_MARKET = [
9
+ TransactionEnvelopeType.feeMarket,
10
+ TransactionEnvelopeType.setCode,
11
+ ];
8
12
  /**
9
13
  * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.
10
14
  *
11
- * @param permittedAddresses - The permitted accounts for the given origin.
12
- * @param selectedAddress - The currently selected Ethereum address in the wallet.
13
- * @param from - The address from which the transaction is initiated.
14
- * @param origin - The origin or source of the transaction.
15
+ * @param options - Options bag.
16
+ * @param options.from - The address from which the transaction is initiated.
17
+ * @param options.internalAccounts - The internal accounts added to the wallet.
18
+ * @param options.origin - The origin or source of the transaction.
19
+ * @param options.permittedAddresses - The permitted accounts for the given origin.
20
+ * @param options.selectedAddress - The currently selected Ethereum address in the wallet.
21
+ * @param options.txParams - The transaction parameters.
22
+ * @param options.type - The transaction type.
15
23
  * @throws Throws an error if the transaction is not permitted.
16
24
  */
17
- export async function validateTransactionOrigin(permittedAddresses, selectedAddress, from, origin) {
18
- if (origin === ORIGIN_METAMASK) {
19
- // Ensure the 'from' address matches the currently selected address
20
- if (from !== selectedAddress) {
21
- throw rpcErrors.internal({
22
- message: `Internally initiated transaction is using invalid account.`,
23
- data: {
24
- origin,
25
- fromAddress: from,
26
- selectedAddress,
27
- },
28
- });
29
- }
30
- return;
25
+ export async function validateTransactionOrigin({ from, internalAccounts, origin, permittedAddresses, selectedAddress, txParams, type, }) {
26
+ const isInternal = origin === ORIGIN_METAMASK;
27
+ const isExternal = origin && origin !== ORIGIN_METAMASK;
28
+ const { authorizationList, to, type: envelopeType } = txParams;
29
+ if (isInternal && from !== selectedAddress) {
30
+ throw rpcErrors.internal({
31
+ message: `Internally initiated transaction is using invalid account.`,
32
+ data: {
33
+ origin,
34
+ fromAddress: from,
35
+ selectedAddress,
36
+ },
37
+ });
31
38
  }
32
- // Check if the origin has permissions to initiate transactions from the specified address
33
- if (!permittedAddresses.includes(from)) {
39
+ if (isExternal && permittedAddresses && !permittedAddresses.includes(from)) {
34
40
  throw providerErrors.unauthorized({ data: { origin } });
35
41
  }
42
+ if (isExternal &&
43
+ (authorizationList || envelopeType === TransactionEnvelopeType.setCode)) {
44
+ throw rpcErrors.invalidParams('External EIP-7702 transactions are not supported');
45
+ }
46
+ if (isExternal &&
47
+ internalAccounts?.some((account) => account.toLowerCase() === to?.toLowerCase()) &&
48
+ type !== TransactionType.batch) {
49
+ throw rpcErrors.invalidParams('External transactions to internal accounts are not supported');
50
+ }
36
51
  }
37
52
  /**
38
53
  * Validates the transaction params for required properties and throws in
@@ -50,6 +65,7 @@ export function validateTxParams(txParams, isEIP1559Compatible = true) {
50
65
  validateParamData(txParams.data);
51
66
  validateParamChainId(txParams.chainId);
52
67
  validateGasFeeParams(txParams);
68
+ validateAuthorizationList(txParams);
53
69
  }
54
70
  /**
55
71
  * Validates the `type` property, ensuring that if it is specified, it is a valid transaction envelope type.
@@ -230,19 +246,25 @@ function validateGasFeeParams(txParams) {
230
246
  * expectations for provided field.
231
247
  */
232
248
  function ensureProperTransactionEnvelopeTypeProvided(txParams, field) {
249
+ const type = txParams.type;
233
250
  switch (field) {
251
+ case 'authorizationList':
252
+ if (type && type !== TransactionEnvelopeType.setCode) {
253
+ throw rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${type}" but including authorizationList requires type: "${TransactionEnvelopeType.setCode}"`);
254
+ }
255
+ break;
234
256
  case 'maxFeePerGas':
235
257
  case 'maxPriorityFeePerGas':
236
- if (txParams.type &&
237
- txParams.type !== TransactionEnvelopeType.feeMarket) {
238
- throw rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${txParams.type}" but including maxFeePerGas and maxPriorityFeePerGas requires type: "${TransactionEnvelopeType.feeMarket}"`);
258
+ if (type &&
259
+ !TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {
260
+ throw rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${type}" but including maxFeePerGas and maxPriorityFeePerGas requires type: "${TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.join(', ')}"`);
239
261
  }
240
262
  break;
241
263
  case 'gasPrice':
242
264
  default:
243
- if (txParams.type &&
244
- txParams.type === TransactionEnvelopeType.feeMarket) {
245
- throw rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${txParams.type}" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`);
265
+ if (type &&
266
+ TRANSACTION_ENVELOPE_TYPES_FEE_MARKET.includes(type)) {
267
+ throw rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${type}" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`);
246
268
  }
247
269
  }
248
270
  }
@@ -265,14 +287,63 @@ function ensureMutuallyExclusiveFieldsNotProvided(txParams, fieldBeingValidated,
265
287
  * Ensures that the provided value for field is a valid hexadecimal.
266
288
  * Throws an invalidParams error if field is not a valid hexadecimal.
267
289
  *
268
- * @param txParams - The transaction parameters object
290
+ * @param data - The object containing the field
269
291
  * @param field - The current field being validated
270
292
  * @throws {rpcErrors.invalidParams} Throws if field is not a valid hexadecimal
271
293
  */
272
- function ensureFieldIsValidHex(txParams, field) {
273
- const value = txParams[field];
294
+ function ensureFieldIsValidHex(data, field) {
295
+ const value = data[field];
274
296
  if (typeof value !== 'string' || !isStrictHexString(value)) {
275
- throw rpcErrors.invalidParams(`Invalid transaction params: ${field} is not a valid hexadecimal. got: (${String(value)})`);
297
+ throw rpcErrors.invalidParams(`Invalid transaction params: ${String(field)} is not a valid hexadecimal string. got: (${String(value)})`);
298
+ }
299
+ }
300
+ /**
301
+ * Validate the authorization list property in the transaction parameters.
302
+ *
303
+ * @param txParams - The transaction parameters containing the authorization list to validate.
304
+ */
305
+ function validateAuthorizationList(txParams) {
306
+ const { authorizationList } = txParams;
307
+ if (!authorizationList) {
308
+ return;
309
+ }
310
+ ensureProperTransactionEnvelopeTypeProvided(txParams, 'authorizationList');
311
+ if (!Array.isArray(authorizationList)) {
312
+ throw rpcErrors.invalidParams(`Invalid transaction params: authorizationList must be an array`);
313
+ }
314
+ for (const authorization of authorizationList) {
315
+ validateAuthorization(authorization);
316
+ }
317
+ }
318
+ /**
319
+ * Validate an authorization object.
320
+ *
321
+ * @param authorization - The authorization object to validate.
322
+ */
323
+ function validateAuthorization(authorization) {
324
+ ensureFieldIsValidHex(authorization, 'address');
325
+ validateHexLength(authorization.address, 20, 'address');
326
+ for (const field of ['chainId', 'nonce', 'r', 's']) {
327
+ if (authorization[field]) {
328
+ ensureFieldIsValidHex(authorization, field);
329
+ }
330
+ }
331
+ const { yParity } = authorization;
332
+ if (yParity && !['0x', '0x1'].includes(yParity)) {
333
+ throw rpcErrors.invalidParams(`Invalid transaction params: yParity must be '0x' or '0x1'. got: ${yParity}`);
334
+ }
335
+ }
336
+ /**
337
+ * Validate the number of bytes in a hex string.
338
+ *
339
+ * @param value - The hex string to validate.
340
+ * @param lengthBytes - The expected length in bytes.
341
+ * @param fieldName - The name of the field being validated.
342
+ */
343
+ function validateHexLength(value, lengthBytes, fieldName) {
344
+ const actualLengthBytes = remove0x(value).length / 2;
345
+ if (actualLengthBytes !== lengthBytes) {
346
+ throw rpcErrors.invalidParams(`Invalid transaction params: ${fieldName} must be ${lengthBytes} bytes. got: ${actualLengthBytes} bytes`);
276
347
  }
277
348
  }
278
349
  //# sourceMappingURL=validation.mjs.map