@metamask/transaction-controller 53.0.0 → 54.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -1
- package/dist/TransactionController.cjs +99 -102
- package/dist/TransactionController.cjs.map +1 -1
- package/dist/TransactionController.d.cts +9 -15
- package/dist/TransactionController.d.cts.map +1 -1
- package/dist/TransactionController.d.mts +9 -15
- package/dist/TransactionController.d.mts.map +1 -1
- package/dist/TransactionController.mjs +99 -102
- package/dist/TransactionController.mjs.map +1 -1
- package/dist/helpers/GasFeePoller.cjs +2 -1
- package/dist/helpers/GasFeePoller.cjs.map +1 -1
- package/dist/helpers/GasFeePoller.d.cts +1 -1
- package/dist/helpers/GasFeePoller.d.cts.map +1 -1
- package/dist/helpers/GasFeePoller.d.mts +1 -1
- package/dist/helpers/GasFeePoller.d.mts.map +1 -1
- package/dist/helpers/GasFeePoller.mjs +2 -1
- package/dist/helpers/GasFeePoller.mjs.map +1 -1
- package/dist/helpers/PendingTransactionTracker.cjs +1 -0
- package/dist/helpers/PendingTransactionTracker.cjs.map +1 -1
- package/dist/helpers/PendingTransactionTracker.d.cts.map +1 -1
- package/dist/helpers/PendingTransactionTracker.d.mts.map +1 -1
- package/dist/helpers/PendingTransactionTracker.mjs +1 -0
- package/dist/helpers/PendingTransactionTracker.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +28 -0
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +28 -0
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/batch.cjs +16 -8
- package/dist/utils/batch.cjs.map +1 -1
- package/dist/utils/batch.d.cts +4 -3
- package/dist/utils/batch.d.cts.map +1 -1
- package/dist/utils/batch.d.mts +4 -3
- package/dist/utils/batch.d.mts.map +1 -1
- package/dist/utils/batch.mjs +16 -8
- package/dist/utils/batch.mjs.map +1 -1
- package/dist/utils/nonce.cjs +4 -1
- package/dist/utils/nonce.cjs.map +1 -1
- package/dist/utils/nonce.d.cts +1 -1
- package/dist/utils/nonce.d.cts.map +1 -1
- package/dist/utils/nonce.d.mts +1 -1
- package/dist/utils/nonce.d.mts.map +1 -1
- package/dist/utils/nonce.mjs +4 -1
- package/dist/utils/nonce.mjs.map +1 -1
- package/dist/utils/validation.cjs +4 -2
- package/dist/utils/validation.cjs.map +1 -1
- package/dist/utils/validation.d.cts.map +1 -1
- package/dist/utils/validation.d.mts.map +1 -1
- package/dist/utils/validation.mjs +4 -2
- package/dist/utils/validation.mjs.map +1 -1
- package/package.json +1 -1
package/dist/utils/batch.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"batch.mjs","sourceRoot":"","sources":["../../src/utils/batch.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,wBAAwB;AACjE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,aAAa;AAEjC,OAAO,EACL,uBAAuB,EACvB,+BAA+B,EAC/B,0BAA0B,EAC3B,sBAAkB;AACnB,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,gCAAgC,EACjC,4BAAwB;AACzB,OAAO,EAAE,oBAAoB,EAAE,yBAAqB;AACpD,OAAO,EACL,wBAAwB,EAKzB,qBAAW;AACZ,OAAO,EAAE,kBAAkB,EAAE,wCAAoC;AACjE,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAW1C,OAAO,EACL,uBAAuB,EAGvB,eAAe,EAChB,qBAAiB;AAyBlB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;;;;GAKG;AACH,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e,EAAE,KAAK;KACvB,CACF,CAAC;IAEF,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,GAAG,eAAe,CAAC;IACzC,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAuB,CAAC;IAC9C,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAsB,CAAC;IAC5C,MAAM,YAAY,GAAG,QAAQ,CAAC,YAA+B,CAAC;IAC9D,MAAM,oBAAoB,GAAG,QAAQ,CAAC,oBAAuC,CAAC;IAC9E,MAAM,EAAE,GAAG,QAAQ,CAAC,EAAqB,CAAC;IAC1C,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAwB,CAAC;IAEhD,MAAM,SAAS,GAA2B;QACxC,IAAI;QACJ,GAAG;QACH,YAAY;QACZ,oBAAoB;QACpB,EAAE;QACF,KAAK;KACN,CAAC;IAEF,GAAG,CAAC,qCAAqC,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;IAEtE,OAAO;QACL,EAAE;QACF,MAAM,EAAE,SAAS;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { bytesToHex, createModuleLogger } from '@metamask/utils';\nimport { parse, v4 } from 'uuid';\n\nimport {\n doesChainSupportEIP7702,\n generateEIP7702BatchTransaction,\n isAccountUpgradedToEIP7702,\n} from './eip7702';\nimport {\n getBatchSizeLimit,\n getEIP7702SupportedChains,\n getEIP7702UpgradeContractAddress,\n} from './feature-flags';\nimport { validateBatchRequest } from './validation';\nimport {\n determineTransactionType,\n type BatchTransactionParams,\n type TransactionController,\n type TransactionControllerMessenger,\n type TransactionMeta,\n} from '..';\nimport { CollectPublishHook } from '../hooks/CollectPublishHook';\nimport { projectLogger } from '../logger';\nimport type {\n NestedTransactionMetadata,\n SecurityAlertResponse,\n TransactionBatchSingleRequest,\n PublishBatchHook,\n PublishBatchHookTransaction,\n PublishHook,\n TransactionBatchRequest,\n ValidateSecurityRequest,\n} from '../types';\nimport {\n TransactionEnvelopeType,\n type TransactionBatchResult,\n type TransactionParams,\n TransactionType,\n} from '../types';\n\ntype AddTransactionBatchRequest = {\n addTransaction: TransactionController['addTransaction'];\n getChainId: (networkClientId: string) => Hex;\n getEthQuery: (networkClientId: string) => EthQuery;\n getInternalAccounts: () => Hex[];\n getTransaction: (id: string) => TransactionMeta;\n messenger: TransactionControllerMessenger;\n publishBatchHook?: PublishBatchHook;\n publicKeyEIP7702?: Hex;\n request: TransactionBatchRequest;\n updateTransaction: (\n options: { transactionId: string },\n callback: (transactionMeta: TransactionMeta) => void,\n ) => void;\n};\n\ntype IsAtomicBatchSupportedRequest = {\n address: Hex;\n getEthQuery: (chainId: Hex) => EthQuery;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n};\n\nconst log = createModuleLogger(projectLogger, 'batch');\n\n/**\n * Add a batch transaction.\n *\n * @param request - The request object including the user request and necessary callbacks.\n * @returns The batch result object including the batch ID.\n */\nexport async function addTransactionBatch(\n request: AddTransactionBatchRequest,\n): Promise<TransactionBatchResult> {\n const {\n addTransaction,\n getChainId,\n getInternalAccounts,\n messenger,\n publicKeyEIP7702,\n request: userRequest,\n } = request;\n\n const sizeLimit = getBatchSizeLimit(messenger);\n\n validateBatchRequest({\n internalAccounts: getInternalAccounts(),\n request: userRequest,\n sizeLimit,\n });\n\n const {\n batchId: batchIdOverride,\n from,\n networkClientId,\n requireApproval,\n securityAlertId,\n transactions,\n useHook,\n validateSecurity,\n } = userRequest;\n\n log('Adding', userRequest);\n\n if (useHook) {\n return await addTransactionBatchWithHook(request);\n }\n\n const chainId = getChainId(networkClientId);\n const ethQuery = request.getEthQuery(networkClientId);\n const isChainSupported = doesChainSupportEIP7702(chainId, messenger);\n\n if (!isChainSupported) {\n log('Chain does not support EIP-7702', chainId);\n throw rpcErrors.internal('Chain does not support EIP-7702');\n }\n\n if (!publicKeyEIP7702) {\n throw rpcErrors.internal('EIP-7702 public key not specified');\n }\n\n const { delegationAddress, isSupported } = await isAccountUpgradedToEIP7702(\n from,\n chainId,\n publicKeyEIP7702,\n messenger,\n ethQuery,\n );\n\n log('Account', { delegationAddress, isSupported });\n\n if (!isSupported && delegationAddress) {\n log('Account upgraded to unsupported contract', from, delegationAddress);\n throw rpcErrors.internal('Account upgraded to unsupported contract');\n }\n\n const nestedTransactions = await Promise.all(\n transactions.map((tx) =>\n getNestedTransactionMeta(userRequest, tx, ethQuery),\n ),\n );\n\n const batchParams = generateEIP7702BatchTransaction(from, nestedTransactions);\n\n const txParams: TransactionParams = {\n from,\n ...batchParams,\n };\n\n if (!isSupported) {\n const upgradeContractAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKeyEIP7702,\n );\n\n if (!upgradeContractAddress) {\n throw rpcErrors.internal('Upgrade contract address not found');\n }\n\n txParams.type = TransactionEnvelopeType.setCode;\n txParams.authorizationList = [{ address: upgradeContractAddress }];\n }\n\n if (validateSecurity) {\n const securityRequest: ValidateSecurityRequest = {\n method: 'eth_sendTransaction',\n params: [\n {\n ...txParams,\n authorizationList: undefined,\n type: TransactionEnvelopeType.feeMarket,\n },\n ],\n delegationMock: txParams.authorizationList?.[0]?.address,\n };\n\n log('Security request', securityRequest);\n\n validateSecurity(securityRequest, chainId).catch((error) => {\n log('Security validation failed', error);\n });\n }\n\n log('Adding batch transaction', txParams, networkClientId);\n\n const batchId = batchIdOverride ?? generateBatchId();\n\n const securityAlertResponse = securityAlertId\n ? ({ securityAlertId } as SecurityAlertResponse)\n : undefined;\n\n const { result } = await addTransaction(txParams, {\n batchId,\n nestedTransactions,\n networkClientId,\n requireApproval,\n securityAlertResponse,\n type: TransactionType.batch,\n });\n\n // Wait for the transaction to be published.\n await result;\n\n return {\n batchId,\n };\n}\n\n/**\n * Determine which chains support atomic batch transactions for the given account.\n *\n * @param request - The request object including the account address and necessary callbacks.\n * @returns The chain IDs that support atomic batch transactions.\n */\nexport async function isAtomicBatchSupported(\n request: IsAtomicBatchSupportedRequest,\n): Promise<Hex[]> {\n const {\n address,\n getEthQuery,\n messenger,\n publicKeyEIP7702: publicKey,\n } = request;\n\n if (!publicKey) {\n throw rpcErrors.internal('EIP-7702 public key not specified');\n }\n\n const chainIds7702 = getEIP7702SupportedChains(messenger);\n const chainIds: Hex[] = [];\n\n for (const chainId of chainIds7702) {\n const ethQuery = getEthQuery(chainId);\n\n const { isSupported, delegationAddress } = await isAccountUpgradedToEIP7702(\n address,\n chainId,\n publicKey,\n messenger,\n ethQuery,\n );\n\n if (!delegationAddress || isSupported) {\n chainIds.push(chainId);\n }\n }\n\n log('Atomic batch supported chains', chainIds);\n\n return chainIds;\n}\n\n/**\n * Generate a tranasction batch ID.\n *\n * @returns A unique batch ID as a hexadecimal string.\n */\nfunction generateBatchId(): Hex {\n const idString = v4();\n const idBytes = new Uint8Array(parse(idString));\n return bytesToHex(idBytes);\n}\n\n/**\n * Generate the metadata for a nested transaction.\n *\n * @param request - The batch request.\n * @param singleRequest - The request for a single transaction.\n * @param ethQuery - The EthQuery instance used to interact with the Ethereum blockchain.\n * @returns The metadata for the nested transaction.\n */\nasync function getNestedTransactionMeta(\n request: TransactionBatchRequest,\n singleRequest: TransactionBatchSingleRequest,\n ethQuery: EthQuery,\n): Promise<NestedTransactionMetadata> {\n const { from } = request;\n const { params } = singleRequest;\n\n const { type } = await determineTransactionType(\n { from, ...params },\n ethQuery,\n );\n\n return {\n ...params,\n type,\n };\n}\n\n/**\n * Process a batch transaction using a publish batch hook.\n *\n * @param request - The request object including the user request and necessary callbacks.\n * @returns The batch result object including the batch ID.\n */\nasync function addTransactionBatchWithHook(\n request: AddTransactionBatchRequest,\n): Promise<TransactionBatchResult> {\n const { publishBatchHook, request: userRequest } = request;\n\n const {\n from,\n networkClientId,\n transactions: nestedTransactions,\n } = userRequest;\n\n log('Adding transaction batch using hook', userRequest);\n\n if (!publishBatchHook) {\n log('No publish batch hook provided');\n throw new Error('No publish batch hook provided');\n }\n\n const batchId = generateBatchId();\n const transactionCount = nestedTransactions.length;\n const collectHook = new CollectPublishHook(transactionCount);\n const publishHook = collectHook.getHook();\n const hookTransactions: Omit<PublishBatchHookTransaction, 'signedTx'>[] = [];\n\n try {\n for (const nestedTransaction of nestedTransactions) {\n const hookTransaction = await processTransactionWithHook(\n batchId,\n nestedTransaction,\n publishHook,\n request,\n );\n\n hookTransactions.push(hookTransaction);\n }\n\n const { signedTransactions } = await collectHook.ready();\n\n const transactions = hookTransactions.map((transaction, index) => ({\n ...transaction,\n signedTx: signedTransactions[index],\n }));\n\n log('Calling publish batch hook', { from, networkClientId, transactions });\n\n const result = await publishBatchHook({\n from,\n networkClientId,\n transactions,\n });\n\n log('Publish batch hook result', result);\n\n if (!result) {\n throw new Error('Publish batch hook did not return a result');\n }\n\n const transactionHashes = result.results.map(\n ({ transactionHash }) => transactionHash,\n );\n\n collectHook.success(transactionHashes);\n\n log('Completed batch transaction with hook', transactionHashes);\n\n return {\n batchId,\n };\n } catch (error) {\n log('Publish batch hook failed', error);\n\n collectHook.error(error);\n\n throw error;\n }\n}\n\n/**\n * Process a single transaction with a publish batch hook.\n *\n * @param batchId - ID of the transaction batch.\n * @param nestedTransaction - The nested transaction request.\n * @param publishHook - The publish hook to use for each transaction.\n * @param request - The request object including the user request and necessary callbacks.\n * @returns The single transaction request to be processed by the publish batch hook.\n */\nasync function processTransactionWithHook(\n batchId: Hex,\n nestedTransaction: TransactionBatchSingleRequest,\n publishHook: PublishHook,\n request: AddTransactionBatchRequest,\n) {\n const { existingTransaction, params } = nestedTransaction;\n\n const {\n addTransaction,\n getTransaction,\n request: userRequest,\n updateTransaction,\n } = request;\n\n const { from, networkClientId } = userRequest;\n\n if (existingTransaction) {\n const { id, onPublish, signedTransaction } = existingTransaction;\n const transactionMeta = getTransaction(id);\n\n updateTransaction({ transactionId: id }, (_transactionMeta) => {\n _transactionMeta.batchId = batchId;\n });\n\n publishHook(transactionMeta, signedTransaction)\n .then(onPublish)\n .catch(() => {\n // Intentionally empty\n });\n\n log('Processed existing transaction with hook', {\n id,\n params,\n });\n\n return {\n id,\n params,\n };\n }\n\n const { transactionMeta } = await addTransaction(\n {\n ...params,\n from,\n },\n {\n batchId,\n disableGasBuffer: true,\n networkClientId,\n publishHook,\n requireApproval: false,\n },\n );\n\n const { id, txParams } = transactionMeta;\n const data = txParams.data as Hex | undefined;\n const gas = txParams.gas as Hex | undefined;\n const maxFeePerGas = txParams.maxFeePerGas as Hex | undefined;\n const maxPriorityFeePerGas = txParams.maxPriorityFeePerGas as Hex | undefined;\n const to = txParams.to as Hex | undefined;\n const value = txParams.value as Hex | undefined;\n\n const newParams: BatchTransactionParams = {\n data,\n gas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n };\n\n log('Processed new transaction with hook', { id, params: newParams });\n\n return {\n id,\n params: newParams,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"batch.mjs","sourceRoot":"","sources":["../../src/utils/batch.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,6BAA6B;AAEjD,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,wBAAwB;AACjE,OAAO,EAAE,KAAK,EAAE,EAAE,EAAE,aAAa;AAEjC,OAAO,EACL,uBAAuB,EACvB,+BAA+B,EAC/B,0BAA0B,EAC3B,sBAAkB;AACnB,OAAO,EACL,iBAAiB,EACjB,yBAAyB,EACzB,gCAAgC,EACjC,4BAAwB;AACzB,OAAO,EAAE,oBAAoB,EAAE,yBAAqB;AACpD,OAAO,EACL,wBAAwB,EAKzB,qBAAW;AACZ,OAAO,EAAE,kBAAkB,EAAE,wCAAoC;AACjE,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAa1C,OAAO,EACL,uBAAuB,EAGvB,eAAe,EAChB,qBAAiB;AA0BlB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;;;;GAKG;AACH,MAAM,CAAC,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AAE;YACF,MAAM;SACP,CAAC;KACH;IAED,MAAM,EAAE,eAAe,EAAE,GAAG,MAAM,cAAc,CAC9C;QACE,GAAG,MAAM;QACT,IAAI;KACL,EACD;QACE,OAAO;QACP,gBAAgB,EAAE,IAAI;QACtB,eAAe;QACf,WAAW;QACX,eAAe,EAAE,KAAK;KACvB,CACF,CAAC;IAEF,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,GAAG,eAAe,CAAC;IACzC,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAuB,CAAC;IAC9C,MAAM,GAAG,GAAG,QAAQ,CAAC,GAAsB,CAAC;IAC5C,MAAM,YAAY,GAAG,QAAQ,CAAC,YAA+B,CAAC;IAC9D,MAAM,oBAAoB,GAAG,QAAQ,CAAC,oBAAuC,CAAC;IAC9E,MAAM,EAAE,GAAG,QAAQ,CAAC,EAAqB,CAAC;IAC1C,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAwB,CAAC;IAEhD,MAAM,SAAS,GAA2B;QACxC,IAAI;QACJ,GAAG;QACH,YAAY;QACZ,oBAAoB;QACpB,EAAE;QACF,KAAK;KACN,CAAC;IAEF,GAAG,CAAC,qCAAqC,EAAE,EAAE,EAAE,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;IAEtE,OAAO;QACL,EAAE;QACF,MAAM,EAAE,SAAS;KAClB,CAAC;AACJ,CAAC","sourcesContent":["import type EthQuery from '@metamask/eth-query';\nimport { rpcErrors } from '@metamask/rpc-errors';\nimport type { Hex } from '@metamask/utils';\nimport { bytesToHex, createModuleLogger } from '@metamask/utils';\nimport { parse, v4 } from 'uuid';\n\nimport {\n doesChainSupportEIP7702,\n generateEIP7702BatchTransaction,\n isAccountUpgradedToEIP7702,\n} from './eip7702';\nimport {\n getBatchSizeLimit,\n getEIP7702SupportedChains,\n getEIP7702UpgradeContractAddress,\n} from './feature-flags';\nimport { validateBatchRequest } from './validation';\nimport {\n determineTransactionType,\n type BatchTransactionParams,\n type TransactionController,\n type TransactionControllerMessenger,\n type TransactionMeta,\n} from '..';\nimport { CollectPublishHook } from '../hooks/CollectPublishHook';\nimport { projectLogger } from '../logger';\nimport type {\n NestedTransactionMetadata,\n SecurityAlertResponse,\n TransactionBatchSingleRequest,\n PublishBatchHook,\n PublishBatchHookTransaction,\n PublishHook,\n TransactionBatchRequest,\n ValidateSecurityRequest,\n IsAtomicBatchSupportedResult,\n IsAtomicBatchSupportedResultEntry,\n} from '../types';\nimport {\n TransactionEnvelopeType,\n type TransactionBatchResult,\n type TransactionParams,\n TransactionType,\n} from '../types';\n\ntype AddTransactionBatchRequest = {\n addTransaction: TransactionController['addTransaction'];\n getChainId: (networkClientId: string) => Hex;\n getEthQuery: (networkClientId: string) => EthQuery;\n getInternalAccounts: () => Hex[];\n getTransaction: (id: string) => TransactionMeta;\n messenger: TransactionControllerMessenger;\n publishBatchHook?: PublishBatchHook;\n publicKeyEIP7702?: Hex;\n request: TransactionBatchRequest;\n updateTransaction: (\n options: { transactionId: string },\n callback: (transactionMeta: TransactionMeta) => void,\n ) => void;\n};\n\ntype IsAtomicBatchSupportedRequestInternal = {\n address: Hex;\n chainIds?: Hex[];\n getEthQuery: (chainId: Hex) => EthQuery;\n messenger: TransactionControllerMessenger;\n publicKeyEIP7702?: Hex;\n};\n\nconst log = createModuleLogger(projectLogger, 'batch');\n\n/**\n * Add a batch transaction.\n *\n * @param request - The request object including the user request and necessary callbacks.\n * @returns The batch result object including the batch ID.\n */\nexport async function addTransactionBatch(\n request: AddTransactionBatchRequest,\n): Promise<TransactionBatchResult> {\n const {\n addTransaction,\n getChainId,\n getInternalAccounts,\n messenger,\n publicKeyEIP7702,\n request: userRequest,\n } = request;\n\n const sizeLimit = getBatchSizeLimit(messenger);\n\n validateBatchRequest({\n internalAccounts: getInternalAccounts(),\n request: userRequest,\n sizeLimit,\n });\n\n const {\n batchId: batchIdOverride,\n from,\n networkClientId,\n requireApproval,\n securityAlertId,\n transactions,\n useHook,\n validateSecurity,\n origin,\n } = userRequest;\n\n log('Adding', userRequest);\n\n if (useHook) {\n return await addTransactionBatchWithHook(request);\n }\n\n const chainId = getChainId(networkClientId);\n const ethQuery = request.getEthQuery(networkClientId);\n const isChainSupported = doesChainSupportEIP7702(chainId, messenger);\n\n if (!isChainSupported) {\n log('Chain does not support EIP-7702', chainId);\n throw rpcErrors.internal('Chain does not support EIP-7702');\n }\n\n if (!publicKeyEIP7702) {\n throw rpcErrors.internal('EIP-7702 public key not specified');\n }\n\n const { delegationAddress, isSupported } = await isAccountUpgradedToEIP7702(\n from,\n chainId,\n publicKeyEIP7702,\n messenger,\n ethQuery,\n );\n\n log('Account', { delegationAddress, isSupported });\n\n if (!isSupported && delegationAddress) {\n log('Account upgraded to unsupported contract', from, delegationAddress);\n throw rpcErrors.internal('Account upgraded to unsupported contract');\n }\n\n const nestedTransactions = await Promise.all(\n transactions.map((tx) =>\n getNestedTransactionMeta(userRequest, tx, ethQuery),\n ),\n );\n\n const batchParams = generateEIP7702BatchTransaction(from, nestedTransactions);\n\n const txParams: TransactionParams = {\n from,\n ...batchParams,\n };\n\n if (!isSupported) {\n const upgradeContractAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKeyEIP7702,\n );\n\n if (!upgradeContractAddress) {\n throw rpcErrors.internal('Upgrade contract address not found');\n }\n\n txParams.type = TransactionEnvelopeType.setCode;\n txParams.authorizationList = [{ address: upgradeContractAddress }];\n }\n\n if (validateSecurity) {\n const securityRequest: ValidateSecurityRequest = {\n method: 'eth_sendTransaction',\n params: [\n {\n ...txParams,\n authorizationList: undefined,\n type: TransactionEnvelopeType.feeMarket,\n },\n ],\n delegationMock: txParams.authorizationList?.[0]?.address,\n };\n\n log('Security request', securityRequest);\n\n validateSecurity(securityRequest, chainId).catch((error) => {\n log('Security validation failed', error);\n });\n }\n\n log('Adding batch transaction', txParams, networkClientId);\n\n const batchId = batchIdOverride ?? generateBatchId();\n\n const securityAlertResponse = securityAlertId\n ? ({ securityAlertId } as SecurityAlertResponse)\n : undefined;\n\n const { result } = await addTransaction(txParams, {\n batchId,\n nestedTransactions,\n networkClientId,\n requireApproval,\n securityAlertResponse,\n type: TransactionType.batch,\n origin,\n });\n\n // Wait for the transaction to be published.\n await result;\n\n return {\n batchId,\n };\n}\n\n/**\n * Determine which chains support atomic batch transactions for the given account.\n *\n * @param request - The request object including the account address and necessary callbacks.\n * @returns The chain IDs that support atomic batch transactions.\n */\nexport async function isAtomicBatchSupported(\n request: IsAtomicBatchSupportedRequestInternal,\n): Promise<IsAtomicBatchSupportedResult> {\n const {\n address,\n chainIds,\n getEthQuery,\n messenger,\n publicKeyEIP7702: publicKey,\n } = request;\n\n if (!publicKey) {\n throw rpcErrors.internal('EIP-7702 public key not specified');\n }\n\n const chainIds7702 = getEIP7702SupportedChains(messenger);\n const results: IsAtomicBatchSupportedResultEntry[] = [];\n\n for (const chainId of chainIds7702) {\n if (chainIds && !chainIds.includes(chainId)) {\n continue;\n }\n\n const ethQuery = getEthQuery(chainId);\n\n const { isSupported, delegationAddress } = await isAccountUpgradedToEIP7702(\n address,\n chainId,\n publicKey,\n messenger,\n ethQuery,\n );\n\n const upgradeContractAddress = getEIP7702UpgradeContractAddress(\n chainId,\n messenger,\n publicKey,\n );\n\n results.push({\n chainId,\n delegationAddress,\n isSupported,\n upgradeContractAddress,\n });\n }\n\n log('Atomic batch supported results', results);\n\n return results;\n}\n\n/**\n * Generate a tranasction batch ID.\n *\n * @returns A unique batch ID as a hexadecimal string.\n */\nfunction generateBatchId(): Hex {\n const idString = v4();\n const idBytes = new Uint8Array(parse(idString));\n return bytesToHex(idBytes);\n}\n\n/**\n * Generate the metadata for a nested transaction.\n *\n * @param request - The batch request.\n * @param singleRequest - The request for a single transaction.\n * @param ethQuery - The EthQuery instance used to interact with the Ethereum blockchain.\n * @returns The metadata for the nested transaction.\n */\nasync function getNestedTransactionMeta(\n request: TransactionBatchRequest,\n singleRequest: TransactionBatchSingleRequest,\n ethQuery: EthQuery,\n): Promise<NestedTransactionMetadata> {\n const { from } = request;\n const { params } = singleRequest;\n\n const { type } = await determineTransactionType(\n { from, ...params },\n ethQuery,\n );\n\n return {\n ...params,\n type,\n };\n}\n\n/**\n * Process a batch transaction using a publish batch hook.\n *\n * @param request - The request object including the user request and necessary callbacks.\n * @returns The batch result object including the batch ID.\n */\nasync function addTransactionBatchWithHook(\n request: AddTransactionBatchRequest,\n): Promise<TransactionBatchResult> {\n const { publishBatchHook, request: userRequest } = request;\n\n const {\n from,\n networkClientId,\n transactions: nestedTransactions,\n } = userRequest;\n\n log('Adding transaction batch using hook', userRequest);\n\n if (!publishBatchHook) {\n log('No publish batch hook provided');\n throw new Error('No publish batch hook provided');\n }\n\n const batchId = generateBatchId();\n const transactionCount = nestedTransactions.length;\n const collectHook = new CollectPublishHook(transactionCount);\n const publishHook = collectHook.getHook();\n const hookTransactions: Omit<PublishBatchHookTransaction, 'signedTx'>[] = [];\n\n try {\n for (const nestedTransaction of nestedTransactions) {\n const hookTransaction = await processTransactionWithHook(\n batchId,\n nestedTransaction,\n publishHook,\n request,\n );\n\n hookTransactions.push(hookTransaction);\n }\n\n const { signedTransactions } = await collectHook.ready();\n\n const transactions = hookTransactions.map((transaction, index) => ({\n ...transaction,\n signedTx: signedTransactions[index],\n }));\n\n log('Calling publish batch hook', { from, networkClientId, transactions });\n\n const result = await publishBatchHook({\n from,\n networkClientId,\n transactions,\n });\n\n log('Publish batch hook result', result);\n\n if (!result) {\n throw new Error('Publish batch hook did not return a result');\n }\n\n const transactionHashes = result.results.map(\n ({ transactionHash }) => transactionHash,\n );\n\n collectHook.success(transactionHashes);\n\n log('Completed batch transaction with hook', transactionHashes);\n\n return {\n batchId,\n };\n } catch (error) {\n log('Publish batch hook failed', error);\n\n collectHook.error(error);\n\n throw error;\n }\n}\n\n/**\n * Process a single transaction with a publish batch hook.\n *\n * @param batchId - ID of the transaction batch.\n * @param nestedTransaction - The nested transaction request.\n * @param publishHook - The publish hook to use for each transaction.\n * @param request - The request object including the user request and necessary callbacks.\n * @returns The single transaction request to be processed by the publish batch hook.\n */\nasync function processTransactionWithHook(\n batchId: Hex,\n nestedTransaction: TransactionBatchSingleRequest,\n publishHook: PublishHook,\n request: AddTransactionBatchRequest,\n) {\n const { existingTransaction, params } = nestedTransaction;\n\n const {\n addTransaction,\n getTransaction,\n request: userRequest,\n updateTransaction,\n } = request;\n\n const { from, networkClientId } = userRequest;\n\n if (existingTransaction) {\n const { id, onPublish, signedTransaction } = existingTransaction;\n const transactionMeta = getTransaction(id);\n\n updateTransaction({ transactionId: id }, (_transactionMeta) => {\n _transactionMeta.batchId = batchId;\n });\n\n publishHook(transactionMeta, signedTransaction)\n .then(onPublish)\n .catch(() => {\n // Intentionally empty\n });\n\n log('Processed existing transaction with hook', {\n id,\n params,\n });\n\n return {\n id,\n params,\n };\n }\n\n const { transactionMeta } = await addTransaction(\n {\n ...params,\n from,\n },\n {\n batchId,\n disableGasBuffer: true,\n networkClientId,\n publishHook,\n requireApproval: false,\n },\n );\n\n const { id, txParams } = transactionMeta;\n const data = txParams.data as Hex | undefined;\n const gas = txParams.gas as Hex | undefined;\n const maxFeePerGas = txParams.maxFeePerGas as Hex | undefined;\n const maxPriorityFeePerGas = txParams.maxPriorityFeePerGas as Hex | undefined;\n const to = txParams.to as Hex | undefined;\n const value = txParams.value as Hex | undefined;\n\n const newParams: BatchTransactionParams = {\n data,\n gas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n to,\n value,\n };\n\n log('Processed new transaction with hook', { id, params: newParams });\n\n return {\n id,\n params: newParams,\n };\n}\n"]}
|
package/dist/utils/nonce.cjs
CHANGED
|
@@ -12,7 +12,10 @@ const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'nonce');
|
|
|
12
12
|
* @returns The next hexadecimal nonce to be used for the given transaction, and optionally a function to release the nonce lock.
|
|
13
13
|
*/
|
|
14
14
|
async function getNextNonce(txMeta, getNonceLock) {
|
|
15
|
-
const { customNonceValue, txParams: { from, nonce: existingNonce }, } = txMeta;
|
|
15
|
+
const { customNonceValue, isExternalSign, txParams: { from, nonce: existingNonce }, } = txMeta;
|
|
16
|
+
if (isExternalSign) {
|
|
17
|
+
return [undefined, undefined];
|
|
18
|
+
}
|
|
16
19
|
const customNonce = customNonceValue ? (0, controller_utils_1.toHex)(customNonceValue) : undefined;
|
|
17
20
|
if (customNonce) {
|
|
18
21
|
log('Using custom nonce', customNonce);
|
package/dist/utils/nonce.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nonce.cjs","sourceRoot":"","sources":["../../src/utils/nonce.ts"],"names":[],"mappings":";;;AAAA,iEAAmD;AAMnD,0CAA8D;AAG9D,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;;;;;GAMG;AACI,KAAK,UAAU,YAAY,CAChC,MAAuB,EACvB,YAAqD;IAErD,MAAM,EACJ,gBAAgB,EAChB,QAAQ,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,aAAa,EAAE,GACzC,GAAG,MAAM,CAAC;IAEX,MAAM,WAAW,GAAG,gBAAgB,CAAC,CAAC,CAAC,IAAA,wBAAK,EAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAE3E,IAAI,WAAW,EAAE;QACf,GAAG,CAAC,oBAAoB,EAAE,WAAW,CAAC,CAAC;QACvC,OAAO,CAAC,WAAW,EAAE,SAAS,CAAC,CAAC;KACjC;IAED,IAAI,aAAa,EAAE;QACjB,GAAG,CAAC,sBAAsB,EAAE,aAAa,CAAC,CAAC;QAC3C,OAAO,CAAC,aAAa,EAAE,SAAS,CAAC,CAAC;KACnC;IAED,MAAM,SAAS,GAAG,MAAM,YAAY,CAAC,IAAI,CAAC,CAAC;IAC3C,MAAM,KAAK,GAAG,IAAA,wBAAK,EAAC,SAAS,CAAC,SAAS,CAAC,CAAC;IACzC,MAAM,WAAW,GAAG,SAAS,CAAC,WAAW,CAAC,IAAI,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,EAAE,KAAK,EAAE,SAAS,CAAC,YAAY,CAAC,CAAC;IAErE,OAAO,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;AAC9B,CAAC;AAjCD,oCAiCC;AAED;;;;;;;;GAQG;AACH,SAAgB,uCAAuC,CACrD,cAAsB,EACtB,WAAmB,EACnB,mBAAwC,EACxC,YAA+B;IAE/B,OAAO,YAAY;SAChB,MAAM,CACL,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,CACvE,CAAC,UAAU;QACX,CAAC,eAAe;QAChB,OAAO,KAAK,cAAc;QAC1B,mBAAmB,CAAC,QAAQ,CAAC,MAAM,CAAC;QACpC,IAAI,CAAC,WAAW,EAAE,KAAK,WAAW,CAAC,WAAW,EAAE,CACnD;SACA,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QACzD,4CAA4C;QAC5C,6DAA6D;QAC7D,kDAAkD;QAClD,0BAA0B;QAC1B,OAAO;YACL,MAAM;YACN,OAAO,EAAE,CAAC,EAAE,CAAC;YACb,QAAQ,EAAE;gBACR,IAAI,EAAE,IAAI,IAAI,EAAE;gBAChB,GAAG,EAAE,GAAG,IAAI,EAAE;gBACd,KAAK,EAAE,KAAK,IAAI,EAAE;gBAClB,KAAK,EAAE,KAAK,IAAI,EAAE;aACnB;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACP,CAAC;AA/BD,0FA+BC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type {\n NonceLock,\n Transaction as NonceTrackerTransaction,\n} from '@metamask/nonce-tracker';\n\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionMeta, TransactionStatus } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'nonce');\n\n/**\n * Determine the next nonce to be used for a transaction.\n *\n * @param txMeta - The transaction metadata.\n * @param getNonceLock - An anonymous function that acquires the nonce lock for an address\n * @returns The next hexadecimal nonce to be used for the given transaction, and optionally a function to release the nonce lock.\n */\nexport async function getNextNonce(\n txMeta: TransactionMeta,\n getNonceLock: (address: string) => Promise<NonceLock>,\n): Promise<[string | undefined, (() => void) | undefined]> {\n const {\n customNonceValue,\n isExternalSign,\n txParams: { from, nonce: existingNonce },\n } = txMeta;\n\n if (isExternalSign) {\n return [undefined, undefined];\n }\n\n const customNonce = customNonceValue ? toHex(customNonceValue) : undefined;\n\n if (customNonce) {\n log('Using custom nonce', customNonce);\n return [customNonce, undefined];\n }\n\n if (existingNonce) {\n log('Using existing nonce', existingNonce);\n return [existingNonce, undefined];\n }\n\n const nonceLock = await getNonceLock(from);\n const nonce = toHex(nonceLock.nextNonce);\n const releaseLock = nonceLock.releaseLock.bind(nonceLock);\n\n log('Using nonce from nonce tracker', nonce, nonceLock.nonceDetails);\n\n return [nonce, releaseLock];\n}\n\n/**\n * Filter and format transactions for the nonce tracker.\n *\n * @param currentChainId - Chain ID of the current network.\n * @param fromAddress - Address of the account from which the transactions to filter from are sent.\n * @param transactionStatuses - Status of the transactions for which to filter.\n * @param transactions - Array of transactionMeta objects that have been prefiltered.\n * @returns Array of transactions formatted for the nonce tracker.\n */\nexport function getAndFormatTransactionsForNonceTracker(\n currentChainId: string,\n fromAddress: string,\n transactionStatuses: TransactionStatus[],\n transactions: TransactionMeta[],\n): NonceTrackerTransaction[] {\n return transactions\n .filter(\n ({ chainId, isTransfer, isUserOperation, status, txParams: { from } }) =>\n !isTransfer &&\n !isUserOperation &&\n chainId === currentChainId &&\n transactionStatuses.includes(status) &&\n from.toLowerCase() === fromAddress.toLowerCase(),\n )\n .map(({ status, txParams: { from, gas, value, nonce } }) => {\n // the only value we care about is the nonce\n // but we need to return the other values to satisfy the type\n // TODO: refactor nonceTracker to not require this\n /* istanbul ignore next */\n return {\n status,\n history: [{}],\n txParams: {\n from: from ?? '',\n gas: gas ?? '',\n value: value ?? '',\n nonce: nonce ?? '',\n },\n };\n });\n}\n"]}
|
package/dist/utils/nonce.d.cts
CHANGED
|
@@ -7,7 +7,7 @@ import type { TransactionMeta, TransactionStatus } from "../types.cjs";
|
|
|
7
7
|
* @param getNonceLock - An anonymous function that acquires the nonce lock for an address
|
|
8
8
|
* @returns The next hexadecimal nonce to be used for the given transaction, and optionally a function to release the nonce lock.
|
|
9
9
|
*/
|
|
10
|
-
export declare function getNextNonce(txMeta: TransactionMeta, getNonceLock: (address: string) => Promise<NonceLock>): Promise<[string, (() => void) | undefined]>;
|
|
10
|
+
export declare function getNextNonce(txMeta: TransactionMeta, getNonceLock: (address: string) => Promise<NonceLock>): Promise<[string | undefined, (() => void) | undefined]>;
|
|
11
11
|
/**
|
|
12
12
|
* Filter and format transactions for the nonce tracker.
|
|
13
13
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nonce.d.cts","sourceRoot":"","sources":["../../src/utils/nonce.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,SAAS,EACT,WAAW,IAAI,uBAAuB,EACvC,gCAAgC;AAGjC,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,qBAAiB;AAInE;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,eAAe,EACvB,YAAY,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,SAAS,CAAC,GACpD,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"nonce.d.cts","sourceRoot":"","sources":["../../src/utils/nonce.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,SAAS,EACT,WAAW,IAAI,uBAAuB,EACvC,gCAAgC;AAGjC,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,qBAAiB;AAInE;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,eAAe,EACvB,YAAY,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,SAAS,CAAC,GACpD,OAAO,CAAC,CAAC,MAAM,GAAG,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC,CA8BzD;AAED;;;;;;;;GAQG;AACH,wBAAgB,uCAAuC,CACrD,cAAc,EAAE,MAAM,EACtB,WAAW,EAAE,MAAM,EACnB,mBAAmB,EAAE,iBAAiB,EAAE,EACxC,YAAY,EAAE,eAAe,EAAE,GAC9B,uBAAuB,EAAE,CA0B3B"}
|
package/dist/utils/nonce.d.mts
CHANGED
|
@@ -7,7 +7,7 @@ import type { TransactionMeta, TransactionStatus } from "../types.mjs";
|
|
|
7
7
|
* @param getNonceLock - An anonymous function that acquires the nonce lock for an address
|
|
8
8
|
* @returns The next hexadecimal nonce to be used for the given transaction, and optionally a function to release the nonce lock.
|
|
9
9
|
*/
|
|
10
|
-
export declare function getNextNonce(txMeta: TransactionMeta, getNonceLock: (address: string) => Promise<NonceLock>): Promise<[string, (() => void) | undefined]>;
|
|
10
|
+
export declare function getNextNonce(txMeta: TransactionMeta, getNonceLock: (address: string) => Promise<NonceLock>): Promise<[string | undefined, (() => void) | undefined]>;
|
|
11
11
|
/**
|
|
12
12
|
* Filter and format transactions for the nonce tracker.
|
|
13
13
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nonce.d.mts","sourceRoot":"","sources":["../../src/utils/nonce.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,SAAS,EACT,WAAW,IAAI,uBAAuB,EACvC,gCAAgC;AAGjC,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,qBAAiB;AAInE;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,eAAe,EACvB,YAAY,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,SAAS,CAAC,GACpD,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"nonce.d.mts","sourceRoot":"","sources":["../../src/utils/nonce.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,SAAS,EACT,WAAW,IAAI,uBAAuB,EACvC,gCAAgC;AAGjC,OAAO,KAAK,EAAE,eAAe,EAAE,iBAAiB,EAAE,qBAAiB;AAInE;;;;;;GAMG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,eAAe,EACvB,YAAY,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,SAAS,CAAC,GACpD,OAAO,CAAC,CAAC,MAAM,GAAG,SAAS,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC,CA8BzD;AAED;;;;;;;;GAQG;AACH,wBAAgB,uCAAuC,CACrD,cAAc,EAAE,MAAM,EACtB,WAAW,EAAE,MAAM,EACnB,mBAAmB,EAAE,iBAAiB,EAAE,EACxC,YAAY,EAAE,eAAe,EAAE,GAC9B,uBAAuB,EAAE,CA0B3B"}
|
package/dist/utils/nonce.mjs
CHANGED
|
@@ -9,7 +9,10 @@ const log = createModuleLogger(projectLogger, 'nonce');
|
|
|
9
9
|
* @returns The next hexadecimal nonce to be used for the given transaction, and optionally a function to release the nonce lock.
|
|
10
10
|
*/
|
|
11
11
|
export async function getNextNonce(txMeta, getNonceLock) {
|
|
12
|
-
const { customNonceValue, txParams: { from, nonce: existingNonce }, } = txMeta;
|
|
12
|
+
const { customNonceValue, isExternalSign, txParams: { from, nonce: existingNonce }, } = txMeta;
|
|
13
|
+
if (isExternalSign) {
|
|
14
|
+
return [undefined, undefined];
|
|
15
|
+
}
|
|
13
16
|
const customNonce = customNonceValue ? toHex(customNonceValue) : undefined;
|
|
14
17
|
if (customNonce) {
|
|
15
18
|
log('Using custom nonce', customNonce);
|
package/dist/utils/nonce.mjs.map
CHANG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B,EACnB,mBAAwC,EACxC,YAA+B;IAE/B,OAAO,YAAY;SAChB,MAAM,CACL,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,CACvE,CAAC,UAAU;QACX,CAAC,eAAe;QAChB,OAAO,KAAK,cAAc;QAC1B,mBAAmB,CAAC,QAAQ,CAAC,MAAM,CAAC;QACpC,IAAI,CAAC,WAAW,EAAE,KAAK,WAAW,CAAC,WAAW,EAAE,CACnD;SACA,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QACzD,4CAA4C;QAC5C,6DAA6D;QAC7D,kDAAkD;QAClD,0BAA0B;QAC1B,OAAO;YACL,MAAM;YACN,OAAO,EAAE,CAAC,EAAE,CAAC;YACb,QAAQ,EAAE;gBACR,IAAI,EAAE,IAAI,IAAI,EAAE;gBAChB,GAAG,EAAE,GAAG,IAAI,EAAE;gBACd,KAAK,EAAE,KAAK,IAAI,EAAE;gBAClB,KAAK,EAAE,KAAK,IAAI,EAAE;aACnB;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type {\n NonceLock,\n Transaction as NonceTrackerTransaction,\n} from '@metamask/nonce-tracker';\n\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionMeta, TransactionStatus } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'nonce');\n\n/**\n * Determine the next nonce to be used for a transaction.\n *\n * @param txMeta - The transaction metadata.\n * @param getNonceLock - An anonymous function that acquires the nonce lock for an address\n * @returns The next hexadecimal nonce to be used for the given transaction, and optionally a function to release the nonce lock.\n */\nexport async function getNextNonce(\n txMeta: TransactionMeta,\n getNonceLock: (address: string) => Promise<NonceLock>,\n): Promise<[string, (() => void) | undefined]> {\n const {\n customNonceValue,\n txParams: { from, nonce: existingNonce },\n } = txMeta;\n\n const customNonce = customNonceValue ? toHex(customNonceValue) : undefined;\n\n if (customNonce) {\n log('Using custom nonce', customNonce);\n return [customNonce, undefined];\n }\n\n if (existingNonce) {\n log('Using existing nonce', existingNonce);\n return [existingNonce, undefined];\n }\n\n const nonceLock = await getNonceLock(from);\n const nonce = toHex(nonceLock.nextNonce);\n const releaseLock = nonceLock.releaseLock.bind(nonceLock);\n\n log('Using nonce from nonce tracker', nonce, nonceLock.nonceDetails);\n\n return [nonce, releaseLock];\n}\n\n/**\n * Filter and format transactions for the nonce tracker.\n *\n * @param currentChainId - Chain ID of the current network.\n * @param fromAddress - Address of the account from which the transactions to filter from are sent.\n * @param transactionStatuses - Status of the transactions for which to filter.\n * @param transactions - Array of transactionMeta objects that have been prefiltered.\n * @returns Array of transactions formatted for the nonce tracker.\n */\nexport function getAndFormatTransactionsForNonceTracker(\n currentChainId: string,\n fromAddress: string,\n transactionStatuses: TransactionStatus[],\n transactions: TransactionMeta[],\n): NonceTrackerTransaction[] {\n return transactions\n .filter(\n ({ chainId, isTransfer, isUserOperation, status, txParams: { from } }) =>\n !isTransfer &&\n !isUserOperation &&\n chainId === currentChainId &&\n transactionStatuses.includes(status) &&\n from.toLowerCase() === fromAddress.toLowerCase(),\n )\n .map(({ status, txParams: { from, gas, value, nonce } }) => {\n // the only value we care about is the nonce\n // but we need to return the other values to satisfy the type\n // TODO: refactor nonceTracker to not require this\n /* istanbul ignore next */\n return {\n status,\n history: [{}],\n txParams: {\n from: from ?? '',\n gas: gas ?? '',\n value: value ?? '',\n nonce: nonce ?? '',\n },\n };\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"nonce.mjs","sourceRoot":"","sources":["../../src/utils/nonce.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;AAMnD,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAG9D,MAAM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M,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE,CACvE,CAAC,UAAU;QACX,CAAC,eAAe;QAChB,OAAO,KAAK,cAAc;QAC1B,mBAAmB,CAAC,QAAQ,CAAC,MAAM,CAAC;QACpC,IAAI,CAAC,WAAW,EAAE,KAAK,WAAW,CAAC,WAAW,EAAE,CACnD;SACA,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QACzD,4CAA4C;QAC5C,6DAA6D;QAC7D,kDAAkD;QAClD,0BAA0B;QAC1B,OAAO;YACL,MAAM;YACN,OAAO,EAAE,CAAC,EAAE,CAAC;YACb,QAAQ,EAAE;gBACR,IAAI,EAAE,IAAI,IAAI,EAAE;gBAChB,GAAG,EAAE,GAAG,IAAI,EAAE;gBACd,KAAK,EAAE,KAAK,IAAI,EAAE;gBAClB,KAAK,EAAE,KAAK,IAAI,EAAE;aACnB;SACF,CAAC;IACJ,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type {\n NonceLock,\n Transaction as NonceTrackerTransaction,\n} from '@metamask/nonce-tracker';\n\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionMeta, TransactionStatus } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'nonce');\n\n/**\n * Determine the next nonce to be used for a transaction.\n *\n * @param txMeta - The transaction metadata.\n * @param getNonceLock - An anonymous function that acquires the nonce lock for an address\n * @returns The next hexadecimal nonce to be used for the given transaction, and optionally a function to release the nonce lock.\n */\nexport async function getNextNonce(\n txMeta: TransactionMeta,\n getNonceLock: (address: string) => Promise<NonceLock>,\n): Promise<[string | undefined, (() => void) | undefined]> {\n const {\n customNonceValue,\n isExternalSign,\n txParams: { from, nonce: existingNonce },\n } = txMeta;\n\n if (isExternalSign) {\n return [undefined, undefined];\n }\n\n const customNonce = customNonceValue ? toHex(customNonceValue) : undefined;\n\n if (customNonce) {\n log('Using custom nonce', customNonce);\n return [customNonce, undefined];\n }\n\n if (existingNonce) {\n log('Using existing nonce', existingNonce);\n return [existingNonce, undefined];\n }\n\n const nonceLock = await getNonceLock(from);\n const nonce = toHex(nonceLock.nextNonce);\n const releaseLock = nonceLock.releaseLock.bind(nonceLock);\n\n log('Using nonce from nonce tracker', nonce, nonceLock.nonceDetails);\n\n return [nonce, releaseLock];\n}\n\n/**\n * Filter and format transactions for the nonce tracker.\n *\n * @param currentChainId - Chain ID of the current network.\n * @param fromAddress - Address of the account from which the transactions to filter from are sent.\n * @param transactionStatuses - Status of the transactions for which to filter.\n * @param transactions - Array of transactionMeta objects that have been prefiltered.\n * @returns Array of transactions formatted for the nonce tracker.\n */\nexport function getAndFormatTransactionsForNonceTracker(\n currentChainId: string,\n fromAddress: string,\n transactionStatuses: TransactionStatus[],\n transactions: TransactionMeta[],\n): NonceTrackerTransaction[] {\n return transactions\n .filter(\n ({ chainId, isTransfer, isUserOperation, status, txParams: { from } }) =>\n !isTransfer &&\n !isUserOperation &&\n chainId === currentChainId &&\n transactionStatuses.includes(status) &&\n from.toLowerCase() === fromAddress.toLowerCase(),\n )\n .map(({ status, txParams: { from, gas, value, nonce } }) => {\n // the only value we care about is the nonce\n // but we need to return the other values to satisfy the type\n // TODO: refactor nonceTracker to not require this\n /* istanbul ignore next */\n return {\n status,\n history: [{}],\n txParams: {\n from: from ?? '',\n gas: gas ?? '',\n value: value ?? '',\n nonce: nonce ?? '',\n },\n };\n });\n}\n"]}
|
|
@@ -43,6 +43,9 @@ async function validateTransactionOrigin({ data, from, internalAccounts, origin,
|
|
|
43
43
|
if (isExternal && permittedAddresses && !permittedAddresses.includes(from)) {
|
|
44
44
|
throw rpc_errors_1.providerErrors.unauthorized({ data: { origin } });
|
|
45
45
|
}
|
|
46
|
+
if (type === types_1.TransactionType.batch) {
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
46
49
|
if (isExternal &&
|
|
47
50
|
(authorizationList || envelopeType === types_1.TransactionEnvelopeType.setCode)) {
|
|
48
51
|
throw rpc_errors_1.rpcErrors.invalidParams('External EIP-7702 transactions are not supported');
|
|
@@ -50,8 +53,7 @@ async function validateTransactionOrigin({ data, from, internalAccounts, origin,
|
|
|
50
53
|
const hasData = Boolean(data && data !== '0x');
|
|
51
54
|
if (isExternal &&
|
|
52
55
|
hasData &&
|
|
53
|
-
internalAccounts?.some((account) => account.toLowerCase() === to?.toLowerCase())
|
|
54
|
-
type !== types_1.TransactionType.batch) {
|
|
56
|
+
internalAccounts?.some((account) => account.toLowerCase() === to?.toLowerCase())) {
|
|
55
57
|
throw rpc_errors_1.rpcErrors.invalidParams('External transactions to internal accounts cannot include data');
|
|
56
58
|
}
|
|
57
59
|
}
|
|
@@ -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;AAEjE,2CAA8D;AAE9D,uCAA+C;AAE/C,wCAIkB;AAElB,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,eAAe,EACf,QAAQ,EACR,IAAI,GAUL;IACC,MAAM,UAAU,GAAG,MAAM,KAAK,kCAAe,CAAC;IAC9C,MAAM,UAAU,GAAG,MAAM,IAAI,MAAM,KAAK,kCAAe,CAAC;IACxD,MAAM,EAAE,iBAAiB,EAAE,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,QAAQ,CAAC;IAE/D,IAAI,UAAU,IAAI,IAAI,KAAK,eAAe,EAAE;QAC1C,MAAM,sBAAS,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;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 type { Hex } from '@metamask/utils';\nimport { isStrictHexString, remove0x } from '@metamask/utils';\n\nimport { isEIP1559Transaction } from './utils';\nimport type { Authorization, TransactionBatchRequest } 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.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 selectedAddress,\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_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 const hasData = Boolean(data && data !== '0x');\n\n if (\n isExternal &&\n hasData &&\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 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 transactionTargetsNormalized = request.transactions.map((tx) =>\n tx.params.to?.toLowerCase(),\n );\n\n const internalAccountsNormalized = internalAccounts.map((account) =>\n account.toLowerCase(),\n );\n\n if (\n isExternal &&\n transactionTargetsNormalized.some((target) =>\n internalAccountsNormalized.includes(target as string),\n )\n ) {\n throw rpcErrors.invalidParams(\n 'Calls to internal accounts are not supported',\n );\n }\n\n if (isExternal && request.transactions.length > sizeLimit) {\n throw rpcErrors.invalidParams(\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 (\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
|
+
{"version":3,"file":"validation.cjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":";;;AAAA,4CAA+C;AAC/C,iEAAgF;AAChF,mEAAuD;AACvD,qDAAiE;AAEjE,2CAA8D;AAE9D,uCAA+C;AAE/C,wCAIkB;AAElB,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,eAAe,EACf,QAAQ,EACR,IAAI,GAUL;IACC,MAAM,UAAU,GAAG,MAAM,KAAK,kCAAe,CAAC;IAC9C,MAAM,UAAU,GAAG,MAAM,IAAI,MAAM,KAAK,kCAAe,CAAC;IACxD,MAAM,EAAE,iBAAi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AC,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 type { Hex } from '@metamask/utils';\nimport { isStrictHexString, remove0x } from '@metamask/utils';\n\nimport { isEIP1559Transaction } from './utils';\nimport type { Authorization, TransactionBatchRequest } 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.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 selectedAddress,\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_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 (type === TransactionType.batch) {\n return;\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 const hasData = Boolean(data && data !== '0x');\n\n if (\n isExternal &&\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 transactionTargetsNormalized = request.transactions.map((tx) =>\n tx.params.to?.toLowerCase(),\n );\n\n const internalAccountsNormalized = internalAccounts.map((account) =>\n account.toLowerCase(),\n );\n\n if (\n isExternal &&\n transactionTargetsNormalized.some((target) =>\n internalAccountsNormalized.includes(target as string),\n )\n ) {\n throw rpcErrors.invalidParams(\n 'Calls to internal accounts are not supported',\n );\n }\n\n if (isExternal && request.transactions.length > sizeLimit) {\n throw rpcErrors.invalidParams(\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 (\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 +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,KAAK,EAAiB,uBAAuB,EAAE,qBAAiB;AACvE,OAAO,EAEL,eAAe,EACf,KAAK,iBAAiB,EACvB,qBAAiB;AAclB;;;;;;;;;;;;;GAaG;AACH,wBAAsB,yBAAyB,CAAC,EAC9C,IAAI,EACJ,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,QAAQ,EACR,IAAI,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;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,gBAAgB,EAChB,OAAO,EACP,SAAS,GACV,EAAE;IACD,gBAAgB,EAAE,MAAM,EAAE,CAAC;IAC3B,OAAO,EAAE,uBAAuB,CAAC;IACjC,SAAS,EAAE,MAAM,CAAC;CACnB,QA4BA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.d.mts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAiB,uBAAuB,EAAE,qBAAiB;AACvE,OAAO,EAEL,eAAe,EACf,KAAK,iBAAiB,EACvB,qBAAiB;AAclB;;;;;;;;;;;;;GAaG;AACH,wBAAsB,yBAAyB,CAAC,EAC9C,IAAI,EACJ,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,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,
|
|
1
|
+
{"version":3,"file":"validation.d.mts","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAiB,uBAAuB,EAAE,qBAAiB;AACvE,OAAO,EAEL,eAAe,EACf,KAAK,iBAAiB,EACvB,qBAAiB;AAclB;;;;;;;;;;;;;GAaG;AACH,wBAAsB,yBAAyB,CAAC,EAC9C,IAAI,EACJ,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,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,iBA8CA;AAED;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,UAAO,EAC1B,OAAO,CAAC,EAAE,GAAG,QAWd;AAwHD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,EAAE,CAAC,EAAE,MAAM,QAI1C;AAED;;;;;;;GAOG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,gBAAgB,EAChB,OAAO,EACP,SAAS,GACV,EAAE;IACD,gBAAgB,EAAE,MAAM,EAAE,CAAC;IAC3B,OAAO,EAAE,uBAAuB,CAAC;IACjC,SAAS,EAAE,MAAM,CAAC;CACnB,QA4BA"}
|
|
@@ -40,6 +40,9 @@ export async function validateTransactionOrigin({ data, from, internalAccounts,
|
|
|
40
40
|
if (isExternal && permittedAddresses && !permittedAddresses.includes(from)) {
|
|
41
41
|
throw providerErrors.unauthorized({ data: { origin } });
|
|
42
42
|
}
|
|
43
|
+
if (type === TransactionType.batch) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
43
46
|
if (isExternal &&
|
|
44
47
|
(authorizationList || envelopeType === TransactionEnvelopeType.setCode)) {
|
|
45
48
|
throw rpcErrors.invalidParams('External EIP-7702 transactions are not supported');
|
|
@@ -47,8 +50,7 @@ export async function validateTransactionOrigin({ data, from, internalAccounts,
|
|
|
47
50
|
const hasData = Boolean(data && data !== '0x');
|
|
48
51
|
if (isExternal &&
|
|
49
52
|
hasData &&
|
|
50
|
-
internalAccounts?.some((account) => account.toLowerCase() === to?.toLowerCase())
|
|
51
|
-
type !== TransactionType.batch) {
|
|
53
|
+
internalAccounts?.some((account) => account.toLowerCase() === to?.toLowerCase())) {
|
|
52
54
|
throw rpcErrors.invalidParams('External transactions to internal accounts cannot include data');
|
|
53
55
|
}
|
|
54
56
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.mjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,2BAA2B;AAC/C,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,mCAAmC;AAChF,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AACvD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,6BAA6B;AAEjE,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,wBAAwB;AAE9D,OAAO,EAAE,oBAAoB,EAAE,oBAAgB;AAE/C,OAAO,EACL,uBAAuB,EACvB,eAAe,EAEhB,qBAAiB;AAElB,MAAM,qCAAqC,GAAG;IAC5C,uBAAuB,CAAC,SAAS;IACjC,uBAAuB,CAAC,OAAO;CAChC,CAAC;AASF;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,EAC9C,IAAI,EACJ,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,QAAQ,EACR,IAAI,GAUL;IACC,MAAM,UAAU,GAAG,MAAM,KAAK,eAAe,CAAC;IAC9C,MAAM,UAAU,GAAG,MAAM,IAAI,MAAM,KAAK,eAAe,CAAC;IACxD,MAAM,EAAE,iBAAiB,EAAE,EAAE,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,QAAQ,CAAC;IAE/D,IAAI,UAAU,IAAI,IAAI,KAAK,eAAe,EAAE;QA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MAAM,iBAAiB,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAErD,IAAI,iBAAiB,KAAK,WAAW,EAAE;QACrC,MAAM,SAAS,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 type { Hex } from '@metamask/utils';\nimport { isStrictHexString, remove0x } from '@metamask/utils';\n\nimport { isEIP1559Transaction } from './utils';\nimport type { Authorization, TransactionBatchRequest } 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.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 selectedAddress,\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_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 const hasData = Boolean(data && data !== '0x');\n\n if (\n isExternal &&\n hasData &&\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 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 transactionTargetsNormalized = request.transactions.map((tx) =>\n tx.params.to?.toLowerCase(),\n );\n\n const internalAccountsNormalized = internalAccounts.map((account) =>\n account.toLowerCase(),\n );\n\n if (\n isExternal &&\n transactionTargetsNormalized.some((target) =>\n internalAccountsNormalized.includes(target as string),\n )\n ) {\n throw rpcErrors.invalidParams(\n 'Calls to internal accounts are not supported',\n );\n }\n\n if (isExternal && request.transactions.length > sizeLimit) {\n throw rpcErrors.invalidParams(\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 (\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
|
+
{"version":3,"file":"validation.mjs","sourceRoot":"","sources":["../../src/utils/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,2BAA2B;AAC/C,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,mCAAmC;AAChF,OAAO,EAAE,QAAQ,EAAE,oCAAoC;AACvD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,6BAA6B;AAEjE,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAE,wBAAwB;AAE9D,OAAO,EAAE,oBAAoB,EAAE,oBAAgB;AAE/C,OAAO,EACL,uBAAuB,EACvB,eAAe,EAEhB,qBAAiB;AAElB,MAAM,qCAAqC,GAAG;IAC5C,uBAAuB,CAAC,SAAS;IACjC,uBAAuB,CAAC,OAAO;CAChC,CAAC;AASF;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAAC,EAC9C,IAAI,EACJ,IAAI,EACJ,gBAAgB,EAChB,MAAM,EACN,kBAAkB,EAClB,eAAe,EACf,QAAQ,EACR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AE,GAAG,aAAa,CAAC;IAElC,IAAI,OAAO,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QAC/C,MAAM,SAAS,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,QAAQ,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;IAErD,IAAI,iBAAiB,KAAK,WAAW,EAAE;QACrC,MAAM,SAAS,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 type { Hex } from '@metamask/utils';\nimport { isStrictHexString, remove0x } from '@metamask/utils';\n\nimport { isEIP1559Transaction } from './utils';\nimport type { Authorization, TransactionBatchRequest } 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.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 selectedAddress,\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_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 (type === TransactionType.batch) {\n return;\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 const hasData = Boolean(data && data !== '0x');\n\n if (\n isExternal &&\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 transactionTargetsNormalized = request.transactions.map((tx) =>\n tx.params.to?.toLowerCase(),\n );\n\n const internalAccountsNormalized = internalAccounts.map((account) =>\n account.toLowerCase(),\n );\n\n if (\n isExternal &&\n transactionTargetsNormalized.some((target) =>\n internalAccountsNormalized.includes(target as string),\n )\n ) {\n throw rpcErrors.invalidParams(\n 'Calls to internal accounts are not supported',\n );\n }\n\n if (isExternal && request.transactions.length > sizeLimit) {\n throw rpcErrors.invalidParams(\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 (\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"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask/transaction-controller",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "54.0.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",
|